diff --git a/README.md b/README.md index 20fcf2888..2538bf891 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![ScotLogo](https://raw.githubusercontent.com/sandialabs/scot/master/deploy/scot_logo_highrez_64x64.png) +![ScotLogo](https://raw.githubusercontent.com/sandialabs/scot/master/public/images/scot_logo_highrez_64x64.png) Sandia Cyber Omni Tracker ========================= @@ -21,14 +21,14 @@ Documentation and Install ------------------------- Read our [documentation](http://scot.readthedocs.org/en/latest/install.html) at Read The Docs. -Also, for docker documentation, please read: [https://github.com/sandialabs/scot/blob/scot-docker/docs/source/scotdocker.rst](https://github.com/sandialabs/scot/blob/scot-docker/docs/source/scotdocker.rst) +Also, for docker documentation, please read: [https://github.com/sandialabs/scot/blob/master/docs/source/scotdocker.rst](https://github.com/sandialabs/scot/blob/master/docs/source/scotdocker.rst) Install It! ----------- **Docker Method** -The suggested method for installation of SCOT is using docker. For a walkthrough of installing SCOT via docker, please read: https://github.com/sandialabs/scot/blob/scot-docker/docs/source/scotdocker.rst +The suggested method for installation of SCOT is using docker. For a walkthrough of installing SCOT via docker, please read: https://github.com/sandialabs/scot/blob/master/docs/source/scotdocker.rst Once you have read the documentation, please run the restart-build-deploy.sh script in the root directory of the scot source code to begin the installation process. diff --git a/lib/Scot/App/Responder/Stretch.pm b/lib/Scot/App/Responder/Stretch.pm index 49a2fc96b..4e2668b77 100644 --- a/lib/Scot/App/Responder/Stretch.pm +++ b/lib/Scot/App/Responder/Stretch.pm @@ -35,7 +35,7 @@ sub process_message { return 1; } - my $cleanser = Data::Clean::JSON->get_cleanser; + my $cleanser = Data::Clean::FromJSON->get_cleanser; my $record = $self->get_document($type, $id); $cleanser->clean_in_place($record); diff --git a/pubdev/.snyk b/pubdev/.snyk new file mode 100644 index 000000000..bcc88032e --- /dev/null +++ b/pubdev/.snyk @@ -0,0 +1,22 @@ +# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. +version: v1.12.0 +ignore: {} +# patches apply the minimum changes required to fix a vulnerability +patch: + 'npm:hoek:20180212': + - gulp-sass > node-sass > request > hawk > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > request > hawk > boom > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > request > hawk > sntp > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > request > hawk > cryptiles > boom > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > node-gyp > request > hawk > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > node-gyp > request > hawk > boom > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > node-gyp > request > hawk > sntp > hoek: + patched: '2018-06-19T00:03:57.062Z' + - gulp-sass > node-sass > node-gyp > request > hawk > cryptiles > boom > hoek: + patched: '2018-06-19T00:03:57.062Z' diff --git a/pubdev/build/scot.js b/pubdev/build/scot.js new file mode 100644 index 000000000..627530c31 --- /dev/null +++ b/pubdev/build/scot.js @@ -0,0 +1,170453 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= this.state.maxTags) { + this.setState({ placeholder: 'Only ' + this.state.maxTags + ' allowed. Please delete a tag to add another one' }); + return; + } else { + tags.push(tag); + this.props.onChange(tags); + this.setState({ tags: tags, placeholder: '' }); + } + } + }, { + key: 'componentDidUpdate', + value: function componentDidUpdate() { + this.showHideInput(); + } + }, { + key: 'handleInputChange', + value: function handleInputChange(input) { + if (input && input.length >= 2) { + var arr = []; + $.ajax({ + type: 'get', + url: '/scot/api/v2/ac/' + this.props.type + '/' + input, + success: function (result) { + var result = result.records; + for (var i = 0; i < result.length; i++) { + var obj = {}; + obj.id = i + 1; + obj.name = result[i]; + arr.push(obj); + } + this.setState({ suggestions: arr }); + }.bind(this), + error: function (data) { + console.log('failed to get autocomplete data'); + }.bind(this) + }); + } + } + }, { + key: 'showHideInput', + value: function showHideInput() { + if (this.props.type == 'userdef' && this.props.maxTags && this.state.tags.length >= this.props.maxTags) { + $('.react-tags__search').hide(); + } else { + $('.react-tags__search').show(); + } + } + }, { + key: 'render', + value: function render() { + return _react2.default.createElement( + 'div', + { className: 'TagInput' }, + _react2.default.createElement(_reactTagAutocomplete2.default, { + tags: this.state.tags, + suggestions: this.state.suggestions, + handleAddition: this.handleAdd, + handleDelete: this.handleDelete, + handleInputChange: this.handleInputChange, + autoresize: false, + autofocus: false, + allowBackspace: false, + allowNew: true, + placeholder: this.state.placeholder, + tagComponent: Tag + }) + ); + } + }]); + + return TagInput; +}(_react.Component); + +TagInput.propTypes = { + onChange: _propTypes2.default.func.isRequired, + type: _propTypes2.default.oneOf(['source', 'tag', 'userdef']).isRequired, + value: _propTypes2.default.array.isRequired, + suggestions: _propTypes2.default.array.isRequired +}; + + +var Tag = function Tag(_ref) { + var classNames = _ref.classNames, + onDelete = _ref.onDelete, + tag = _ref.tag; + return _react2.default.createElement( + 'div', + { className: classNames.selectedTag }, + _react2.default.createElement( + 'span', + { className: classNames.selectedTagName }, + tag.name + ), + _react2.default.createElement('i', { className: 'fa fa-remove', 'aria-hidden': 'true', onClick: onDelete }) + ); +}; + +exports.default = TagInput; + +},{"prop-types":512,"react":983,"react-tag-autocomplete":898}],7:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var TinyMCE = require('react-tinymce'); +var Dropzone = require('../../../node_modules/react-dropzone'); +var Button = require('react-bootstrap/lib/Button.js'); +var Prompt = require('react-router-dom').Prompt; +var Link = require('react-router-dom').Link; + +var recently_updated = 0; + +var customButton = {}; + +var AddEntryModal = React.createClass({ + displayName: 'AddEntryModal', + + getInitialState: function getInitialState() { + var key = new Date(); + key = key.getTime(); + var tinyID = 'tiny_' + key; + var content; + if (this.props.entryAction == 'Add' || this.props.entryAction == 'Reply') { + content = ''; + return { + tinyID: tinyID, key: key, content: content, asyncContentLoaded: true, leaveCatch: true, whoami: undefined + }; + } else if (this.props.entryAction == 'Copy To Entry') { + content = this.props.content; + return { + tinyID: tinyID, key: key, content: content, asyncContentLoaded: true, leaveCatch: true, whoami: undefined + }; + } else if (this.props.entryAction == 'Edit') { + return { + tinyID: tinyID, key: key, content: '', asyncContentLoaded: false, leaveCatch: true, whoami: undefined //Wait until componentDidMount to add the content + }; + } else { + //This is just in case a condition is missed + content = ''; + return { + tinyID: tinyID, key: key, content: content, asyncContentLoaded: true, leaveCatch: true, whoami: undefined + }; + } + }, + + componentDidMount: function componentDidMount() { + + var whoami = getSessionStorage('whoami'); + if (whoami) { + this.setState({ whoami: whoami }); + } + + if (this.props.entryAction == 'Edit') { + $.ajax({ + type: 'GET', + url: '/scot/api/v2/entry/' + this.props.id, + success: function (response) { + recently_updated = response.updated; + this.setState({ content: response.body, asyncContentLoaded: true }); + this.forceUpdate(); + }.bind(this), + error: function (data) { + this.props.errorToggle("Error getting original data from source. Copy/Paste original", data); + this.setState({ content: "Error getting original data from source. Copy/Paste original", asyncContentLoaded: true }); + this.forceUpdate(); + }.bind(this) + }); + } + if ($('#not_saved_entry_' + this.state.key).position()) { + $('.entry-wrapper').scrollTop($('.entry-wrapper').scrollTop() + $('#not_saved_entry_' + this.state.key).position().top); + } + }, + + shouldComponentUpdate: function shouldComponentUpdate() { + return false; //prevent updating this component because it causes the page container to scroll upwards and lose focus due to a bug in paste_preprocess. If this is removed it will cause abnormal scrolling. + }, + + render: function render() { + var not_saved_entry_id = 'not_saved_entry_' + this.state.key; + return React.createElement( + 'div', + { id: not_saved_entry_id, className: 'not_saved_entry' }, + React.createElement( + 'div', + { className: 'row-fluid entry-outer', style: { border: '3px solid blue', marginLeft: 'auto', marginRight: 'auto', width: '99.3%' } }, + React.createElement( + 'div', + { className: 'row-fluid entry-header' }, + React.createElement( + 'div', + { className: 'entry-header-inner' }, + '[', + React.createElement( + Link, + { style: { color: 'black' }, to: "not_saved_0" }, + 'Not_Saved_0' + ), + ']by ', + this.state.whoami, + React.createElement( + 'span', + { className: 'pull-right', style: { display: 'inline-flex', paddingRight: '3px' } }, + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.submit }, + 'Submit' + ), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.onCancel }, + 'Cancel' + ) + ) + ) + ), + this.state.asyncContentLoaded ? React.createElement(TinyMCE, { + id: this.state.tinyID, + content: this.state.content, + className: 'inputtext', + config: { + auto_focus: this.state.tinyID, + selector: 'textarea', + plugins: 'advlist lists link image charmap print preview hr anchor pagebreak searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking save table directionality emoticons template paste textcolor colorpicker textpattern imagetools', + table_clone_elements: "strong em b i font h1 h2 h3 h4 h5 h6 p div", + paste_retain_style_properties: 'all', + paste_data_images: true, + paste_preprocess: function paste_preprocess(plugin, args) { + function replaceA(string) { + return string.replace(/<(\/)?a([^>]*)>/g, '<$1span$2>'); + };args.content = replaceA(args.content) + ' '; + }, + relative_urls: false, + remove_script_host: false, + link_assume_external_targets: true, + toolbar1: 'full screen spellchecker | undo redo | bold italic | alignleft aligncenter alignright | bullist numlist | forecolor backcolor fontsizeselect fontselect formatselect | blockquote code link image insertdatetime | customBlockquote', + theme: 'modern', + content_css: '/css/entryeditor.css', + height: 250, + verify_html: false, + setup: function setup(editor) { + + function blockquote() { + return '


'; + } + + function insertBlockquote() { + var html = blockquote(); + editor.insertContent(html); + } + + editor.addButton('customBlockquote', { + text: '500px max-height blockquote', + //image: 'http://p.yusukekamiyamane.com/icons/search/fugue/icons/calendar-blue.png', + tooltip: "Insert a 500px max-height div (blockquote)", + onclick: insertBlockquote + }); + } + } }) : React.createElement( + 'div', + null, + 'Loading Editor...' + ) + ), + React.createElement(Prompt, { when: this.state.leaveCatch, message: 'Unsubmitted entry detected. You may want to submit or copy the contents of the entry before navigating elsewhere. Click CANCEL to prevent navigation elsewhere.' }) + ); + }, + + onCancel: function onCancel() { + this.setState({ leaveCatch: false }); + this.props.addedentry(); + this.setState({ change: false }); + }, + + submit: function submit() { + if ($('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").text() == "" && $('#' + this.state.key + '_ifr').contents().find("#tinymce").find('img').length == 0) { + alert("Please Add Some Text"); + } else { + if (this.props.entryAction == 'Reply') { + var data = new Object(); + $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").each(function (x, y) { + $(y).find('img').each(function (key, value) { + if ($(value)[0].src.startsWith('blob')) { + //Checking to see if it's a locally copied file + var canvas = document.createElement('canvas'); + var set = new Image(); + set = $(value); + canvas.width = set[0].width; + canvas.height = set[0].height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(set[0], 0, 0); + var dataURL = canvas.toDataURL("image/png"); + $(value).attr('src', dataURL); + } + }); + }); + data = JSON.stringify({ parent: Number(this.props.id), body: $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").html(), target_id: Number(this.props.targetid), target_type: this.props.type }); + $.ajax({ + type: 'post', + url: '/scot/api/v2/entry', + data: data, + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + this.setState({ leaveCatch: false }); + this.props.addedentry(); + }.bind(this), + error: function (response) { + this.props.errorToggle("Failed to add entry.", response); + }.bind(this) + }); + } else if (this.props.entryAction == 'Edit') { + $.ajax({ + type: 'GET', + url: '/scot/api/v2/entry/' + this.props.id, + success: function (response) { + if (recently_updated != response.updated) { + this.forEdit(false); + var set = false; + var Confirm = { + launch: function (set) { + this.forEdit(set); + }.bind(this) + }; + $.confirm({ + icon: 'glyphicon glyphicon-warning', + confirmButtonClass: 'btn-info', + cancelButtonClass: 'btn-info', + confirmButton: 'Yes, override change', + cancelButton: 'No, Keep edited version from another user', + content: "edit:" + '\n\n' + response.body, + backgroundDismiss: false, + title: "Edit Conflict from another user" + '\n\n', + confirm: function confirm() { + Confirm.launch(true); + }, + cancel: function cancel() { + return; + } + }); + } else { + this.forEdit(true); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get data for edit', data); + }.bind(this) + }); + } else if (this.props.type == 'alert') { + var data; + $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").each(function (x, y) { + $(y).find('img').each(function (key, value) { + if ($(value)[0].src.startsWith('blob')) { + //Checking if it's a locally copied file + var canvas = document.createElement('canvas'); + var set = new Image(); + set = $(value); + canvas.width = set[0].width; + canvas.height = set[0].height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(set[0], 0, 0); + var dataURL = canvas.toDataURL("image/png"); + $(value).attr('src', dataURL); + } + }); + }); + data = JSON.stringify({ body: $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").html(), target_id: Number(this.props.targetid), target_type: 'alert', parent: 0 }); + $.ajax({ + type: 'post', + url: '/scot/api/v2/entry', + data: data, + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + this.setState({ leaveCatch: false }); + this.props.addedentry(); + }.bind(this), + error: function (response) { + this.props.errorToggle("Failed to add entry.", response); + }.bind(this) + }); + } else { + var data = new Object(); + $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").each(function (x, y) { + $(y).find('img').each(function (key, value) { + if ($(value)[0].src.startsWith('blob')) { + //Checking if its a locally copied file + var canvas = document.createElement('canvas'); + var set = new Image(); + set = $(value); + canvas.width = set[0].width; + canvas.height = set[0].height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(set[0], 0, 0); + var dataURL = canvas.toDataURL("image/png"); + $(value).attr('src', dataURL); + } + }); + }); + data = { parent: 0, body: $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").html(), target_id: Number(this.props.targetid), target_type: this.props.type }; + $.ajax({ + type: 'post', + url: '/scot/api/v2/entry', + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + this.setState({ leaveCatch: false }); + this.props.addedentry(); + }.bind(this), + error: function (response) { + this.props.errorToggle("Failed to add entry.", response); + }.bind(this) + }); + } + } + }, + forEdit: function forEdit(set) { + if (set) { + $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").each(function (x, y) { + $(y).find('img').each(function (key, value) { + if ($(value)[0].src.startsWith('blob')) { + //Checking if its a lcoally copied file + var canvas = document.createElement('canvas'); + var set = new Image(); + set = $(value); + canvas.width = set[0].width; + canvas.height = set[0].height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(set[0], 0, 0); + var dataURL = canvas.toDataURL("image/png"); + $(value).attr('src', dataURL); + } + }); + }); + var data = { + parent: Number(this.props.parent), + body: $('#tiny_' + this.state.key + '_ifr').contents().find("#tinymce").html(), + target_id: Number(this.props.targetid), + target_type: this.props.type, + parsed: 0 + }; + $.ajax({ + type: 'put', + url: '/scot/api/v2/entry/' + this.props.id, + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + this.setState({ leaveCatch: false }); + this.props.addedentry(); + }.bind(this), + error: function (response) { + this.props.errorToggle("Failed to edit entry.", response); + }.bind(this) + }); + } + } +}); + +module.exports = AddEntryModal; + +},{"../../../node_modules/react-dropzone":805,"react":983,"react-bootstrap/lib/Button.js":527,"react-router-dom":878,"react-tinymce":909}],8:[function(require,module,exports){ +'use strict'; + +var AddFlair = { + entityUpdate: function entityUpdate(entityData, flairToolbarToggle, type, linkWarningToggle, id, scrollTo) { + setTimeout(function () { + var entityResult = {}; + for (var key in entityData) { + entityResult[$('', { html: key }).html()] = entityData[key]; + } + + if (type != 'alertgroup') { + $('iframe').each(function (index, ifr) { + //requestAnimationFrame waits for the frame to be rendered (allowing the iframe to fully render before excuting the next bit of code!!! + ifr.contentWindow.requestAnimationFrame(function () { + if (ifr.contentDocument != null) { + var ifrContents = $(ifr).contents(); + //This makes all href point to blank so they don't reload the iframe + $(ifr.contentDocument.body).find('a').attr('target', '_blank'); + //Copies href to a new attribute, url, before we make href an anchor (so it doesn't go anywhere when clicked) + ifrContents.find('a').each(function (index, a) { + var url = $(a).attr('href'); + $(a).attr('url', url); + }.bind(this)); + //Make href an anchor so it doesn't go anywhere when clicked and instead opens up the modal in linkWarningPopup + //$(ifr.contentDocument.body).find('a').find('.entity').wrap(""); + ifrContents.find('.entity').each(function (index, entity) { + if ($(entity).find('.extras')[0] == null) { + //var currentEntityValue = $(entity).attr('data-entity-value'); + var currentEntityValue = $('', { html: $(entity).attr('data-entity-value') }).html(); + if (currentEntityValue != undefined && entityResult != undefined) { + + var entityMatched = entityResult; + if (entityMatched[currentEntityValue.toLowerCase()] != undefined) { + entityMatched = entityMatched[currentEntityValue.toLowerCase()]; + } else { + entityMatched = entityMatched[currentEntityValue]; + } + + if (entityMatched != undefined) { + var entityType = entityMatched.type; + var entityid = entityMatched.id; + var entityCount = abbreviateNumber(parseInt(entityMatched.count), 0); + var entitydata = entityMatched.data; + var entityEntryCount = entityMatched.entry; + var entitystatus = entityMatched.status; + var circle = $(''); + circle.addClass('circleNumber'); + circle.addClass('extras'); + circle.text(entityCount); + $(entity).append(circle); + $(entity).attr('data-entity-id', entityid); + $(entity).unbind('click'); + if (entitydata != undefined) { + if (entitydata.geoip != undefined) { + if (entitydata.geoip.data.isocode != undefined) { + var country_code; + if (entitydata.geoip.data.isp == 'Sandia National Laboratories') { + country_code = 'sandia'; + } else { + country_code = entitydata.geoip.data.isocode; + } + var flag = $('').attr('src', '/images/flags/' + country_code.toLowerCase() + '.png'); + flag.addClass('extras'); + $(entity).append(flag); + } + } + if (entitydata.sidd != undefined) { + if (entitydata.sidd.data.blocklist != undefined) { + if (entitydata.sidd.data.blocklist.action != undefined) { + if (entitydata.sidd.data.blocklist.action.firewall != false) { + $(entity).append($('').attr('src', '/images/flair/firewalled.png')); + } + if (entitydata.sidd.data.blocklist.action.watch != false) { + $(entity).append($('').attr('src', '/images/flair/watch.png')); + } + if (entitydata.sidd.data.blocklist.action.whitelist != false) { + $(entity).append($('').attr('src', '/images/flair/white_list.jpg')); + } + if (entitydata.sidd.data.blocklist.action.blackhole != false) { + $(entity).append($('').attr('src', '/images/flair/blackholed.png'));; + } + if (entitydata.sidd.data.blocklist.action.proxy_block != false) { + $(entity).append($('').attr('src', '/images/flair/blocked.png')); + } + } + } + } + } + /*if (entitystatus == 'untracked') { + $(entity).append($('').attr('src', '/images/flair/notrack64.jpeg')); + }*/ + if (entityEntryCount != undefined) { + if (entityEntryCount != 0) { + var entityEntry = entityMatched.entries[0].body_plain; + $(entity).append($('').attr('src', '/images/flair/note.png')); + } + } + } + } + } + }.bind(this)); + //} + //pentry(ifr,flairToolbarToggle,type,linkWarningToggle,id); + } + }.bind(this)); + }.bind(this)); + } else if (type == 'alertgroup') { + $(document.body).find('.alertTableHorizontal').find('.entity').each(function (index, entity) { + if ($(entity).find('.extras')[0] == null) { + var subtable = $(document.body).find('.alertTableHorizontal'); + subtable.find('a').attr('target', '_blank'); + subtable.find('a').find('.entity').wrap(""); + //Copies href to a new attribute, url, before we make href an anchor (so it doesn't go anywhere when clicked) + subtable.find('a').each(function (index, a) { + var url = $(a).attr('href'); + $(a).attr('url', url); + }.bind(this)); + //var currentEntityValue = $(entity).attr('data-entity-value'); + var currentEntityValue = $('', { html: $(entity).attr('data-entity-value') }).html(); + if (currentEntityValue != undefined && entityResult != undefined) { + + var entityMatched = entityResult; + if (entityMatched[currentEntityValue.toLowerCase()] != undefined) { + entityMatched = entityMatched[currentEntityValue.toLowerCase()]; + } else { + entityMatched = entityMatched[currentEntityValue]; + } + + if (entityMatched != undefined) { + var entityType = entityMatched.type; + var entityid = entityMatched.id; + var entityCount = abbreviateNumber(entityMatched.count); + var entitydata = entityMatched.data; + var entityEntryCount = entityMatched.entry; + var entitystatus = entityMatched.status; + var circle = $(''); + circle.addClass('circleNumber'); + circle.addClass('extras'); + circle.text(entityCount); + $(entity).append(circle); + $(entity).attr('data-entity-id', entityid); + $(entity).unbind('click'); + if (entitydata != undefined) { + if (entitydata.geoip != undefined) { + if (entitydata.geoip.data.isocode != undefined) { + var country_code; + if (entitydata.geoip.data.isp == 'Sandia National Laboratories') { + country_code = 'sandia'; + } else { + country_code = entitydata.geoip.data.isocode; + } + var flag = $('').attr('src', '/images/flags/' + country_code.toLowerCase() + '.png'); + flag.addClass('extras'); + $(entity).append(flag); + } + } + if (entitydata.sidd != undefined) { + if (entitydata.sidd.data.blocklist != undefined) { + if (entitydata.sidd.data.blocklist.action != undefined) { + if (entitydata.sidd.data.blocklist.action.firewall != false) { + $(entity).append($('').attr('src', '/images/flair/firewalled.png')); + } + if (entitydata.sidd.data.blocklist.action.watch != false) { + $(entity).append($('').attr('src', '/images/flair/watch.png')); + } + if (entitydata.sidd.data.blocklist.action.whitelist != false) { + $(entity).append($('').attr('src', '/images/flair/white_list.jpg')); + } + if (entitydata.sidd.data.blocklist.action.blackhole != false) { + $(entity).append($('').attr('src', '/images/flair/blackholed.png')); + } + if (entitydata.sidd.data.blocklist.action.proxy_block != false) { + $(entity).append($('').attr('src', '/images/flair/blocked.png')); + } + } + } + } + } + /*if (entitystatus == 'untracked') { + $(entity).append($('').attr('src', '/images/flair/notrack64.jpeg')); + }*/ + if (entityEntryCount != undefined) { + if (entityEntryCount != 0) { + var entityEntry = entityMatched.entries[0].body_plain; + $(entity).append($('').attr('src', '/images/flair/note.png')); + } + } + } + } + } + }.bind(this)); + } + if (scrollTo != undefined) { + scrollTo(); + } + }.bind(this), 1000); + } + + /* Placed in selectedHeader and selectedEntry accordingly + var Watcher = { + pentry: function(ifr,flairToolbarToggle,type,linkWarningToggle,id) { + if(type != 'alertgroup') { + $('iframe').each(function(index,ifr) { + //requestAnimationFrame waits for the frame to be rendered (allowing the iframe to fully render before excuting the next bit of code!!! + ifr.contentWindow.requestAnimationFrame( function() { + if(ifr.contentDocument != null) { + $(ifr).hover( function() { + var intervalID = setInterval(checkFlairHover, 50, ifr, flairToolbarToggle,type,linkWarningToggle); + $(ifr).data('intervalID', intervalID); + console.log('Now watching iframe ' + intervalID); + }, function() { + var intervalID = $(ifr).data('intervalID'); + window.clearInterval(intervalID); + console.log('No longer watching iframe ' + intervalID); + }).bind(this); + } + }.bind(this)) + }.bind(this)) + } else { + $('.alert-wrapper').find('a, .entity').not('.not_selectable').each(function(index,tr) { + $(tr).hover( function() { + var intervalID = setInterval(checkFlairHover, 50, null, flairToolbarToggle,type,linkWarningToggle,id); + $(tr).data('intervalID', intervalID); + console.log('Now watching item ' + intervalID); + }, function() { + var intervalID = $(tr).data('intervalID'); + window.clearInterval(intervalID); + console.log('No longer watching item ' + intervalID); + }).bind(this); + }).bind(this) + } + } + } + + function checkFlairHover(iframe,flairToolbarToggle,type,linkWarningToggle,id) { + if(type != 'alertgroup') { + if(iframe.contentDocument != null) { + $(iframe).contents().find('.entity').each(function(index, entity) { + if($(entity).css('background-color') == 'rgb(255, 0, 0)') { + $(entity).data('state', 'down'); + } else if ($(entity).data('state') == 'down') { + $(entity).data('state', 'up'); + var entityid = $(entity).attr('data-entity-id'); + var entityvalue = $(entity).attr('data-entity-value'); + infopop(entityid, entityvalue, flairToolbarToggle); + } + }.bind(this)); + } + if(iframe.contentDocument != null) { + $(iframe).contents().find('a').each(function(index,a) { + if($(a).css('color') == 'rgb(255, 0, 0)') { + $(a).data('state','down'); + } else if ($(a).data('state') == 'down') { + $(a).data('state','up'); + var url = $(a).attr('url'); + linkWarningPopup(url,linkWarningToggle); + } + }.bind(this)); + } + } else if (type == 'alertgroup') { + var subtable = $(document.body).find('.alertTableHorizontal'); + subtable.find('.entity').each(function(index, entity) { + if($(entity).css('background-color') == 'rgb(255, 0, 0)') { + $(entity).data('state', 'down'); + } else if ($(entity).data('state') == 'down') { + $(entity).data('state', 'up'); + var entityid = $(entity).attr('data-entity-id'); + var entityvalue = $(entity).attr('data-entity-value'); + infopop(entityid, entityvalue, flairToolbarToggle); + } + }.bind(this)); + subtable.find('a').each(function(index,a) { + if($(a).css('color') == 'rgb(255, 0, 0)') { + $(a).data('state','down'); + } else if ($(a).data('state') == 'down') { + $(a).data('state','up'); + var url = $(a).attr('url'); + linkWarningPopup(url,linkWarningToggle); + } + }.bind(this)); + } + } + + function infopop(entityid, entityvalue, flairToolbarToggle) { + flairToolbarToggle(entityid,entityvalue,'entity'); + } + function linkWarningPopup(url,linkWarningToggle) { + linkWarningToggle(url); + }*/ +};function abbreviateNumber(num, fixed) { + if (num === null) { + return null; + } // terminate early + if (num === 0) { + return '0'; + } // terminate early + fixed = !fixed || fixed < 0 ? 0 : fixed; // number of decimal places to show + var b = num.toPrecision(2).split("e"), + // get power + k = b.length === 1 ? 0 : Math.floor(Math.min(b[1].slice(1), 14) / 3), + // floor at decimals, ceiling at trillions + c = k < 1 ? num.toFixed(0 + fixed) : (num / Math.pow(10, k * 3)).toFixed(1 + fixed), + // divide by power + d = c < 0 ? c : Math.abs(c), + // enforce -0 is 0 + e = d + ['', 'K', 'M', 'B', 'T'][k]; // append power + return e; +} + +//module.exports = {AddFlair, Watcher} +module.exports = { AddFlair: AddFlair }; + +},{}],9:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactAutocomplete = require('react-autocomplete'); + +var _reactAutocomplete2 = _interopRequireDefault(_reactAutocomplete); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var AutoCompleteInput = function (_Component) { + _inherits(AutoCompleteInput, _Component); + + function AutoCompleteInput(props) { + _classCallCheck(this, AutoCompleteInput); + + var _this = _possibleConstructorReturn(this, (AutoCompleteInput.__proto__ || Object.getPrototypeOf(AutoCompleteInput)).call(this, props)); + + _this.state = { + suggestions: [], + value: '' + }; + + _this.HandleAdd = _this.HandleAdd.bind(_this); + _this.HandleInputChange = _this.HandleInputChange.bind(_this); + + return _this; + } + + _createClass(AutoCompleteInput, [{ + key: 'componentWillMount', + value: function componentWillMount() { + if (this.props.value) { + this.setState({ value: this.props.value }); + } + } + }, { + key: 'HandleAdd', + value: function HandleAdd(value) { + this.setState({ value: value }); + this.props.OnChange(value); + } + }, { + key: 'HandleInputChange', + value: function HandleInputChange(input) { + + this.props.OnChange(input.target.value); + + this.setState({ value: input.target.value }); + + if (input.target && input.target.value.length >= 1) { + var arr = []; + $.ajax({ + type: 'get', + url: '/scot/api/v2/ac/' + this.props.type + '/' + input.target.value, + success: function (result) { + var result = result.records; + for (var i = 0; i < result.length; i++) { + if (typeof result[i] == 'string') { + var obj = {}; + obj.label = result[i]; + arr.push(obj); + } + } + + this.setState({ suggestions: arr }); + }.bind(this), + error: function (data) { + console.log('failed to get autocomplete data'); + }.bind(this) + }); + } + } + }, { + key: 'render', + value: function render() { + return _react2.default.createElement( + 'div', + { className: 'AutoCompleteInput' }, + _react2.default.createElement(_reactAutocomplete2.default, { + getItemValue: function getItemValue(item) { + return item.label; + }, + items: this.state.suggestions, + renderItem: function renderItem(item, isHighlighted) { + return _react2.default.createElement( + 'div', + { style: { background: isHighlighted ? 'lightgray' : 'white' } }, + item.label + ); + }, + value: this.state.value, + onChange: this.HandleInputChange, + onSelect: this.HandleAdd, + menuStyle: { + borderRadius: '3px', + boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)', + background: 'rgba(255, 255, 255, 0.9)', + padding: '2px 0', + fontSize: '90%', + overflow: 'auto', + maxHeight: '200px', // TODO: don't cheat, let it flow to the bottom + top: 'unset', + left: 'unset', + position: 'absolute' + }, + inputProps: { style: { width: '100%' } }, + wrapperProps: { style: { width: '300px' } } + }) + ); + } + }]); + + return AutoCompleteInput; +}(_react.Component); + +AutoCompleteInput.propTypes = { + onChange: _propTypes2.default.func.isRequired, + value: _propTypes2.default.array.isRequired +}; +exports.default = AutoCompleteInput; + +},{"prop-types":512,"react":983,"react-autocomplete":521}],10:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Panel = require('react-bootstrap/lib/Panel.js'); +var Badge = require('react-bootstrap/lib/Badge.js'); +var Tooltip = require('react-bootstrap/lib/Tooltip.js'); +var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger.js'); + +var Gamification = React.createClass({ + displayName: 'Gamification', + + getInitialState: function getInitialState() { + return { + GameData: null + }; + }, + componentDidMount: function componentDidMount() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/game', + success: function (response) { + this.setState({ GameData: response }); + }.bind(this), + error: function (data) { + this.props.errorToggle('unable to get game data', data); + }.bind(this) + }); + }, + titleCase: function titleCase(string) { + var newstring = string.charAt(0).toUpperCase() + string.slice(1); + return newstring; + }, + render: function render() { + var GameRows = []; + if (this.state.GameData != null) { + for (var key in this.state.GameData) { + var keyCapitalized = this.titleCase(key); + GameRows.push(React.createElement( + OverlayTrigger, + { placement: 'top', overlay: React.createElement( + Tooltip, + { id: 'tooltip' }, + this.state.GameData[key][0].tooltip + ) }, + React.createElement( + Panel, + { header: keyCapitalized }, + React.createElement( + 'div', + null, + React.createElement( + 'div', + null, + this.state.GameData[key][0].username, + ' ', + React.createElement( + Badge, + null, + this.state.GameData[key][0].count + ) + ), + React.createElement( + 'div', + null, + this.state.GameData[key][1].username, + ' ', + React.createElement( + Badge, + null, + this.state.GameData[key][1].count + ) + ), + React.createElement( + 'div', + null, + this.state.GameData[key][2].username, + ' ', + React.createElement( + Badge, + null, + this.state.GameData[key][2].count + ) + ) + ) + ) + )); + } + } + return React.createElement( + 'div', + { id: 'gamification', className: 'dashboard col-md-2' }, + React.createElement( + 'div', + null, + React.createElement( + 'h2', + null, + 'Leader Board' + ) + ), + React.createElement( + 'div', + null, + GameRows + ) + ); + } +}); + +module.exports = Gamification; + +},{"react":983,"react-bootstrap/lib/Badge.js":524,"react-bootstrap/lib/OverlayTrigger.js":582,"react-bootstrap/lib/Panel.js":589,"react-bootstrap/lib/Tooltip.js":606}],11:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Panel = require('react-bootstrap/lib/Panel.js'); +var Badge = require('react-bootstrap/lib/Badge.js'); + +var Online = React.createClass({ + displayName: 'Online', + + getInitialState: function getInitialState() { + return { + OnlineData: null + }; + }, + componentDidMount: function componentDidMount() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/who', + success: function (response) { + this.setState({ OnlineData: response.records }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get current user', data); + }.bind(this) + }); + }, + render: function render() { + var OnlineRows = []; + if (this.state.OnlineData != null) { + for (var i = 0; i < this.state.OnlineData.length; i++) { + var timeago = timeSince(this.state.OnlineData[i].last_activity); + OnlineRows.push(React.createElement( + Panel, + { header: this.state.OnlineData[i].username }, + React.createElement( + 'div', + { style: { display: 'flex', flexFlow: 'column' } }, + React.createElement( + 'div', + null, + timeago, + ' ago' + ) + ) + )); + } + } else { + OnlineRows.push(React.createElement( + Panel, + { header: 'SCOT 3.5 Online' }, + React.createElement('br', null), + React.createElement( + 'div', + { style: { fontWeight: 'bold' } }, + 'Coming Soon' + ), + React.createElement('br', null) + )); + } + return React.createElement( + 'div', + { id: 'online', className: 'dashboard col-md-2' }, + React.createElement( + 'div', + { style: { textAlign: 'center' } }, + React.createElement( + 'h2', + null, + 'Activity' + ) + ), + React.createElement( + 'div', + null, + OnlineRows + ) + ); + } +}); + +module.exports = Online; + +},{"react":983,"react-bootstrap/lib/Badge.js":524,"react-bootstrap/lib/Panel.js":589}],12:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SingleReport = exports.ReportPage = exports.ReportDashboard = undefined; + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactRouterDom = require('react-router-dom'); + +var _report_heatmap = require('./report_heatmap'); + +var _report_heatmap2 = _interopRequireDefault(_report_heatmap); + +var _report_art = require('./report_art'); + +var _report_art2 = _interopRequireDefault(_report_art); + +var _report_alertpower = require('./report_alertpower'); + +var _report_alertpower2 = _interopRequireDefault(_report_alertpower); + +var _report_created = require('./report_created'); + +var _report_created2 = _interopRequireDefault(_report_created); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var reportComponentByType = function reportComponentByType(reportType) { + switch (reportType) { + default: + case 'heatmap': + return _react2.default.createElement(_report_heatmap2.default, null); + case 'alertpower': + return _react2.default.createElement(_report_alertpower2.default, null); + case 'art': + return _react2.default.createElement(_report_art2.default, null); + case 'created': + return _react2.default.createElement(_report_created2.default, null); + } +}; + +var reportTitleByType = function reportTitleByType(reportType) { + switch (reportType) { + default: + case 'heatmap': + return "Heatmap"; + case 'alertpower': + return "Alert Power"; + case 'art': + return "Alert Response Time"; + case 'created': + return "Items Created"; + } +}; + +var reportPanelHeader = function reportPanelHeader(type) { + var expandButton = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var backButton = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + return _react2.default.createElement( + 'div', + { style: { position: 'relative' } }, + reportTitleByType(type), + expandButton && _react2.default.createElement( + _reactRouterDom.Link, + { to: '/reports/' + type, className: 'panel-button right' }, + _react2.default.createElement( + _reactBootstrap.Button, + { bsSize: 'small' }, + _react2.default.createElement('i', { className: 'fa fa-external-link', 'aria-hidden': true }) + ) + ), + backButton && _react2.default.createElement( + _reactRouterDom.Link, + { to: '/reports', className: 'panel-button left' }, + _react2.default.createElement( + _reactBootstrap.Button, + { bsSize: 'small' }, + _react2.default.createElement('i', { className: 'fa fa-arrow-left', 'aria-hidden': true }) + ) + ) + ); +}; + +var ReportDashboard = exports.ReportDashboard = function ReportDashboard() { + return _react2.default.createElement( + 'div', + { id: 'report', className: 'dashboard' }, + _react2.default.createElement( + 'div', + { style: { textAlign: 'center' } }, + _react2.default.createElement( + 'h2', + null, + 'Reports' + ) + ), + _react2.default.createElement( + 'div', + { id: 'heatmap', className: 'dashboard col-md-4' }, + _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + _reactBootstrap.Panel, + { header: 'Heatmap' }, + _react2.default.createElement(_report_heatmap2.default, null) + ), + _react2.default.createElement( + _reactBootstrap.Panel, + { header: 'Alert Response Time' }, + _react2.default.createElement(_report_art2.default, null) + ) + ) + ) + ); +}; + +// + +var ReportPage = exports.ReportPage = function ReportPage() { + return _react2.default.createElement( + 'div', + { id: 'report', className: 'dashboard', style: { height: 'calc( 100vh - 51px )', overflow: 'auto' } }, + _react2.default.createElement( + 'div', + { style: { textAlign: 'center' } }, + _react2.default.createElement( + 'h2', + null, + 'Reports' + ) + ), + _react2.default.createElement( + 'div', + { className: 'container-fluid' }, + _react2.default.createElement( + 'div', + { className: 'col-md-6' }, + _react2.default.createElement( + _reactBootstrap.Panel, + { header: reportPanelHeader('heatmap', true) }, + _react2.default.createElement(_report_heatmap2.default, null) + ), + _react2.default.createElement( + _reactBootstrap.Panel, + { header: reportPanelHeader('alertpower', true) }, + _react2.default.createElement(_report_alertpower2.default, null) + ) + ), + _react2.default.createElement( + 'div', + { className: 'col-md-6' }, + _react2.default.createElement( + _reactBootstrap.Panel, + { header: reportPanelHeader('art', true) }, + _react2.default.createElement(_report_art2.default, null) + ), + _react2.default.createElement( + _reactBootstrap.Panel, + { header: reportPanelHeader('created', true) }, + _react2.default.createElement(_report_created2.default, null) + ) + ) + ) + ); +}; + +var SingleReport = exports.SingleReport = function SingleReport(_ref) { + var _ref$reportType = _ref.reportType, + reportType = _ref$reportType === undefined ? 'heatmap' : _ref$reportType; + return _react2.default.createElement( + 'div', + { id: 'report', className: 'dashboard', style: { height: 'calc( 100vh - 51px )', overflow: 'auto' } }, + _react2.default.createElement( + 'div', + { className: 'container' }, + _react2.default.createElement( + _reactBootstrap.Panel, + { header: reportPanelHeader(reportType, false, true) }, + reportComponentByType(reportType) + ) + ) + ); +}; + +},{"./report_alertpower":13,"./report_art":14,"./report_created":15,"./report_heatmap":16,"react":983,"react-bootstrap":608,"react-router-dom":878}],13:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +var _debounce = require('../../utils/debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var wrapText = function wrapText(text, width) { + // FYI: not an arrow function because of 'this' injection + text.each(function (value, i) { + if (this.getComputedTextLength() < width) { + return; + } + + var text = d3.select(this), + words = text.text().split(/\s+/).reverse(), + word = null, + line = [], + lineCount = 1, + lineHeight = 0.8, + // ems + x = text.attr('x'), + y = text.attr('y'), + dy = parseFloat(text.attr('dy')), + row = text.text(null).append('tspan').attr('x', x).attr('y', y).attr('dy', dy + 'em'); + + while (word = words.pop()) { + line.push(word); + row.text(line.join(' ')); + if (row.node().getComputedTextLength() > width) { + lineCount++; + line.pop(); + row.text(line.join(' ')); + line = [word]; + row = text.append('tspan').attr('x', x).attr('y', y).attr('dy', lineHeight + dy + 'em').text(word); + } + } + + var yOffset = this.getBBox().height / (2 * lineCount) * (lineCount - 1); + text.attr('transform', 'translate( 0, -' + yOffset + ' )'); + }); +}; + +var margin = { + top: 5, left: 200, right: 30, bottom: 60 +}, + width = 1000 - margin.left - margin.right, + legendHeight = 20, + legendSpacing = 15, + legendTextSpacing = 5; + +var ReportAlertpower = function (_PureComponent) { + _inherits(ReportAlertpower, _PureComponent); + + function ReportAlertpower(props) { + _classCallCheck(this, ReportAlertpower); + + var _this = _possibleConstructorReturn(this, (ReportAlertpower.__proto__ || Object.getPrototypeOf(ReportAlertpower)).call(this, props)); + + _this.state = { + displayMode: 'stacked', + chartData: [], + chartResults: 20, + chartSort: 'power', + chartSortDir: 'desc', + chartFilter: '' + + // LoadData is automatically debounced + };_this.loadData = (0, _debounce2.default)(_this.loadData); + + _this.dataChange = _this.dataChange.bind(_this); + _this.displayModeChange = _this.displayModeChange.bind(_this); + return _this; + } + + _createClass(ReportAlertpower, [{ + key: 'initChart', + value: function initChart() { + // Height is initially 0, is calculated after we have data + this.height = 0; + + this.xScale = d3.scaleLinear().rangeRound([0, width]); + this.yScale = d3.scaleBand().rangeRound([0, this.height]).padding(.3); + + this.colors = d3.scaleOrdinal(d3.schemeCategory20); + + this.xAxis = d3.axisBottom().scale(this.xScale); + + this.yAxis = d3.axisLeft().scale(this.yScale); + + this.svg = d3.select('#report_alertpower').attr('viewBox', '0 0 1000 ' + (this.height + margin.top + margin.bottom)).append('g').attr('transform', 'translate( ' + margin.left + ', ' + margin.top + ' )'); + + this.yAxisEl = this.svg.append('g').attr('class', 'y axis'); + + this.xAxisEl = this.svg.append('g').attr('class', 'x axis').attr('transform', 'translate( 0, ' + this.height + ' )'); + + this.xAxisEl.append('text').attr('text-anchor', 'middle').attr('x', width / 2).attr('y', 30).style('fill', 'black').style('font-size', '12px').text('Alert Count'); + + this.LegendHolder = this.svg.append('g').attr('class', 'legend-holder'); + + this.chartInit = true; + } + }, { + key: 'updateChart', + value: function updateChart() { + var _this2 = this; + + var dataset = this.state.chartData; + + // Calculate height + this.height = 32 * dataset.length; + d3.select('#report_alertpower').transition().attr('viewBox', '0 0 1000 ' + (this.height + margin.top + margin.bottom)); + + this.dataTypes = d3.keys(dataset[0]).filter(function (key) { + return !['name', 'values', 'total', 'score', 'max'].includes(key); + }); + + // Build color domain from keys except name + this.colors.domain(this.dataTypes); + + dataset.forEach(function (d) { + // Remove number at the end + d.name = d.name.replace(/ \([0-9]+\)/, ''); + + /* // False Data + this.dataTypes.forEach( type => { + d[ type ] = Math.round( Math.random() * 5 ); + } ); + if ( !d.score ) { + d.score = ( Math.random() * 10 ).toPrecision( 2 ); + } + /**/ + if (typeof d.score === 'number') { + d.score = '' + d.score; + } + + // Calculate bar start/end points + var start = 0; + d.values = _this2.dataTypes.map(function (name) { + var curStart = start, + curEnd = start + d[name]; + + start += d[name]; + return { + name: name, + count: d[name], + start: curStart, + end: curEnd + }; + }); + + d.total = d.values[d.values.length - 1].end; + d.max = d3.max(_this2.dataTypes, function (b) { + return d[b]; + }); + }); + + this.stackedMax = d3.max(dataset, function (d) { + return d.total; + }); + this.groupedMax = d3.max(dataset, function (d) { + return d3.max(_this2.dataTypes, function (b) { + return d[b]; + }); + }); + + this.yScale.rangeRound([0, this.height]).domain(dataset.map(function (d) { + return d.name; + })); + + /* + // Animated, but multiline flashes + this.yAxisEl.transition().call( g => { + g.call( this.yAxis ) + setTimeout( () => { + g.selectAll( '.tick text' ).call( wrapText, margin.left - 20 ); + }, 50 ) + } ) + /**/ + /**/ + // Not animated + this.yAxisEl.call(this.yAxis); + this.svg.selectAll('.y.axis .tick text').call(wrapText, margin.left - 20); // Wrap axis labels + /**/ + + var alerts = this.svg.selectAll('.alert').data(dataset, function (d) { + return d.name; + }); + + alerts.exit().transition().attr('height', 0).style('opacity', 0).remove(); + + alerts.enter().append('g').attr('class', 'alert').attr('transform', function (d) { + return 'translate( 1, ' + _this2.yScale(d.name) + ' )'; + }).append('text').attr('dy', '1.2em'); + + alerts.transition().attr('transform', function (d) { + return 'translate( 1, ' + _this2.yScale(d.name) + ' )'; + }); + + var alertTypes = this.svg.selectAll('.alert').selectAll('rect').data(function (d) { + return d.values; + }); + + var bars = alertTypes.enter().append('rect').attr('x', 0).attr('y', 0).attr('width', 0).attr('height', this.yScale.bandwidth()); + bars.merge(alertTypes).style('fill', function (d) { + return _this2.colors(d.name); + }); + + bars.append('title').merge(alertTypes.select('title')).text(function (d) { + return d.name + ': ' + d.count; + }); + + // Legend + var legend = this.LegendHolder.selectAll('.legend').data(this.dataTypes); + + legend.exit().remove(); + + legend = legend.enter().append('g').attr('class', 'legend'); + + // Legend Boxes + legend.append('rect').attr('width', legendHeight).attr('x', 0).attr('y', 0).attr('height', legendHeight).style('fill', function (d) { + return _this2.colors(d); + }); + + // Legend Text + legend.append('text').attr('x', legendHeight + legendTextSpacing).attr('y', legendHeight / 2).attr('dy', '.35em').style('text-anchor', 'start').style('text-transform', 'capitalize').text(function (d) { + return d; + }); + + // Legend Position + var widthSums = 0; + this.LegendHolder.selectAll('.legend').attr('transform', function (d, i) { + var value = widthSums; + widthSums += this.getBBox().width + legendSpacing; + return 'translate( ' + value + ', 0 )'; + }); + var legendWidth = this.LegendHolder.node().getBBox().width; + this.LegendHolder.transition().attr('transform', 'translate( ' + (width / 2 - legendWidth / 2) + ', ' + (this.height + margin.bottom - legendHeight) + ' )'); + + if (this.state.displayMode === 'grouped') { + this.transitionGrouped(); + } else { + this.transitionStacked(); + } + } + }, { + key: 'transitionStacked', + value: function transitionStacked() { + var _this3 = this; + + this.xScale.domain([0, this.stackedMax]).nice(); + this.xAxisEl.transition().call(this.xAxis).attr('transform', 'translate( 0, ' + this.height + ' )'); + + this.svg.selectAll('.alert rect').transition().delay(function (d, i) { + return i * 5; + }).duration(500).attr('width', function (d) { + return _this3.xScale(d.end) - _this3.xScale(d.start); + }).attr('x', function (d) { + return _this3.xScale(d.start); + }).transition().attr('height', this.yScale.bandwidth()).attr('y', 0); + + this.svg.selectAll('.alert text').transition().delay(function (d, i) { + return i * _this3.dataTypes.length * 5 + i; + }).duration(500).attr('transform', function (d) { + return 'translate( ' + (_this3.xScale(d.total) + 10) + ', 0 )'; + }).tween('text', function (d) { + var text = d3.select(this); + var i = d3.interpolateNumber(text.text(), d.score), + prec = d.score.split('.'), + round = prec.length > 1 ? Math.pow(10, prec[0].length) : 1; + + return function (t) { + return text.text(Math.round(i(t) * round) / round); + }; + }); + } + }, { + key: 'transitionGrouped', + value: function transitionGrouped() { + var _this4 = this; + + this.xScale.domain([0, this.groupedMax]).nice(); + this.xAxisEl.transition().call(this.xAxis).attr('transform', 'translate( 0, ' + this.height + ' )'); + + var initialDuration = this.displayModeChanged ? 500 : 0; + + this.svg.selectAll('.alert').selectAll('rect').transition().delay(function (d, i) { + return i * 5; + }).duration(initialDuration).attr('height', this.yScale.bandwidth() / this.dataTypes.length).attr('y', function (d, i) { + return _this4.yScale.bandwidth() / _this4.dataTypes.length * i; + }).transition().duration(500).attr('x', 0).attr('width', function (d) { + return _this4.xScale(d.end) - _this4.xScale(d.start); + }); + + this.svg.selectAll('.alert text').transition().delay(function (d, i) { + return i * 5 + initialDuration; + }).attr('transform', function (d) { + return 'translate( ' + (_this4.xScale(d.max) + 10) + ', 0 )'; + }).tween('text', function (d) { + var text = d3.select(this); + var i = d3.interpolateNumber(text.text(), d.score), + prec = d.score.split('.'), + round = prec.length > 1 ? Math.pow(10, prec[0].length) : 1; + + return function (t) { + return text.text(Math.round(i(t) * round) / round); + }; + }); + + this.displayModeChanged = false; + } + }, { + key: 'loadData', + value: function loadData() { + var _this5 = this; + + if (!this.state.chartResults) { + return; + } + + var url = '/scot/api/v2/metric/alert_power'; + var opts = '?sort=' + this.state.chartSort + '&dir=' + this.state.chartSortDir + '&count=' + this.state.chartResults + '&filter=' + encodeURIComponent(this.state.chartFilter); + + d3.json(url + opts, function (dataset) { + _this5.setState({ + chartData: dataset + }); + }); + } + }, { + key: 'componentDidMount', + value: function componentDidMount() { + this.initChart(); + this.updateChart(); + this.loadData(); + } + }, { + key: 'dataChange', + value: function dataChange(event) { + var target = event.target; + + if (target.name === 'chartResults' && target.value) { + if (target.value > 50) target.value = 50; + if (target.value < 1) target.value = 1; + } + + this.setState(_defineProperty({}, target.name, target.value), this.loadData); + } + }, { + key: 'displayModeChange', + value: function displayModeChange(event) { + this.displayModeChanged = true; + this.setState({ + displayMode: event.target.value + }); + } + }, { + key: 'preventSubmit', + value: function preventSubmit(event) { + event.preventDefault(); + event.stopPropagation(); + } + }, { + key: 'exportToPNG', + value: function exportToPNG() { + var svgString = new XMLSerializer().serializeToString(document.querySelector('#report_alertpower')); + + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + var DOMURL = self.URL || self.webkitURL || self; + var img = new Image(); + var svg = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' }); + var url = DOMURL.createObjectURL(svg); + img.onload = function () { + ctx.drawImage(img, 0, 0); + var png = canvas.toDataURL('image/png'); + document.querySelector('#png-container').innerHTML = ''; + DOMURL.revokeObjectURL(png); + var a = $('').attr('href', png).attr('download', 'img.png').appendTo('body'); + + a[0].click(); + + a.remove(); + }; + img.src = url; + } + }, { + key: 'render', + value: function render() { + if (this.chartInit) { + this.updateChart(); + } + + return _react2.default.createElement( + 'div', + { className: 'dashboard' }, + _react2.default.createElement( + 'h1', + null, + 'Alert Power' + ), + _react2.default.createElement( + 'form', + { onSubmit: this.preventSubmit }, + _react2.default.createElement( + 'label', + null, + 'Filter =\xA0', + _react2.default.createElement('input', { + className: 'report_input', + type: 'text', + style: { background: 'initial', border: '1px solid #ccc' }, + name: 'chartFilter', + value: this.state.chartFilter, + onChange: this.dataChange, + placeholder: 'All' + }) + ) + ), + _react2.default.createElement( + 'form', + { onSubmit: this.preventSubmit }, + _react2.default.createElement( + 'label', + null, + 'Sort by =\xA0', + _react2.default.createElement( + 'select', + { + name: 'chartSort', + value: this.state.chartSort, + onChange: this.dataChange + }, + _react2.default.createElement( + 'option', + { value: 'power' }, + 'Power Score' + ), + _react2.default.createElement( + 'option', + { value: 'count' }, + 'Alert Count' + ), + _react2.default.createElement( + 'option', + { value: 'promoted' }, + 'Promoted Count' + ), + _react2.default.createElement( + 'option', + { value: 'incident' }, + 'Incident Count' + ) + ), + _react2.default.createElement( + 'select', + { + name: 'chartSortDir', + value: this.state.chartSortDir, + onChange: this.dataChange + }, + _react2.default.createElement( + 'option', + { value: 'desc' }, + 'Desc' + ), + _react2.default.createElement( + 'option', + { value: 'asc' }, + 'Asc' + ) + ) + ), + _react2.default.createElement( + 'label', + null, + 'Results =\xA0', + _react2.default.createElement('input', { + className: 'report_input', + type: 'number', + min: 1, + max: 50, + name: 'chartResults', + value: this.state.chartResults, + onChange: this.dataChange + }) + ) + ), + _react2.default.createElement( + 'form', + null, + _react2.default.createElement( + 'label', + null, + _react2.default.createElement('input', { + className: 'report_input', + type: 'radio', + name: 'mode', + value: 'grouped', + checked: this.state.displayMode === 'grouped', + onChange: this.displayModeChange + }), + ' Grouped' + ), + '\xA0', + _react2.default.createElement( + 'label', + null, + _react2.default.createElement('input', { + className: 'report_input', + type: 'radio', + name: 'mode', + value: 'stacked', + checked: this.state.displayMode === 'stacked', + onChange: this.displayModeChange + }), + ' Stacked' + ), + _react2.default.createElement( + _reactBootstrap.Button, + { id: 'export', bsSize: 'xsmall', bsStyle: 'default', onClick: this.exportToPNG }, + 'Export to PNG' + ) + ), + _react2.default.createElement( + 'div', + { id: 'chart' }, + _react2.default.createElement('svg', { id: 'report_alertpower', viewBox: '0 0 1000 100' }) + ), + _react2.default.createElement('div', { id: 'png-container', hidden: true }) + ); + } + }]); + + return ReportAlertpower; +}(_react.PureComponent); + +exports.default = ReportAlertpower; + +},{"../../utils/debounce":87,"react":983,"react-bootstrap":608}],14:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactDaterangePicker = require('react-daterange-picker'); + +var _reactDaterangePicker2 = _interopRequireDefault(_reactDaterangePicker); + +var _debounce = require('../../utils/debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var formatTickTime = function formatTickTime(domain) { + var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + var start = domain[0], + end = domain[domain.length - 1], + step = d3.tickStep(start, end, count); + + return function (d) { + var daySeconds = 3600 * 24; + var days = Math.floor(d / daySeconds), + hours = Math.floor(d % daySeconds / 3600), + minutes = Math.floor(d % 3600 / 60), + seconds = Math.floor(d % 60); + + if (days) { + if (step < daySeconds) { + return days + 'd ' + hours + 'h'; + } + return days + 'd'; + } + if (hours) { + if (step < 3600) { + return hours + 'h ' + minutes + 'm'; + } + return hours + 'h'; + } + if (minutes) { + if (step < 60) { + return minutes + 'm ' + seconds + 's'; + } + return minutes + 'm'; + } + return seconds + 's'; + }; +}; + +var formatTime = function formatTime(d) { + var daySeconds = 3600 * 24; + var days = Math.floor(d / daySeconds), + hours = Math.floor(d % daySeconds / 3600), + minutes = Math.floor(d % 3600 / 60), + seconds = Math.floor(d % 60); + + var output = seconds + 's'; + if (minutes) { + output = minutes + 'm ' + output; + } + if (hours) { + output = hours + 'h ' + output; + } + if (days) { + output = days + 'd ' + output; + } + return output; +}; + +var margin = { top: 20, right: 20, bottom: 60, left: 50 }, + width = 1000 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom, + barColors = { + 'All': '#3b35a6', + 'Promoted': '#eebd31', + 'Incident': '#e63041' +}; + +var ReportArt = function (_PureComponent) { + _inherits(ReportArt, _PureComponent); + + function ReportArt(props) { + _classCallCheck(this, ReportArt); + + var _this = _possibleConstructorReturn(this, (ReportArt.__proto__ || Object.getPrototypeOf(ReportArt)).call(this, props)); + + var today = new Date().toISOString().slice(0, 10); + _this.state = { + length: 7, + date: today, + unit: 'day', + chartData: { + dates: [], + lines: [] + } + + // Load Art is auto debounced + };_this.loadArt = (0, _debounce2.default)(_this.loadArt); + + _this.unitChange = _this.unitChange.bind(_this); + _this.lengthChange = _this.lengthChange.bind(_this); + _this.dateChange = _this.dateChange.bind(_this); + return _this; + } + + _createClass(ReportArt, [{ + key: 'componentDidMount', + value: function componentDidMount() { + this.initChart(); + this.loadArt(); + } + }, { + key: 'componentDidUpdate', + value: function componentDidUpdate() {} + }, { + key: 'initChart', + value: function initChart() { + this.svg = d3.select('#report_art').append('g').attr('transform', 'translate( ' + margin.left + ',' + margin.top + ' )'); + + this.xAxisEl = this.svg.append('g').attr('class', 'x axis').attr('transform', 'translate( 0, ' + height + ' )'); + + this.yAxisEl = this.svg.append('g').attr('class', 'y axis'); + + this.yAxisEl.append('text').attr('transform', 'rotate(-90)').attr('x', 0 - height / 2).attr('y', 0).attr('dy', '1em').style('text-anchor', 'start').style('fill', 'black').text('Response Time'); + + this.chartInit = true; + } + }, { + key: 'updateChart', + value: function updateChart() { + // Bar names + var barNames = new Set(); + this.state.chartData.dates.forEach(function (d) { + d.values.forEach(function (b) { + barNames.add(b.name); + }); + }); + + // Line names + var lineNames = new Set(); + this.state.chartData.lines.forEach(function (d) { + lineNames.add(d.name); + }); + + // Scales + var maxValue = d3.max(this.state.chartData.dates, function (d) { + return d3.max(d.values, function (b) { + return b.value; + }); + }); + + var dateScale = d3.scaleBand().padding(0.1).rangeRound([0, width]).domain(this.state.chartData.dates.map(function (d) { + return d.date; + })); + var barScale = d3.scaleBand().domain(Array.from(barNames)).rangeRound([0, dateScale.bandwidth()]); + var yScale = d3.scaleLinear().clamp(true).range([height, 0]).domain([0, maxValue]).nice(); + + // Axes + var xAxis = d3.axisBottom().scale(dateScale); + + var yAxis = d3.axisLeft().scale(yScale).ticks(20).tickFormat(formatTickTime(yScale.domain(), 20)); + + this.xAxisEl.transition().call(xAxis); + this.yAxisEl.transition().call(yAxis); + + // Bars + var dates = this.svg.selectAll('.date').data(this.state.chartData.dates, function (d) { + return d.date; + }); + + dates.exit().transition().style('opacity', 0).attr('height', 0).attr('y', height).remove(); + + var bars = dates.enter().append('g').attr('class', 'date').attr('transform', function (d) { + return 'translate( ' + dateScale(d.date) + ', 0 )'; + }).selectAll('.bar').data(function (d) { + return d.values; + }).enter().append('rect').attr('class', 'bar').style('fill', function (d) { + return barColors[d.name]; + }).attr('width', barScale.bandwidth()).attr('x', function (d) { + return barScale(d.name); + }).attr('y', height).attr('height', 0); + + bars.append('title').text(function (d) { + return formatTime(d.value); + }); + + dates.transition().attr('transform', function (d) { + return 'translate( ' + dateScale(d.date) + ', 0 )'; + }); + + this.svg.selectAll('.date').selectAll('.bar').transition().attr('width', barScale.bandwidth()).attr('x', function (d) { + return barScale(d.name); + }).attr('y', function (d) { + return yScale(d.value); + }).attr('height', function (d) { + return height - yScale(d.value); + }); + + // Avg Box + this.svg.select('.avg-holder').remove(); + this.svg.select('.avg-holder-border').remove(); + var AvgHolder = this.svg.append('g').attr('class', 'avg-holder'); + + var averages = AvgHolder.selectAll('.avg').data(this.state.chartData.lines).enter().append('text').attr('class', 'avg').attr('transform', function (d, i) { + return 'translate( 0, ' + i * 15 + ' )'; + }); + + averages.append('tspan').attr('x', 0).attr('font-weight', 'bold').text(function (d) { + return d.name + ':'; + }); + + averages.append('tspan').attr('x', 100).text(function (d) { + return formatTime(d.value); + }); + + var AvgHolderBox = AvgHolder.node().getBBox(); + AvgHolder.attr('transform', 'translate( ' + (width - AvgHolderBox.width) + ', 0 )'); + + var borderOffset = 2; + var border = this.svg.append('rect').attr('fill', 'none').attr('stroke', 'black').attr('class', 'avg-holder-border').attr('x', AvgHolderBox.x - borderOffset).attr('y', AvgHolderBox.y - borderOffset).attr('width', AvgHolderBox.width + borderOffset * 2).attr('height', AvgHolderBox.height + borderOffset * 2); + border.node().transform.baseVal.initialize(AvgHolder.node().transform.baseVal.getItem(0)); + + // Legend + var legendHeight = 20, + legendSpacing = 15, + legendTextSpacing = 5; + this.svg.select('.legend-holder').remove(); + var LegendHolder = this.svg.append('g').attr('class', 'legend-holder'); + var legend = LegendHolder.selectAll('.legend').data(Array.from(barNames)).enter().append('g').attr('class', 'legend'); + + // Legend Boxes + legend.append('rect').attr('width', legendHeight).attr('x', 0).attr('y', 0).attr('height', legendHeight).style('fill', function (d) { + return barColors[d]; + }); + + // Legend Text + legend.append('text').attr('x', legendHeight + legendTextSpacing).attr('y', legendHeight / 2).attr('dy', '.35em').style('text-anchor', 'start').text(function (d) { + return d; + }); + + // Legend Position + var widthSums = 0; + LegendHolder.selectAll('.legend').attr('transform', function (d, i) { + var value = widthSums; + widthSums += this.getBBox().width + legendSpacing; + return 'translate( ' + value + ', 0 )'; + }); + var legendWidth = LegendHolder.node().getBBox().width; + LegendHolder.attr('transform', 'translate( ' + (width / 2 - legendWidth / 2) + ', ' + (height + margin.bottom / 2) + ' )'); + } + }, { + key: 'loadArt', + value: function loadArt() { + var _this2 = this; + + if (!this.state.date || !this.state.length) { + return; + } + + var url = '/scot/api/v2/metric/response_avg_last_x_days'; + var opts = '?days=' + this.state.length + '&targetdate=' + this.state.date + '&unit=' + this.state.unit; + d3.json(url + opts, function (data) { + _this2.setState({ + chartData: data + }); + }); + } + }, { + key: 'unitChange', + value: function unitChange(event) { + var _this3 = this; + + this.setState({ unit: event.target.value }, function () { + return _this3.loadArt(); + }); + } + }, { + key: 'lengthChange', + value: function lengthChange(event) { + var _this4 = this; + + this.setState({ length: event.target.value }, function () { + return _this4.loadArt(); + }); + } + }, { + key: 'dateChange', + value: function dateChange(event) { + var _this5 = this; + + this.setState({ date: event.target.value }, function () { + return _this5.loadArt(); + }); + } + }, { + key: 'exportToPNG', + value: function exportToPNG() { + var svgString = new XMLSerializer().serializeToString(document.querySelector('#report_art')); + + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext("2d"); + var DOMURL = self.URL || self.webkitURL || self; + var img = new Image(); + var svg = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" }); + var url = DOMURL.createObjectURL(svg); + img.onload = function () { + ctx.drawImage(img, 0, 0); + var png = canvas.toDataURL("image/png"); + document.querySelector('#png-container').innerHTML = ''; + DOMURL.revokeObjectURL(png); + var a = $("").attr("href", png).attr("download", "img.png").appendTo("body"); + + a[0].click(); + + a.remove(); + }; + img.src = url; + } + }, { + key: 'render', + value: function render() { + if (this.chartInit) { + this.updateChart(); + } + + return _react2.default.createElement( + 'div', + { className: 'dashboard' }, + _react2.default.createElement( + 'h1', + null, + 'Alert Response Time' + ), + _react2.default.createElement( + 'label', + { htmlFor: 'date', style: { display: "inline-block", textAlign: "right" } }, + 'Initial Date =\xA0', + _react2.default.createElement('input', { + className: 'report_input', + type: 'date', + value: this.state.date, + onChange: this.dateChange, + placeholder: 'yyyy-mm-dd', + pattern: '[0-9]{4}-[0-9]{2}-[0-9]{2}' + }) + ), + _react2.default.createElement( + 'label', + { htmlFor: 'length', style: { display: "inline-block", textAlign: "right" } }, + 'Length =\xA0', + _react2.default.createElement('input', { className: 'report_name', type: 'number', min: '1', step: '1', value: this.state.length, id: 'length', onChange: this.lengthChange }) + ), + _react2.default.createElement( + 'label', + { htmlFor: 'unit', style: { display: "inline-block", width: "240px", textAlign: "right" } }, + 'Unit =\xA0', + _react2.default.createElement( + 'select', + { id: 'unit', value: this.state.unit, onChange: this.unitChange, disabled: true }, + _react2.default.createElement( + 'option', + { value: 'hour' }, + 'hourly' + ), + _react2.default.createElement( + 'option', + { value: 'day' }, + 'daily' + ), + _react2.default.createElement( + 'option', + { value: 'month' }, + 'monthly' + ), + _react2.default.createElement( + 'option', + { value: 'year' }, + 'yearly' + ) + ) + ), + _react2.default.createElement( + _reactBootstrap.Button, + { id: 'export', bsSize: 'xsmall', bsStyle: 'default', onClick: this.exportToPNG }, + 'Export to PNG' + ), + _react2.default.createElement( + 'div', + { id: 'chart' }, + _react2.default.createElement('svg', { id: 'report_art', viewBox: '0 0 1000 500' }) + ), + _react2.default.createElement('div', { id: 'png-container', hidden: true }) + ); + } + }]); + + return ReportArt; +}(_react.PureComponent); + +exports.default = ReportArt; + +},{"../../utils/debounce":87,"react":983,"react-bootstrap":608,"react-daterange-picker":619}],15:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +var _debounce = require('../../utils/debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var margin = { + top: 5, left: 40, right: 20, bottom: 60 +}, + width = 1000 - margin.left - margin.right, + height = 600 - margin.top - margin.bottom, + timeWindow = 7 * 24 * 3600 * 1000, + legendHeight = 20, + legendSpacing = 15, + legendTextSpacing = 5; + +var ReportCreated = function (_Component) { + _inherits(ReportCreated, _Component); + + function ReportCreated(props) { + _classCallCheck(this, ReportCreated); + + var _this = _possibleConstructorReturn(this, (ReportCreated.__proto__ || Object.getPrototypeOf(ReportCreated)).call(this, props)); + + _this.state = { + chartData: [] + + // LoadData is automatically debounced + };_this.loadData = (0, _debounce2.default)(_this.loadData); + + // this.dataChange = this.dataChange.bind( this ); + // this.displayModeChange = this.displayModeChange.bind( this ); + return _this; + } + + _createClass(ReportCreated, [{ + key: 'initChart', + value: function initChart() { + var _this2 = this; + + var now = new Date(); + + this.xScale = d3.scaleTime().rangeRound([0, width]).domain([now - timeWindow, now]); + this.yScale = d3.scaleLinear().rangeRound([height, 0]).domain([0, 0]); + + this.xAxis = d3.axisBottom().scale(this.xScale); + + this.yAxis = d3.axisLeft().scale(this.yScale); + + this.svg = d3.select('#report_created').attr('viewBox', '0 0 1000 ' + (height + margin.top + margin.bottom)).append('g').attr('transform', 'translate( ' + margin.left + ', ' + margin.top + ' )'); + + var clip = this.svg.append('defs').append('clipPath').attr('id', 'bounds').append('rect').attr('id', 'clip-rect').attr('x', 1).attr('y', 0).attr('width', width).attr('height', height); + + this.yAxisEl = this.svg.append('g').attr('class', 'y axis'); + + this.yAxisEl.call(this.yAxis); + + this.xAxisEl = this.svg.append('g').attr('class', 'x axis').attr('transform', 'translate( 0, ' + height + ' )'); + + this.xAxisEl.append('text').attr('text-anchor', 'middle').attr('x', width / 2).attr('y', margin.bottom - 10).style('font-size', '10px').style('fill', 'black').text('Toggle Trendlines'); + + this.xAxisEl.call(this.xAxis); + + this.statusLine = d3.line().curve(d3.curveBasis).x(function (d) { + return _this2.xScale(d.time); + }).y(function (d) { + return _this2.yScale(d.value); + }); + + this.lineHolder = this.svg.append('g').attr('class', 'lines').attr('clip-path', 'url(#bounds)'); + + // Legend + this.LegendHolder = this.svg.append('g').attr('class', 'legend-holder').style('font-family', 'sans-serif'); + + this.chartInit = true; + } + }, { + key: 'updateChart', + value: function updateChart() { + var _this3 = this; + + this.yScale.domain([0, Math.max(d3.max(this.state.chartData, function (d) { + if (!d.shown || !d.data.length) return 0; + + return d3.max(d.data, function (b) { + return b.value; + }); + }), 10)]).nice(); + + this.colors = d3.scaleOrdinal(d3.schemeCategory10).domain(this.state.chartData.map(function (line) { + return line.name; + })); + + var lines = this.lineHolder.selectAll('.line').data(this.state.chartData, function (d) { + return d.name; + }); + + lines.exit().transition().style('opacity', 0).remove(); + + lines.enter().append('path').attr('class', function (d) { + return 'line ' + d.name; + }).style('stroke', function (d) { + return _this3.colors(d.name); + }).style('stroke-width', 2).style('fill', 'none').attr('d', function (d) { + return _this3.statusLine(d.data); + }); + + this.LegendHolder.selectAll('.legend').remove(); + + var legend = this.LegendHolder.selectAll('.legend').data(this.state.chartData, function (d) { + return d.name; + }); + + legend = legend.enter().append('g').attr('class', 'legend').style('cursor', 'pointer').on('click', function (d) { + var newData = _this3.state.chartData.map(function (row) { + if (row.name === d.name) { + row.shown = !d.shown; + } + return row; + }); + _this3.setState({ + chartData: newData + }); + }); + + // Legend Boxes + legend.append('rect').attr('width', legendHeight).attr('x', 0).attr('y', (legendHeight - 5) / 2).attr('height', 5).style('fill', function (d) { + return d.shown ? _this3.colors(d.name) : 'transparent'; + }).style('stroke', function (d) { + return _this3.colors(d.name); + }).style('stroke-width', 1); + + // Legend Text + legend.append('text').attr('x', legendHeight + legendTextSpacing).attr('y', legendHeight / 2).attr('dy', '.35em').style('text-anchor', 'start').style('text-transform', 'capitalize').text(function (d) { + return d.name; + }).append('title').text(function (d) { + return 'Toggle ' + d.name + ' line'; + }); + + // Legend Position + var widthSums = 0; + this.LegendHolder.selectAll('.legend').attr('transform', function (d, i) { + var value = widthSums; + widthSums += this.getBBox().width + legendSpacing; + return 'translate( ' + value + ', 0 )'; + }); + var legendWidth = this.LegendHolder.node().getBBox().width; + this.LegendHolder.attr('transform', 'translate( ' + (width / 2 - legendWidth / 2) + ', ' + (height + margin.bottom - legendHeight * 2) + ' )'); + + // Animate changes + this.yAxisEl.transition().call(this.yAxis); + + lines.transition().attr('d', function (d) { + return _this3.statusLine(d.data); + }).style('stroke', function (d) { + return d.shown ? _this3.colors(d.name) : 'transparent'; + }); + } + }, { + key: 'loadData', + value: function loadData() { + var _this4 = this; + + var url = '/scot/api/v2/metric/creation_bullet'; + var opts = '?range=7'; + + d3.json(url + opts, function (dataset) { + try { + // Add line visibility to data + dataset = dataset.map(function (line) { + line.shown = _this4.state.chartData.reduce(function (shown, d) { + return shown && (d.name === line.name ? d.shown : true); + }, true); + + return line; + }); + + _this4.setState({ + chartData: dataset + }); + } catch (e) { + console.log("Malformed data"); + console.log(dataset); + console.log("Replacing with random data"); + + dataset = _this4.genData(); + + // Add line visibility to data + dataset = dataset.map(function (line) { + line.shown = _this4.state.chartData.reduce(function (shown, d) { + return shown && (d.name === line.name ? d.shown : true); + }, true); + + return line; + }); + + _this4.setState({ + chartData: dataset + }); + } + }); + } + }, { + key: 'genData', + value: function genData() { + var dataTypes = ['alerts', 'alertgroups', 'events', 'incidents', 'entries', 'intel']; + var dataMaxes = { + alerts: 5000, + alertgroups: 500, + entries: 100, + events: 15, + intel: 5, + incidents: 5 + }; + + var now = new Date(), + date = new Date(Date.now() - timeWindow); + var lineData = []; + dataTypes.forEach(function (d) { + lineData.push({ + name: d, + data: [] + }); + }); + for (; date <= now; date = new Date(date.getTime() + 6 * 3600 * 1000)) { + lineData.forEach(function (line) { + line.data.push({ + time: date, + value: Math.random() * dataMaxes[line.name] + }); + }); + } + + return lineData; + } + }, { + key: 'componentDidMount', + value: function componentDidMount() { + this.initChart(); + this.loadData(); + } + }, { + key: 'dataChange', + value: function dataChange(event) { + var target = event.target; + + if (target.name === 'chartResults' && target.value) { + if (target.value > 50) target.value = 50; + if (target.value < 1) target.value = 1; + } + + this.setState(_defineProperty({}, target.name, target.value), this.loadData); + } + }, { + key: 'exportToPNG', + value: function exportToPNG() { + var svgString = new XMLSerializer().serializeToString(document.querySelector('#report_created')); + + var canvas = document.createElement('canvas'); + var ctx = canvas.getContext('2d'); + var DOMURL = self.URL || self.webkitURL || self; + var img = new Image(); + var svg = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' }); + var url = DOMURL.createObjectURL(svg); + img.onload = function () { + ctx.drawImage(img, 0, 0); + var png = canvas.toDataURL('image/png'); + document.querySelector('#png-container').innerHTML = ''; + DOMURL.revokeObjectURL(png); + var a = $('').attr('href', png).attr('download', 'img.png').appendTo('body'); + + a[0].click(); + + a.remove(); + }; + img.src = url; + } + }, { + key: 'render', + value: function render() { + if (this.chartInit) { + this.updateChart(); + } + + return _react2.default.createElement( + 'div', + { className: 'dashboard' }, + _react2.default.createElement( + 'h1', + null, + 'Items Created' + ), + _react2.default.createElement( + 'form', + null, + _react2.default.createElement( + _reactBootstrap.Button, + { id: 'export', bsSize: 'xsmall', bsStyle: 'default', onClick: this.exportToPNG }, + 'Export to PNG' + ) + ), + _react2.default.createElement( + 'div', + { id: 'chart' }, + _react2.default.createElement('svg', { id: 'report_created', viewBox: '0 0 1000 600' }) + ), + _react2.default.createElement('div', { id: 'png-container', hidden: true }) + ); + } + }]); + + return ReportCreated; +}(_react.Component); + +exports.default = ReportCreated; + +},{"../../utils/debounce":87,"react":983,"react-bootstrap":608}],16:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var ReportHeatmap = function (_PureComponent) { + _inherits(ReportHeatmap, _PureComponent); + + function ReportHeatmap(props) { + _classCallCheck(this, ReportHeatmap); + + var _this = _possibleConstructorReturn(this, (ReportHeatmap.__proto__ || Object.getPrototypeOf(ReportHeatmap)).call(this, props)); + + _this.state = { + collection: 'event', + type: 'created', + year: '2017' + }; + + _this.collectionChange = _this.collectionChange.bind(_this); + _this.yearChange = _this.yearChange.bind(_this); + return _this; + } + + _createClass(ReportHeatmap, [{ + key: 'componentDidMount', + value: function componentDidMount() { + this.loadHeatMap(); + } + }, { + key: 'componentDidUpdate', + value: function componentDidUpdate() { + this.loadHeatMap(); + } + }, { + key: 'loadHeatMap', + value: function loadHeatMap() { + var margin = { + top: 30, + bottom: 30, + left: 30, + right: 0 + }, + width = 1000 - (margin.left - margin.right), + height = 300 - (margin.top - margin.bottom), + gridSize = Math.floor(width / 24), + legendElementWidth = gridSize * 1.5, + buckets = 9, + colors = ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'], + days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'], + times = ['1a', '2a', '3a', '4a', '5a', '6a', '7a', '8a', '9a', '10a', '11a', '12a', '1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p', '10p', '11p', '12p']; + + var container = d3.select('#report_heatmap'); + var graph = container.select('g'); + if (graph.empty()) { + graph = container.append('g').attr('transform', 'translate( ' + margin.left + ', ' + margin.top + ' )'); + } + + // Day Labels + graph.selectAll('.dayLabel').data(days).enter().append('text').text(function (d) { + return d; + }).attr('x', 0).attr('y', function (d, i) { + return i * gridSize; + }).style('text-anchor', 'end').attr('transform', 'translate( -6, ' + gridSize / 1.5 + ' )').attr('class', function (d, i) { + return i >= 0 && i <= 4 ? 'dayLabel axis axis-worktime' : 'dayLabel axis'; + }); + + // Time Labels + graph.selectAll('.timeLabel').data(times).enter().append('text').text(function (d) { + return d; + }).attr('x', function (d, i) { + return i * gridSize; + }).attr('y', 0).style('text-anchor', 'middle').attr('transform', 'translate( ' + gridSize / 2 + ', -6 )').attr('class', function (d, i) { + return i >= 7 && i <= 16 ? 'timeLabel axis axis-worktime' : 'timeLabel axis'; + }); + + var url = '/scot/api/v2/graph/dhheatmap?collection=' + this.state.collection + '&type=' + this.state.type + '&year=' + this.state.year; + d3.json(url, function (error, data) { + /* + container.selectAll( '.hour' ).remove(); + */ + container.selectAll('.legend').remove(); + container.selectAll('.legend-text').remove(); + + var colorScale = d3.scaleQuantile().domain([0, buckets - 1, d3.max(data, function (d) { + return d.value; + })]).range(colors); + + // Cards + var cards = graph.selectAll('.hour').data(data, function (d) { + return d.day + ':' + d.hour; + }); + cards.append('title'); + cards.enter().append('rect').style('fill', colors[0]).merge(cards).attr('x', function (d) { + return (d.hour - 1) * gridSize; + }).attr('y', function (d) { + return (d.day - 1) * gridSize; + }).attr('rx', 4).attr('ry', 4).attr('class', 'hour').attr('width', gridSize).attr('height', gridSize).transition().duration(1000).style('fill', function (d) { + return colorScale(d.value); + }); + cards.select('title').text(function (d) { + return d.value; + }); + cards.exit().remove(); + + // Legend + var legend = graph.selectAll('.legend').data([0].concat(colorScale.quantiles()), function (d) { + return d; + }); + + legend.enter().append('rect').attr('class', 'legend').attr('x', function (d, i) { + return legendElementWidth * i; + }).attr('y', height).attr('width', legendElementWidth).attr('height', gridSize / 2).style('fill', function (d, i) { + return colors[i]; + }); + + legend.enter().append('text').text(function (d) { + return '≥ ' + Math.round(d); + }).attr('class', 'legend-text').attr('x', function (d, i) { + return legendElementWidth * i; + }).attr('y', height + gridSize); + }); + } + }, { + key: 'collectionChange', + value: function collectionChange(event) { + this.setState({ collection: event.target.value }); + } + }, { + key: 'yearChange', + value: function yearChange(event) { + this.setState({ year: event.target.value }); + } + }, { + key: 'exportToPNG', + value: function exportToPNG() { + var svgString = new XMLSerializer().serializeToString(document.querySelector('#report_heatmap')); + + var canvas = document.createElement("canvas"); + var ctx = canvas.getContext("2d"); + var DOMURL = self.URL || self.webkitURL || self; + var img = new Image(); + var svg = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" }); + var url = DOMURL.createObjectURL(svg); + img.onload = function () { + ctx.drawImage(img, 0, 0); + var png = canvas.toDataURL("image/png"); + document.querySelector('#png-container').innerHTML = ''; + DOMURL.revokeObjectURL(png); + var a = $("").attr("href", png).attr("download", "img.png").appendTo("body"); + + a[0].click(); + + a.remove(); + }; + img.src = url; + } + }, { + key: 'render', + value: function render() { + return _react2.default.createElement( + 'div', + { className: 'dashboard' }, + _react2.default.createElement( + 'h1', + null, + 'Day of Week, Hour of Day Heatmap' + ), + _react2.default.createElement( + 'label', + { htmlFor: 'year', style: { display: "inline-block", width: "240px", textAlign: "right" } }, + 'Year = ', + _react2.default.createElement('span', { id: 'year-value' }), + _react2.default.createElement('input', { className: 'report_input', type: 'number', min: '2013', step: '1', value: this.state.year, id: 'year', onChange: this.yearChange }) + ), + _react2.default.createElement( + 'label', + { htmlFor: 'collection', style: { display: "inline-block", width: "240px", textAlign: "right" } }, + 'Collection = ', + _react2.default.createElement('span', { id: 'year-value' }), + _react2.default.createElement( + 'select', + { id: 'collection', value: this.state.collection, onChange: this.collectionChange }, + _react2.default.createElement( + 'option', + { value: 'event' }, + 'event' + ), + _react2.default.createElement( + 'option', + { value: 'alert' }, + 'alert' + ), + _react2.default.createElement( + 'option', + { value: 'incident' }, + 'incident' + ) + ) + ), + _react2.default.createElement( + _reactBootstrap.Button, + { id: 'export', bsSize: 'xsmall', bsStyle: 'default', onClick: this.exportToPNG }, + 'Export to PNG' + ), + _react2.default.createElement( + 'div', + { id: 'chart' }, + _react2.default.createElement('svg', { id: 'report_heatmap', viewBox: '0 0 1000 380' }) + ), + _react2.default.createElement('div', { id: 'png-container', hidden: true }) + ); + } + }]); + + return ReportHeatmap; +}(_react.PureComponent); + +exports.default = ReportHeatmap; + +},{"react":983,"react-bootstrap":608}],17:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Panel = require('react-bootstrap/lib/Panel.js'); +var Badge = require('react-bootstrap/lib/Badge.js'); + +var Status = React.createClass({ + displayName: 'Status', + + getInitialState: function getInitialState() { + return { + StatusData: null + }; + }, + componentDidMount: function componentDidMount() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/status', + success: function (response) { + this.setState({ StatusData: response }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get status', data); + }.bind(this) + }); + }, + render: function render() { + var StatusRows = []; + if (this.state.StatusData != null) { + for (var key in this.state.StatusData) { + var className = 'dashboardStatusDetail'; + if (this.state.StatusData[key] == 'Not Running') { + className = 'dashboardStatusDetailNotRunning'; + } else if (this.state.StatusData[key] == 'Running') { + className = 'dashboardStatusDetailRunning'; + } + StatusRows.push(React.createElement( + Panel, + { header: key }, + React.createElement( + 'div', + { className: 'dashboardStatusChild' }, + React.createElement( + 'div', + { className: className }, + this.state.StatusData[key] + ) + ) + )); + } + } else { + StatusRows.push(React.createElement( + Panel, + { header: 'SCOT 3.5 Status' }, + React.createElement('br', null), + React.createElement( + 'div', + { style: { fontWeight: 'bold' } }, + 'Coming Soon' + ), + React.createElement('br', null) + )); + } + return React.createElement( + 'div', + { id: 'status', className: 'dashboardStatusParent' }, + React.createElement( + 'div', + null, + React.createElement( + 'h2', + null, + 'Status' + ) + ), + React.createElement( + 'div', + null, + StatusRows + ) + ); + } +}); + +module.exports = Status; + +},{"react":983,"react-bootstrap/lib/Badge.js":524,"react-bootstrap/lib/Panel.js":589}],18:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var ButtonToolbar = require('react-bootstrap/lib/ButtonToolbar'); +var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger'); +var MenuItem = require('react-bootstrap/lib/MenuItem'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton'); +var Popover = require('react-bootstrap/lib/Popover'); +var Link = require('react-router-dom').Link; + +var DetailDataStatus = React.createClass({ + displayName: 'DetailDataStatus', + + getInitialState: function getInitialState() { + return { + key: this.props.id + }; + }, + componentDidMount: function componentDidMount() { + //Adds open/close hot keys for alertgroup + if (this.props.type == 'alertgroup') { + $('#list-view').keydown(function (event) { + //prevent from working when in input + if ($('input').is(':focus')) { + return; + }; + //check for character "o" for 79 or "c" for 67 + if (this.props.status != 'promoted') { + if (event.keyCode == 79 && event.ctrlKey != true && event.metaKey != true) { + this.statusAjax('open'); + } else if (event.keyCode == 67 && event.ctrlKey != true && event.metaKey != true) { + this.statusAjax('closed'); + } + } + }.bind(this)); + } + }, + componentWillUnmount: function componentWillUnmount() { + $('#list-view').unbind('keydown'); + }, + /*eventStatusToggle: function () { + if (this.props.status == 'open') { + this.statusAjax('closed'); + } else if (this.props.status == 'closed') { + this.statusAjax('open'); + } + },*/ + trackAll: function trackAll() { + this.statusAjax('tracked'); + }, + untrackAll: function untrackAll() { + this.statusAjax('untracked'); + }, + closeAll: function closeAll() { + this.statusAjax('closed'); + }, + openAll: function openAll() { + this.statusAjax('open'); + }, + enableAll: function enableAll() { + this.statusAjax('enabled'); + }, + disableAll: function disableAll() { + this.statusAjax('disabled'); + }, + statusAjax: function statusAjax(newStatus) { + console.log(newStatus); + var json = { 'status': newStatus }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success status change to: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to change status', data); + }.bind(this) + }); + }, + render: function render() { + var buttonStyle = ''; + var open = ''; + var closed = ''; + var promoted = ''; + var title = ''; + var classStatus = ''; + var href; + if (this.props.status == 'open' || this.props.status == 'disabled' || this.props.status == 'untracked') { + buttonStyle = 'danger'; + classStatus = 'alertgroup_open'; + } else if (this.props.status == 'closed' || this.props.status == 'enabled' || this.props.status == 'tracked') { + buttonStyle = 'success'; + classStatus = 'alertgroup_closed'; + } else if (this.props.status == 'promoted') { + buttonStyle = 'default'; + classStatus = 'alertgroup_promoted'; + }; + + if (this.props.type == 'alertgroup') { + open = this.props.data.open_count; + closed = this.props.data.closed_count; + promoted = this.props.data.promoted_count; + title = open + ' / ' + closed + ' / ' + promoted; + } + + if (this.props.type == 'event') { + href = '/incident/' + this.props.data.promotion_id; + } else if (this.props.type == 'intel') { + href = '/event/' + this.props.data.promotion_id; + } + + if (this.props.type == 'guide' || this.props.type == 'intel') { + return React.createElement('div', null); + } else if (this.props.type == 'alertgroup') { + return React.createElement( + ButtonToolbar, + null, + React.createElement( + OverlayTrigger, + { placement: 'top', overlay: React.createElement( + Popover, + { id: this.props.id }, + 'open/closed/promoted alerts' + ) }, + React.createElement( + DropdownButton, + { bsSize: 'xsmall', bsStyle: buttonStyle, title: title, id: 'dropdown', className: classStatus }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.openAll, bsSize: 'xsmall' }, + React.createElement( + 'b', + null, + 'Open' + ), + ' All Alerts' + ), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.closeAll }, + React.createElement( + 'b', + null, + 'Close' + ), + ' All Alerts' + ) + ) + ) + ); + } else if (this.props.type == 'incident') { + return React.createElement( + DropdownButton, + { bsSize: 'xsmall', bsStyle: buttonStyle, id: 'event_status', className: classStatus, style: { fontSize: '14px' }, title: this.props.status }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.openAll }, + 'Open Incident' + ), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.closeAll }, + 'Close Incident' + ) + ); + } else if (this.props.type == 'signature') { + return React.createElement( + DropdownButton, + { bsSize: 'xsmall', bsStyle: buttonStyle, id: 'event_status', className: classStatus, style: { fontSize: '14px' }, title: this.props.status }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.enableAll }, + 'Enable Signature' + ), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.disableAll }, + 'Disable Signature' + ) + ); + } else if (this.props.type == 'entity') { + return React.createElement( + DropdownButton, + { bsSize: 'xsmall', bsStyle: buttonStyle, id: 'event_status', className: classStatus, style: { fontSize: '14px' }, title: this.props.status }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.trackAll }, + 'Track' + ), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.untrackAll }, + 'Untracked' + ) + ); + } else { + return React.createElement( + 'div', + null, + this.props.status == 'promoted' ? React.createElement( + Link, + { to: href, role: 'button', className: 'btn btn-warning' }, + this.props.status + ) : React.createElement( + DropdownButton, + { bsSize: 'xsmall', bsStyle: buttonStyle, id: 'event_status', className: classStatus, style: { fontSize: '14px' }, title: this.props.status }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.openAll }, + 'Open' + ), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.closeAll }, + 'Close' + ) + ) + ); + } + } +}); + +module.exports = DetailDataStatus; + +},{"react":983,"react-bootstrap/lib/ButtonToolbar":529,"react-bootstrap/lib/DropdownButton":539,"react-bootstrap/lib/MenuItem":566,"react-bootstrap/lib/OverlayTrigger":582,"react-bootstrap/lib/Popover":591,"react-router-dom":878}],19:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _promoted_data = require('../modal/promoted_data.jsx'); + +var _promoted_data2 = _interopRequireDefault(_promoted_data); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DetailHeaderMoreOptions = function (_Component) { + _inherits(DetailHeaderMoreOptions, _Component); + + function DetailHeaderMoreOptions(props) { + _classCallCheck(this, DetailHeaderMoreOptions); + + var _this = _possibleConstructorReturn(this, (DetailHeaderMoreOptions.__proto__ || Object.getPrototypeOf(DetailHeaderMoreOptions)).call(this, props)); + + _this.state = { + optionsActive: false + }; + + _this.ToggleOptions = _this.ToggleOptions.bind(_this); + return _this; + } + + _createClass(DetailHeaderMoreOptions, [{ + key: 'componentWillMount', + value: function componentWillMount() {} + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() {} + }, { + key: 'componentWillReceiveProps', + value: function componentWillReceiveProps() {} + }, { + key: 'render', + value: function render() { + + return _react2.default.createElement( + 'div', + { className: 'detail-header-more-options' }, + this.props.showData ? _react2.default.createElement( + _reactBootstrap.Dropdown, + { id: 'detail-header-more-options', pullRight: true, noCaret: true, bsSize: 'small' }, + _react2.default.createElement( + _reactBootstrap.Dropdown.Toggle, + null, + 'More' + ), + _react2.default.createElement( + _reactBootstrap.Dropdown.Menu, + null, + this.props.type == 'event' || this.props.type == 'incident' ? _react2.default.createElement(_promoted_data2.default, { data: this.props.data.promoted_from, type: this.props.type, id: this.props.id }) : null, + _react2.default.createElement( + _reactBootstrap.MenuItem, + null, + 'Links' + ), + _react2.default.createElement( + _reactBootstrap.MenuItem, + null, + 'Checkbox & Marked Objects' + ) + ) + ) : null + ); + } + }, { + key: 'ToggleOptions', + value: function ToggleOptions() { + var newState = !this.state.optionsActive; + this.setState({ optionsActive: newState }); + } + }]); + + return DetailHeaderMoreOptions; +}(_react.Component); + +exports.default = DetailHeaderMoreOptions; + +},{"../modal/promoted_data.jsx":84,"prop-types":512,"react":983,"react-bootstrap":608}],20:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Draggable = require('react-draggable'); +var Link = require('react-router-dom').Link; +var type = ''; +var id = 0; +var sourceid = ''; +var body = ''; +var owner = ''; +var typeid = ''; + +var Search = React.createClass({ + displayName: 'Search', + + getInitialState: function getInitialState() { + return { + showSearchToolbar: false, + searchResults: null, + entityHeight: '60vh', + searching: false, + searchString: '' + }; + }, + componentDidMount: function componentDidMount() { + function searchEscHandler(event) { + if ($('#main-search-results')[0] != undefined) { + if (event.keyCode == 27) { + this.closeSearch(); + event.preventDefault(); + } + } + } + $(document).keyup(searchEscHandler.bind(this)); + }, + closeSearch: function closeSearch() { + this.setState({ showSearchToolbar: false }); + }, + doSearch: function doSearch(string) { + $.ajax({ + type: 'get', + url: '/scot/api/v2/esearch', + data: { qstring: string }, + success: function (response) { + if (string == $('#main-search')[0].value) { + this.setState({ results: response.records, showSearchToolbar: true, searching: false, searchString: string }); + } + }.bind(this), + error: function (response) { + //this.props.errorToggle('search failed') + this.setState({ searching: false }); + }.bind(this) + }); + this.setState({ searching: true }); + }, + handleEnterKey: function handleEnterKey(e) { + if (e.key == 'Enter') { + this.doSearch(e.target.value); + } + }, + onChange: function onChange(e) { + //only do auto search if there are at least 3 characters + //if (e.target.value.length > 2) { + this.doSearch(e.target.value); + //} + }, + componentDidUpdate: function componentDidUpdate() { + if (this.state.searchString != undefined) { + //var re = new RegExp(this.state.searchString,"gi"); + //$(".search-snippet").html(function(_, html) { + // return html.replace(re, '$&'); + //}); + $(".search-snippet").mark(this.state.searchString, { "element": "span", "className": "search_highlight" }); + } + }, + render: function render() { + var tableRows = []; + if (this.state.results != undefined) { + if (this.state.results[0] != undefined) { + for (var i = 0; i < this.state.results.length; i++) { + tableRows.push(React.createElement(SearchDataEachRows, { dataOne: this.state.results[i], key: i, index: i })); + } + } else { + tableRows.push(React.createElement( + 'div', + { style: { display: 'inline-flex' } }, + React.createElement( + 'div', + { style: { display: 'flex' } }, + 'No results returned' + ) + )); + } + } + return React.createElement( + 'div', + { className: 'esearch' }, + React.createElement( + 'div', + { style: { display: 'flex' } }, + React.createElement('input', { id: 'main-search', className: 'esearch-query', style: { marginTop: '3px', padding: '10px 10px', backgroundColor: 'white', color: 'black', float: 'right', borderRadius: '50px', position: 'relative' }, placeholder: 'Search...', onKeyPress: this.handleEnterKey, onChange: this.onChange }), + this.state.searching ? React.createElement('i', { className: 'fa fa-spinner fa-spin fa-3x fa-fw', style: { color: 'white' } }) : null + ), + this.state.showSearchToolbar ? React.createElement( + 'div', + { id: 'main-search-results', style: { display: 'flex', flexFlow: 'row', position: 'absolute', right: '10px', top: '53px', background: '#f3f3f3', border: 'black', borderStyle: 'solid' } }, + React.createElement( + 'div', + null, + React.createElement(SearchDataEachHeader, { closeSearch: this.closeSearch }), + React.createElement( + 'div', + { style: { overflowY: 'auto', maxHeight: '600px', display: 'table-caption' } }, + tableRows + ) + ) + ) : null + ); + }, + componentWillUnmount: function componentWillUnmount() { + $(document).off('keypress'); + } +}); + +var SearchDataEachHeader = React.createClass({ + displayName: 'SearchDataEachHeader', + + render: function render() { + /*return ( +
+
+
+ ID +
+
+ Type +
+
+ Score +
+
+ Snippet + +
+
+
+ )*/ + return React.createElement( + 'div', + { className: 'table-row header', style: { color: 'black', display: 'flex' } }, + React.createElement( + 'div', + { style: { flexGrow: 1, display: 'flex' } }, + React.createElement( + 'div', + { style: { width: '100%', textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, + 'Search Results - Score Displayed', + React.createElement('i', { className: 'fa fa-times pull-right', style: { color: 'red', margin: '2px', cursor: 'pointer' }, onClick: this.props.closeSearch }) + ) + ) + ); + } +}); + +var SearchDataEachRows = React.createClass({ + displayName: 'SearchDataEachRows', + + render: function render() { + var type = this.props.dataOne.type; + var id = this.props.dataOne.id; + var entryid = this.props.dataOne.entryid; + var score = this.props.dataOne.score; + var snippet = this.props.dataOne.snippet; + var highlight = []; + + var rowEvenOdd = 'even'; + if (!isEven(this.props.index)) { + rowEvenOdd = 'odd'; + }; + + var rowClassName = 'search_result_row list-view-row' + rowEvenOdd; + + var href = '/' + type + '/' + id; + if (entryid != undefined) { + href = '/' + type + '/' + id + '/' + entryid; + } + + if (this.props.dataOne.highlight != undefined) { + if (typeof this.props.dataOne.highlight == 'string') { + highlight.push(React.createElement( + 'span', + { className: 'search_snippet_container panel col' }, + React.createElement( + 'span', + { className: 'search_snippet_header' }, + 'Snippet:' + ), + React.createElement( + 'span', + { className: 'search_snippet_result' }, + this.props.dataOne.highlight + ) + )); + } else if ($.isArray(this.props.dataOne.highlight)) { + highlight.push(React.createElement( + 'span', + { className: 'search_snippet_container panel col' }, + React.createElement( + 'span', + { className: 'search_snippet_header' }, + 'Snippet:' + ), + React.createElement( + 'span', + { className: 'search_snippet_result' }, + this.props.dataOne.highlight[0] + ) + )); + } else { + for (var key in this.props.dataOne.highlight) { + highlight.push(React.createElement( + 'span', + { className: 'search_snippet_container panel col' }, + React.createElement( + 'span', + { className: 'search_snippet_header' }, + key + ), + React.createElement( + 'span', + { className: 'search_snippet_result' }, + this.props.dataOne.highlight[key] + ) + )); + } + } + } + return React.createElement( + 'div', + { key: Date.now(), className: rowClassName }, + React.createElement( + Link, + { to: href, style: { display: 'flex' } }, + React.createElement( + 'span', + { className: 'panel panel-default', style: { display: 'flex', flexFlow: 'column', borderColor: 'black', borderWidth: 'thin', margin: '0px' } }, + React.createElement( + 'div', + { className: 'panel-heading h4 search-heading' }, + type, + ' ', + id, + ' - ', + score + ), + React.createElement( + 'div', + { className: 'search-snippet', style: { display: 'flex', overflowX: 'hidden', wordWrap: 'break-word' } }, + React.createElement( + 'span', + { className: 'container-fluid', style: { textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis', width: '600px' } }, + highlight + ) + ) + ) + ) + ); + /* + return ( +
+ )*/ + } +}); + +function isEven(n) { + return n % 2 == 0; +} + +module.exports = Search; + +},{"react":983,"react-draggable":804,"react-router-dom":878}],21:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var TinyMCE = require('react-tinymce'); +var Dropzone = require('../../../node_modules/react-dropzone'); +var Button = require('react-bootstrap/lib/Button.js'); +var Link = require('react-router-dom').Link; +var finalfiles = []; + +var timestamp = new Date(); +var output = "By You "; +timestamp = new Date(timestamp.toString()); +output = output + timestamp.toLocaleString(); +var FileUpload = React.createClass({ + displayName: 'FileUpload', + + getInitialState: function getInitialState() { + return { + files: [], edit: false, stagecolor: '#000', enable: true, addentry: true, saved: true, enablesave: true, whoami: undefined }; + }, + + componentDidMount: function componentDidMount() { + var whoami = getSessionStorage('whoami'); + if (whoami) { + this.setState({ whoami: whoami }); + } + + $('.entry-wrapper').scrollTop($('.entry-wrapper').scrollTop() + $('#not_saved_entry_' + this.props.id).position().top); + }, + + render: function render() { + var not_saved_entry_id = 'not_saved_entry_' + this.props.id; + return React.createElement( + 'div', + { id: not_saved_entry_id }, + React.createElement( + 'div', + { className: 'row-fluid entry-outer', style: { border: '3px solid blue', marginLeft: 'auto', marginRight: 'auto', width: '99.3%' } }, + React.createElement( + 'div', + { className: 'row-fluid entry-header' }, + React.createElement( + 'div', + { className: 'entry-header-inner' }, + '[', + React.createElement( + Link, + { style: { color: 'black' }, to: "not_saved_0" }, + 'Not_Saved_0' + ), + ']by ', + this.state.whoami, + React.createElement( + 'span', + { className: 'pull-right', style: { display: 'inline-flex', paddingRight: '3px' } }, + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.submit }, + 'Submit' + ), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.onCancel }, + 'Cancel' + ) + ) + ) + ), + React.createElement( + Dropzone, + { onDrop: this.onDrop, style: { 'border-width': '2px', 'border-color': '#000', 'border-radius': '4px', 'border-style': 'dashed', 'text-align': 'center', 'background-color': 'azure' } }, + React.createElement( + 'div', + { style: { fontSize: '16px', color: 'black', margin: '5px' } }, + 'Click or Drop files here to upload' + ) + ), + this.state.files ? React.createElement( + 'div', + null, + ' ', + this.state.files.map(function (file) { + return React.createElement( + 'ul', + { style: { 'list-style-type': 'none', margin: '0', padding: '0' } }, + React.createElement( + 'li', + null, + React.createElement( + 'p', + { style: { display: 'inline' } }, + file.name + ), + React.createElement( + 'button', + { style: { 'line-height': '1px' }, className: 'btn btn-info', id: file.name, onClick: this.Close }, + 'x' + ) + ) + ); + }.bind(this)) + ) : null + ) + ); + }, + onCancel: function onCancel() { + finalfiles = []; + this.props.fileUploadToggle(); + }, + Close: function Close(i) { + for (var x = 0; x < finalfiles.length; x++) { + if (i.target.id == finalfiles[x].name) { + finalfiles.splice(x, 1); + } + } + this.setState({ files: finalfiles }); + }, + onDrop: function onDrop(files) { + for (var i = 0; i < files.length; i++) { + finalfiles.push(files[i]); + } + this.setState({ files: finalfiles }); + }, + submit: function submit() { + if (finalfiles.length > 0) { + for (var i = 0; i < finalfiles.length; i++) { + var file = { file: finalfiles[i].name }; + var data = new FormData(); + data.append('upload', finalfiles[i]); + data.append('target_type', this.props.type); + data.append('target_id', Number(this.props.targetid)); + if (this.props.entryid != null) { + data.append('entry_id', this.props.entryid); + } + var xhr = new XMLHttpRequest(); + xhr.addEventListener("progress", this.uploadProgress); + xhr.addEventListener("load", this.uploadComplete); + xhr.addEventListener("error", this.uploadFailed); + xhr.addEventListener("abord", this.uploadCancelled); + xhr.open("POST", "/scot/api/v2/file"); + xhr.send(data); + } + } else { + alert('Select a file to upload before submitting.'); + } + }, + uploadComplete: function uploadComplete() { + this.onCancel(); + }, + uploadFailed: function uploadFailed() { + this.props.errorToggle('An error occured. Upload failed.'); + }, + uploadProgress: function uploadProgress() { + //TODO add progress bar + }, + uploadCancelled: function uploadCancelled() { + //this.props.errorToggle('Upload Cancelled'); + } +}); + +module.exports = FileUpload; + +},{"../../../node_modules/react-dropzone":805,"react":983,"react-bootstrap/lib/Button.js":527,"react-router-dom":878,"react-tinymce":909}],22:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var ReactDateTime = require('react-datetime'); + +var IncidentTable = React.createClass({ + displayName: 'IncidentTable', + + getInitialState: function getInitialState() { + var dropdown = { + 'Type': ['NONE', 'FYI', 'Type 1 : Root Comprimise', 'Type 1 : User Compromise', 'Type 1 : Loss/Theft/Missing Desktop', 'Type 1 : Loss/Theft/Missing Laptop', 'Type 1 : Loss/Theft/Missing Media', 'Type 1 : Loss/Theft/Missing Other', 'Type 1 : Malicious Code Trojan', 'Type 1 : Malicious Code Virus', 'Type 1 : Malicious Code Worm', 'Type 1 : Malicious Code Other', 'Type 1 : Web Site Defacement', 'Type 1 : Denial of Service', 'Type 1 : Critical Infrastructure Protection', 'Type 1 : Unauthorized Use', 'Type 1 : Information Compromise', 'Type 2 : Attempted Intrusion', 'Type 2 : Reconnaissance Activity'], + 'DOE Category': ['NONE', 'IMI-1', 'IMI-2', 'IMI-3', 'IMI-4'], + 'DOE Information Sensitivity': ['NONE', 'OUO', 'PII', 'SUI', 'UCNI', 'Other'], + 'DOE Security Category': ['NONE', 'Low', 'Moderate', 'High'] + }; + var title_to_data_name = { + 'Type': 'type', + 'DOE Category': 'category', + 'DOE Information Sensitivity': 'sensitivity', + 'DOE Security Category': 'security_category' + }; + var date_types = ['Occurred', 'Discovered', 'Reported', 'Closed']; + var report_types = { 'DOE Report Id:': 'doe_report_id' }; + var reportValue = ''; + var reportTypeShort = ''; + var reportType = ''; + $(Object.getOwnPropertyNames(report_types)).each(function (index, report_type) { + reportTypeShort = report_types[report_type]; + if (this.props.headerData != null) { + reportValue = this.props.headerData[reportTypeShort]; + } + reportType = report_type; + }.bind(this)); + + return { + dropdownOptions: dropdown, + title_to_data_name: title_to_data_name, + date_types: date_types, + report_types: report_types, + occurred: 0, + discovered: 0, + reported: 0, + closed: 0, + reportId: 0, + reportValue: reportValue, + reportTypeShort: reportTypeShort, + reportType: reportType + }; + }, + onChange: function onChange(event) { + var k = event.target.id; + var v = event.target.value; + var json = {}; + json[k] = v; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('successfully changed incident data'); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to updated incident data', data); + }.bind(this) + }); + }, + inputOnChange: function inputOnChange(event) { + this.setState({ reportValue: event.target.value }); + }, + render: function render() { + var incidentData = this.props.headerData; + var wholeTable = []; + var dropdownArr = []; + var datesArr = []; + var reportingArr = []; + var incidentProps = Object.getOwnPropertyNames(incidentData); + $(Object.getOwnPropertyNames(this.state.dropdownOptions)).each(function (index, dropdown_name) { + var arr = []; + for (var i = 0; i < this.state.dropdownOptions[dropdown_name].length; i++) { + var item = this.state.dropdownOptions[dropdown_name][i]; + arr.push(React.createElement( + 'option', + null, + item + )); + } + var datetype = this.state.title_to_data_name[dropdown_name]; + var selectValue = this.props.headerData[datetype]; + var dropdownTitle = dropdown_name + ':'; + dropdownArr.push(React.createElement( + 'div', + null, + React.createElement( + 'span', + { className: 'incidentTableWidth' }, + dropdownTitle + ), + React.createElement( + 'span', + null, + React.createElement( + 'select', + { id: datetype, value: selectValue, onChange: this.onChange }, + arr + ) + ) + )); + }.bind(this)); + for (var i = 0; i < this.state.date_types.length; i++) { + var datetype = this.state.date_types[i]; + var typeLower = this.state.date_types[i].toLowerCase(); + var typeTitle = datetype + ':'; + var value = this.props.headerData[typeLower] * 1000; + datesArr.push(React.createElement(IncidentDates, { typeTitle: typeTitle, value: value, typeLower: typeLower, type: this.props.type, id: this.props.id })); + } + var arr = []; + arr.push(React.createElement('input', { onBlur: this.onChange, onChange: this.inputOnChange, value: this.state.reportValue, id: this.state.reportTypeShort })); + reportingArr.push(React.createElement( + 'div', + null, + React.createElement( + 'span', + { className: 'incidentTableWidth' }, + this.state.reportType + ), + React.createElement( + 'span', + null, + arr + ) + )); + return React.createElement( + 'div', + { className: 'incidentTable' }, + dropdownArr, + datesArr, + reportingArr + ); + } +}); + +var IncidentDates = React.createClass({ + displayName: 'IncidentDates', + + getInitialState: function getInitialState() { + return { + showCalendar: false + }; + }, + onChange: function onChange(event) { + var k = this.props.typeLower; + var v = event._d.getTime() / 1000; + var json = {}; + json[k] = v; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('successfully changed incident data'); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to updated incident data', data); + }.bind(this) + }); + }, + showCalendar: function showCalendar() { + if (this.state.showCalendar == false) { + this.setState({ showCalendar: true }); + } else { + this.setState({ showCalendar: false }); + } + }, + render: function render() { + return React.createElement( + 'div', + { style: { display: 'flex', flexFlow: 'row' } }, + React.createElement( + 'span', + { className: 'incidentTableWidth' }, + this.props.typeTitle + ), + React.createElement(ReactDateTime, { value: this.props.value, onChange: this.onChange }) + ); + } +}); + +module.exports = IncidentTable; + +},{"react":983,"react-datetime":636}],23:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.setMarkedItems = exports.getMarkedItems = exports.removeMarkedItems = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Marker = function (_Component) { + _inherits(Marker, _Component); + + function Marker(props) { + _classCallCheck(this, Marker); + + var _this = _possibleConstructorReturn(this, (Marker.__proto__ || Object.getPrototypeOf(Marker)).call(this, props)); + + _this.state = { + isMarked: false + }; + + _this.removeMarkedItemsHandler = _this.removeMarkedItemsHandler.bind(_this); + _this.getMarkedItemsHandler = _this.getMarkedItemsHandler.bind(_this); + _this.setMarkedItemsHandler = _this.setMarkedItemsHandler.bind(_this); + _this.getSelectedAlerts = _this.getSelectedAlerts.bind(_this); + return _this; + } + + _createClass(Marker, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.mounted = true; + + this.getMarkedItemsHandler(); + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'componentWillReceiveProps', + value: function componentWillReceiveProps(nextProps) { + this.getMarkedItemsHandler(); + if (nextProps.isAlert) { + //set marked to false if alert since we can't predict if new ones are selected + this.setState({ isMarked: false }); + } + } + }, { + key: 'render', + value: function render() { + if (this.props.type == 'entry') { + + return _react2.default.createElement( + _reactBootstrap.MenuItem, + { onClick: this.state.isMarked ? this.removeMarkedItemsHandler : this.setMarkedItemsHandler }, + _react2.default.createElement('i', { style: { color: (this.state.isMarked ? 'green' : '') + ' ' }, className: 'fa fa' + (this.state.isMarked ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }), + this.state.isMarked ? _react2.default.createElement( + 'span', + null, + 'Marked' + ) : _react2.default.createElement( + 'span', + null, + 'Mark' + ) + ); + } else { + + return _react2.default.createElement( + _reactBootstrap.OverlayTrigger, + { placement: 'top', overlay: _react2.default.createElement( + _reactBootstrap.Tooltip, + { id: 'mark_tooltip' }, + 'Mark selected ', + this.props.isAlert ? _react2.default.createElement( + 'span', + null, + 'alerts' + ) : this.props.type + ) }, + _react2.default.createElement( + _reactBootstrap.Button, + { bsSize: 'xsmall', onClick: this.state.isMarked ? this.removeMarkedItemsHandler : this.setMarkedItemsHandler }, + _react2.default.createElement('i', { style: { color: (this.state.isMarked ? 'green' : '') + ' ' }, className: 'fa fa' + (this.state.isMarked ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }), + this.props.isAlert ? _react2.default.createElement( + 'span', + null, + 'Mark selected' + ) : null + ) + ); + } + } + }, { + key: 'getMarkedItemsHandler', + value: function getMarkedItemsHandler() { + var markedItems = getMarkedItems(); + var isMarked = false; + + if (markedItems) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = markedItems[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var key = _step.value; + + if (key.id === this.props.id && key.type === this.props.type) { + isMarked = true; + break; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + this.setState({ isMarked: isMarked }); + } + }, { + key: 'removeMarkedItemsHandler', + value: function removeMarkedItemsHandler() { + + if (this.props.isAlert) { + var selectedAlerts = this.getSelectedAlerts(); + for (var i = 0; i < selectedAlerts.length; i++) { + removeMarkedItems('alert', selectedAlerts[i]); + } + } else { + removeMarkedItems(this.props.type, this.props.id); + } + this.setState({ isMarked: false }); + } + }, { + key: 'setMarkedItemsHandler', + value: function setMarkedItemsHandler() { + if (this.props.isAlert) { + //parse alerts then iterate through them to add to marking list + var selectedAlerts = this.getSelectedAlerts(); + for (var i = 0; i < selectedAlerts.length; i++) { + setMarkedItems('alert', selectedAlerts[i], this.props.string); + } + } else { + setMarkedItems(this.props.type, this.props.id, this.props.string); + } + this.setState({ isMarked: true }); + } + }, { + key: 'getSelectedAlerts', + value: function getSelectedAlerts() { + var array = []; + + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push(id); + }.bind(this)); + + return array; + } + }]); + + return Marker; +}(_react.Component); + +var removeMarkedItems = exports.removeMarkedItems = function removeMarkedItems(type, id) { + var currentMarked = getMarkedItems(); + + if (currentMarked) { + for (var i = 0; i < currentMarked.length; i++) { + if (currentMarked[i].type == type && currentMarked[i].id == id) { + currentMarked.splice(i, 1); + break; + } + } + + setLocalStorage('marked', JSON.stringify(currentMarked)); + } +}; + +var getMarkedItems = exports.getMarkedItems = function getMarkedItems() { + var markedItems = getLocalStorage('marked'); + if (markedItems) { + markedItems = JSON.parse(markedItems); + return markedItems; + } +}; + +var setMarkedItems = exports.setMarkedItems = function setMarkedItems(type, id, string) { + var nextMarked = []; + var currentMarked = getMarkedItems(); + + if (currentMarked) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = currentMarked[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var key = _step2.value; + + if (key.type != type || key.id != id) { + nextMarked.push(key); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + nextMarked.push({ id: id, type: type, subject: string.substring(0, 120) }); + setLocalStorage('marked', JSON.stringify(nextMarked)); +}; + +Marker.propTypes = { + isMarked: _propTypes2.default.bool +}; + +Marker.defaultProps = { + isMarked: false +}; + +exports.default = Marker; + +},{"prop-types":512,"react":983,"react-bootstrap":608}],24:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); +var ReactTags = require('react-tag-input').WithContext; + +var SelectedPermission = React.createClass({ + displayName: 'SelectedPermission', + + getInitialState: function getInitialState() { + return { readPermissionEntry: false, modifyPermissionEntry: false }; + }, + toggleNewReadPermission: function toggleNewReadPermission() { + if (this.state.readPermissionEntry == false) { + this.setState({ readPermissionEntry: true }); + } else if (this.state.readPermissionEntry == true) { + this.setState({ readPermissionEntry: false }); + }; + }, + toggleNewModifyPermission: function toggleNewModifyPermission() { + if (this.state.modifyPermissionEntry == false) { + this.setState({ modifyPermissionEntry: true }); + } else if (this.state.modifyPermissionEntry == true) { + this.setState({ modifyPermissionEntry: false }); + }; + }, + permissionsfunc: function permissionsfunc(permissionData) { + console.log(permissionData.groups); + var writepermissionsarr = []; + var readpermissionsarr = []; + var readwritepermissionsarr = []; + for (var prop in permissionData.groups) { + var fullprop = permissionData.groups[prop]; + if (prop == 'read') { + permissionData.groups[prop].forEach(function (fullprop) { + readpermissionsarr.push(fullprop); + }); + } else if (prop == 'modify') { + permissionData.groups[prop].forEach(function (fullprop) { + writepermissionsarr.push(fullprop); + }); + }; + }; + readwritepermissionsarr.push(readpermissionsarr); + readwritepermissionsarr.push(writepermissionsarr); + return readwritepermissionsarr; + }, + render: function render() { + var modifyRows = []; + var readRows = []; + var permissionData = this.props.permissionData; + var data = this.permissionsfunc(permissionData); //pos 0 is read and pos 1 is write + var id = this.props.id; + var type = this.props.type; + if (data[0] !== undefined) { + for (var i = 0; i < data[0].length; i++) { + var read_modify = 'read'; + readRows.push(React.createElement(PermissionIterator, { data: data[0][i], dataRead: data[0], dataModify: data[1], updateid: this.props.updateid, id: id, type: type, read_modify: read_modify, updated: this.props.updated })); + } + } + if (data[1] !== undefined) { + for (var i = 0; i < data[1].length; i++) { + var read_modify = 'modify'; + modifyRows.push(React.createElement(PermissionIterator, { data: data[1][i], dataRead: data[0], dataModify: data[1], updateid: this.props.updateid, id: id, type: type, read_modify: read_modify, updated: this.props.updated })); + } + } + if (type == 'entry') { + return React.createElement( + 'div', + { id: '', className: '' }, + React.createElement( + 'span', + { style: { display: 'inline-flex' } }, + 'Read Groups: ', + readRows, + this.state.readPermissionEntry ? React.createElement( + 'span', + { style: { display: 'inherit', color: 'white' } }, + React.createElement(NewPermission, { readUpdate: 1, modifyUpdate: 0, dataRead: data[0], dataModify: data[1], type: type, updateid: this.props.updateid, id: id, toggleNewReadPermission: this.toggleNewReadPermission, updated: this.props.updated, permissionsToggle: this.props.permissionsToggle }) + ) : null, + this.state.readPermissionEntry ? React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleNewReadPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) : React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleNewReadPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ), + React.createElement( + 'span', + { style: { paddingLeft: '5px' } }, + 'Modify Groups: ' + ), + modifyRows, + this.state.modifyPermissionEntry ? React.createElement( + 'span', + { style: { display: 'inherit', color: 'white' } }, + React.createElement(NewPermission, { readUpdate: 0, modifyUpdate: 1, dataRead: data[0], dataModify: data[1], type: type, updateid: this.props.updateid, id: id, toggleNewModifyPermission: this.toggleNewModifyPermission, updated: this.props.updated, permissionsToggle: this.props.permissionsToggle }) + ) : null, + this.state.modifyPermissionEntry ? React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleNewModifyPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) : React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleNewModifyPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ) + ) + ); + } else { + return React.createElement( + 'div', + { id: '', className: 'toolbar entry-header-info-null', style: { paddingTop: '0px' } }, + React.createElement( + 'span', + { style: { display: 'inline-flex', paddingRight: '10px', paddingLeft: '5px' } }, + React.createElement( + 'h4', + null, + 'Permissions:' + ) + ), + 'Read Groups: ', + readRows, + this.state.readPermissionEntry ? React.createElement(NewPermission, { readUpdate: 1, modifyUpdate: 0, dataRead: data[0], dataModify: data[1], type: type, updateid: this.props.updateid, id: id, toggleNewReadPermission: this.toggleNewReadPermission, updated: this.props.updated, permissionsToggle: this.props.permissionsToggle }) : null, + this.state.readPermissionEntry ? React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleNewReadPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) : React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleNewReadPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ), + React.createElement( + 'span', + { style: { paddingLeft: '5px' } }, + 'Modify Groups: ' + ), + modifyRows, + this.state.modifyPermissionEntry ? React.createElement(NewPermission, { readUpdate: 0, modifyUpdate: 1, dataRead: data[0], dataModify: data[1], type: type, updateid: this.props.updateid, id: id, toggleNewModifyPermission: this.toggleNewModifyPermission, updated: this.props.updated, permissionsToggle: this.props.permissionsToggle }) : null, + this.state.modifyPermissionEntry ? React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleNewModifyPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) : React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleNewModifyPermission }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ), + React.createElement('img', { src: '/images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.permissionsToggle }) + ); + } + } +}); + +var PermissionIterator = React.createClass({ + displayName: 'PermissionIterator', + + getInitialState: function getInitialState() { + return { + key: this.props.updateid + }; + }, + permissionDelete: function permissionDelete() { + var newPermission = {}; + var tempArr = []; + var data = this.props.data; + var dataRead = this.props.dataRead; + var dataModify = this.props.dataModify; + var toggle = this.props.permissionsToggle; + if (this.props.read_modify == 'read') { + for (var i = 0; i < dataRead.length; i++) { + if (dataRead[i] != data) { + tempArr.push(dataRead[i]); + } + } + newPermission.read = tempArr; + newPermission.modify = dataModify; + } else if (this.props.read_modify == 'modify') { + for (var i = 0; i < dataModify.length; i++) { + if (dataModify[i] != data) { + tempArr.push(dataModify[i]); + } + } + newPermission.read = dataRead; + newPermission.modify = tempArr; + } + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'groups': newPermission }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success'); + }.bind(this), + error: function (data) { + this.props.errorToggle('error Failed to delete group', data); + }.bind(this) + }); + }, + render: function render() { + var data = this.props.data; + var type = this.props.type; + if (type == 'entry') { + return React.createElement( + 'span', + { id: 'permission_source', className: 'permissionButton' }, + data, + React.createElement('span', { className: 'fa fa-times permissionButtonClose', 'aria-hidden': 'true', onClick: this.permissionDelete }) + ); + } else { + return React.createElement( + 'span', + { id: 'permission_source', className: 'permissionButton' }, + data, + React.createElement('span', { className: 'fa fa-times permissionButtonClose', 'aria-hidden': 'true', onClick: this.permissionDelete }) + ); + } + } +}); + +var NewPermission = React.createClass({ + displayName: 'NewPermission', + + getInitialState: function getInitialState() { + return { + suggestions: this.props.options, + key: this.props.updateid + }; + }, + handleAddition: function handleAddition(tag) { + var newPermission = {}; + var dataRead = this.props.dataRead; + var dataModify = this.props.dataModify; + var toggle = this.props.permissionsToggle; + if (this.props.readUpdate == 1) { + dataRead.push(tag); + } else if (this.props.modifyUpdate == 1) { + dataModify.push(tag); + } + if (this.props.toggleNewModifyPermission != undefined) { + toggle = this.props.toggleNewModifyPermission; + } else if (this.props.toggleNewReadPermission != undefined) { + toggle = this.props.toggleNewReadPermission; + } + newPermission.read = dataRead; + newPermission.modify = dataModify; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'groups': newPermission }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: permission added'); + toggle(); + }.bind(this), + error: function (data) { + toggle(); + this.props.errorToggle('error Failed to add group', data); + }.bind(this) + }); + }, + handleInputChange: function handleInputChange(input) { + //blank until there's a lookup for group permissions + /*var arr = []; + this.serverRequest = $.get('/scot/api/v2/ac/source/' + input, function (result) { + var result = result.records; + console.log(result); + for (var prop in result) { + arr.push(result[prop].value) + } + this.setState({suggestions:arr}) + }.bind(this));*/ + }, + handleDelete: function handleDelete() { + //blank since buttons are handled outside of this + }, + handleDrag: function handleDrag() { + //blank since buttons are handled outside of this + }, + render: function render() { + var suggestions = this.state.suggestions; + return React.createElement( + 'span', + { className: 'tag-new' }, + React.createElement(ReactTags, { + suggestions: suggestions, + handleAddition: this.handleAddition, + handleInputChange: this.handleInputChange, + handleDelete: this.handleDelete, + handleDrag: this.handleDrag, + minQueryLength: 1, + customCSS: 1 }) + ); + } +}); +module.exports = SelectedPermission; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-tag-input":901}],25:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button.js'); + +var Promote = React.createClass({ + displayName: 'Promote', + + getInitialState: function getInitialState() { + return { + newURL: null, + newType: null + }; + }, + componentDidMount: function componentDidMount() { + if (this.props.type == "alert") { + this.setState({ newType: "Event" }); + this.setState({ newURL: 'event' }); + } else if (this.props.type == "event") { + this.setState({ newType: "Incident" }); + this.setState({ newURL: 'incident' }); + } + }, + promote: function promote() { + var data = JSON.stringify({ promote: 'new' }); + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: data, + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('successfully promoted'); + window.location.assign('#/' + this.state.newURL + '/' + data.pid); + }.bind(this), + error: function (data) { + this.props.errorToggle('error', 'Failed to promote', data); + }.bind(this) + }); + }, + render: function render() { + var type = this.props.type; + var id = this.props.id; + return React.createElement( + Button, + { bsStyle: 'warning', eventKey: '1', bsSize: 'xsmall', onClick: this.promote }, + React.createElement('img', { src: '/images/megaphone.png' }), + React.createElement( + 'span', + null, + 'Promote to ', + this.state.newType + ) + ); + } +}); + +module.exports = Promote; + +},{"react":983,"react-bootstrap/lib/Button.js":527}],26:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactDom = require('react-dom'); + +var _brace = require('brace'); + +var _brace2 = _interopRequireDefault(_brace); + +var _reactAce = require('react-ace'); + +var _reactAce2 = _interopRequireDefault(_reactAce); + +var _Button = require('react-bootstrap/lib/Button.js'); + +var _Button2 = _interopRequireDefault(_Button); + +var _DropdownButton = require('react-bootstrap/lib/DropdownButton.js'); + +var _DropdownButton2 = _interopRequireDefault(_DropdownButton); + +var _OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger.js'); + +var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger); + +var _ButtonGroup = require('react-bootstrap/lib/ButtonGroup.js'); + +var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); + +var _MenuItem = require('react-bootstrap/lib/MenuItem.js'); + +var _MenuItem2 = _interopRequireDefault(_MenuItem); + +var _Popover = require('react-bootstrap/lib/Popover.js'); + +var _Popover2 = _interopRequireDefault(_Popover); + +var _store = require('../activemq/store.jsx'); + +var _store2 = _interopRequireDefault(_store); + +var _Grid = require('react-bootstrap/lib/Grid.js'); + +var _Grid2 = _interopRequireDefault(_Grid); + +require('brace/mode/bro'); + +require('brace/mode/javascript'); + +require('brace/mode/java'); + +require('brace/mode/python'); + +require('brace/mode/xml'); + +require('brace/mode/ruby'); + +require('brace/mode/sass'); + +require('brace/mode/markdown'); + +require('brace/mode/mysql'); + +require('brace/mode/json'); + +require('brace/mode/html'); + +require('brace/mode/c_cpp'); + +require('brace/mode/csharp'); + +require('brace/mode/perl'); + +require('brace/mode/powershell'); + +require('brace/mode/yaml'); + +require('brace/theme/github'); + +require('brace/theme/monokai'); + +require('brace/theme/kuroir'); + +require('brace/theme/solarized_dark'); + +require('brace/theme/solarized_light'); + +require('brace/theme/terminal'); + +require('brace/theme/textmate'); + +require('brace/theme/tomorrow'); + +require('brace/theme/twilight'); + +require('brace/theme/xcode'); + +require('brace/keybinding/vim'); + +require('brace/keybinding/emacs'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var SignatureTable = _react2.default.createClass({ + displayName: 'SignatureTable', + + getInitialState: function getInitialState() { + var key = new Date(); + key = key.getTime(); + var value = ''; + var currentKeyboardHandler = 'none'; + var currentLanguageMode = 'java'; + var currentEditorTheme = 'github'; + var viewVersionid = this.props.headerData.prod_sigbody_id; + var viewSigBodyid; + if (checkCookie('signatureKeyboardHandler') != undefined) { + currentKeyboardHandler = checkCookie('signatureKeyboardHandler'); + } + if (checkCookie('signatureLanguageMode') != undefined) { + currentLanguageMode = checkCookie('signatureLanguageMode'); + } + if (checkCookie('signatureEditorTheme') != undefined) { + currentEditorTheme = checkCookie('signatureEditorTheme'); + } + if (!jQuery.isEmptyObject(this.props.headerData.version)) { + if (this.props.headerData.version[this.props.headerData.prod_sigbody_id] != undefined || this.props.headerData.version[this.props.headerData.prod_sigbody_id] == 0) { + value = this.props.headerData.version[this.props.headerData.prod_sigbody_id].body; + viewSigBodyid = this.props.headerData.version[this.props.headerData.prod_sigbody_id].id; + } else { + for (var key in this.props.headerData.version) { + if (key < viewVersionid) { + continue; + } else { + viewVersionid = key; + value = this.props.headerData.version[key].body; + viewSigBodyid = this.props.headerData.version[key].id; + } + } + } + } + return { + readOnly: true, + value: value, + signatureData: this.props.headerData, + loaded: true, + viewSigBodyid: viewSigBodyid, + viewVersionid: viewVersionid, + lastViewVersionid: null, + key: key, + cursorEnabledDisabled: 'cursorDisabled', + keyboardHandlers: ['none', 'vim', 'emacs'], + currentKeyboardHandler: currentKeyboardHandler, + languageModes: ['bro', 'csharp', 'c_cpp', 'html', 'javascript', 'java', 'json', 'markdown', 'mysql', 'perl', 'powershell', 'python', 'ruby', 'sass', 'xml', 'yaml'], + currentLanguageMode: currentLanguageMode, + editorThemes: ['github', 'monokai', 'kuroir', 'solarized_dark', 'solarized_light', 'terminal', 'textmate', 'tomorrow', 'twilight', 'xcode'], + currentEditorTheme: currentEditorTheme, + ajaxType: null + }; + }, + onChange: function onChange(value) { + this.setState({ value: value }); + }, + submitSigBody: function submitSigBody(e) { + var url = 'scot/api/v2/sigbody/'; + var versionid = this.state.viewVersionid; //version revision if creating a new sigbody + if (this.state.ajaxType == 'put') { + versionid = this.state.viewSigBodyid; //version id (not revision id) if editing an existing sigbody + url = 'scot/api/v2/sigbody/' + versionid; + } + $.ajax({ + type: this.state.ajaxType, + url: url, + data: JSON.stringify({ signature_id: parseInt(this.props.id), body: this.state.value }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('successfully changed signature data'); + var viewVersionid; + if (data.revision == undefined) { + viewVersionid = this.state.viewVersionid; + } else { + viewVersionid = data.revision; + } + this.setState({ readOnly: true, cursorEnabledDisabled: 'cursorDisabled', ajaxType: null, viewVersionid: viewVersionid, viewSigBodyid: data.id }); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to create/update sigbody', data); + }.bind(this) + }); + }, + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + this.setState({ signatureData: nextProps.headerData }); + }, + editSigBody: function editSigBody(e) { + this.setState({ readOnly: false, lastViewVersionid: this.state.viewVersionid, cursorEnabledDisabled: 'cursorEnabled', ajaxType: 'put' }); + }, + createNewSigBody: function createNewSigBody() { + this.setState({ readOnly: false, viewVersionid: null, lastViewVersionid: this.state.viewVersionid, value: '', cursorEnabledDisabled: 'cursorEnabled', ajaxType: 'post' }); + }, + createNewSigBodyFromSig: function createNewSigBodyFromSig() { + this.setState({ readOnly: false, lastViewVersionid: this.state.viewVersionid, cursorEnabledDisabled: 'cursorEnabled', ajaxType: 'post', viewVersionid: null }); + }, + Cancel: function Cancel() { + var value = ''; + if (!jQuery.isEmptyObject(this.state.signatureData.version)) { + if (this.state.signatureData.version[this.state.signatureData.prod_sigbody_id] != undefined) { + value = this.state.signatureData.version[this.state.lastViewVersionid].body; + } + } + this.setState({ readOnly: true, value: value, viewVersionid: this.state.lastViewVersionid, cursorEnabledDisabled: 'cursorDisabled', ajaxType: null }); + }, + viewSigBody: function viewSigBody(e) { + if (this.state.readOnly == true) { + //only allow button click if you can't edit the signature + this.setState({ value: this.state.signatureData.version[e.target.id].body, viewVersionid: e.target.id, viewSigBodyid: e.target.viewSigBodyid }); + } + }, + keyboardHandlerUpdate: function keyboardHandlerUpdate(e) { + setCookie('signatureKeyboardHandler', e.target.text, 1000); + this.setState({ currentKeyboardHandler: e.target.text }); + }, + languageModeUpdate: function languageModeUpdate(e) { + setCookie('signatureLanguageMode', e.target.text, 1000); + this.setState({ currentLanguageMode: e.target.text }); + }, + editorThemeUpdate: function editorThemeUpdate(e) { + setCookie('signatureEditorTheme', e.target.text, 1000); + this.setState({ currentEditorTheme: e.target.text }); + }, + render: function render() { + var versionsArray = []; + var keyboardHandlersArray = []; + var languageModesArray = []; + var editorThemesArray = []; + var not_saved_signature_entry_id = 'not_saved_signature_entry_' + this.state.key; + var currentKeyboardHandlerApplied = this.state.currentKeyboardHandler; + var viewVersionid = []; + var highestVersionid = 0; + if (!jQuery.isEmptyObject(this.state.signatureData)) { + if (!jQuery.isEmptyObject(this.state.signatureData.version)) { + for (var key in this.state.signatureData.version) { + var versionidrevision = this.state.signatureData.version[key].revision; + var versionidrevisionprodqual = this.state.signatureData.version[key].revision; + var versionidSigBodyid = this.state.signatureData.version[key].id; + if (this.state.signatureData.prod_sigbody_id == versionidrevision) { + versionidrevisionprodqual = versionidrevision + ' - Production'; + } else if (this.state.signatureData.qual_sigbody_id == versionidrevision) { + versionidrevisionprodqual = versionidrevision + ' - Quality'; + }; //add production and quality text to identify current status on the menu + var disabled; + if (this.state.readOnly == true) { + disabled = false; + } else { + disabled = true; + }; + versionsArray.push(_react2.default.createElement( + _MenuItem2.default, + { id: versionidrevision, key: versionidrevision, onClick: this.viewSigBody, eventKey: versionidrevision, viewSigBodyid: versionidSigBodyid, bsSize: 'xsmall', disabled: disabled }, + versionidrevisionprodqual + )); + if (versionidrevision > highestVersionid) { + highestVersionid = versionidrevision; + }; + } + } + } + + if (this.state.keyboardHandlers != undefined) { + for (var i = 0; i < this.state.keyboardHandlers.length; i++) { + keyboardHandlersArray.push(_react2.default.createElement( + _MenuItem2.default, + { id: i, key: i, onClick: this.keyboardHandlerUpdate, eventKey: i, bsSize: 'xsmall' }, + this.state.keyboardHandlers[i] + )); + } + } + + if (this.state.currentKeyboardHandler == 'none') { + currentKeyboardHandlerApplied = null; + } + + if (this.state.languageModes != undefined) { + for (var i = 0; i < this.state.languageModes.length; i++) { + languageModesArray.push(_react2.default.createElement( + _MenuItem2.default, + { id: i, key: i, onClick: this.languageModeUpdate, eventKey: i, bsSize: 'xsmall' }, + this.state.languageModes[i] + )); + } + } + + if (this.state.editorThemes != undefined) { + for (var i = 0; i < this.state.editorThemes.length; i++) { + editorThemesArray.push(_react2.default.createElement( + _MenuItem2.default, + { id: i, key: i, onClick: this.editorThemeUpdate, eventKey: i, bsSize: 'xsmall' }, + this.state.editorThemes[i] + )); + } + } + if (this.state.signatureData.prod_sigbody_id == this.state.viewVersionid) { + viewVersionid.push(_react2.default.createElement( + 'span', + { className: 'signature_production_color' }, + this.state.viewVersionid, + ' - Production' + )); + } else if (this.state.signatureData.qual_sigbody_id == this.state.viewVersionid) { + viewVersionid.push(_react2.default.createElement( + 'span', + { className: 'signature_quality_color' }, + this.state.viewVersionid, + ' - Quality' + )); + } else { + viewVersionid.push(_react2.default.createElement( + 'span', + null, + this.state.viewVersionid + )); + } + return _react2.default.createElement( + 'div', + { id: 'signatureDetail', className: 'signatureDetail' }, + this.state.loaded ? _react2.default.createElement( + 'div', + null, + _react2.default.createElement(SignatureMetaData, { signatureData: this.state.signatureData, type: this.props.type, id: this.props.id, currentLanguageMode: this.state.currentLanguageMode, currentEditorTheme: this.state.currentEditorTheme, currentKeyboardHandlerApplied: currentKeyboardHandlerApplied, errorToggle: this.props.errorToggle, showSignatureOptions: this.props.showSignatureOptions }), + _react2.default.createElement( + 'div', + { id: not_saved_signature_entry_id, className: 'not_saved_signature_entry' }, + _react2.default.createElement( + 'div', + { className: 'row-fluid signature-entry-outer', style: { marginLeft: 'auto', marginRight: 'auto' } }, + _react2.default.createElement( + 'div', + { className: 'row-fluid signature-entry-header' }, + _react2.default.createElement( + 'div', + { className: 'signature-entry-header-inner' }, + 'Signature Body: ', + viewVersionid, + _react2.default.createElement( + 'span', + { className: 'pull-right', style: { display: 'inline-flex', paddingRight: '3px' } }, + 'Editor Theme:', + _react2.default.createElement( + _DropdownButton2.default, + { bsSize: 'xsmall', title: this.state.currentEditorTheme, id: 'bg-nested-dropdown', style: { marginRight: '10px' } }, + editorThemesArray + ), + 'Language Handler:', + _react2.default.createElement( + _DropdownButton2.default, + { bsSize: 'xsmall', title: this.state.currentLanguageMode, id: 'bg-nested-dropdown', style: { marginRight: '10px' } }, + languageModesArray + ), + 'Keyboard Handler:', + _react2.default.createElement( + _DropdownButton2.default, + { bsSize: 'xsmall', title: this.state.currentKeyboardHandler, id: 'bg-nested-dropdown', style: { marginRight: '10px' } }, + keyboardHandlersArray + ), + 'Signature Body Version:', + _react2.default.createElement( + _DropdownButton2.default, + { bsSize: 'xsmall', title: viewVersionid, id: 'bg-nested-dropdown', style: { marginRight: '10px' } }, + versionsArray + ), + this.state.readOnly ? _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', onClick: this.createNewSigBody, bsStyle: 'success' }, + 'Create new version' + ), + this.state.viewVersionid != 0 ? _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', onClick: this.createNewSigBodyFromSig }, + 'Create new version using this base' + ), + _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', onClick: this.editSigBody }, + 'Update displayed version' + ) + ) : null + ) : _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', onClick: this.submitSigBody }, + 'Submit' + ), + _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', onClick: this.Cancel }, + 'Cancel' + ) + ) + ) + ) + ), + _react2.default.createElement(_reactAce2.default, { + mode: this.state.currentLanguageMode, + theme: this.state.currentEditorTheme, + onChange: this.onChange, + name: 'signatureEditor', + editorProps: { $blockScrolling: true }, + keyboardHandler: currentKeyboardHandlerApplied, + value: this.state.value, + width: '100%', + maxLines: 50, + minLines: 10, + readOnly: this.state.readOnly, + className: this.state.cursorEnabledDisabled, + showPrintMargin: false + }) + ) + ) + ) : _react2.default.createElement( + 'div', + null, + 'Loading Signature Data...' + ) + ); + } +}); + +var SignatureMetaData = _react2.default.createClass({ + displayName: 'SignatureMetaData', + + getInitialState: function getInitialState() { + var inputArrayType = ['description', 'type', 'prod_sigbody_id', 'qual_sigbody_id', 'signature_group', 'target']; + var inputArrayTypeDisplay = ['Description', 'Type', 'Production Signature Body Version', 'Quality Signature Body Version', 'Signature Group', 'Target']; + var target = {}; + if (this.props.signatureData.target == undefined) { + target = {}; + target['target.id'] = null; + target['target.type'] = null; + } else { + target['target.id'] = this.props.signatureData.target.id; + target['target.type'] = this.props.signatureData.target.type; + } + return { + descriptionValue: this.props.signatureData.description, + inputArrayType: inputArrayType, + inputArrayTypeDisplay: inputArrayTypeDisplay, + description: this.props.signatureData.description, + type: this.props.signatureData.type, + prod_sigbody_id: this.props.signatureData.prod_sigbody_id, + qual_sigbody_id: this.props.signatureData.qual_sigbody_id, + signature_group: this.props.signatureData.signature_group, + optionsValue: JSON.stringify(this.props.signatureData.options), + target: target + }; + }, + InputChange: function InputChange(event) { + var key = event.target.id; + var newValue = {}; + newValue[key] = event.target.value; + this.setState(newValue); + }, + TargetInputChange: function TargetInputChange(event) { + var currentTarget = this.state.target; + var key = event.target.id; + currentTarget[key] = event.target.value; + this.setState({ target: currentTarget }); + }, + submitMetaData: function submitMetaData(event) { + var k = event.target.id; + var v = event.target.value; + if (k == 'options' || k == 'target') { + try { + v = JSON.parse(v); + } catch (err) { + this.props.errorToggle('Failed to convert string to object. Try adding quotation marks around the key and values');return; + } + var optionsType = typeof v === 'undefined' ? 'undefined' : _typeof(v); + if (optionsType !== 'object') { + this.props.errorToggle('options need to be an object but were detected as: ' + optionsType);return; + }; + }; //Convery v to JSON for options as its type is JSON + var json = {}; + json[k] = v; + $.ajax({ + type: 'put', + url: 'scot/api/v2/signature/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('successfully changed signature data'); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to update signature metadata', data); + }.bind(this) + }); + }, + onOptionsChange: function onOptionsChange(optionsValue) { + this.setState({ optionsValue: optionsValue }); + }, + render: function render() { + var inputArray = []; + for (var i = 0; i < this.state.inputArrayType.length; i++) { + var value = this.props.signatureData[this.state.inputArrayType[i]]; + if (this.state.inputArrayType[i] == 'prod_sigbody_id' || this.state.inputArrayType[i] == 'qual_sigbody_id') { + var sigBodyVersionArray = []; + var productionNewerVersionExists = false; + if (!jQuery.isEmptyObject(this.props.signatureData)) { + for (var key in this.props.signatureData.version) { + var versionidrevision = this.props.signatureData.version[key].revision; + var versionidrevisionprodqual = this.props.signatureData.version[key].revision; + var versionid = this.props.signatureData.version[key].id; + if (this.props.signatureData.prod_sigbody_id == versionidrevision) { + versionidrevisionprodqual = versionidrevision + ' - Production'; + } else if (this.props.signatureData.qual_sigbody_id == versionidrevision) { + versionidrevisionprodqual = versionidrevision + ' - Quality'; + }; //add production and quality text to identify current status on the menu + sigBodyVersionArray.push(_react2.default.createElement( + _Button2.default, + { id: this.state.inputArrayType[i], key: versionidrevision, onClick: this.submitMetaData, eventKey: versionidrevision, bsSize: 'xsmall', value: versionidrevision }, + versionidrevisionprodqual + )); + if (value < versionidrevision) { + productionNewerVersionExists = true; + }; //check if the production/quality versions are the highest, if not, show warning. + } + } + inputArray.push(_react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + this.state.inputArrayTypeDisplay[i], + ':' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement( + _OverlayTrigger2.default, + { trigger: 'focus', placement: 'bottom', overlay: _react2.default.createElement( + _Popover2.default, + { id: 'sigversionpicker' }, + _react2.default.createElement( + _ButtonGroup2.default, + { vertical: true }, + sigBodyVersionArray + ) + ) }, + _react2.default.createElement('input', { id: this.state.inputArrayType[i], onChange: this.InputChange, value: value }) + ) + ), + productionNewerVersionExists == true && this.state.inputArrayType[i] == 'prod_sigbody_id' ? _react2.default.createElement( + 'div', + { style: { color: 'red' } }, + 'A higher signature body version exists, do you want to apply it?' + ) : null + )); + } else if (this.state.inputArrayType[i] == 'target') { + inputArray.push(_react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + 'Reference Type: ' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement('input', { id: 'target.type', onChange: this.TargetInputChange, value: this.state.target['target.type'], placeholder: 'event, intel, entry... (only type one)', onBlur: this.submitMetaData }) + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + 'Reference ID: ' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement('input', { id: 'target.id', onChange: this.TargetInputChange, value: this.state.target['target.id'], placeholder: 'ID of above', onBlur: this.submitMetaData }) + ) + )); + } else if (this.state.inputArrayType[i] == 'signature_group') { + inputArray.push(_react2.default.createElement(SignatureGroup, { metaType: 'signature_group', id: this.props.id, data: this.props.signatureData[this.state.inputArrayType[i]], errorToggle: this.props.errorToggle })); + } else if (this.state.inputArrayType[i] == 'description') { + inputArray.push(_react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + this.state.inputArrayTypeDisplay[i], + ':' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement( + 'textarea', + { id: this.state.inputArrayType[i], onChange: this.InputChange, value: this.state[this.state.inputArrayType[i]], onBlur: this.submitMetaData, className: 'signatureMetaTextArea' }, + this.state[this.state.inputArrayType[i]] + ) + ) + )); + } else if (this.state.inputArrayType[i] == 'type') { + inputArray.push(_react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + this.state.inputArrayTypeDisplay[i], + ':' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement('input', { id: this.state.inputArrayType[i], onChange: this.InputChange, value: this.state[this.state.inputArrayType[i]], placeholder: 'yara, snort, etc.', onBlur: this.submitMetaData }) + ) + )); + } else { + inputArray.push(_react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + this.state.inputArrayTypeDisplay[i], + ':' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement('input', { id: this.state.inputArrayType[i], onChange: this.InputChange, value: this.state[this.state.inputArrayType[i]], onBlur: this.submitMetaData }) + ) + )); + } + } + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { id: 'signatureTable', className: 'signatureTable' }, + _react2.default.createElement( + 'div', + { className: 'row' }, + inputArray + ) + ), + this.props.showSignatureOptions ? _react2.default.createElement( + 'div', + { id: 'signatureTable2', className: 'signatureTableOptions' }, + _react2.default.createElement( + 'div', + { className: 'row-fluid signature-entry-outer', style: { marginLeft: 'auto', marginRight: 'auto' } }, + _react2.default.createElement( + 'div', + { className: 'row-fluid signature-entry-header' }, + _react2.default.createElement( + 'div', + { className: 'signature-entry-header-inner' }, + 'Signature Options', + _react2.default.createElement( + _Button2.default, + { type: 'submit', bsSize: 'xsmall', bsStyle: 'success', onClick: this.submitMetaData, id: 'options', value: this.state.optionsValue }, + 'Apply' + ) + ) + ), + _react2.default.createElement(_reactAce2.default, { + mode: 'json', + theme: this.props.currentEditorTheme, + onChange: this.onOptionsChange, + name: 'signatureEditorOptions', + editorProps: { $blockScrolling: true }, + keyboardHandler: this.props.currentKeyboardHandlerApplied, + value: this.state.optionsValue, + minLines: 10, + maxLines: 25, + width: '100%', + readOnly: false, + showPrintMargin: false + }) + ) + ) : null + ); + } +}); + +var SignatureGroup = _react2.default.createClass({ + displayName: 'SignatureGroup', + + getInitialState: function getInitialState() { + return { + signatureGroupValue: '' + }; + }, + handleAddition: function handleAddition(signature_group) { + var newSignatureGroupArr = []; + var data = this.props.data; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + newSignatureGroupArr.push(data[i]); + } else { + newSignatureGroupArr.push(data[i].value); + } + } + } + newSignatureGroupArr.push(signature_group.target.value); + $.ajax({ + type: 'put', + url: 'scot/api/v2/signature/' + this.props.id, + data: JSON.stringify({ 'signature_group': newSignatureGroupArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: signature_group added'); + this.setState({ signatureGroupValue: '' }); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to add signature_group', data); + }.bind(this) + }); + }, + InputChange: function InputChange(event) { + this.setState({ signatureGroupValue: event.target.value }); + }, + handleDelete: function handleDelete(event) { + var data = this.props.data; + var clickedThing = event.target.id; + var newSignatureGroupArr = []; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + if (data[i] != clickedThing) { + newSignatureGroupArr.push(data[i]); + } + } else { + if (data[i].value != clickedThing) { + newSignatureGroupArr.push(data[i].value); + } + } + } + } + $.ajax({ + type: 'put', + url: 'scot/api/v2/signature/' + this.props.id, + data: JSON.stringify({ 'signature_group': newSignatureGroupArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('deleted signature_group success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to delete signature_group', data); + }.bind(this) + }); + }, + + render: function render() { + var data = this.props.data; + var signatureGroupArr = []; + var value; + for (var i = 0; i < data.length; i++) { + if (typeof data[i] == 'string') { + value = data[i]; + } else if (_typeof(data[i]) == 'object') { + if (data[i] != undefined) { + value = data[i].value; + } + } + signatureGroupArr.push(_react2.default.createElement( + 'span', + { id: 'event_signature', className: 'tagButton' }, + value, + ' ', + _react2.default.createElement('i', { id: value, onClick: this.handleDelete, className: 'fa fa-times tagButtonClose' }) + )); + } + var rows = []; + var id = this.props.id; + var type = 'signature'; + return _react2.default.createElement( + 'div', + { className: 'col-lg-2 col-md-4' }, + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + 'Signature Group:' + ), + _react2.default.createElement( + 'span', + { className: 'signatureTableWidth' }, + _react2.default.createElement('input', { id: this.props.metaType, onChange: this.InputChange, value: this.state.signatureGroupValue }), + this.state.signatureGroupValue != '' ? _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.handleAddition, value: this.state.signatureGroupValue }, + 'Submit' + ) : _react2.default.createElement( + _Button2.default, + { bsSize: 'xsmall', bsType: 'submit', disabled: true }, + 'Submit' + ) + ), + signatureGroupArr + ); + } +}); + +module.exports = SignatureTable; + +},{"../activemq/store.jsx":5,"brace":205,"brace/keybinding/emacs":206,"brace/keybinding/vim":207,"brace/mode/bro":208,"brace/mode/c_cpp":209,"brace/mode/csharp":210,"brace/mode/html":211,"brace/mode/java":212,"brace/mode/javascript":213,"brace/mode/json":214,"brace/mode/markdown":215,"brace/mode/mysql":216,"brace/mode/perl":217,"brace/mode/powershell":218,"brace/mode/python":219,"brace/mode/ruby":220,"brace/mode/sass":221,"brace/mode/xml":222,"brace/mode/yaml":223,"brace/theme/github":224,"brace/theme/kuroir":225,"brace/theme/monokai":226,"brace/theme/solarized_dark":227,"brace/theme/solarized_light":228,"brace/theme/terminal":229,"brace/theme/textmate":230,"brace/theme/tomorrow":231,"brace/theme/twilight":232,"brace/theme/xcode":233,"react":983,"react-ace":516,"react-bootstrap/lib/Button.js":527,"react-bootstrap/lib/ButtonGroup.js":528,"react-bootstrap/lib/DropdownButton.js":539,"react-bootstrap/lib/Grid.js":549,"react-bootstrap/lib/MenuItem.js":566,"react-bootstrap/lib/OverlayTrigger.js":582,"react-bootstrap/lib/Popover.js":591,"react-dom":677}],27:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); +var ReactTags = require('react-tag-input').WithContext; + +var Source = React.createClass({ + displayName: 'Source', + + getInitialState: function getInitialState() { + return { sourceEntry: false }; + }, + toggleSourceEntry: function toggleSourceEntry() { + if (this.state.sourceEntry == false) { + this.setState({ sourceEntry: true }); + } else if (this.state.sourceEntry == true) { + this.setState({ sourceEntry: false }); + }; + }, + render: function render() { + var rows = []; + var id = this.props.id; + var type = this.props.type; + var data = this.props.data; + + //Don't show if guide + if (this.props.type == 'guide') { + return React.createElement('th', null); + } + + if (data != undefined) { + for (var i = 0; i < data.length; i++) { + rows.push(React.createElement(SourceDataIterator, { data: data, dataOne: data[i], id: id, type: type, updated: this.props.updated, key: i })); + } + } + return React.createElement( + 'th', + null, + React.createElement( + 'th', + null, + 'Sources:' + ), + React.createElement( + 'td', + null, + rows, + this.state.sourceEntry ? React.createElement(NewSource, { data: data, type: type, id: id, toggleSourceEntry: this.toggleSourceEntry, updated: this.props.updated }) : null, + this.state.sourceEntry ? React.createElement( + 'span', + { className: 'add-source-button' }, + React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleSourceEntry }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) + ) : React.createElement( + 'span', + { className: 'remove-source-button' }, + React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleSourceEntry }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ) + ) + ) + ); + } +}); + +var SourceDataIterator = React.createClass({ + displayName: 'SourceDataIterator', + + sourceDelete: function sourceDelete() { + var data = this.props.data; + var newSourceArr = []; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + if (data[i] != this.props.dataOne) { + newSourceArr.push(data[i]); + } + } else { + if (data[i].value != this.props.dataOne.value) { + newSourceArr.push(data[i].value); + } + } + } + } + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'source': newSourceArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('deleted source success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to delete the source', data); + }.bind(this) + }); + }, + render: function render() { + var dataOne = this.props.dataOne; + var value; + if (typeof dataOne == 'string') { + value = dataOne; + } else if ((typeof dataOne === 'undefined' ? 'undefined' : _typeof(dataOne)) == 'object') { + if (dataOne != undefined) { + value = dataOne.value; + } + } + return React.createElement( + 'span', + { id: 'event_source', className: 'sourceButton' }, + value, + ' ', + React.createElement( + 'span', + { className: 'sourceButtonClose' }, + React.createElement('i', { onClick: this.sourceDelete, className: 'fa fa-times' }) + ) + ); + } +}); + +var NewSource = React.createClass({ + displayName: 'NewSource', + + getInitialState: function getInitialState() { + return { + suggestions: this.props.options + }; + }, + handleAddition: function handleAddition(source) { + var newSourceArr = []; + var data = this.props.data; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + newSourceArr.push(data[i]); + } else { + newSourceArr.push(data[i].value); + } + } + } + newSourceArr.push(source); + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'source': newSourceArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: source added'); + this.props.toggleSourceEntry(); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to add source', data); + this.props.toggleSourceEntry(); + }.bind(this) + }); + }, + handleInputChange: function handleInputChange(input) { + var arr = []; + $.ajax({ + type: 'get', + url: '/scot/api/v2/ac/source/' + input, + success: function (result) { + var result = result.records; + for (var i = 0; i < result.length; i++) { + arr.push(result[i]); + } + this.setState({ suggestions: arr }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get source autocomplete data', data); + }.bind(this) + }); + }, + handleDelete: function handleDelete() { + //blank since buttons are handled outside of this + }, + handleDrag: function handleDrag() { + //blank since buttons are handled outside of this + }, + render: function render() { + var suggestions = this.state.suggestions; + return React.createElement( + 'span', + { className: 'tag-new' }, + React.createElement(ReactTags, { + suggestions: suggestions, + handleAddition: this.handleAddition, + handleInputChange: this.handleInputChange, + handleDelete: this.handleDelete, + handleDrag: this.handleDrag, + minQueryLength: 1, + customCSS: 1 }) + ); + } +}); + +module.exports = Source; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-tag-input":901}],28:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var Summary = React.createClass({ + displayName: 'Summary', + + getInitialState: function getInitialState() { + return { + key: this.props.id + }; + }, + toggle: function toggle() { + var newClass; + if (this.props.summary === 1) { + newClass = 'entry'; + } else if (this.props.summary === 0) { + newClass = 'summary'; + } + var json = { 'class': newClass }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/entry/' + this.props.entryid, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to make summary', data); + }.bind(this) + }); + }, + render: function render() { + var summaryDisplay = 'Summary Loading...'; + var onClick; + if (this.props.summary == 0) { + summaryDisplay = 'Make Summary'; + onClick = this.toggle; + } else if (this.props.summary == 1) { + summaryDisplay = 'Remove Summary'; + onClick = this.toggle; + } + return React.createElement( + 'span', + { style: { display: 'block' }, onClick: onClick }, + summaryDisplay + ); + } +}); + +module.exports = Summary; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839}],29:[function(require,module,exports){ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); +var ReactTags = require('react-tag-input').WithContext; + +var Tag = React.createClass({ + displayName: 'Tag', + + getInitialState: function getInitialState() { + return { tagEntry: false }; + }, + toggleTagEntry: function toggleTagEntry() { + if (this.state.tagEntry == false) { + this.setState({ tagEntry: true }); + } else if (this.state.tagEntry == true) { + this.setState({ tagEntry: false }); + }; + }, + render: function render() { + var rows = []; + var id = this.props.id; + var type = this.props.type; + var data = this.props.data; + + //Don't show if guide + if (this.props.type == 'guide') { + return React.createElement('th', null); + } + + if (data != undefined) { + for (var i = 0; i < data.length; i++) { + rows.push(React.createElement(TagDataIterator, { data: data, dataOne: data[i], id: id, type: type, updated: this.props.updated, key: i, errorToggle: this.props.errorToggle })); + } + } + return React.createElement( + 'th', + null, + React.createElement( + 'th', + null, + 'Tags:' + ), + React.createElement( + 'td', + null, + rows, + this.state.tagEntry ? React.createElement(NewTag, { data: data, type: type, id: id, toggleTagEntry: this.toggleTagEntry, updated: this.props.updated, errorToggle: this.props.errorToggle }) : null, + this.state.tagEntry ? React.createElement( + 'span', + { className: 'add-tag-button' }, + React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'danger', onClick: this.toggleTagEntry }, + React.createElement('span', { className: 'glyphicon glyphicon-minus', 'aria-hidden': 'true' }) + ) + ) : React.createElement( + 'span', + { className: 'remove-tag-button' }, + React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.toggleTagEntry }, + React.createElement('span', { className: 'glyphicon glyphicon-plus', 'aria-hidden': 'true' }) + ) + ) + ) + ); + } +}); + +var TagDataIterator = React.createClass({ + displayName: 'TagDataIterator', + + tagDelete: function tagDelete() { + var data = this.props.data; + var newTagArr = []; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + if (data[i] != this.props.dataOne) { + newTagArr.push(data[i]); + } + } else { + if (data[i].value != this.props.dataOne.value) { + newTagArr.push(data[i].value); + } + } + } + } + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'tag': newTagArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('deleted tag success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to delete tag', data); + }.bind(this) + }); + }, + render: function render() { + var dataOne = this.props.dataOne; + var value; + if (typeof dataOne == 'string') { + value = dataOne; + } else if ((typeof dataOne === 'undefined' ? 'undefined' : _typeof(dataOne)) == 'object') { + if (dataOne != undefined) { + value = dataOne.value; + } + } + return React.createElement( + 'span', + { id: 'event_tag', className: 'tagButton' }, + value, + ' ', + React.createElement( + 'span', + { className: 'tagButtonClose' }, + React.createElement('i', { onClick: this.tagDelete, className: 'fa fa-times' }) + ) + ); + } +}); + +var NewTag = React.createClass({ + displayName: 'NewTag', + + getInitialState: function getInitialState() { + return { + suggestions: this.props.options + }; + }, + handleAddition: function handleAddition(tag) { + var newTagArr = []; + var data = this.props.data; + for (var i = 0; i < data.length; i++) { + if (data[i] != undefined) { + if (typeof data[i] == 'string') { + newTagArr.push(data[i]); + } else { + newTagArr.push(data[i].value); + } + } + } + newTagArr.push(tag); + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ 'tag': newTagArr }), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: tag added'); + this.props.toggleTagEntry(); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to add tag', data); + this.props.toggleTagEntry(); + }.bind(this) + }); + }, + handleInputChange: function handleInputChange(input) { + var arr = []; + $.ajax({ + type: 'get', + url: '/scot/api/v2/ac/tag/' + input, + success: function (result) { + var result = result.records; + for (var i = 0; i < result.length; i++) { + arr.push(result[i]); + } + this.setState({ suggestions: arr }); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to get autocomplete data for tag', data); + }.bind(this) + }); + }, + handleDelete: function handleDelete() { + //blank since buttons are handled outside of this + }, + handleDrag: function handleDrag() { + //blank since buttons are handled outside of this + }, + render: function render() { + var suggestions = this.state.suggestions; + return React.createElement( + 'span', + { className: 'tag-new' }, + React.createElement(ReactTags, { + suggestions: suggestions, + handleAddition: this.handleAddition, + handleDelete: this.handleDelete, + handleDrag: this.handleDrag, + handleInputChange: this.handleInputChange, + minQueryLength: 1, + customCSS: 1 }) + ); + } +}); + +module.exports = Tag; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-tag-input":901}],30:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); + +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; +var Task = React.createClass({ + displayName: 'Task', + + getInitialState: function getInitialState() { + return { + key: this.props.id, + whoami: undefined + }; + }, + + componentDidMount: function componentDidMount() { + var whoami = getSessionStorage('whoami'); + this.setState({ whoami: whoami }); + }, + + makeTask: function makeTask() { + var json = { 'make_task': 1 }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/entry/' + this.props.entryid, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to close task', data); + }.bind(this) + }); + }, + closeTask: function closeTask() { + var json = { 'close_task': 1 }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/entry/' + this.props.entryid, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to close task', data); + }.bind(this) + }); + }, + takeTask: function takeTask() { + var json = { 'take_task': 1 }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/entry/' + this.props.entryid, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to make Task owner', data); + }.bind(this) + }); + }, + render: function render() { + var taskDisplay = 'Task Loading...'; + var onClick; + if (this.props.taskData.class == 'task') { + if (this.props.taskData.metadata.task.status === undefined || this.props.taskData.metadata.task.status === null || this.props.taskData.class != 'task') { + taskDisplay = 'Make Task'; + onClick = this.makeTask; + } else if (this.state.whoami != this.props.taskData.metadata.task.who && this.props.taskData.metadata.task.status == 'open') { + taskDisplay = 'Assign task to me'; + onClick = this.takeTask; + } else if (this.state.whoami == this.props.taskData.metadata.task.who && this.props.taskData.metadata.task.status == 'open') { + taskDisplay = 'Close Task'; + onClick = this.closeTask; + } else if (this.props.taskData.metadata.task.status == 'closed' || this.props.taskData.metadata.task.status == 'completed') { + taskDisplay = 'Reopen Task'; + onClick = this.makeTask; + } else if (this.state.whoami == this.props.taskData.metadata.task.who && this.props.taskData.metadata.task.status == 'assigned') { + taskDisplay = 'Close Task'; + onClick = this.closeTask; + } else if (this.state.whoami != this.props.taskData.metadata.task.who && this.props.taskData.metadata.task.status == 'assigned') { + taskDisplay = 'Assign task to me'; + onClick = this.takeTask; + } + } else { + taskDisplay = 'Make Task'; + onClick = this.makeTask; + } + return React.createElement( + 'span', + { style: { display: 'block' }, onClick: onClick }, + taskDisplay + ); + } +}); + +module.exports = Task; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839}],31:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); +var Dropdown = require('react-bootstrap/lib/Dropdown'); +var MenuItem = require('react-bootstrap/lib/MenuItem'); +var DropdownToggle = require("react-bootstrap/lib/DropdownToggle"); +var DropdownMenu = require("react-bootstrap/lib/DropdownMenu"); +var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger'); +var Tooltip = require('react-bootstrap/lib/Tooltip'); + +var TrafficLightProtocol = React.createClass({ + displayName: 'TrafficLightProtocol', + + + selectColor: function selectColor(e) { + var data = { 'tlp': e }; + this.serverRequest = $.ajax({ + type: 'put', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id + '/', + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('set tlp'); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to set TLP', data); + }.bind(this) + }); + //this.setState({ color: e }); + }, + + render: function render() { + return React.createElement( + 'span', + { style: { padding: this.props.type == 'entry' ? '3px 20px' : null } }, + React.createElement( + OverlayTrigger, + { placement: 'top', overlay: React.createElement( + Tooltip, + { id: 'tlp-tooltip' }, + this.props.tlp + ) }, + React.createElement( + Dropdown, + { bsSize: 'xsmall', bsStyle: { padding: this.props.type == 'entry' ? '3px 20px' : null } }, + React.createElement( + DropdownToggle, + null, + React.createElement( + 'svg', + { id: 'trafficlight1', style: { width: '12px', height: '12px' } }, + React.createElement('circle', { id: 'circle1', r: '5', cx: '6', cy: '6', style: { fill: this.props.tlp == 'red' || this.props.tlp == 'white' ? this.props.tlp : 'gray', stroke: 'black', strokeWidth: '2' } }) + ), + React.createElement( + 'svg', + { id: 'trafficlight2', style: { width: '12px', height: '12px' } }, + React.createElement('circle', { id: 'circle2', r: '5', cx: '6', cy: '6', style: { fill: this.props.tlp == 'amber' && this.props.tlp != 'white' ? 'orange' : this.props.tlp == 'white' ? 'white' : 'gray', stroke: 'black', strokeWidth: '2' } }) + ), + React.createElement( + 'svg', + { id: 'trafficlight2', style: { width: '12px', height: '12px' } }, + React.createElement('circle', { id: 'circle3', r: '5', cx: '6', cy: '6', style: { fill: this.props.tlp == 'green' || this.props.tlp == 'white' ? this.props.tlp : 'gray', stroke: 'black', strokeWidth: '2' } }) + ) + ), + React.createElement( + DropdownMenu, + null, + React.createElement( + MenuItem, + { header: true }, + 'Traffic Light Protocol (TLP) Color' + ), + React.createElement( + MenuItem, + { eventKey: 'unset', onSelect: this.selectColor }, + 'Unset' + ), + React.createElement( + MenuItem, + { eventKey: 'red', onSelect: this.selectColor }, + 'Red' + ), + React.createElement( + MenuItem, + { eventKey: 'amber', onSelect: this.selectColor }, + 'Amber' + ), + React.createElement( + MenuItem, + { eventKey: 'green', onSelect: this.selectColor }, + 'Green' + ), + React.createElement( + MenuItem, + { eventKey: 'white', onSelect: this.selectColor }, + 'White' + ), + React.createElement(MenuItem, { divider: true }), + React.createElement( + MenuItem, + { href: 'https://www.us-cert.gov/tlp' }, + 'What is TLP?' + ) + ) + ) + ) + ); + } +}); + +module.exports = TrafficLightProtocol; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-bootstrap/lib/Dropdown":538,"react-bootstrap/lib/DropdownMenu":540,"react-bootstrap/lib/DropdownToggle":541,"react-bootstrap/lib/MenuItem":566,"react-bootstrap/lib/OverlayTrigger":582,"react-bootstrap/lib/Tooltip":606}],32:[function(require,module,exports){ +var BoundingBox, Vec; + +Vec = require('./vec'); + +BoundingBox = (function() { + function BoundingBox(x, y, w, h) { + this.x = x != null ? x : 0; + this.y = y != null ? y : 0; + this.w = w != null ? w : 0; + this.h = h != null ? h : 0; + } + + BoundingBox.prototype.containing = function(pts) { + var i, len, max_x, max_y, pt, ref; + this.x = pts[0].x(); + this.y = pts[0].y(); + this.w = 0; + this.h = 0; + max_x = pts[0].x(); + max_y = pts[0].y(); + ref = pts.slice(1); + for (i = 0, len = ref.length; i < len; i++) { + pt = ref[i]; + if (pt.x() < this.x) { + this.x = pt.x(); + } + if (pt.y() < this.y) { + this.y = pt.y(); + } + if (pt.x() > max_x) { + max_x = pt.x(); + } + if (pt.y() > max_y) { + max_y = pt.y(); + } + } + this.w = max_x - this.x; + this.h = max_y - this.y; + return this; + }; + + BoundingBox.prototype.ul = function() { + return new Vec([this.x, this.y]); + }; + + BoundingBox.prototype.left = function() { + return this.x; + }; + + BoundingBox.prototype.right = function() { + return this.x + this.w; + }; + + BoundingBox.prototype.top = function() { + return this.y; + }; + + BoundingBox.prototype.bottom = function() { + return this.y + this.h; + }; + + BoundingBox.prototype.lr = function() { + return new Vec([this.x + this.w, this.y + this.h]); + }; + + BoundingBox.prototype.contains = function(pt) { + var ref, ref1; + return ((this.x <= (ref = pt.x()) && ref <= this.x + this.w)) && ((this.y <= (ref1 = pt.y()) && ref1 <= this.y + this.h)); + }; + + BoundingBox.prototype.bbox = function() { + return this; + }; + + return BoundingBox; + +})(); + +module.exports = BoundingBox; + + +},{"./vec":36}],33:[function(require,module,exports){ +var Edge, Vec; + +Vec = require('./vec'); + +Edge = (function() { + function Edge(p11, p21) { + this.p1 = p11; + this.p2 = p21; + } + + Edge.prototype.norm = function() { + return (this.p2.sub(this.p1)).norm(); + }; + + Edge.prototype.crosses = function(edge) { + return ((edge.p1.edgetest(this)) !== edge.p2.edgetest(this)) && ((this.p1.edgetest(edge)) !== this.p2.edgetest(edge)); + }; + + Edge.prototype.contains = function(pt) { + var me, ratio, v1; + v1 = pt.sub(this.p1); + me = this.p2.sub(this.p1); + ratio = (v1.nth(0)) / (me.nth(0)); + return (flte(0, ratio)) && (flte(ratio, 1)) && (me.scale(ratio)).eq(v1); + }; + + Edge.prototype.direction = function() { + return this.p2.sub(this.p1); + }; + + Edge.prototype.parallel = function(edge) { + return feq(1, this.direction().normalize().dot(edge.direction().normalize())); + }; + + Edge.prototype.intersection = function(edge) { + var denom, n1, n2, p1, p2, ref, ref1, x1, x2, x3, x4, y1, y2, y3, y4; + if (this.parallel(edge)) { + return void 0; + } + ref = [this.p1.nth(0), this.p1.nth(1), this.p2.nth(0), this.p2.nth(1)], x1 = ref[0], y1 = ref[1], x2 = ref[2], y2 = ref[3]; + ref1 = [edge.p1.nth(0), edge.p1.nth(1), edge.p2.nth(0), edge.p2.nth(1)], x3 = ref1[0], y3 = ref1[1], x4 = ref1[2], y4 = ref1[3]; + denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + n1 = x1 * y2 - y1 * x2; + n2 = x3 * y4 - y3 * x4; + p1 = (n1 * (x3 - x4) - (x1 - x2) * n2) / denom; + p2 = (n1 * (y3 - y4) - (y1 - y2) * n2) / denom; + return new Vec([p1, p2]); + }; + + return Edge; + +})(); + +module.exports = Edge; + + +},{"./vec":36}],34:[function(require,module,exports){ +var feps, feq, fgt, fgte, flt, flte, fnz, fzero; + +feps = 0.0000001; + +feq = function(a, b) { + return (Math.abs(a - b)) < feps; +}; + +fgt = function(a, b) { + return (a - b) > feps; +}; + +fgte = function(a, b) { + return ((a - b) > feps) || (feq(a, b)); +}; + +flt = function(a, b) { + return fgt(b, a); +}; + +flte = function(a, b) { + return fgte(b, a); +}; + +fnz = function(a) { + return !fzero(a); +}; + +fzero = function(a) { + return feq(a, 0); +}; + +module.exports = { + feps: feps, + feq: feq, + fgt: fgt, + fgte: fgte, + flt: flt, + flte: flte, + fnz: fnz, + fzero: fzero +}; + + +},{}],35:[function(require,module,exports){ +var BoundingBox, Edge, Polygon, Shell, Vec, fgt, flt, polygon, ref; + +Shell = require('../ui/shell'); + +Vec = require('./vec'); + +BoundingBox = require('./boundingbox'); + +Edge = require('./edge'); + +ref = require('./eps'), fgt = ref.fgt, flt = ref.flt; + +polygon = function(pts) { + return new Polygon(pts.map(function(p) { + return new Vec(p); + })); +}; + +Polygon = (function() { + function Polygon(verts) { + this.verts = verts.slice(0); + } + + Polygon.prototype.edges = function() { + var i, k, ref1, results; + results = []; + for (i = k = 0, ref1 = this.verts.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) { + results.push(new Edge(this.verts[i], this.verts[(i + 1) % this.verts.length])); + } + return results; + }; + + Polygon.prototype.contains = function(pt) { + var count, i, j, k, ref1, xdesc; + count = 0; + for (i = k = 0, ref1 = this.verts.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) { + j = (i + 1) % this.verts.length; + xdesc = (this.verts[j].x() - this.verts[i].x()) * (pt.y() - this.verts[i].y()) / (this.verts[j].y() - this.verts[i].y()) + this.verts[i].x(); + if (((fgt(this.verts[i].y(), pt.y())) !== (fgt(this.verts[j].y(), pt.y()))) && (flt(pt.x(), xdesc))) { + count++; + } + } + return (count % 2) !== 0; + }; + + Polygon.prototype.containsEdge = function(edge) { + var e, k, len, ref1; + if (!this.contains(edge.p1)) { + return false; + } + ref1 = this.edges(); + for (k = 0, len = ref1.length; k < len; k++) { + e = ref1[k]; + if (e.crosses(edge)) { + return false; + } + } + return true; + }; + + Polygon.prototype.containsPoly = function(poly) { + var e, k, len, ref1; + ref1 = poly.edges(); + for (k = 0, len = ref1.length; k < len; k++) { + e = ref1[k]; + if (!this.containsEdge(e)) { + return false; + } + } + return true; + }; + + Polygon.prototype.center = function() { + var cx, cy, k, len, pt, ref1; + cx = 0; + cy = 0; + ref1 = this.verts; + for (k = 0, len = ref1.length; k < len; k++) { + pt = ref1[k]; + cx += pt.x(); + cy += pt.y(); + } + cx /= this.verts.length; + cy /= this.verts.length; + return new Vec([cx, cy]); + }; + + Polygon.prototype.toPbool = function() { + var v; + return { + regions: [ + (function() { + var k, len, ref1, results; + ref1 = this.verts; + results = []; + for (k = 0, len = ref1.length; k < len; k++) { + v = ref1[k]; + results.push([v.x(), v.y()]); + } + return results; + }).call(this) + ], + inverted: false + }; + }; + + Polygon.fromPbool = function(pb) { + var k, len, ref1, region, results; + ref1 = pb.regions; + results = []; + for (k = 0, len = ref1.length; k < len; k++) { + region = ref1[k]; + results.push(polygon(region)); + } + return results; + }; + + Polygon.prototype.intersect = function(poly) { + return Polygon.fromPbool(PolyBool.intersect(poly.toPbool(), this.toPbool())); + }; + + Polygon.prototype.union = function(poly) { + return Polygon.fromPbool(PolyBool.union(poly.toPbool(), this.toPbool())); + }; + + Polygon.prototype.trim = function(poly) { + return (this.intersect(poly))[0]; + }; + + Polygon.prototype.subtract = function(poly) { + return Polygon.fromPbool(PolyBool.difference(poly.toPbool(), this.toPbool())); + }; + + Polygon.prototype.xor = function(poly) { + return Polygon.fromPBool(PolyBool.difference(poly.toPbool(), this.toPbool())); + }; + + Polygon.prototype.bbox = function() { + if (this.bounds) { + return this.bounds; + } else { + this.bounds = new BoundingBox().containing(this.verts); + return this.bounds; + } + }; + + Polygon.prototype.scale = function(factor) { + var vert; + this.verts = (function() { + var k, len, ref1, results; + ref1 = this.verts; + results = []; + for (k = 0, len = ref1.length; k < len; k++) { + vert = ref1[k]; + results.push(vert.scale(factor)); + } + return results; + }).call(this); + return this; + }; + + return Polygon; + +})(); + +module.exports = { + Polygon: Polygon, + polygon: polygon +}; + + +},{"../ui/shell":50,"./boundingbox":32,"./edge":33,"./eps":34,"./vec":36}],36:[function(require,module,exports){ +var Vec; + +Vec = (function() { + function Vec(coords) { + this.coords = coords.slice(0); + } + + Vec.prototype.add = function(other) { + var i; + return new Vec((function() { + var j, ref, results; + results = []; + for (i = j = 0, ref = this.coords.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + results.push((other.nth(i)) + (this.nth(i))); + } + return results; + }).call(this)); + }; + + Vec.prototype.sub = function(other) { + var i; + return new Vec((function() { + var j, ref, results; + results = []; + for (i = j = 0, ref = this.coords.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + results.push((this.nth(i)) - (other.nth(i))); + } + return results; + }).call(this)); + }; + + Vec.prototype.dot = function(other) { + var i; + return ((function() { + var j, ref, results; + results = []; + for (i = j = 0, ref = this.coords.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + results.push((this.nth(i)) * (other.nth(i))); + } + return results; + }).call(this)).reduce(function(a, b) { + return a + b; + }); + }; + + Vec.prototype.norm = function() { + return this.dot(this); + }; + + Vec.prototype.normalize = function() { + return this.scale(1.0 / (this.norm())); + }; + + Vec.prototype.scale = function(f) { + var x; + return new Vec((function() { + var j, len, ref, results; + ref = this.coords; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + x = ref[j]; + results.push(f * x); + } + return results; + }).call(this)); + }; + + Vec.prototype.x = function() { + return this.nth(0); + }; + + Vec.prototype.y = function() { + return this.nth(1); + }; + + Vec.prototype.z = function() { + return this.nth(2); + }; + + Vec.prototype.w = function() { + return this.nth(3); + }; + + Vec.prototype.dim = function() { + return this.coords.length; + }; + + Vec.prototype.nth = function(n) { + if (n >= this.coords.length) { + throw "Error: out of bounds access on vector"; + } else { + return this.coords[n]; + } + }; + + Vec.prototype.cross2 = function(other) { + return ((this.nth(1)) * (other.nth(0))) - ((this.nth(0)) * (other.nth(1))); + }; + + Vec.prototype.eq = function(other) { + var i, j, ref; + for (i = j = 0, ref = this.coords.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + if (!feq(this.nth(i), other.nth(i))) { + return false; + } + } + return true; + }; + + Vec.prototype.edgetest = function(edge) { + var anchor, result, test; + anchor = edge.p2.sub(edge.p1); + test = this.sub(edge.p1); + result = anchor.cross2(test); + switch (false) { + case !flt(result, 0): + return -1; + case !fgt(result, 0): + return 1; + case !feq(result, 0): + return 0; + } + }; + + Vec.prototype.leftof = function(edge) { + return (this.edgetest(edge)) < 0; + }; + + Vec.prototype.rightof = function(edge) { + return (this.edgetest(edge)) > 0; + }; + + Vec.prototype.colinear = function(edge) { + return (this.edgetest(edge)) === 0; + }; + + return Vec; + +})(); + +module.exports = Vec; + + +},{}],37:[function(require,module,exports){ +var Polygon, Voronoi, polygon, ref; + +ref = require('./polygon'), polygon = ref.polygon, Polygon = ref.Polygon; + +Voronoi = (function() { + function Voronoi(points, boundary) { + this.points = points; + this.setBoundary(boundary); + } + + Voronoi.prototype.addCell = function(pt) { + if (!this.boundary || (this.boundary && this.boundary.contains(pt))) { + this.points.push(pt); + } else { + throw "Error - can't add point outside voronoi diagram boundary!"; + } + return this; + }; + + Voronoi.prototype.setBoundary = function(poly) { + var i, len, pt, ref1; + this.boundary = poly; + if (this.boundary) { + ref1 = this.points; + for (i = 0, len = ref1.length; i < len; i++) { + pt = ref1[i]; + if (!(this.boundary.contains(pt))) { + throw "Error - new voronoi diagram boundary doesn't contain all points!"; + } + } + } + return this; + }; + + Voronoi.prototype.layout = function() { + var bbox, i, len, poly, polys, trimmed; + bbox = this.boundary.bbox(); + this.polygons = []; + polys = d3.voronoi().extent([bbox.ul().coords, bbox.lr().coords]).polygons(this.points.map(function(pt) { + return pt.coords; + })).map(function(pts) { + return polygon(pts); + }); + console.log("polygons in voronoi: " + JSON.stringify(polys)); + if (this.boundary && (this.boundary instanceof Polygon)) { + for (i = 0, len = polys.length; i < len; i++) { + poly = polys[i]; + trimmed = poly.trim(this.boundary); + if (trimmed) { + this.polygons.push(trimmed); + } + } + } else { + this.polygons = polys; + } + return this; + }; + + Voronoi.prototype.drawable = function() { + return { + polygons: this.polygons + }; + }; + + return Voronoi; + +})(); + +module.exports = Voronoi; + + +},{"./polygon":35}],38:[function(require,module,exports){ +var API, Barchart, BaseCommands, BoundingBox, Dotchart, Edge, Editor, Eps, Forcegraph, Http, Linechart, List, Nspace, Poly, Polygon, Preview, React, Result, ResultPromise, Revl, ScriptEditor, Shell, Strings, Struct, Utils, Vec, Visualization, Voronoi, polygon, ref, ref1, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Editor = require('./ui/editor'); + +Preview = require('./ui/preview'); + +Visualization = require('./ui/visualization'); + +Shell = require('./ui/shell'); + +BaseCommands = require('./ui/base-commands'); + +Barchart = require('./viz/barchart'); + +Linechart = require('./viz/linechart'); + +Dotchart = require('./viz/dotchart'); + +Forcegraph = require('./viz/forcegraph'); + +Poly = require('./viz/poly'); + +Nspace = require('./space/nspace'); + +ref = require('./geometry/polygon'), Polygon = ref.Polygon, polygon = ref.polygon; + +Edge = require('./geometry/edge'); + +BoundingBox = require('./geometry/boundingbox'); + +Voronoi = require('./geometry/voronoi'); + +Eps = require('./geometry/eps'); + +Vec = require('./geometry/vec'); + +List = require('./utils/list'); + +Struct = require('./utils/struct'); + +Http = require('./utils/http'); + +Utils = require('./utils/utils'); + +Strings = require('./utils/strings'); + +API = require('./utils/api'); + +ref1 = require('./utils/result'), Result = ref1.Result, ResultPromise = ref1.ResultPromise; + +ScriptEditor = require('./ui/script-editor'); + +Revl = (function(superClass) { + extend(Revl, superClass); + + function Revl(props) { + Revl.__super__.constructor.call(this, props); + this.shell = new Shell(this.output.bind(this), this); + this.shell.addCommands(BaseCommands); + this.shell.addCommands(Barchart.commands); + this.shell.addCommands(Dotchart.commands); + this.shell.addCommands(Linechart.commands); + this.shell.addCommands(Forcegraph.commands); + this.shell.addCommands(Poly.commands); + this.shell.addCommands(Http.commands); + this.shell.addCommands(Nspace.commands); + this.shell.addCommands(Voronoi.commands); + this.shell.addCommands(Strings.commands); + this.shell.addCommands(API.commands); + this.shell.addCommands(Result.commands); + this.shell.addCommands(ResultPromise.commands); + this.shell.addScope(List); + this.shell.addScope(Polygon.scope); + this.shell.addScope(Eps); + this.shell.addScope({ + Struct: Struct, + Vec: Vec, + Poly: Poly, + Voronoi: Voronoi, + Pgon: Polygon, + polygon: polygon, + Http: Http, + Edge: Edge, + BBox: BoundingBox, + Utils: Utils, + Strings: Strings, + Nspace: Nspace, + API: API, + Result: Result, + ResultPromise: ResultPromise + }); + this.shell.loadSavedData(); + this.state = { + script_display: "none", + script_data: {}, + script_name: '', + script: { + body: void 0, + help: void 0 + } + }; + Revl.revl = this; + } + + Revl.prototype.output = function(str) { + if (this.refs.editor) { + return this.refs.editor.output(str); + } else { + console.log("Editor undefined"); + return console.log(str); + } + }; + + Revl.prototype.render = function() { + var div; + div = React.DOM.div; + return div({ + tabIndex: 0, + id: "revl", + style: { + position: 'absolute', + top: '5vh', + bottom: 0, + right: 0, + left: 0, + height: '95vh', + width: '100vw' + } + }, [ + Visualization({ + key: 2, + revl: this, + ref: 'visualization' + }), Editor({ + key: 0, + shell: this.shell, + revl: this, + ref: 'editor' + }), ScriptEditor({ + key: 1, + data: this.state.script_data, + shell: this.shell, + revl: this, + ref: 'script_editor', + initialScript: this.state.script, + initialName: this.state.script_name, + display: this.state.script_display + }) + ]); + }; + + Revl.prototype.showScriptEditor = function(data, script, initialName) { + console.log("Show editor for " + (JSON.stringify(script))); + this.setState({ + script: script, + script_name: initialName, + script_display: "block", + script_data: data + }); + return Result.wrap("Script editor active"); + }; + + Revl.prototype.hideScriptEditor = function() { + return this.setState({ + script_display: "none" + }); + }; + + Revl.commands = {}; + + return Revl; + +})(React.Component); + +module.exports = React.createFactory(Revl); + +console.log("revl exports: " + (Object.keys(module.exports))); + +console.log("revl Revl export: " + module.exports.Revl); + + +},{"./geometry/boundingbox":32,"./geometry/edge":33,"./geometry/eps":34,"./geometry/polygon":35,"./geometry/vec":36,"./geometry/voronoi":37,"./space/nspace":39,"./ui/base-commands":40,"./ui/editor":42,"./ui/preview":45,"./ui/script-editor":48,"./ui/shell":50,"./ui/visualization":51,"./utils/api":52,"./utils/http":53,"./utils/list":54,"./utils/result":55,"./utils/strings":56,"./utils/struct":57,"./utils/utils":58,"./viz/barchart":59,"./viz/dotchart":60,"./viz/forcegraph":61,"./viz/linechart":62,"./viz/poly":63,"react":983}],39:[function(require,module,exports){ +var Nspace, Vec, feq, fgt, fgte, fle, fzero, ref; + +Vec = require('../geometry/vec'); + +ref = require('../geometry/eps'), feq = ref.feq, fzero = ref.fzero, fgt = ref.fgt, fgte = ref.fgte, fle = ref.fle; + +Nspace = (function() { + var Node; + + Nspace.MaxLoad = 5; + + Nspace.Node = Node = (function() { + function Node(bounds) { + this.bounds = bounds.slice(0); + this.items = []; + this.childpaths = {}; + this.childlist = []; + } + + Node.prototype.insert = function(item, vec) { + if (!this.contains(vec)) { + return; + } + if (this.children().length !== 0) { + return (this.getChildFor(vec)).insert(item, vec); + } else { + this.items.push([item, vec]); + if (this.items.length >= Nspace.MaxLoad) { + return this.split(); + } + } + }; + + Node.prototype.split = function() { + var coords, item, j, len, ref1, ref2; + ref1 = this.items; + for (j = 0, len = ref1.length; j < len; j++) { + ref2 = ref1[j], item = ref2[0], coords = ref2[1]; + (this.getChildFor(coords)).insert(item, coords); + } + return this.items = []; + }; + + Node.prototype.low = function(i) { + return this.bounds[i][0]; + }; + + Node.prototype.high = function(i) { + return this.bounds[i][1]; + }; + + Node.prototype.getChildFor = function(vec) { + var i, j, newbound, ref1, ref2, section; + section = this.childpaths; + newbound = []; + for (i = j = 0, ref1 = vec.dim(); 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + if (((this.low(i)) <= (ref2 = vec.nth(i)) && ref2 < ((this.low(i)) + (this.high(i))) / 2)) { + if (section.low == null) { + section.low = {}; + } + section = section.low; + newbound.push([this.low(i), ((this.low(i)) + (this.high(i))) / 2]); + } else { + if (section.high == null) { + section.high = {}; + } + section = section.high; + newbound.push([((this.low(i)) + (this.high(i))) / 2, this.high(i)]); + } + } + if ((typeof section.node) === "undefined") { + section.node = new Nspace.Node(newbound); + this.childlist.push(section.node); + } + return section.node; + }; + + Node.prototype.contains = function(vec) { + var i, j, ref1, ref2; + for (i = j = 0, ref1 = vec.dim(); 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + if (!(((this.low(i)) <= (ref2 = vec.nth(i)) && ref2 <= (this.high(i))))) { + return false; + } + } + return true; + }; + + Node.prototype.leaves = function() { + var child; + if (this.children().length !== 0) { + return [].concat.apply([], (function() { + var j, len, ref1, results; + ref1 = this.children(); + results = []; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + results.push(child.leaves()); + } + return results; + }).call(this)); + } else { + return [this]; + } + }; + + Node.prototype.children = function() { + return this.childlist; + }; + + return Node; + + })(); + + function Nspace() { + this.coord_index = {}; + this.lowbound = 0; + this.highbound = 0; + this.nextdim = 0; + this.items = []; + } + + Nspace.prototype.insert = function(item, coords) { + var base, coord, j, len, name, results; + this.items.push([item, coords]); + results = []; + for (j = 0, len = coords.length; j < len; j++) { + coord = coords[j]; + if ((base = this.coord_index)[name = coord[0]] == null) { + base[name] = this.nextdim++; + } + results.push(this.updatebounds(coord)); + } + return results; + }; + + Nspace.prototype.updatebounds = function(coord) { + var results; + if (coord[1] < this.lowbound) { + this.lowbound = coord[1]; + } + if (coord[1] > this.highbound) { + this.highbound = coord[1]; + } + results = []; + while (feq(this.lowbound, this.highbound)) { + this.lowbound -= Math.random(); + results.push(this.highbound += Math.random()); + } + return results; + }; + + Nspace.prototype.subdivide = function() { + var b, bounds, coord, coords, i, item, j, k, len, len1, ref1, ref2; + bounds = (function() { + var j, ref1, results; + results = []; + for (i = j = 0, ref1 = this.nextdim; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + results.push([this.lowbound, this.highbound]); + } + return results; + }).call(this); + this.root = new Nspace.Node(bounds); + ref1 = this.items; + for (j = 0, len = ref1.length; j < len; j++) { + item = ref1[j]; + coords = (function() { + var k, len1, results; + results = []; + for (k = 0, len1 = bounds.length; k < len1; k++) { + b = bounds[k]; + results.push(0); + } + return results; + })(); + ref2 = item[1]; + for (k = 0, len1 = ref2.length; k < len1; k++) { + coord = ref2[k]; + coords[this.coord_index[coord[0]]] = coord[1]; + } + this.root.insert(item, new Vec(coords)); + } + this.items = void 0; + return this; + }; + + Nspace.prototype.leaves = function() { + return this.root.leaves(); + }; + + Nspace.commands = { + help__Nspace: function() { + return "Nspace (class)\n\nNspace is a space partitioning tree that works in an\narbitrary number of dimensions. Its purpose is to make it\neasy to take vectors of high-dimensional data and find\nwhich ones are close together (i.e. spatial clustering),\nand to do other high-dimensional spatial calculations (find\nitems within a distance of some point, within a bounding\nbox, intersecting some polytope, etc).\n\nThe main mode of use is as an accumulator on the command\nline in the fold commands (foldl, foldr). It allows you to\nbuild up the high-dimensional space incrementally by just\ninserting data points. Each data point is represented as a\nlist of pairs, where the first element of the pair is the\n*name* of the coordinate (more on this later), and the\nsecond element is the value of the coordinate. For example,\nif you are just using the standard 3d coordinate system,\nyou could use something like this:\n\n [item1, [[x,1],[y,33],[z,-10]]]\n\nThe power of this representation is that it allows you to\nuse an arbitrary naming scheme for your coordinates. Let's\nsay you want to cluster a large collection of messages\naccording to the domain names that are harvested from them\nas flair in SCOT. You could just decide that each domain\nname will be a coordinate, and pass in points as the data\nelement followed by the list of domains it references, with\nones for the values:\n \n [msg1, [[\"foo.com\",1],[\"bar.com\",1],[\"baz.com\",1]]]\n \nNot all messages will reference all domains (obviously),\nbut you don't have to try to precompute the full set of\ndomains because the Nspace will accumulate them for you. If\nyour message set references 100 domains in total, but any\ngiven message only references two or three, then the Nspace\nwill have 100 dimensions after the inserts are\ncomplete. Each coordinate that is not defined for an\ninserted item is set to zero automatically.\n\nThe downside of this incremental load process is that you\nhave to wait until all of your inserts are done, then call\nthe 'subdivide' function in order to actually build the\ndata structure. In practice, this adds one more element to\nthe pipeline in your command.\n\nHere is a command you can try that uses Nspace to draw a\nquadtree based on random data:\n\n [1..100] \\\n foldl new Nspace (s,pt) -> s.insert pt,[['x',Math.random()],['y',Math.random()]]; s \\\n (s)->s.subdivide() \\\n (sp)->sp.leaves() \\\n (l)->l.bounds \\\n (bnd)->List.zip bnd \\\n (pts)->[[pts[0][0],pts[0][1]],[pts[0][0],pts[1][1]],[pts[1][0],pts[1][1]],[pts[1][0],pts[0][1]]] \\\n (pts)->(polygon pts).scale 200 \\\n into (polys)->{polygons: polys} \\\n draw\n\n This command starts by generating a list of length 100,\n then converts that into a list of 100 points. Each point\n has its index number for data, and randomly generated 'x'\n and 'y' coordinates.\n\n The points are inserted into an empty Nspace object using\n the foldl command.\n\n The resulting data structure is finalized using the ()->\n map construct to call subdivide()\n\n The leaf nodes are collected (these are the only nodes\n with actual data)\n\n The bounds of each leaf node are found (this gives a lower\n and upper bound on each coordinate dimension)\n\n The bounds lists are re-zipped so that they become a\n lower-left corner and upper right corner\n ([[x_low,x_high],[y_low,y_high]] => [[x_low,y_low],[x_high,y_high]])\n\n The remaining corners of a square are created by copying\n the appropriate parts of the lower-left and upper-right\n corners into a lower-right and upper-left.\n\n Polygons are created from those point lists, and scaled up\n by a factor of 200 to make them visible\n\n The list of polygons is converted into a drawable object\n (basically just put a list of polygons into an object\n under the name 'polygons')\n\n Finally, the whole mess is piped into the draw function,\n which puts a colorful rendering of the tree on screen.\n\n This object is designed to be used with dimensionality\n reduction code, see 'help pca' for more details."; + } + }; + + return Nspace; + +})(); + +module.exports = Nspace; + + +},{"../geometry/eps":34,"../geometry/vec":36}],40:[function(require,module,exports){ +var BaseCommands, List, Result, ResultPromise, Struct, Utils, ref, + hasProp = {}.hasOwnProperty; + +Utils = require('../utils/utils'); + +List = require('../utils/list'); + +Struct = require('../utils/struct'); + +ref = require('../utils/result'), Result = ref.Result, ResultPromise = ref.ResultPromise; + +BaseCommands = { + help__into: function() { + return "into <function>\n \nTake the input and apply the function directly to it,\nregardless of its internal format. Normally, data is checked\nto see if it is list-like or not before deciding what the\nbehavior of map and fold, etc should be. In this case, you're\nsaying that you just want whatever the contents of the data is\nto be handed to you directly in one piece.\n\nExample:\n $ [1,2,3] \\ into (f) -> 12\n 12\nWithout into:\n $ [1,2,3] \\ (f)->12\n [12,12,12]"; + }, + into: (function(_this) { + return function(argv, d, ctx) { + console.log("into(proc)"); + return Utils.parsefunction(argv.join(" "), ctx).and_then(function(proc) { + var e; + try { + return Result.wrap(proc(d)); + } catch (error) { + e = error; + console.log("exception " + e); + return Result.err('' + e); + } + }).map_err(function(e) { + console.log("error"); + return Result.err("into(proc): " + e); + }); + }; + })(this), + help__map: function() { + return "map <function>\n\nMap applies the given function to the data. If the data is an\narray (list), map will apply the function to each element of\nthe list and return a list containing the results. If the data\nis an object, proc will be called on each item in the struct\nwith the value and the key as args (yes, in that order - this\nway you can ignore the key most times, which is what you\nprobably want).\n\n\nExample:\n $ [1,2,3,4] \\ map (n) -> n*2\n [2,4,6,8]\n $ {foo: 12} \\ map (v,k) -> v*9\n {foo: 108}"; + }, + map: (function(_this) { + return function(argv, ls, ctx) { + console.log("map(proc)"); + return Utils.parsefunction(argv.join(" "), ctx).and_then(function(proc) { + var e; + try { + if (Utils.isArray(ls)) { + return Result.wrap(List.map(ls, proc)); + } else if (Utils.isObject(ls)) { + return Result.wrap(Struct.map(ls, proc)); + } else { + return Result.wrap(proc(ls)); + } + } catch (error) { + e = error; + return Result.err('' + e); + } + }).map_err(function(msg) { + return "map(proc): " + msg; + }); + }; + })(this), + help__tolist: function() { + return "tolist\n\nConvert a struct to a list. If argument is a list, it will be\nunchanged. The result is a list of pairs, where the first\nelement of each pair is the key for an item in the struct, and\nthe second element is the value associated with that key.\n\nExample:\n $ {a: 1, b: 2} \\ tolist\n [[a,1],[b,2]]"; + }, + tolist: (function(_this) { + return function(argv, d, ctx) { + return Result.wrap(Struct.tolist(d)); + }; + })(this), + help__tostruct: function() { + return "tostruct\n\nConvert a list of pairs into an object (struct) that has an\nentry for each pair in the list. The keys will be the first\nelements of each pair, and the values will be the second\nelements. In other words, create a struct from an association\nlist.\n\nExample:\n $ [[1,'a'],['b',2]] \\ tostruct\n {1: 'a', b: 2}"; + }, + tostruct: (function(_this) { + return function(argv, d, ctx) { + return Result.wrap(List.tostruct(d)); + }; + })(this), + help__mapall: function() { + return "mapall function\n \nMapall works on a list of lists. It will proceed through all\nsublists in parallel, taking the next element of each sublist and\nproviding them in order as arguments to a single call of the\nfunction. The resulting value will be appended to the final\nresult, which will be a single list of the same length as one of\nthe sublists. This is hard to explain in words, so here are some\nexamples:\n \n $ [[1,2,3],[1,2,3],[1,2,3]] \\ mapall (a,b,c) -> [a,b,c]\n [[1,1,1],[2,2,2],[3,3,3]]\n \n $ [[1,2,3],[1,2,3],[1,2,3]] \\ mapall (a,b,c) -> a+b+c\n [3,6,9]\n \n $ [[1,2,3],[1,2,3],[1,2,3]] \\ mapall (args...) -> args\n [[1,1,1],[2,2,2],[3,3,3]]"; + }, + mapall: (function(_this) { + return function(argv, ls, ctx) { + console.log("mapall"); + return Utils.parsefunction(argv.join(" "), ctx).and_then(function(proc) { + var e; + try { + return Result.wrap(List.mapall(ls, proc)); + } catch (error) { + e = error; + return Result.err('' + e); + } + }).map_err(function(msg) { + return "mapall(proc): " + msg; + }); + }; + })(this), + help__filter: function() { + return "filter function\n\nFilter calls the given function on each element of the data\nlist and only adds the element to the output list if the\nresult is truthy (i.e. not false).\n\nExample:\n $ [1,2,3] \\ filter (n) -> n>=2\n [2,3]"; + }, + filter: (function(_this) { + return function(argv, ls, ctx) { + return Utils.parsefunction(argv.join(" "), ctx).and_then(function(proc) { + if (Utils.isArray(ls)) { + return Result.wrap(List.filter(ls, proc)); + } else if (Utils.isObject(ls)) { + return Result.wrap(Struct.filter(ls, proc)); + } else { + throw "Can't filter something that is neither object nor list"; + } + }).map_err(function(msg) { + return "filter: " + msg; + }); + }; + })(this), + help__foldl: function() { + return "foldl <initial_value> <function(accumulator,next_val)>\n\nfoldl takes an initial value and a function, and repeatedly\ncalls the given function on two arguments: the value of an\naccumulator and the value of the next item in the input\nlist. This is done left-associatively (hence the 'l' in\n'foldl'), so that the first call to the function consumes the\ninitial value with the first list element, and it proceeds in\norder through the list from left to right. foldr is also\navailable, which works right-associatively. In this way you\ncan do things like add up all of the numbers in a list, or\nconcatenate all of the strings in a list, or turn a list of\npairs into an object with keys and values:\n\nExamples:\n $ [1,2,3] \\ foldl 0 (acc,n) -> acc+n\n 6\n\n $ ['a','b','c'] \\ foldl \"\" (acc,n) -> acc+n\n 'abc'\n\n $ [['a', 1],['b',2],['c',3]] \\ foldl {} (acc,n) -> acc[n[0]] = n[1]; acc\n {a: 1, b: 2, c: 3}\n\n $ ['a','b','c'] \\ foldl 'x' (acc,n) -> '(' + acc + ',' + n + ')'\n ((('x','a'),'b'),'c')\n\nNote in the object example that you have to explicitly return\nthe accumulator, otherwise you'll just get undefined (the\nmember assignment operator doesn't return anything in\ncoffeescript) "; + }, + foldl: (function(_this) { + return function(argv, ls, ctx) { + var args, parts; + console.log("foldl"); + args = argv.join(' '); + parts = args.match(/^([^>]+)(\([a-zA-Z,]*\) *->.*)$/m); + console.log("Parts: " + JSON.stringify(parts)); + return (!parts ? Result.err("expected an initial value and a function") : Utils.parsefunction(parts[2], ctx).and_then(function(proc) { + return Utils.parsevalue(parts[1], ctx).and_then(function(acc) { + var e; + try { + return Result.wrap(List.foldl(acc, ls, proc)); + } catch (error) { + e = error; + return Result.err('' + e); + } + }); + })).map_err(function(e) { + return "foldl: " + e; + }); + }; + })(this), + help__foldr: function() { + return "foldr <initial_value> <function(next_val,accumulator)>\n\nfoldr takes an initial value and a function, and repeatedly\ncalls the given function on two arguments: the value of an\naccumulator and the value of the next item in the input\nlist. This is done right-associatively (hence the 'r' in\n'foldr'), so that the first call to the function consumes the\ninitial value with the last list element, and it proceeds in\norder through the list from right to left. foldl is also\navailable, which works left-associatively. In this way you\ncan do things like add up all of the numbers in a list, or\nconcatenate all of the strings in a list, or turn a list of\npairs into an object with keys and values:\n\nExamples:\n $ [1,2,3] \\ foldr 0 (n,acc) -> n+acc\n 6\n\n $ ['a','b','c'] \\ foldr \"\" (n,acc) -> n+acc\n 'abc'\n\n $ [['a', 1],['b',2],['c',3]] \\ foldr {} (n,acc) -> acc[n[0]] = n[1]; acc\n {a: 1, b: 2, c: 3}\n\n $ ['a','b','c'] \\ foldr 'x' (n,acc) -> '(' + n + ',' + acc + ')'\n ('a',('b',('c','x')))\n\nNote in the object example that you have to explicitly return\nthe accumulator, otherwise you'll just get undefined (the\nmember assignment operator doesn't return anything in\ncoffeescript) "; + }, + foldr: (function(_this) { + return function(argv, ls, ctx) { + var args, parts; + console.log("foldr"); + args = argv.join(' '); + parts = args.match(/^([^(]+)(\([^)]*\)\s*->.*)$/m); + return (!parts ? Result.err("expected an initial value and a function") : Utils.parsefunction(parts[2], ctx).and_then(function(proc) { + return Utils.parsevalue(parts[1], ctx).and_then(function(acc) { + var e; + try { + return Result.wrap(List.foldr(ls, acc, proc)); + } catch (error) { + e = error; + return Result.err('' + e); + } + }); + })).map_err(function(e) { + return "foldr: " + e; + }); + }; + })(this), + help__group: function() { + return "group <function(item)>\n \ngroup takes a list from the input and groups the items into fields\nof an object. The function argument should take an item from the\nlist and return the name of the group it belongs with. The value\nreturned will be an object with each item assigned to a list under\nthe appropriate name.\n \nExamples:\n $ [1,2,3] \\ group (n)-> if n < 3 then 'small' else 'large'\n {small: [1,2], large: [3]}\n"; + }, + group: (function(_this) { + return function(argv, d, ctx) { + console.log("group"); + return Utils.parsefunction(argv.join(" "), ctx).and_then(function(proc) { + var e; + try { + return Result.wrap(List.group(d, proc)); + } catch (error) { + e = error; + return Result.err('' + e); + } + }).map_err(function(e) { + return "group: " + e; + }); + }; + })(this), + help__zip: function() { + return "zip\n\nzip takes a list of lists and returns a new list of lists,\nwhere the sublists contain all of the elements that have the\nsame positions in the original sublists. In other words, the\nfirst returned sublist will have the first element from each\nof the input sublists, and the second result sublist will have\nthe second element from each input sublist, etc.\n\nExample:\n $ [[1,2,3],['a','b','c']] \\ zip\n [[1,'a'],[2,'b'],[3,'c']]"; + }, + zip: (function(_this) { + return function(argv, ls, ctx) { + var e; + return ((function() { + if (argv.length !== 0) { + return Result.err("zip does not accept parameters"); + } else { + try { + return Result.wrap(List.zip(ls)); + } catch (error) { + e = error; + return Result.err('' + e); + } + } + })()).map_err(function(msg) { + return "zip: " + msg; + }); + }; + })(this), + help__unzip: function() { + return "unzip\n\nunzip does exactly the same thing as zip. It's just an alias\nin case you forget that zip undoes itself by just calling it\nagain\n\nExample:\n $ [[1,2,3],['a','b','c']] \\ zip\n [[1,'a'],[2,'b'],[3,'c']]\n\n $ [[1,'a'],[2,'b'],[3,'c']] \\ unzip\n [[1,2,3],['a','b','c']]"; + }, + unzip: (function(_this) { + return function(argv, ls, ctx) { + var e; + return ((function() { + if (argv.length !== 0) { + return Result.err("unzip does not accept parameters"); + } else { + try { + return Result.wrap(List.zip(ls)); + } catch (error) { + e = error; + return Result.err('' + e); + } + } + })()).map_err(function(msg) { + return "unzip: " + msg; + }); + }; + })(this), + help__flatten: function() { + return "flatten\n\nflatten takes a list of lists and removes one layer of\nnesting. If your data looks like a list of flat lists, and you\nwant it to just be a single flat list, flatten will do\nthat. It ignores elements that aren't sublists, leaving them\nalone in the data, so you can use this to get rid of unwanted\nnesting with mixed data.\n\nExamples:\n $ [[1,2,3],[4,5,6]] \\ flatten\n [1,2,3,4,5,6]\n\n $ [[[1,2],3], 4] \\ flatten\n [[1,2],3,4] "; + }, + flatten: (function(_this) { + return function(argv, ls, ctx) { + var e; + return ((function() { + if (argv.length !== 0) { + return Result.err("flatten does not accept parameters"); + } else { + try { + return Result.wrap(List.flatten(ls)); + } catch (error) { + e = error; + return Result.err('' + e); + } + } + })()).map_err(function(msg) { + return "flatten: " + msg; + }); + }; + })(this), + help__squash: function() { + return "squash\n\nsquash removes all levels of nesting from a nested list. No\nmatter how deeply the list is nested, the returned value will\nbe a flat list, which preserves the order of the elements as\nyou would expect.\n\nExample:\n $ [[[[1],2],3],[[[4]]]] \\ squash\n [1,2,3,4]"; + }, + squash: (function(_this) { + return function(argv, ls, ctx) { + var e; + return ((function() { + if (argv.length !== 0) { + return Result.err("squash does not accept parameters"); + } else { + try { + return Result.wrap(List.squash(ls)); + } catch (error) { + e = error; + return Result.err('' + e); + } + } + })()).map_err(function(msg) { + return "squash: " + msg; + }); + }; + })(this), + help__sort: function() { + return "sort [function(a,b)]\n\nsort the input list according to the given comparison\nfunction. The comparison function should return values as\nfollows:\n if a before b then return -1\n if a same as b then return 0\n if a after b then return 1\n\nThe sort function is optional. If you use the default, it will\nsort numbers according to their value (NOT the javascript\ndefault of sorting them according to their alphabetical\norder), and it will sort strings alphabetically. In mixed\ndata, numbers are less than strings, and everything else is\nsorted using javascript's default comparison.\n\nExamples:\n $ [3,31,5,22] \\ sort\n [3,5,22,31]\n\n $ [3,'a',{b:12},31,5,22] \\ sort\n [3, 5, 22, 31, {b: 12}, 'a']"; + }, + sort: (function(_this) { + return function(argv, ls, ctx) { + var cmp; + console.log("sort"); + cmp = Utils.smartcmp; + return (argv.length > 0 ? Utils.parsefunction(argv.join(" "), ctx).map_err(function(e) { + return "sort: expected a comparison function, or nothing"; + }).and_then(function(cmp) { + var e; + try { + return Result.wrap(List.sort(ls, cmp)); + } catch (error) { + e = error; + return Result.err('' + e); + } + }) : Result.wrap(List.sort(ls, cmp))).map_err(function(e) { + return "sort: " + e; + }); + }; + })(this), + help__uniq: function() { + return "uniq [compare]\n\nuniq takes an optional comparison function and returns the\ninput list with all duplicate entries removed. This works like\nthe unix uniq command, which means you *have* to give it\nsorted data. You can use the same comparison function for uniq\nthat you use for sort (and the default function will work in\nalmost all cases, which means you can usually just skip this\nparameter entirely). If you need to wrote a comparison\nfunction, it should return zero if the two items are equal.\n\nUniq only compares adjacent items in the list. If your list is\nnot sorted so that the duplicate items are all next to each\nother, it will not work.\n\nExamples:\n $ [1,2,2,3,3,3,4] \\ uniq\n [1,2,3,4]\n\n $ [1,2,1,2,1,2,1,2] \\ uniq\n [1,2,1,2,1,2,1,2]\n\n The first example shows how uniq dedups the list. The\n second example shows that it doesn't work if your dups\n aren't all adjacent to each other (which can be easily\n achieved with the sort command, see 'help sort'). "; + }, + uniq: function(argv, ls, ctx) { + var cmp; + cmp = Utils.smartcmp; + return (argv.length > 0 ? Utils.parsefunction(argv.join(' '), ctx).map_err(function(e) { + return "expected a list"; + }).and_then(function(proc) { + return Result.wrap(List.uniq(ls, proc)); + }) : Result.wrap(List.uniq(ls, cmp))).map_err(function(e) { + return "uniq: " + e; + }); + }, + help__wrap: function() { + return "wrap <value>\n\nThis just turns a coffeescript expression into a result object\nthat can be used to feed data through a pipeline of\ncommands. This function is called implicitly when you start a\ncommand line out with a coffeescript expression instead of a\ncommand.\n\nThese two examples are identical in their behavior internally:\n\nExamples:\n $ wrap [1,2,3]\n [1,2,3]\n\n $ [1,2,3]\n [1,2,3]"; + }, + wrap: (function(_this) { + return function(argv, data, ctx) { + return Utils.parsevalue(argv.join(" "), ctx).map_err(function(e) { + return "wrap: " + e; + }); + }; + })(this), + help__nest: function() { + return "nest <path_function>\n\nnest works like group, except that your function should return\na list of keys to use like a filesystem path. Each item in the\ndata set will be placed into an object hierarchy so that its\nkey list will locate it uniqely. This is useful for making\ntree structures.\n\nExample:\n $ [1,2,3,4,5] \\ nest (n) -> [\n (if n > 3 then 'large' else 'small'),\n (if n % 2 == 0 then 'even' else 'odd')]\n {\n large: {even: [4], odd:[5]},\n small: {even: [2], odd: [1,3]}\n }\n\nNote: If you get the message 'expected a function', ensure\nthat you have any if/else statements that are used like\nexpressions surrounded by parentheses. Coffeescript fails to\nparse the expression otherwise. The if statements in the\nexample demonstrate how to do this. "; + }, + nest: (function(_this) { + return function(argv, d, ctx) { + return (Utils.parsefunction(argv.join(" "), ctx).map_err(function(e) { + return "expected a function"; + }).and_then(function(pathmkr) { + var e; + try { + return Result.wrap(List.nest(d, pathmkr)); + } catch (error) { + e = error; + return Result.err('' + e); + } + })).map_err(function(e) { + if (('' + e === 'expected a function') && (argv.join(' ')).indexOf("if") !== -1) { + return Result.err("nest: " + e + ' (ensure all "if" expressions are surrounded by parentheses)'); + } else { + return Result.err("nest: " + e); + } + }); + }; + })(this), + help__bfs: function() { + return "bfs <func(item)>\n\nbfs traverses a nested list or object in breadth-first\nfashion, calling the function on each element and appending\nits return value to a list (which will be in breadth-first\norder.\n\nExamples:\n $ [1,[4,[9,10,11],5],2,[6,7,8],3] \\ bfs (x)-> x\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\n $ {a: 1, b: [1,2,3], c: {d: 5, e: 6}} \ bfs (x,p) -> '['+(p.join ',')+']' + '=' + x\n ['[a]=1', '[b]=1,2,3', '[c,d]=5', '[c,e]=6']"; + }, + bfs: (function(_this) { + return function(argv, d, ctx) { + return (Utils.parsefunction(argv.join(" "), ctx).map_err(function(e) { + return "expected a function"; + }).and_then(function(proc) { + var e; + try { + if (Utils.isArray(d)) { + return Result.wrap(List.bfs(d, proc)); + } else if (Utils.isObject(d)) { + return Result.wrap(Struct.bfs(d, proc)); + } else { + return Result.wrap(proc(d)); + } + } catch (error) { + e = error; + return Result.err('' + e); + } + })).map_err(function(e) { + return "bfs: " + e; + }); + }; + })(this), + help__histogram: function() { + return "histogram\n\nCompute the histogram of the data. Expects the data to be in a\nlist format where each element is an instance of one of the\nbins to be counted. The result is returned as an object with\none key for each unique element, and a count of the instances\nof that element as the value.\n\nExample:\n $ [1,1,1,2,3,3,3,4,4,4,4,4] \ pdf\n {1:3, 2: 1, 3: 3, 4: 5}\n"; + }, + histogram: (function(_this) { + return function(argv, d, ctx) { + var e; + return ((function() { + try { + return Result.wrap(List.histogram(d)); + } catch (error) { + e = error; + return Result.err('' + e); + } + })()).map_err(function(e) { + return "pdf: " + e; + }); + }; + })(this), + help__tabulate: function() { + return "tabulate [basevalue]\n\ntabulate fills out a 2d table from a sparse representation of\nthe table. Assuming you have an object, which has a number of\nkeys whose associated values are also objects, tabulate will\niterate through all keys and subkeys to collect all of the row\nidentifiers and column identifiers. It will then generate a\ntable that includes *all* rows and columns from all data\nelements, with the elements themselves populated at the\nappropriate positions. An example of using this might be to\ntransform an association list representation of a network into\na full association matrix. For example, if you have data that\ntells you when messages have passed between various hosts on a\nnetwork, use the pipe system to work that data into an object\nwith a key for each entity that has sent a message, and a\nvalue that's an object with a key for each entity that the\nsender has sent *to*. Then, pipe that data into tabulate, and\nit will generate a full table for you so that you can render\nit or further manipulate it in a normalized way.\n\nbasevalue is optional, and allows you to either generate a\nlist-structured table or an object-structured table. It\ndefaults to object-structured.\n\nExample (association matrix of communicating hosts):\n $ get \"http://somewhere.com/messages.json\" \\\n .. group (msg)->msg.sender \\\n .. mapkeys (sender, receivers) -> List.group receivers, (msg)->msg.receiver \\\n .. tabulate\n\nThe example will fetch a list of messages from some server,\nthen group them by sender (this returns an object with a key\nfor each unique sender, and a list of all messages that sender\nsent). It then iterates over the senders in that object to\nfurther group the messages by receiver. The object now has the\nstructure obj[sender][receiver] = [list of messages]. This is\npassed to tabulate, which generates a full 2d table and puts\nthe message lists in the appropriate row and column. At this\npoint you could easily generate a heatmap from the data to\nshow which hosts are talking most frequently, or do some other\nprocessing to it that takes advantage of the full table\nstructure."; + }, + tabulate: (function(_this) { + return function(argv, data, ctx) { + return (Utils.parsevalue(argv, ctx)).and_then(function(baseval) { + var base, col, cols, e, i, j, k, key, len, len1, len2, ref1, result, row, rows; + if (baseval == null) { + baseval = {}; + } + try { + rows = ((function() { + var results; + results = []; + for (key in data) { + if (!hasProp.call(data, key)) continue; + results.push(key); + } + return results; + })()).sort(); + cols = {}; + result = {}; + for (i = 0, len = rows.length; i < len; i++) { + row = rows[i]; + ref1 = data[row]; + for (col in ref1) { + if (!hasProp.call(ref1, col)) continue; + cols[col] = true; + } + } + cols = ((function() { + var results; + results = []; + for (key in cols) { + if (!hasProp.call(cols, key)) continue; + results.push(key); + } + return results; + })()).sort(); + for (j = 0, len1 = rows.length; j < len1; j++) { + row = rows[j]; + for (k = 0, len2 = cols.length; k < len2; k++) { + col = cols[k]; + if (result[row] == null) { + result[row] = {}; + } + if ((base = result[row])[col] == null) { + base[col] = baseval; + } + if (data[row][col]) { + result[row][col] = data[row][col]; + } + } + } + return Result.wrap(result); + } catch (error) { + e = error; + return Result.err(e); + } + }).map_err(function(e) { + return "tabulate: " + e; + }); + }; + })(this), + help__deepmap: function() { + return "deepmap \n\nApply proc to every element of a nested data structure. The\nstructure can be either a list or an object. In both cases, an\nitem is considered to be a leaf when it's not the same type as\nthe overall object (so anything that's not an object is a leaf\nfor the object, and anything that's not an array is a leaf for\nthe array version). The resulting value will mirror the\noriginal structure, but the values will all be replaced with\nthe result of running proc on the original value in that\nplace.\n\nExample:\n $ [[1,[2,3],4],5] \\ deepmap (n)->n*2\n [[2,[4,6],8],10]"; + }, + deepmap: (function(_this) { + return function(argv, d, ctx) { + return (Utils.parsefunction(argv.join(' ', ctx))).and_then(function(proc) { + if (Utils.isArray(d)) { + return Result.wrap(List.deepmap(d, proc)); + } else { + return Result.wrap(Struct.deepmap(d, proc)); + } + }).map_err(function(e) { + return "deepmap: " + e; + }); + }; + })(this), + help__cmb: function() { + return "cmb \n\nAccept a list from the pipeline and generate all possible\ncombinations of n items from the list. This is useful for\nsituations where you want to generate a network diagram and\nyou have lists of things that should be connected with each\nother. Just set n to 2 and you're done.\n\nThis treats different orderings of the pair as different\nentities, so [2,3] is not the same as [3,2].\n\nExample:\n $ [1,2,3] \\ cmb 2\n [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]"; + }, + cmb: (function(_this) { + return function(argv, d, ctx) { + return (Utils.parsevalue(argv.join(' ', ctx))).and_then(function(ct) { + return Result.wrap(List.cmb(d, ct)); + }).map_err(function(e) { + return "cmb: " + e; + }); + }; + })(this), + help__window: function() { + return "window n proc\n\nSliding window calculation - starting at data[0...n], call\nproc on those n elements for each element up to\ndata.length-n. The result is a list of data.length-n items\nrepresenting the result of the function call on each sublist.\n\nExample:\n $ [0...10] \\ window 3 (a,b,c)->a+b+c\n [3, 6, 9, 12, 15, 18, 21, 24]\n\nThe example just sums the current three elements for every\nconsecutive group of three elements in the list. The input\nlist is ten elements, and the output list is seven. "; + }, + window: (function(_this) { + return function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).and_then(function(n) { + return (Utils.parsefunction(argv.slice(1).join(' ', ctx))).and_then(function(proc) { + return Result.wrap(List.window(d, n, proc)); + }); + }).map_err(function(e) { + return "window: " + e; + }); + }; + })(this), + help__intersect: function() { + return "intersect [proc]\n\nintersect finds all of the elements in common between all\nitems in a list of lists or objects. It treats the input as a\nset of sets and computes the intersection of all of them. The\nproc argument is optional, and can be used to specify how to\ndecide which items are equal by providing a name based on the\nitem. For example, if you have a set of lists of groups of\nnumbers, you could specify proc to just sum the numbers in a\ngroup. The intersection would then be calculated based on that\nsum as the identifying property of each group.\n\nThe result returned is an object that has keys for each\nidentified item (result of calling proc), and a list of the\nitems from each set that matched.\n\nIf you have multiple items within a single set that map to the\nsame identifier, you will get unexpected results. The\ncolliding items will count separately toward the intersection\ngoal, so you may get extra elements in the corresponding list,\nor you may get some elements that don't appear in all sets.\n\nExample:\n $ [[[1..3],[6],[2,3]],[[2,4],[5]],[[6],[5],[2,3,4]]] \\\n .. intersect (ls)->ls.reduce (a,b)->a+b\n {\n 5: {count: 3, items: [[2, 3], [5], [5]]},\n 6: {count: 4, items: [[1, 2, 3], [6], [2, 4], [6]]}\n }\n \nIn the example, note that the group that sums to 6 has four\nitems even though there are only three sets involved. This\nhappened because the first set has two items that sum to six\n(the [1..3] group and the [6])"; + }, + intersect: (function(_this) { + return function(argv, data, ctx) { + var proc; + proc = null; + if (argv.length > 0) { + proc = Utils.parsefunction(argv.join(' ', ctx)); + } else { + proc = Utils.parsefunction('(x)->x'); + } + return proc.map(function(p) { + return List.intersect(data, p); + }).map_err(function(e) { + return "intersect: " + e; + }); + }; + })(this), + help__select: function() { + return "select [list,of,keys]\n\nSelect lets you pick only specific items out of an indexable\nobject (array or struct). Provide a coffeescript formatted\nlist on the command line (this will be evaluated, so it can be\ndata from other sources, or even the result of a function\ncall, etc). The returned data will have only the fields\nspecified. If fields are specified but not present in the\ninput, they will be ignored.\n\nExample:\n $ {a: 1,b:2, c:3} \\ select ['a','c','d']\n {a: 1, c:3}\n\nIn the example, fields a and c are picked, but there is no d\nin the input so it is ignored. Field b is removed."; + }, + select: (function(_this) { + return function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' ', ctx)).and_then(function(idx) { + if (Utils.isArray(data)) { + return Result.wrap(List.select(data, idx)); + } else { + return Result.wrap(Struct.select(data, idx)); + } + }).map_err(function(e) { + return "select: " + e; + }); + }; + })(this) +}; + +module.exports = BaseCommands; + + +},{"../utils/list":54,"../utils/result":55,"../utils/struct":57,"../utils/utils":58}],41:[function(require,module,exports){ +var Context, newscope, + hasProp = {}.hasOwnProperty; + +newscope = require('./newscope').newscope; + +Context = (function() { + function Context() { + this.stack = [{}]; + } + + Context.prototype.replace = function(s) { + return this.stack = [s]; + }; + + Context.prototype.top = function() { + return this.stack[0]; + }; + + Context.prototype.pop = function() { + if (this.stack.length > 1) { + return this.stack = this.stack.slice(1); + } + }; + + Context.prototype.push = function(initial) { + if (initial == null) { + initial = {}; + } + initial['--parent--'] = this.top(); + return this.stack.unshift(newscope(initial, this.top())); + }; + + Context.prototype.clear = function() { + return this.stack = [{}]; + }; + + Context.argnames = function(ctx) { + var illegal, name, names; + illegal = /^([^a-zA-Z_$]|try$|catch$|if$|then$|else$|when$|typeof$|return$)/; + names = {}; + while (ctx) { + for (name in ctx) { + if (!hasProp.call(ctx, name)) continue; + if (!name.match(illegal)) { + names[name] = true; + } + } + console.log("update parent to " + parent); + if (ctx === ctx['--parent--']) { + console.log("Parent context problem detected"); + break; + } + ctx = ctx['--parent--']; + } + return Object.keys(names); + }; + + Context.argvals = function(ctx, names) { + var i, len, name, results; + results = []; + for (i = 0, len = names.length; i < len; i++) { + name = names[i]; + results.push(ctx[name]); + } + return results; + }; + + return Context; + +})(); + +module.exports = Context; + + +},{"./newscope":44}],42:[function(require,module,exports){ +var Editor, Progress, Prompt, React, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Prompt = require('./prompt'); + +Progress = require('./progress'); + +Editor = (function(superClass) { + var Backspace, Delete, DownArrow, End, Enter, Escape, Home, LeftArrow, RightArrow, Tab, UpArrow; + + extend(Editor, superClass); + + Backspace = 8; + + Tab = 9; + + Enter = 13; + + Escape = 27; + + End = 35; + + Home = 36; + + LeftArrow = 37; + + UpArrow = 38; + + RightArrow = 39; + + DownArrow = 40; + + Delete = 46; + + function Editor(props) { + this.output = bind(this.output, this); + this.progress = bind(this.progress, this); + this.keyDown = bind(this.keyDown, this); + this.toggleTrace = bind(this.toggleTrace, this); + this.startDrag = bind(this.startDrag, this); + this.render = bind(this.render, this); + Editor.__super__.constructor.call(this, props); + this.history_index = -1; + this._command_handler = function() { + return null; + }; + this._completion_handler = function() { + return null; + }; + this.shell = props.shell; + this.revl = props.revl; + if ((!this.shell) || (!this.revl)) { + throw "Error - Editor must be provided with a Shell and Revl instance in props"; + } + this.shell.registerEditor(this); + this.prompt = "$ "; + this.trace_accumulator = ""; + this.state = { + cmd: "", + trace: "", + cursor: 'none', + traceheight: 50, + progress: { + done: 1, + total: 1, + running: false + } + }; + } + + Editor.prototype.componentDidUpdate = function() { + return this.refs.trace.scrollTop = this.refs.trace.scrollHeight; + }; + + Editor.prototype.render = function() { + var div, pre, ref, span; + this.trace_accumulator = ""; + ref = React.DOM, div = ref.div, span = ref.span, pre = ref.pre; + return div({ + id: "revl-shell-panel", + tabIndex: 0, + ref: 'terminal', + onKeyDown: this.keyDown, + style: { + height: this.state.traceheight + 'px' + } + }, [ + div({ + className: 'drag-vert', + onMouseDown: this.startDrag, + onDoubleClick: this.toggleTrace, + key: 0 + }, ''), div({ + id: "trace", + className: "trace", + ref: "trace", + key: 1, + style: { + border: "none" + } + }, pre({}, this.state.trace)), Progress({ + key: 3, + running: this.state.progress.running, + done: this.state.progress.done, + total: this.state.progress.total + }), Prompt({ + content: this.state.cmd, + onChange: (function(_this) { + return function(cmd) { + return _this.onChange(cmd); + }; + })(this), + ref: 'prompt', + key: 2, + style: { + border: "none" + } + }) + ]); + }; + + Editor.prototype.startDrag = function(e) { + var drag, last_y, stopdrag, term; + last_y = e.pageY; + term = this.refs.terminal; + drag = (function(_this) { + return function(e) { + var dy; + dy = e.pageY - last_y; + last_y = e.pageY; + return _this.setState({ + traceheight: _this.state.traceheight - dy, + minimize: false + }); + }; + })(this); + stopdrag = (function(_this) { + return function(e) { + window.removeEventListener('mousemove', drag); + window.removeEventListener('mouseup', stopdrag); + return window.removeEventListener('mouseleave', stopdrag); + }; + })(this); + window.addEventListener('mousemove', drag); + window.addEventListener('mouseup', stopdrag); + return window.addEventListener('mouseleave', stopdrag); + }; + + Editor.prototype.toggleTrace = function(e) { + if (!this.state.minimize) { + this.setState({ + lastheight: this.state.traceheight, + traceheight: '20' + }); + } else { + this.setState({ + traceheight: this.state.lastheight + }); + } + return this.setState({ + minimize: !this.state.minimize + }); + }; + + Editor.prototype.getKeyInfo = function(e) { + var c, code; + code = e.keyCode || e.charCode; + c = String.fromCharCode(code); + return { + code: code, + character: c, + shift: e.shiftKey, + control: e.controlKey, + alt: e.altKey + }; + }; + + Editor.prototype.isPrintable = function(ch) { + return ((31 < ch && ch < 128)) || ch === 13 || ch === 9; + }; + + Editor.prototype.onChange = function(cmd) { + this.shell.history.setActive(cmd); + return this.setState({ + cmd: cmd + }); + }; + + Editor.prototype.keyDown = function(event) { + var cmd; + if (event.keyCode === 0 || event.defaultPrevented || event.metaKey || event.altKey || event.ctrlKey) { + return false; + } + switch (event.keyCode) { + case Enter: + if (this.state.cmd.trim().slice(-1) === '\\') { + this.setState({ + cmd: this.state.cmd + '\n' + }, (function(_this) { + return function() { + return _this.refs.prompt.moveCaret(); + }; + })(this)); + } else { + cmd = this.state.cmd; + this.output(this.prompt + (cmd.replace(/[ ]*\n/g, '\n.. ')) + "\n"); + this.shell.history.setActive(cmd.replace(/\\ *\n/g, "\\\n")); + this.shell.history.acceptActive(); + this.history_index = -1; + this._command_handler(cmd); + this.setState({ + cmd: '' + }); + } + break; + case Tab: + this.setState({ + cmd: this._completion_handler(this.state.cmd) + }); + break; + case UpArrow: + this.history_index = this.shell.history.changeIndex(this.history_index, 1); + this.setState({ + cmd: this.shell.history.get(this.history_index) + }, (function(_this) { + return function() { + return _this.refs.prompt.moveCaret(); + }; + })(this)); + break; + case DownArrow: + this.history_index = this.shell.history.changeIndex(this.history_index, -1); + this.setState({ + cmd: this.shell.history.get(this.history_index) + }, (function(_this) { + return function() { + return _this.refs.prompt.moveCaret(); + }; + })(this)); + break; + default: + return true; + } + event.preventDefault(); + event.stopPropagation(); + event.cancelBubble = true; + return false; + }; + + Editor.prototype.setCommandHandler = function(handler) { + return this._command_handler = handler; + }; + + Editor.prototype.setCompletionHandler = function(handler) { + return this._completion_handler = handler; + }; + + Editor.prototype.progress = function(done, total) { + return this.setState({ + progress: { + done: done, + total: total, + running: done < total + } + }); + }; + + Editor.prototype.output = function(text) { + this.trace_accumulator += text; + return this.setState({ + trace: this.state.trace + this.trace_accumulator + }); + }; + + return Editor; + +})(React.Component); + +module.exports = React.createFactory(Editor); + + +},{"./progress":46,"./prompt":47,"react":983}],43:[function(require,module,exports){ +var History, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + +History = (function() { + function History() { + this.all = bind(this.all, this); + this.get = bind(this.get, this); + this.clear = bind(this.clear, this); + this.changeIndex = bind(this.changeIndex, this); + this.acceptActive = bind(this.acceptActive, this); + this.setActive = bind(this.setActive, this); + this.stack = JSON.parse(localStorage.getItem('history')); + if (this.stack == null) { + this.stack = []; + } + this.active = ""; + } + + History.prototype.setActive = function(cmd) { + return this.active = cmd; + }; + + History.prototype.acceptActive = function() { + if (this.active !== this.stack[0]) { + this.stack.unshift(this.active + ""); + localStorage.setItem('history', JSON.stringify(this.stack)); + } + return this.active = ""; + }; + + History.prototype.changeIndex = function(old, delta) { + var result; + console.log("history change index: old=" + old + ", delta=" + delta); + result = old + delta; + if (result < 0) { + result = -1; + } + if (result >= this.stack.length) { + result = this.stack.length - 1; + } + return result; + }; + + History.prototype.clear = function() { + this.stack = []; + return localStorage.setItem('history', '[]'); + }; + + History.prototype.get = function(index) { + switch (false) { + case !(this.stack.length === 0 && index !== -1): + return ""; + case !(index >= this.stack.length): + return ""; + case !(index < 0): + return this.active; + default: + return this.stack[index]; + } + }; + + History.prototype.all = function() { + return this.stack; + }; + + return History; + +})(); + +module.exports = History; + + +},{}],44:[function(require,module,exports){ +"use strict"; + +// This uses the ES6 proxy mechanism to implement a transparent +// scope-like copy-on-write for the context. The idea is that values +// are transparently fetched from older contexts for read, but if a +// write happens the new value is kept local. When the scope exits, +// the previous value is automatically restored. Writes will be saved +// in the object passed in via 'data'. Pass the current scope in as +// parent, or leave it blank for the root scope. +function newscope(data, parent) { + var handler = { + get: function get(t, k) { + console.info("Get "); + if (t.hasOwnProperty(k)) return t[k];else if (parent) return parent[k]; + } + }; + return new Proxy(data, handler); +} + +module.exports = { newscope: newscope }; + +},{}],45:[function(require,module,exports){ +var Preview, React, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Preview = (function(superClass) { + extend(Preview, superClass); + + function Preview(props) { + Preview.__super__.constructor.call(this, props); + console.log("Preview constructor"); + this.state = { + content: "" + }; + } + + Preview.prototype.output = function(str) { + return this.setState({ + content: str + }); + }; + + Preview.prototype.render = function() { + var div, pre, ref; + ref = React.DOM, div = ref.div, pre = ref.pre; + console.log("Preview render"); + return div({ + id: "revl-preview" + }, pre({}, this.state.content)); + }; + + return Preview; + +})(React.Component); + +module.exports = React.createFactory(Preview); + + +},{"react":983}],46:[function(require,module,exports){ +var Progress, React, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Progress = (function(superClass) { + extend(Progress, superClass); + + function Progress(props) { + this.render = bind(this.render, this); + Progress.__super__.constructor.call(this, props); + } + + Progress.prototype.render = function() { + var div; + div = React.DOM.div; + return div({ + style: { + width: '100%', + flex: '0 0 0.5em', + height: '0.8em', + border: 'none', + backgroundColor: '#000', + display: this.props.running ? 'block' : 'none', + zIndex: 100000 + } + }, [ + div({ + style: { + width: (this.props.done * 100 / this.props.total) + '%', + backgroundColor: '#00f', + height: '100%' + }, + key: 0 + }, ''), div({ + style: { + right: '0px', + bottom: '0px', + color: '#99f', + backgroundColor: 'rgba(0,0,0,0)', + display: this.props.running, + position: 'absolute' + }, + key: 1 + }, this.props.done + '/' + this.props.total) + ]); + }; + + return Progress; + +})(React.Component); + +module.exports = React.createFactory(Progress); + + +},{"react":983}],47:[function(require,module,exports){ +var ContentEditable, Editable, Prompt, React, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +ContentEditable = (function(superClass) { + extend(ContentEditable, superClass); + + function ContentEditable(props) { + this.content = bind(this.content, this); + ContentEditable.__super__.constructor.call(this, props); + this.lastText = ''; + } + + ContentEditable.prototype.shouldComponentUpdate = function(newprops) { + return newprops.content !== this.refs.element.innerText; + }; + + ContentEditable.prototype.moveCaret = function(pos) { + var elt, range, sel, textelt; + if (pos == null) { + pos = void 0; + } + elt = this.refs.element; + textelt = elt.firstChild; + if ((typeof pos) === 'undefined') { + pos = elt.innerText.length; + } + range = document.createRange(); + range.setStart(textelt, pos); + range.setEnd(textelt, pos); + sel = window.getSelection(); + sel.removeAllRanges(); + return sel.addRange(range); + }; + + ContentEditable.prototype.componentDidUpdate = function() { + if (this.props.content !== this.refs.element.innerText) { + return this.refs.element.innerText = this.props.content; + } + }; + + ContentEditable.prototype.content = function() { + return this.refs.element.innerText || this.refs.element.textContents || ""; + }; + + ContentEditable.prototype.render = function() { + var span; + span = React.DOM.span; + return span({ + contentEditable: true, + spellCheck: false, + className: 'prompt', + onChange: (function(_this) { + return function() { + return _this.emitChange(); + }; + })(this), + onInput: (function(_this) { + return function() { + return _this.emitChange(); + }; + })(this), + onBlur: (function(_this) { + return function() { + return _this.emitChange(); + }; + })(this), + ref: 'element', + style: { + marginRight: '1px', + marginLeft: '1px' + } + }, this.props.content); + }; + + ContentEditable.prototype.focus = function() { + return this.refs.element.focus(); + }; + + ContentEditable.prototype.emitChange = function() { + var text; + text = this.refs.element.innerText; + if (this.props.onChange && text !== this.lastText) { + this.props.onChange(this.content()); + } + this.lastText = text; + return false; + }; + + return ContentEditable; + +})(React.Component); + +Editable = React.createFactory(ContentEditable); + +Prompt = (function(superClass) { + extend(Prompt, superClass); + + function Prompt(props) { + Prompt.__super__.constructor.call(this, props); + } + + Prompt.prototype.content = function() { + return this.refs.prompt.content(); + }; + + Prompt.prototype.render = function() { + var div, ref, span; + ref = React.DOM, div = ref.div, span = ref.span; + return div({ + onClick: (function(_this) { + return function() { + return _this.focus(); + }; + })(this), + onFocus: (function(_this) { + return function() { + return _this.focus(); + }; + })(this), + tabIndex: "-1", + className: 'promptbox', + style: { + cursor: "text" + } + }, [ + span({ + key: 0, + className: 'prompt' + }, "$ "), Editable({ + key: 1, + ref: 'prompt', + onChange: this.props.onChange, + content: this.props.content + }) + ]); + }; + + Prompt.prototype.focus = function(e) { + console.log("focus prompt"); + return this.refs.prompt.focus(); + }; + + Prompt.prototype.moveCaret = function(p) { + return this.refs.prompt.moveCaret(p); + }; + + return Prompt; + +})(React.Component); + +module.exports = React.createFactory(Prompt); + + +},{"react":983}],48:[function(require,module,exports){ +var React, Result, ScriptEditor, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Result = require('../utils/result').Result; + +ScriptEditor = (function(superClass) { + extend(ScriptEditor, superClass); + + function ScriptEditor(props) { + this.onTryIt = bind(this.onTryIt, this); + this.onCancel = bind(this.onCancel, this); + this.onSave = bind(this.onSave, this); + this.changeHelp = bind(this.changeHelp, this); + this.changeName = bind(this.changeName, this); + this.changeScript = bind(this.changeScript, this); + this.render = bind(this.render, this); + var ref, ref1; + ScriptEditor.__super__.constructor.call(this, props); + console.log("got props: " + props); + this.state = { + body: ((ref = props.initialScript) != null ? ref.body : void 0) || "", + help: ((ref1 = props.initialScript) != null ? ref1.help : void 0) || "", + name: props.initialName || "" + }; + } + + ScriptEditor.prototype.componentWillReceiveProps = function(props) { + var ref, ref1; + return this.setState({ + body: ((ref = props.initialScript) != null ? ref.body : void 0) || "", + help: ((ref1 = props.initialScript) != null ? ref1.help : void 0) || "", + name: props.initialName || "" + }); + }; + + ScriptEditor.prototype.render = function() { + var div, input, pre, ref, span, textarea; + ref = React.DOM, div = ref.div, span = ref.span, pre = ref.pre, textarea = ref.textarea, input = ref.input; + return div({ + id: "revl-script-editor", + tabIndex: 0, + style: { + position: 'fixed', + zIndex: 10000, + display: this.props.display, + marginTop: '10%', + marginLeft: '10%', + width: '75%', + backgroundColor: 'rgba(200,200,200,0.7)', + border: '1px solid black', + borderRadius: '3px', + padding: '5px' + } + }, [ + span({ + key: 0 + }, "Script name"), input({ + ref: 'name', + value: this.state.name, + onChange: this.changeName, + key: 1, + style: { + paddingLeft: '5px', + width: '100%', + placeholder: 'Script name...', + backgroundColor: 'rgba(0,0,0,0.1)', + color: 'black' + } + }), span({ + key: 2 + }, "Help message"), textarea({ + ref: 'help', + value: this.state.help, + onChange: this.changeHelp, + key: 3, + style: { + paddingLeft: '5px', + width: '100%', + height: '200px', + backgroundColor: 'rgba(0,0,0,0.1)', + color: 'black' + } + }), span({ + key: 4 + }, "Commands (use # for comments)"), textarea({ + ref: 'inputArea', + value: this.state.body, + onChange: this.changeScript, + key: 5, + style: { + paddingLeft: '5px', + width: '100%', + height: '400px', + backgroundColor: 'rgba(0,0,0,0.1)', + color: 'black' + } + }), div({ + key: 6 + }), [ + input({ + type: 'button', + value: 'Try it', + onClick: this.onTryIt, + key: 0 + }), input({ + type: 'button', + value: 'Save', + onClick: this.onSave, + key: 1 + }), input({ + type: 'button', + value: 'Cancel', + onClick: this.onCancel, + key: 2 + }) + ] + ]); + }; + + ScriptEditor.prototype.parseCommands = function() { + var cmds, current, i, len, line, lines; + cmds = []; + current = []; + lines = (this.refs.inputArea.value.split(/[\s]*\n[\s]*/)).map(function(l) { + return l.trim(); + }); + for (i = 0, len = lines.length; i < len; i++) { + line = lines[i]; + if (line.length < 1 || line.startsWith("#")) { + continue; + } + if (!(line.endsWith('\\'))) { + current.push(line); + cmds.push(current.join(' ')); + current = []; + } else { + current.push(line); + } + } + if (current.length !== 0) { + cmds.push(current.join(' ')); + } + return cmds; + }; + + ScriptEditor.prototype.changeScript = function(evt) { + return this.setState({ + body: evt.targetvalue + }); + }; + + ScriptEditor.prototype.changeName = function(evt) { + return this.setState({ + name: evt.target.value + }); + }; + + ScriptEditor.prototype.changeHelp = function(evt) { + return this.setState({ + help: evt.target.value + }); + }; + + ScriptEditor.prototype.onSave = function() { + var content, help, name, scripts; + scripts = JSON.parse(localStorage.getItem('user-scripts')); + name = this.refs.name.value; + content = this.parseCommands(); + help = this.refs.help.value; + if (content.length < 1) { + alert("Error: script body is empty, not saving!"); + return; + } + if (name.length < 1) { + name = prompt("Please enter a name for your script:"); + if (name.length < 1) { + alert("Error: Can't save a script without a name"); + return; + } else { + this.setState({ + name: name + }); + } + } + if (help.length < 1) { + if (!confirm("You didn't enter a help message, your script will be undocumented if you save it.")) { + return; + } + } + this.props.shell.script_manager.saveScript(name, { + body: content, + help: help + }, this.props.initialName); + if ((typeof scripts) === 'undefined') { + scripts = {}; + } + return this.props.revl.hideScriptEditor(); + }; + + ScriptEditor.prototype.onCancel = function() { + return this.props.revl.hideScriptEditor(); + }; + + ScriptEditor.prototype.onTryIt = function() { + return this.props.shell.runScript(Result.wrap(this.props.data), {}, this.parseCommands()); + }; + + return ScriptEditor; + +})(React.Component); + +module.exports = React.createFactory(ScriptEditor); + + +},{"../utils/result":55,"react":983}],49:[function(require,module,exports){ +var Http, Result, ResultPromise, ScriptManager, Struct, ref, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + hasProp = {}.hasOwnProperty; + +ref = require('../utils/result'), ResultPromise = ref.ResultPromise, Result = ref.Result; + +Http = require('../utils/http'); + +Struct = require('../utils/struct'); + +ScriptManager = (function() { + function ScriptManager(shell, revl) { + var pub_cmds, script_cmds; + this.shell = shell; + this.revl = revl; + this.registerCommand = bind(this.registerCommand, this); + this.runScript = bind(this.runScript, this); + script_cmds = JSON.parse(localStorage.getItem('user-scripts')); + this.scripts = {}; + this.loadApiScripts().map((function(_this) { + return function(scr) { + var name; + for (name in script_cmds) { + if (!hasProp.call(script_cmds, name)) continue; + _this.scripts[name] = { + body: script_cmds[name].body, + help: script_cmds[name].help, + signature_id: script_cmds[name].signature_id + }; + } + return _this.registerCommands(); + }; + })(this)); + pub_cmds = Struct.map(ScriptManager.public_commands, (function(_this) { + return function(cmd) { + return cmd.bind(_this); + }; + })(this)); + console.log("ScriptManager commands: ", pub_cmds); + this.shell.addCommands(pub_cmds); + Http.asyncjson("GET", "/scot/api/v2/whoami").map((function(_this) { + return function(r) { + return _this.whoami = r.user; + }; + })(this)); + } + + ScriptManager.getScript = function(owner, name, version) { + return Http.asyncjson("GET", "/scot/api/v2/signature?owner=" + owner + "&type=userscript&name=" + name).and_then((function(_this) { + return function(r) { + var scr; + scr = void 0; + if (r.queryRecordCount < 1) { + return ResultPromise.failed("No matching scripts found"); + } + return Http.asyncjson("GET", "/scot/api/v2/signature/" + (parseInt(r.records[0].id))).map(function(script) { + var latest; + if (!script) { + return ResultPromise.failed("Script failed to load due to mysterious internal errors"); + } + if ((typeof version) === 'undefined') { + version = script.latest_revision; + } + latest = JSON.parse(script.version[version].body); + return { + body: latest.body, + help: latest.help + }; + }); + }; + })(this)); + }; + + ScriptManager.prototype.loadApiScripts = function() { + return Http.asyncjson("GET", "/scot/api/v2/whoami").and_then((function(_this) { + return function(r) { + return Http.asyncjson("GET", "/scot/api/v2/signature?owner=" + r.user + "&type=userscript"); + }; + })(this)).and_then((function(_this) { + return function(r) { + var i, len, ref1, results, scr; + results = []; + _this.shell.output("Loading scripts from server, please wait...\n"); + ref1 = r.records; + for (i = 0, len = ref1.length; i < len; i++) { + scr = ref1[i]; + results.push((Http.asyncjson("GET", "/scot/api/v2/signature/" + scr.id)).map(function(s) { + _this.shell.output("trying " + s.name + "\n"); + return s; + })); + } + return ResultPromise.waitreplace(results, 10); + }; + })(this)).and_then((function(_this) { + return function(scripts) { + var body, current, e, help, i, len, ref1, script; + console.log("got scripts ", scripts); + for (i = 0, len = scripts.length; i < len; i++) { + script = scripts[i]; + current = script.version[script.latest_revision]; + try { + ref1 = JSON.parse(current.body), body = ref1.body, help = ref1.help; + } catch (error) { + e = error; + _this.shell.output("Failed to load " + script.name + ": " + e + "\n"); + continue; + } + if (((typeof body) === 'undefined') || ((typeof help) === 'undefined')) { + _this.shell.output("Script " + script.name + " is incomplete, missing body or help\n"); + } else { + _this.scripts[script.name] = { + body: body, + help: help, + signature_id: script.id + }; + _this.shell.output("Loaded " + script.name + "\n"); + } + } + return ResultPromise.fulfilled(_this.scripts); + }; + })(this)).map_err((function(_this) { + return function(e) { + return _this.shell.showError("Error loading scripts from server: " + e); + }; + })(this)); + }; + + ScriptManager.prototype.runScript = function(argv, data, context, script) { + var innerScript, val; + console.log("Runscript " + (JSON.stringify(script))); + innerScript = (function(_this) { + return function(dat, ctx, scr) { + var result; + console.log("Innerscript, data = " + (JSON.stringify(dat)) + ", script=" + (JSON.stringify(scr))); + if (scr.length > 0) { + result = _this.shell.doCommandQuiet(scr[0], dat); + console.log("Result of innerScript " + scr[0] + " = " + (JSON.stringify(result))); + if (scr.length > 1) { + console.log("executing next part of script (length=" + scr.length + "): " + (JSON.stringify(scr.slice(1)))); + return result.and_then((function() { + return innerScript(Result.wrap({}), ctx, scr.slice(1)); + })); + } else { + return result; + } + } else { + console.log("Empty script, returning error"); + result = new ResultPromise(); + result.fail('Attempted to execute empty script!'); + return result; + } + }; + })(this); + this.shell.context.push({}); + val = (innerScript(data, this.shell.context, script)).map((function(_this) { + return function(r) { + _this.shell.context.pop(); + return r; + }; + })(this)).map_err((function(_this) { + return function(e) { + _this.shell.context.pop(); + return _this.shell.showError(e); + }; + })(this)); + return val; + }; + + ScriptManager.prototype.save = function() { + return localStorage.setItem('user-scripts', JSON.stringify(this.scripts)); + }; + + ScriptManager.prototype.publish = function(publish_set) { + var data, get_sig_id, name, publish_body, r, results; + console.log("Called publish ", publish_set); + publish_body = (function(_this) { + return function(id, script) { + return (Http.asyncjson("POST", "/scot/api/v2/sigbody", { + signature_id: id, + body: JSON.stringify(script) + })).map(function() { + return { + script: name, + status: "ok" + }; + }); + }; + })(this); + get_sig_id = (function(_this) { + return function(name, script) { + return (Http.asyncjson("GET", "/scot/api/v2/whoami")).and_then(function(me) { + return Http.asyncjson("GET", "/scot/api/v2/signature?owner=" + me.user + "&name=" + name + "&type=userscript"); + }).and_then(function(res) { + console.log("got " + res.records.length + " records"); + if (res.records.length > 0) { + console.log("fulfilling with first record (id=" + res.records[0].id); + return ResultPromise.fulfilled(res.records[0].id); + } else { + console.log("Failing, will post new signature"); + return ResultPromise.failed("no such signature"); + } + }).err_and_then(function() { + return (Http.asyncjson("POST", "/scot/api/v2/signature", { + name: name, + description: script.help, + type: 'userscript' + })).map(function(result) { + return result.id; + }); + }); + }; + })(this); + results = []; + for (name in publish_set) { + if (!hasProp.call(publish_set, name)) continue; + data = publish_set[name]; + console.log("Publishing " + name); + r = (get_sig_id(name, data)).and_then((function(_this) { + return function(id) { + console.log("got sigid: " + id); + return publish_body(id, data); + }; + })(this)).map((function(_this) { + return function(result) { + return { + script: name, + status: 'saved', + version: result.version + }; + }; + })(this)); + results.push(r); + } + return ResultPromise.waitreplace(results); + }; + + ScriptManager.prototype.saveScript = function(name, script, replace) { + if ((name in this.scripts) && (replace !== name)) { + if (!(confirm("Saving this script as '" + name + "' will replace an existing version. Continue?"))) { + return Result.err("Cancelled by user"); + } + } + this.scripts[name] = { + body: script.body, + help: script.help + }; + this.registerCommand(name); + this.save(); + return Result.wrap("Script saved"); + }; + + ScriptManager.prototype.getScript = function(name) { + return this.scripts[name]; + }; + + ScriptManager.prototype.registerCommand = function(name) { + var body, commands, help, ref1; + console.log("Registering command " + name); + if (name in this.scripts) { + ref1 = this.scripts[name], body = ref1.body, help = ref1.help; + commands = {}; + commands[name] = ((function(_this) { + return function(argv, data, context) { + return _this.runScript(argv, Result.wrap(data), context, body); + }; + })(this)); + if (help) { + commands['help__' + name] = ((function(_this) { + return function(argv, data, context) { + return help; + }; + })(this)); + } + return this.shell.addCommands(commands); + } else { + return console.log("Error: " + name + " doesn't exist as a script!"); + } + }; + + ScriptManager.prototype.registerCommands = function() { + var name, ref1, results1; + ref1 = this.scripts; + results1 = []; + for (name in ref1) { + if (!hasProp.call(ref1, name)) continue; + results1.push(this.registerCommand(name)); + } + return results1; + }; + + ScriptManager.public_commands = { + help__script: function(argv) { + if (argv && argv[0] && ('help__' + argv[0]) in ScriptManager.commands) { + return ScriptManager.commands['help__' + argv[0]].apply(this); + } else { + return "script [help|new|publish|import|edit]\n \nscript allows you to work with your personal scripts\ncollection. There are several subcommands available. For\nhelp with each, type\n\n# script help \n \nSubcommands:\n help [command] - Display this message, or the help for a specific subcommand\n new - Create a new script\n publish - Upload a script to the server and make it available to others\n import - Get another user's script and make it locally available\n edit - Edit a script\n "; + } + }, + script: function(argv, data, context) { + var arg; + console.log("Script command executed"); + if (argv.length > 0) { + arg = argv.slice(1); + if (argv[0] === 'help') { + return Result.err(ScriptManager.public_commands.help__script(arg)); + } else if (!(argv[0] in ScriptManager.commands)) { + return Result.err(("Subcommand '" + argv[0] + "' was not recognized:\n\n") + ScriptManager.public_commands.help__script()); + } else { + return ScriptManager.commands[argv[0]].apply(this, [arg, data, context]); + } + } else { + return Result.err(ScriptManager.public_commands.help__script(argv)); + } + } + }; + + ScriptManager.commands = { + help__new: function() { + return "script new [name]\n\nCreate a new script. This launches the script editor. If\nthe script already exists you'll get a warning when you\nsave it."; + }, + "new": function(argv, data, ctx) { + var name, script; + name = ""; + script = void 0; + if (argv[0]) { + name = argv[0]; + script = this.getScript(name); + if (script) { + return Result.err(("Script " + name + " already exists, please use ") + "'script edit' if you wish to open it for editing."); + } + } + return this.revl.showScriptEditor(data, script, name); + }, + help__delete: function() { + return "script delete [-a]\n\nDelete a script. By default, this will only delete the\nscript locally, not on the server. If you want to delete\nall copies of the script, give the -a command switch.\n\nExamples:\n # script delete old_and_boring\n Script 'old_and_boring' deleted from local cache\n\n # script delete old_and_boring -a\n Script 'old_and_boring' deleted from local cache and server"; + }, + help__edit: function() { + return "script edit \n\nOpen the script editor with the given script loaded. Saves\nwill update the script in-place."; + }, + edit: function(argv, data, ctx) { + var name, script; + name = ""; + script = void 0; + if (argv[0]) { + name = argv[0]; + script = this.getScript(name); + if (!script) { + return Result.err(("Script " + name + " not found, please use ") + "'script new' if you wish to create a new script."); + } + } + return this.revl.showScriptEditor(data, script, name); + }, + help__publish: function() { + return "publish [script names or *]\n \nThis command allows you to send your locally-defined\nscripts up to the server so that they are accessible by\nother users, and by you from other browsers. Supply the\nnames of the scripts you want to publish on the command\nline, or if you just want to publish all of them, put a\nwildcard ('*'). Note that you can't combine these - either\nspecify names, or use the wildcard. If you do both it will\nraise an error (\"publish: Unknown scripts: '*'\").\n \nExamples:\n $ publish teh_win fastness\n [{script: 'teh_win', status: 'success'}, {script: 'fastness', status: 'success'}]\n \n $ publish *\n [{script: 's1', status: 'success'}, {script: 's2', status: 'success'}, ...] "; + }, + publish: function(argv, data, ctx) { + var i, len, name, nf, notfound, publish_set, s; + if (argv.length < 1) { + return Result.err("publish: Please specify script names to publish, or '*' to publish all saved scripts"); + } + console.log("publish command: argv=", argv); + publish_set = {}; + notfound = []; + if (argv[0] === '*') { + publish_set = this.scripts; + } else { + for (i = 0, len = argv.length; i < len; i++) { + name = argv[i]; + if (name in this.scripts) { + publish_set[name] = this.scripts[name]; + } else { + console.log("publish: Could not find script: " + name); + notfound.push(name); + } + } + } + console.log("publish: this = " + this); + if (notfound.length !== 0) { + nf = (function() { + var j, len1, results1; + results1 = []; + for (j = 0, len1 = notfound.length; j < len1; j++) { + s = notfound[j]; + results1.push("'" + s + "'"); + } + return results1; + })(); + console.log("Not found: " + nf); + return Result.err("publish: Unknown scripts: " + nf); + } + return this.publish(publish_set); + }, + help__import: function() { + return "import <[user/]script> [as ]\n \nIf somebody has published a script that you want to\naccess, you can import it into your environment with this\ncommand.\n \nuser: (Optional) The username of the script's owner.\nscript: (Required) The name of the script to import.\nname: (Optional) The name to give it in your environment.\n \nYou can republish this script under your own name if you\nwant, which will allow you to make changes to fit your own\nneeds. If you republish it, the script will be loaded from\nyour own repository instead of the original, and you will\nnot get updates when the original is updated.\n \nIf you want to use the data from the pipeline in the\npipeline, use the map command and access this utility via\nScript.import in the function body.\n \nExamples:\n $ import jondoe/superbling\n Script 'superbling' imported from user jondoe as superbling\n \n $ import superbling\n Script 'superbling' imported from user jondoe as superbling\n \n $ import superbling as jdbling\n Script 'superbling' imported from user jondoe as jdbling\n \n $ ['superbling','ultrabling','tehblingerator'] \\\n .. (s)-> Script.import 'jondoe/#\{s}','jd#\{s}'\n Script 'superbling' imported from user jondoe as jdsuperbling\n Script 'ultrabling' imported from user jondoe as jdultrabling\n Script 'tehblingerator' imported from user jondoe as jdtehblingerator\n \nThe first three examples use the command in plain form,\nand the last demonstrates how to apply it to pipeline data."; + }, + "import": function(argv, data, ctx) { + var _, name, pat, ref1, script, user; + pat = /^(([a-zA-Z0-9_]+)\/)?([a-zA-Z0-9_]+)( +as +([a-zA-Z0-9_]+))?$/; + ref1 = (argv.join(' ')).match(pat), _ = ref1[0], _ = ref1[1], user = ref1[2], script = ref1[3], _ = ref1[4], name = ref1[5]; + return ScriptManager.getScript(user, script).and_then((function(_this) { + return function(scr) { + return _this.saveScript(name, scr).map(function(_) { + return "Script '" + script + "' imported from user " + user + " as " + name; + }); + }; + })(this)); + } + }; + + return ScriptManager; + +})(); + +module.exports = ScriptManager; + + +},{"../utils/http":53,"../utils/result":55,"../utils/struct":57}],50:[function(require,module,exports){ +var Context, History, Result, ResultPromise, ScriptManager, Shell, Utils, ref, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + hasProp = {}.hasOwnProperty, + indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + +History = require('./history'); + +Utils = require('../utils/utils'); + +Context = require('./context'); + +ScriptManager = require('./script-manager'); + +ref = require('../utils/result'), Result = ref.Result, ResultPromise = ref.ResultPromise; + +Shell = (function() { + function Shell(output, revl) { + this.output = output; + this.revl = revl; + this.getCommands = bind(this.getCommands, this); + this.clearHistory = bind(this.clearHistory, this); + this.clearContext = bind(this.clearContext, this); + this.prettyprint = bind(this.prettyprint, this); + this.doCompletion = bind(this.doCompletion, this); + this.complete = bind(this.complete, this); + this.runScript = bind(this.runScript, this); + this.runCommands = bind(this.runCommands, this); + this.doCommandQuiet = bind(this.doCommandQuiet, this); + this.doCommand = bind(this.doCommand, this); + this.registerEditor = bind(this.registerEditor, this); + this.history = new History(); + if (this.output == null) { + this.output = function(s) { + return alert("Warning- output function not defined!!!\n\n" + s); + }; + } + this.commands = {}; + this.docs = {}; + this.scope = {}; + this.context = new Context(); + this.addCommands(this.getCommands()); + this.editor = void 0; + this.script_manager = new ScriptManager(this, this.revl); + } + + Shell.prototype.registerEditor = function(ed) { + ed.setCompletionHandler(this.doCompletion); + ed.setCommandHandler(this.doCommand); + return this.editor = ed; + }; + + Shell.prototype.loadSavedData = function() { + var func, item, j, len1, recovered, ref1, ref2, results; + this.context.top().__functions = []; + recovered = JSON.parse(localStorage.getItem('context')); + if (recovered) { + this.context.replace(recovered); + if (this.context.top().__functions) { + ref1 = this.context.top().__functions; + for (j = 0, len1 = ref1.length; j < len1; j++) { + func = ref1[j]; + Utils.parsefunction(func.source, this.context.top()).and_then((function(_this) { + return function(f) { + return _this.context.top()[func.name] = f; + }; + })(this)).map_err((function(_this) { + return function(e) { + return console.log("Error recovering function " + func.name + ": " + e); + }; + })(this)); + } + } else { + this.context.top().__functions = []; + } + } + ref2 = this.scope; + results = []; + for (item in ref2) { + if (!hasProp.call(ref2, item)) continue; + results.push(this.context.top()[item] = this.scope[item]); + } + return results; + }; + + Shell.prototype.addCommands = function(cmds) { + var cmd, handler, name, results; + results = []; + for (cmd in cmds) { + handler = cmds[cmd]; + if (cmd.startsWith("help__")) { + name = cmd.slice(6); + if (name) { + results.push(this.docs[name] = handler); + } else { + results.push(void 0); + } + } else { + results.push(this.commands[cmd] = handler); + } + } + return results; + }; + + Shell.prototype.addScope = function(items) { + var item, results; + results = []; + for (item in items) { + if (!hasProp.call(items, item)) continue; + results.push(this.scope[item] = items[item]); + } + return results; + }; + + Shell.prototype.splitCommands = function(cmd) { + var i, re, splits; + console.log("Splitting command " + (JSON.stringify(cmd))); + re = /[^\\]\\[^\\]/g; + splits = [-2]; + i = 0; + while ((i = re.exec(cmd))) { + splits.push(i.index); + } + splits.push(cmd.length); + return ((function() { + var j, ref1, results; + results = []; + for (i = j = 0, ref1 = splits.length - 1; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + results.push(cmd.slice(splits[i] + 2, splits[i + 1] + 1)); + } + return results; + })()).map(function(c) { + return c.trim(); + }).map(function(c) { + return c.split(' '); + }).map(function(c) { + return c.map(function(s) { + return s.replace("\\\\", "\\"); + }); + }); + }; + + Shell.prototype.doCommand = function(cmd, data) { + if (data == null) { + data = Result.wrap({}); + } + console.log("DoCommand " + cmd + ", data=" + (JSON.stringify(data))); + return (this.doCommandQuiet(cmd, data)).map((function(_this) { + return function(d) { + var result; + result = (_this.prettyprint(d)) + '\n'; + return _this.output(result); + }; + })(this)).map_err((function(_this) { + return function(e) { + console.log("fail shell:73,e=" + (JSON.stringify(e))); + return _this.showError(e); + }; + })(this)); + }; + + Shell.prototype.doCommandQuiet = function(cmd, data) { + var cmds, i, j, len1; + if (data == null) { + data = Result.wrap({}); + } + console.log("DoCommandQuiet " + cmd + ", data=" + (JSON.stringify(data))); + cmds = this.splitCommands(cmd); + i = 0; + for (j = 0, len1 = cmds.length; j < len1; j++) { + cmd = cmds[j]; + if (!(cmd[0] in this.commands)) { + if (i === 0) { + cmd.unshift("wrap"); + } else { + cmd.unshift("map"); + } + } + i = 1; + } + return this.runCommands(data, cmds); + }; + + Shell.prototype.runCommands = function(data, cmds) { + var cmd, e, finish, i, j, ref1; + console.log("runCommands data=" + (JSON.stringify(data)) + ", commands=" + (JSON.stringify(cmds))); + finish = new ResultPromise().map(function(d) { + console.log("runcommands finished with " + d); + return d; + }); + for (i = j = 0, ref1 = cmds.length; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + cmd = cmds[i]; + console.log("run command " + cmd); + try { + data = data.and_then((function(_this) { + return function(d) { + _this.context.top()._ = d; + return _this.commands[cmd[0]](cmd.slice(1), d, _this.context.top()); + }; + })(this)); + } catch (error) { + e = error; + data = Result.err(cmds[i] + ': ' + e); + console.log(e); + } + console.log(data); + if (data instanceof ResultPromise) { + return data.progress(((function(_this) { + return function(done, total) { + console.log("Progress: " + done + "/" + total); + return _this.editor.progress(done, total); + }; + })(this))).and_then((function(_this) { + return function(result) { + return _this.runCommands(Result.wrap(result), cmds.slice(i + 1)); + }; + })(this)); + } else if (data.is_err()) { + break; + } + } + console.log("succeeded with data ", data, " fulfilling promise ", finish); + data.and_then(function(d) { + console.log("fulfilling now"); + finish.fulfill(d); + return finish; + }).map_err(function(e) { + console.log("fail shell:117"); + finish.fail(e); + return e; + }); + return finish; + }; + + Shell.prototype.runScript = function(data, context, script) { + var innerScript, val; + innerScript = (function(_this) { + return function(dat, ctx, scr) { + var result; + if (scr.length > 0) { + result = _this.doCommand(scr[0], dat); + console.log("Result of innerScript " + scr[0] + " = " + (JSON.stringify(result))); + if (scr.length > 1) { + return result.map((function() { + return innerScript(Result.wrap({}), ctx, scr.slice(1)); + })); + } else { + return result; + } + } else { + console.log("Empty script, returning error"); + result = new ResultPromise(); + result.fail('Attempted to execute empty script!'); + return result; + } + }; + })(this); + this.context.push(context); + val = (innerScript(data, this.context, script)).map((function(_this) { + return function(r) { + _this.context.pop(); + return r; + }; + })(this)).map_err((function(_this) { + return function(e) { + _this.context.pop(); + return _this.showError(e); + }; + })(this)); + return ResultPromise.wait(val); + }; + + Shell.prototype.showError = function(msg) { + if (typeof msg === 'string') { + this.output(msg + "\n"); + } else { + this.output((JSON.stringify(msg)) + '\n'); + } + return Result.err(msg); + }; + + Shell.prototype.complete = function(commands, stub) { + var c, j, len1; + for (j = 0, len1 = commands.length; j < len1; j++) { + c = commands[j]; + if (c.startsWith(stub)) { + return c; + } + } + return stub; + }; + + Shell.prototype.doCompletion = function(stub) { + var cmd, cmds, othercmd; + cmds = this.splitCommands(stub); + cmd = cmds[cmds.length - 1]; + othercmd = cmds.slice(0, -1); + if (!cmd || cmd.length > 1) { + return stub; + } else { + return ((othercmd.map(function(c) { + return c.join(' '); + })).join(' \\ ')).concat([this.complete(Object.keys(this.commands), cmd[0])].join(' \\ ')); + } + }; + + Shell.prototype.prettyprint = function(data) { + var indented, oneliner; + oneliner = function(strs) { + var j, len, len1, s; + len = 0; + for (j = 0, len1 = strs.length; j < len1; j++) { + s = strs[j]; + if (indexOf.call(s, '\n') >= 0) { + return false; + } + len += s.length; + } + return len <= 80; + }; + indented = function(n, ob) { + var k, keys, ls, pairs, s, spaces; + s = ""; + if (Utils.isArray(ob)) { + ls = ob.map(function(o) { + return indented(n + 2, o); + }); + if (oneliner(ls)) { + s = '[' + ls.join(", ") + ']'; + } else { + s = '[\n' + (' '.repeat(n + 2)) + ls.join(",\n" + ' '.repeat(n + 2)) + '\n' + (' '.repeat(n)) + ']'; + } + return s; + } else if (typeof ob === 'undefined') { + return 'undefined'; + } else if (ob === null) { + return 'null'; + } else if (typeof ob === 'object') { + keys = ((function() { + var results; + results = []; + for (k in ob) { + if (!hasProp.call(ob, k)) continue; + results.push(k); + } + return results; + })()).sort(); + pairs = keys.map(function(k) { + return k + ': ' + (!k.startsWith('__') ? indented(n + 2, ob[k]) : ""); + }); + if (oneliner(pairs)) { + s = '{' + pairs.join(", ") + "}"; + } else { + spaces = ' '.repeat(n + 2); + s = '{\n' + spaces + pairs.join(',\n' + spaces) + '\n' + spaces.slice(0, -2) + '}'; + } + return s; + } else if (typeof ob === 'function') { + return '[function]'; + } else { + return JSON.stringify(ob); + } + }; + return indented(0, data); + }; + + Shell.prototype.clearContext = function() { + localStorage.setItem('context', JSON.stringify({})); + this.context.clear(); + this.loadSavedData(); + return Result.wrap(this.context.top()); + }; + + Shell.prototype.clearHistory = function() { + this.history.clear(); + return Result.wrap({}); + }; + + Shell.prototype.getCommands = function() { + return { + help: (function(_this) { + return function(argv, data, ctx) { + var cmd, columns, getcols, str; + getcols = function(maxw, ncols, index) { + var col, cols, i, j, n, ref1, width; + col = 0; + cols = []; + width = 0; + for (i = j = 0, ref1 = ncols; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) { + n = col; + while (index[n][0] % ncols !== i) { + n++; + } + col = n; + cols.push(index[col][1]); + width += cols[i]; + if (width > maxw) { + return null; + } + } + return cols; + }; + columns = function(maxw, items) { + var cols, index, item, len, maxcols, pos; + index = ((function() { + var j, len1, results; + results = []; + for (pos = j = 0, len1 = items.length; j < len1; pos = ++j) { + item = items[pos]; + results.push([pos, item.length]); + } + return results; + })()).sort(function(a, b) { + return b[1] - a[1]; + }); + len = 0; + maxcols = 0; + while (len + items[maxcols] < maxw) { + len += items[maxcols].length; + maxcols++; + } + while (maxcols > 1) { + cols = getcols(maxw, maxcols, index); + if (cols) { + return cols; + } + } + return [maxw]; + }; + cmd = ""; + if (argv.length > 0) { + cmd = argv[0]; + } + if (cmd in _this.docs && cmd !== "help") { + return Result.err(_this.docs[cmd]()); + } else { + str = ""; + if (cmd !== "" && !(cmd in _this.commands)) { + str += "Command \"" + cmd + "\" is unrecognized\n"; + } else if (cmd !== "") { + str += "Sorry, \"" + cmd + "\" does not have documentation yet"; + } + str += "Read-Eval-Visualize-Loop (REVL)\n \nREVL is a tool to make it easier to transform data\ninto a format that can be run through a\nvisualization. It's built to behave like a\ncommand line, in that you can pipe data through\nvarious primitive operations to transform\nit from the source format into a format that can\nbe dumped into one of the visualization tools.\n\nUse a single backslash ('\\') to separate commands\nas you would use the pipe character on a standard\ncommand line. Each command has help specifically\nwritten for it as well. To view the help for a\nspecific command, type 'help ' where\n is replace with the name of the command\nyou need help with. Every command includes at\nleast one example of how to use it in a realistic\ncontext.\n\nSome commands take parameters on the command line,\nand many take function literals to be run on the\ndata being piped though. Command line arguments\nshould be written in coffeescript syntax (see\nhttp://coffeescript.org for details).\n\nYou will often want to access library features\nfrom within pipeline functions. These are\ngenerally available under the name of the module\nthey come from (Struct,Strings,Poly,etc). The only\nexception is the list features, which are directly\nimported without a namespace because they are so\ncommonly used.\n\nYou can also access the current pipeline data from\nthe command line context using the special name\n'_'. This allows you to use piped data as initial\nvalues, and to use parts of the global data\nstructure from within iterator commands like fold.\n\nThe commands currently supported in this system\nare:\n\t" + (Object.keys(_this.commands)).sort().join("\n\t"); + return Result.err(str); + } + }; + })(this), + help__store: function() { + return "store <name>\n \nstore the current data item in the shell context under the\ngiven name. It can be used from that point forward to\nrecall the value inside other expressions. If you want to\nkeep the value in future browser sessions, use the save\ncommand to dump the context into localstorage.\n"; + }, + store: (function(_this) { + return function(argv, data, ctx) { + if (argv.length !== 1) { + return Result.err("store expects input from a pipe, and a name from the command line"); + } else { + _this.context.top()[argv[0]] = data; + return Result.wrap(data); + } + }; + })(this), + help__save: function() { + return "save\n\nDump the current contents of the context into localstorage\nso that your browser will remember your saved data next\ntime you start up. This takes no arguments and does\nnothing with data from the pipe (just forwards it through\nunchanged)."; + }, + save: (function(_this) { + return function(argv, data, ctx) { + localStorage.setItem('context', JSON.stringify(_this.context.top())); + return Result.wrap(data); + }; + })(this), + help__clear: function() { + return "clear [-h]\n \nIf -h is supplied, clear command history. Otherwise, clear all\nstored variables from the shell. This also clears your local\nstorage, so the variables (or history) will not reappear if\nyou reload. Use with caution! "; + }, + clear: (function(_this) { + return function(argv, data, ctx) { + if (argv.length > 0 && argv[0] === '-h') { + return _this.clearHistory(); + } else { + return _this.clearContext(); + } + }; + })(this), + help__history: function() { + return "history\n \nReturn the list of commands currently held in the history\nobject."; + }, + history: (function(_this) { + return function(argv, data, ctx) { + return Result.wrap(_this.history.all()); + }; + })(this), + help__context: function() { + return "context\n \ncontext prints out the set of variables that are currently\ndefined in the shell."; + }, + context: (function(_this) { + return function(argv, data, ctx) { + return Result.wrap(_this.context.top()); + }; + })(this), + help__define: function() { + return "define <name> <value>\n \nThis is another way to add a value to the context. If you want\nto have a function stored in the context, you should use this\nmethod. Using the store command will work, but only until you\nend your session. With the define command, the source code of\nthe function is saved in the browser's localstorage object so\nthat the function can be recompiled when the session is\nreloaded.\n \nExample:\n $ define sum (args...)->List.foldl args 0, (a,b)->a+b\n [function]"; + }, + define: (function(_this) { + return function(argv, data, ctx) { + var name, src; + name = argv[0]; + src = argv.slice(1).join(' '); + return (Utils.parsevalue(src)).map(function(val) { + ctx[name] = val; + if ((typeof val) === 'function') { + ctx.__functions.push({ + name: name, + source: src + }); + localStorage.setItem('context', JSON.stringify(ctx)); + } + return val; + }).map_err(function(e) { + return 'define: ' + e; + }); + }; + })(this), + help__push: (function(_this) { + return function() { + return "push [definitions]\n\nPush a new context frame onto the stack. This is mostly\nused for running scripts, where several commands will\nexecute in sequence and may need to store intermediate\nvalues in the context. For that use, the script gets its\nown frame, which is popped back off after the script\nfinishes.\n\nPush can optionally take an object on the command line,\nwhich will be used as the initial set of definitions for\nthe new context. Each named field in the object will be\navailable as a global variable in the context until it is\npopped.\n\nYou can use this feature to give yourself some working\nspace that's easy to clear when you need to keep some\ntemporary values handy for a while.\n\nExamples:\n # Basic Usage:\n \n $ push\n \"ok\"\n $ [1..4] \\ store x\n [1, 2, 3, 4]\n $ x\n [1, 2, 3, 4]\n $ x \\ pop\n [1, 2, 3, 4]\n $ x\n undefined\n\n # More features:\n \n $ [1..3] \\ push a:12,b:14 \\ store x\n [1, 2, 3]\n $ x\n [1, 2, 3]\n $ a\n 12\n $ x \\ (n)->n*n \\ pop\n [1, 4, 9]\n $ x\n undefined\n $ a\n undefined"; + }; + })(this), + push: (function(_this) { + return function(argv, data, ctx) { + var frame; + frame = Result.wrap({}); + if (argv.length > 0) { + frame = (Utils.parsevalue(argv.join(' '), ctx)).map(function(val) { + if (Utils.isObject(val)) { + return Result.wrap(val); + } else { + return Result.err("Argument must be an object"); + } + }); + } + return frame.map(function(f) { + _this.context.push(f); + return data; + }); + }; + })(this), + help__pop: function() { + return "pop\n\nPop a frame off of the context stack. You can give\nyourself temporary working space with semi-global\nvariables by calling push (see help push for\ndetails). That puts a new frame on top of the context\nstack, and this takes it off. This command will pass the\ndata parameter it receives back out to the other side, so\nyour computation can store its value in the parent context\nif you want.\n\nExample:\n $ push\n \"ok\"\n $ [1..4] \\ store x\n [1, 2, 3, 4]\n $ x\n [1, 2, 3, 4]\n $ x \\ pop\n [1, 2, 3, 4]\n $ x\n undefined\n\nIn the example, a clean context frame is pushed on the\nstack, x is stored into it and retrieved, and then the\nframe is popped off, taking the definition of x with\nit."; + }, + pop: (function(_this) { + return function(argv, data, ctx) { + _this.context.pop(); + return Result.wrap(data); + }; + })(this) + }; + }; + + return Shell; + +})(); + +module.exports = Shell; + + +},{"../utils/result":55,"../utils/utils":58,"./context":41,"./history":43,"./script-manager":49}],51:[function(require,module,exports){ +var React, Visualization, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + +React = require('react'); + +Visualization = (function(superClass) { + extend(Visualization, superClass); + + function Visualization(props) { + Visualization.__super__.constructor.call(this, props); + console.log("viz constructor"); + this.rendered = false; + this.state = {}; + } + + Visualization.prototype.render = function() { + var div; + this.rendered = true; + div = React.DOM.div; + console.log("viz render"); + return div({ + id: "revl-vizbox" + }, ""); + }; + + Visualization.prototype.shouldComponentUpdate = function() { + return !this.rendered; + }; + + return Visualization; + +})(React.Component); + +module.exports = React.createFactory(Visualization); + + +},{"react":983}],52:[function(require,module,exports){ +var API, Http, Result, ResultPromise, Utils, ref, + hasProp = {}.hasOwnProperty; + +Http = require('./http'); + +ref = require('./result'), Result = ref.Result, ResultPromise = ref.ResultPromise; + +Utils = require('./utils'); + +API = { + fetch: function(url) { + return Http.asyncjson("GET", url).map(function(r) { + if ('queryRecordCount' in r) { + return r.records; + } else { + return r; + } + }); + }, + stringify: function(data) { + switch (false) { + case !((typeof data) === "string"): + return data; + case !((typeof data) === 'number'): + return data; + case !Utils.isArray(data): + return escape(JSON.stringify(data)); + case !Utils.isObject(data): + return escape(JSON.stringify(data)); + default: + return escape(JSON.stringify(data)); + } + }, + paramstr: function(params) { + var flattened, p, s, v, val; + flattened = []; + for (p in params) { + if (!hasProp.call(params, p)) continue; + v = params[p]; + if (Utils.isArray(v)) { + flattened = flattened.concat((function() { + var i, len, results; + results = []; + for (i = 0, len = v.length; i < len; i++) { + val = v[i]; + results.push(p + '=' + (API.stringify(val))); + } + return results; + })()); + } else { + flattened.push(p + '=' + (API.stringify(v))); + } + } + s = flattened.join('&'); + if (s !== '') { + return '?' + s; + } else { + return s; + } + }, + url: function(path, params) { + var url; + url = window.location.origin + path; + if ('id' in params) { + url += '/' + params.id; + delete params.id; + if ('sub' in params) { + url += '/' + params.sub; + delete params.sub; + } + } + if ('sub' in params) { + throw "{sub: " + params.sub + "} provided without an 'id' in API call to " + path; + } + return url + (this.paramstr(params)); + }, + entry: function(params) { + return this.fetch(this.url('/scot/api/v2/entry', params)); + }, + entity: function(params) { + return this.fetch(this.url('/scot/api/v2/entity', params)); + }, + alertgroup: function(params) { + return this.fetch(this.url('/scot/api/v2/alertgroup', params)); + }, + alert: function(params) { + return this.fetch(this.url("/scot/api/v2/alert", params)); + }, + event: function(params) { + return this.fetch(this.url("/scot/api/v2/event", params)); + }, + tag: function(params) { + return this.fetch(this.url("/scot/api/v2/tag", params)); + }, + putSignature: function(sig) { + return Http.asyncjson("POST"); + }, + commands: { + server: function(argv, data, ctx) { + if (argv.length < 1) { + return Result.err("server: you must provide a URL to use for the default API server"); + } + window.API.server = argv[0]; + return Result.wrap(window.API.server); + }, + help__api: (function(_this) { + return function() { + return "SCOT API endpoint helpers\n\nThe API module offers helpers to make it easy to query the\nvarious endpoints of the SCOT API. Each command has its\nown help defined, so look there for more details if you\nneed them. All API commands have a few properties in\ncommon though:\n\n 1. You specify the URL parameters as a javascript\n object on the command line (or as the sole argument to\n the function if you're calling it from user code).\n\n 2. There are two special parameters that behave\n slightly differently: 'id', and 'sub'. 'id' allows you\n to specify which specific object you're interested in,\n and 'sub' allows you to get items that are referenced\n by the parent object. For example, you can query the\n entity endpoint without id or sub, and you'll get a\n list of entries. If you add the id, you'll get the\n single entry with that id. If you add sub: 'entity',\n you'll get the list of entities associated with that\n entry. This pattern applies to all API endpoints.\n\nAll API functions are available from within your pipeline\nfunctions under the API namespace (e.g. API.entity).\n\nPROMISES\n\nIf you use the API endpoints from inside user code (for\nexample mapping the entry helper over a list of ids from\nsome other source), be aware that these endpoints are\nasynchronous and thus return ResultPromise instances. If\nyou want to turn a list of ResultPromise instances into a\nlist of actual instances, use the wait command (see 'help\nwait' for more on that one)."; + }; + })(this), + help__entry: function() { + return "entry [params]\n\nQuery the /scot/api/v2/entry API endpoint. params is an\noptional object with name/value pairs that will be turned\ninto parameters in a GET URL. If you specify an 'id' in\nthe params, the path will be changed to\n/scot/api/v2/entry/. You can also supply the 'sub' key\nin the params, which should be the name of a thing that is\nreferenced by the entry (for example: sub: 'entity' to get\nthe entities associated with the entry). If you provide\nsub, you must also provide an id.\n\nYou can access this from a pipeline function under the\nname API.entry.\n\nExample:\n $ entry id:10987,limit:2\n [ {id:...},{id:...}]\n\n $ entry id:10987,sub:'entity',limit:1\n [{id:...}]\n \n In the first example, the actual API endpoint queried is\n '/scot/api/v2/entry/10987?limit=2'\n\n In the second example, the endpoint is\n '/scot/api/v2/entry/10987/entity?limit=1'"; + }, + entry: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.entry(p); + }).map_err(function(e) { + return 'entry: ' + e; + }); + }, + help__alertgroup: function() { + return "alertgroup [params]\n\nQuery the /scot/api/v2/alertgroup API endpoint. params is an\noptional object with name/value pairs that will be turned\ninto parameters in a GET URL. If you specify an 'id' in\nthe params, the path will be changed to\n/scot/api/v2/alertgroup/. You can also supply the 'sub' key\nin the params, which should be the name of a thing that is\nreferenced by the alertgroup (for example: sub: 'alert' to get\nthe alerts associated with the alertgroup). If you provide\nsub, you must also provide an id.\n\nYou can access this from a pipeline function under the\nname API.alertgroup.\n\nExample:\n $ alertgroup id:10987,limit:2\n [ {id:...},{id:...}]\n\n $ alertgroup id:10987,sub:'alert',limit:1\n [{id:...}]\n \n In the first example, the actual API endpoint queried is\n '/scot/api/v2/alertgroup/10987?limit=2'\n\n In the second example, the endpoint is\n '/scot/api/v2/alertgroup/10987/alert?limit=1'"; + }, + alertgroup: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.alertgroup(p); + }).map_err(function(e) { + return 'alertgroup: ' + e; + }); + }, + help__entity: function() { + return "entity [params]\n\nQuery the /scot/api/v2/entity API endpoint. params is an\noptional object with name/value pairs that will be turned\ninto parameters in a GET URL. If you specify an 'id' in\nthe params, the path will be changed to\n/scot/api/v2/entity/. You can also supply the 'sub'\nkey in the params, which should be the name of a thing\nthat is referenced by the entity (for example: sub:\n'entry' to get the entries associated with the entity). If\nyou provide sub, you must also provide an id.\n\nYou can access this from a pipeline function under the\nname API.entity.\n\nExample:\n $ entity id:10987,limit:2\n [ {id:...},{id:...}]\n\n $ entity id:10987,sub:'entry',limit:1\n [{id:...}]\n \n In the first example, the actual API endpoint queried is\n '/scot/api/v2/entity/10987?limit=2'\n\n In the second example, the endpoint is\n '/scot/api/v2/entity/10987/entry?limit=1'"; + }, + entity: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.entity(p); + }).map_err(function(e) { + return 'entity: ' + e; + }); + }, + help__alert: function() { + return "alert [params]\n\nQuery the /scot/api/v2/alert API endpoint. params is an\noptional object with name/value pairs that will be turned\ninto parameters in a GET URL. If you specify an 'id' in\nthe params, the path will be changed to\n/scot/api/v2/alert/. You can also supply the 'sub' key\nin the params, which should be the name of a thing that is\nreferenced by the alert (for example: sub: 'entry' to get\nthe entries associated with the alert). If you provide\nsub, you must also provide an id.\n\nYou can access this from a pipeline function under the\nname API.alert.\n\nExample:\n $ alert id:10987,limit:2\n [ {id:...},{id:...}]\n\n $ alert id:10987,sub:'entry',limit:1\n [{id:...}]\n \n In the first example, the actual API endpoint queried is\n '/scot/api/v2/alert/10987?limit=2'\n\n In the second example, the endpoint is\n '/scot/api/v2/alert/10987/entry?limit=1'"; + }, + alert: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.alert(p); + }).map_err(function(e) { + return 'alert: ' + e; + }); + }, + help__event: function() { + return "event [params]\n\nQuery the /scot/api/v2/event API endpoint. params is an\noptional object with name/value pairs that will be turned\ninto parameters in a GET URL. If you specify an 'id' in\nthe params, the path will be changed to\n/scot/api/v2/event/. You can also supply the 'sub' key\nin the params, which should be the name of a thing that is\nreferenced by the event (for example: sub: 'entry' to get\nthe entries associated with the event). If you provide\nsub, you must also provide an id.\n\nYou can access this from a pipeline function under the\nname API.event.\n\nExample:\n $ event id:10987,limit:2\n [ {id:...},{id:...}]\n\n $ event id:10987,sub:'entry',limit:1\n [{id:...}]\n \n In the first example, the actual API endpoint queried is\n '/scot/api/v2/event/10987?limit=2'\n\n In the second example, the endpoint is\n '/scot/api/v2/event/10987/entity?limit=1'"; + }, + event: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.event(p); + }).map_err(function(e) { + return 'event: ' + e; + }); + }, + tag: function(argv, data, ctx) { + return Utils.parsevalue(argv.join(' '), ctx).and_then(function(p) { + return API.tag(p); + }).map_err(function(e) { + return 'tag: ' + e; + }); + } + } +}; + +module.exports = API; + + +},{"./http":53,"./result":55,"./utils":58}],53:[function(require,module,exports){ +var Http, Result, ResultPromise, Utils, ref; + +Utils = require('./utils'); + +ref = require('./result'), Result = ref.Result, ResultPromise = ref.ResultPromise; + +Http = { + asyncjson: function(method, url, data) { + var ret, rq; + console.log("asyncjson " + method + " " + url + " " + (JSON.stringify(data))); + rq = new XMLHttpRequest(); + rq.open(method, url, true); + ret = new ResultPromise(); + rq.onreadystatechange = function() { + var e, msg, ref1; + if (this.readyState === 4) { + try { + if ((200 <= (ref1 = rq.status) && ref1 < 400)) { + console.log("Fulfill " + method + " " + url + " with ", rq.response); + console.log("Data is type " + (typeof rq.response)); + data = JSON.parse(rq.responseText); + return ret.fulfill(data); + } else { + msg = JSON.parse(rq.responseText)['error_msg'] || rq.response; + console.log("Error in asyncjson: ", msg); + return ret.fail(rq.statusText + ": " + msg); + } + } catch (error) { + e = error; + console.log("Exception in asyncjson: ", e, rq.response); + return ret.fail(rq.statusText + ": " + rq.response); + } + } + }; + if (data) { + rq.send(JSON.stringify(data)); + } else { + rq.send(null); + } + return ret; + }, + syncjson: function(method, url, data) { + var ref1, rq; + rq = new XMLHttpRequest(); + rq.open(method, url, false); + if (data) { + rq.setRequestHeader("Content-Type", "text/plain"); + rq.send(JSON.stringify(data)); + } else { + rq.send(null); + } + if ((200 <= (ref1 = rq.status) && ref1 < 400)) { + console.log(JSON.stringify(rq)); + data = JSON.parse(rq.responseText); + return Result.wrap(data); + } else { + console.log("Error in syncjson: ", rq.statusText); + return Result.err(rq.statusText + ": " + rq.response); + } + }, + commands: { + help__get_s: function() { + return "get_s \n\n*Synchronously* fetch JSON data from the given URL using\nthe HTTP GET method. If you have data in the pipeline\ngoing in, it will be sent to the server as the request\nbody in JSON format.\n\nThis command operates in synchronous mode, which means\nyour browser will stop until the request completes. For an\ninteractive command line, this typically isn't a problem,\nbut if your request might take a long time and you want do\nuse the browser for other things in the mean time, use the\nplain 'get' command instead.\n\nExample:\n $ get_s '/jsonstuff' \\ (item)->item.name\n\nThe example fetches a list of somethings from foo.com and\nextracts the name field of each one, returning a list of\nnames."; + }, + get_s: function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).map_err(function(e) { + return "You must provide a valid URL on the command line"; + }).and_then(function(url) { + return Http.syncjson("GET", url, d); + }).map_err(function(e) { + return "get: " + e; + }); + }, + help__get: function() { + return "get \n\nThis is the asynchronous version of the HTTP GET\nmethod. Use it to fetch JSON formatted data from a remote\nserver. The data will be automatically parsed into\njavascript objects compatible with the command pipeline.\n\nThis command operates in asynchronous mode, which means\nthat you should be able to interact with your browser\nwhile the request is waiting to be fulfilled. The command\nline will still wait until the request is fulfilled and\nfinish running the remaining pipeline at that time.\n\n Example:\n $ get_s '/jsonstuff' \\ (item)->item.name\n\nThe example fetches a list of somethings from foo.com and\nextracts the name field of each one, returning a list of\nnames."; + }, + get: function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).map_err(function(e) { + return "You must provide a valid URL on the command line: " + e; + }).and_then(function(url) { + return Http.asyncjson("GET", url, d); + }).map_err(function(e) { + return "get: " + e; + }); + }, + help__put: function() { + return "put \n\nSend data to the server using the HTTP PUT method. Data\ncan be embedded in the URL or it can be provided from the\npipeline. Any data coming in to the put command on the\npipeline will be sent to the server as the request body.\n\nExample:\n $ {superbling: true} \\ put \"/myaccount/set\"\n\nThe example sets superbling on your account."; + }, + put: function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).map_err(function(e) { + return "You must provide a valid URL on the command line"; + }).and_then(function(url) { + return Http.asyncjson("PUT", url, d); + }).map_err(function(e) { + console.log("put err: " + e); + return "put: " + e; + }); + }, + post: function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).map_err(function(e) { + return "You must provide a valid URL on the command line"; + }).and_then(function(url) { + return Http.asyncjson("POST", url, d); + }).map_err(function(e) { + console.log("post error: " + e); + return "post: " + e; + }); + } + } +}; + +module.exports = Http; + + +},{"./result":55,"./utils":58}],54:[function(require,module,exports){ +var List, Utils, + slice = [].slice, + hasProp = {}.hasOwnProperty; + +Utils = require('./utils'); + +List = { + map: function(list, proc) { + return list.map(proc); + }, + filter: function(list, proc) { + return list.filter(proc); + }, + foldl: function(acc, list, proc) { + var item, j, len, n, result; + result = acc; + for (n = j = 0, len = list.length; j < len; n = ++j) { + item = list[n]; + result = proc(result, item, n); + } + return result; + }, + foldr: function(list, acc, proc) { + var j, n, ref, result; + result = acc; + for (n = j = ref = list.length - 1; ref <= 0 ? j <= 0 : j >= 0; n = ref <= 0 ? ++j : --j) { + result = proc(list[n], result, n); + } + return result; + }, + group: function(list, sep) { + return List.foldl({}, list, (function(groups, element) { + var name; + name = sep(element); + if (groups[name] == null) { + groups[name] = []; + } + groups[name].push(element); + return groups; + })); + }, + deepmap: function(ls, proc) { + var item, j, len, result; + result = []; + for (j = 0, len = ls.length; j < len; j++) { + item = ls[j]; + if (Utils.isArray(item)) { + result.push(List.deepmap(item, proc)); + } else { + result.push(proc(item)); + } + } + return result; + }, + mapall: function(ls, proc) { + var i, j, ref, result; + result = []; + if ((ls.length < 1) || !(Utils.isArray(ls[0]))) { + return result; + } + for (i = j = 0, ref = ls[0].length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + result.push(proc.apply(null, ls.map(function(l) { + return l[i]; + }))); + } + return result; + }, + zip: function(ls) { + return List.mapall(ls, function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + return args; + }); + }, + flatten: function(ls) { + return List.foldl([], ls, function(acc, val) { + return acc.concat(val); + }); + }, + squash: function(ls) { + var acc, squasher; + acc = []; + squasher = function(item) { + var i, j, len, results; + if (Utils.isArray(item)) { + results = []; + for (j = 0, len = item.length; j < len; j++) { + i = item[j]; + results.push(squasher(i)); + } + return results; + } else { + return acc.push(item); + } + }; + squasher(ls); + return acc; + }, + sort: function(ls, proc) { + if (proc == null) { + proc = Utils.smartcmp; + } + return ls.sort(proc); + }, + uniq: function(ls, cmp) { + if (cmp == null) { + cmp = Utils.smartcmp; + } + return List.foldl([ls[0]], ls.slice(1), (function(r, item) { + if (0 !== cmp(item, r[r.length - 1])) { + r.push(item); + } + return r; + })); + }, + nest: function(ls, proc) { + var current, entry, item, j, len, len1, m, n, name, nested, paths, ref; + paths = (function() { + var j, len, results; + results = []; + for (n = j = 0, len = ls.length; j < len; n = ++j) { + item = ls[n]; + results.push({ + item: item, + path: proc(item, n) + }); + } + return results; + })(); + nested = {}; + for (j = 0, len = paths.length; j < len; j++) { + entry = paths[j]; + current = nested; + ref = entry.path; + for (m = 0, len1 = ref.length; m < len1; m++) { + name = ref[m]; + if (current[name] == null) { + current[name] = {}; + } + current = current[name]; + } + if (current.$ == null) { + current.$ = []; + } + current.$.push(entry.item); + } + return nested; + }, + bfs: function(ls, proc) { + var i, item, n, q, result; + result = []; + q = (function() { + var j, len, results; + results = []; + for (j = 0, len = ls.length; j < len; j++) { + i = ls[j]; + results.push(i); + } + return results; + })(); + n = 0; + while (q.length > 0) { + item = q.shift(); + if (Utils.isArray(item)) { + q.push.apply(q, item); + } else { + result.push(proc(item, n)); + n = n + 1; + } + } + return result; + }, + histogram: function(ls, proc) { + var j, len, n, p; + p = {}; + for (j = 0, len = ls.length; j < len; j++) { + n = ls[j]; + if (p[n] == null) { + p[n] = 0; + } + p[n]++; + } + return p; + }, + tostruct: function(ls) { + return List.foldl({}, ls, (function(acc, l) { + acc[l[0]] = l[1]; + return acc; + })); + }, + cmb: function(ls, n) { + var i, j, r, ref, result; + console.log("cmb " + (JSON.stringify(ls)) + "," + n); + result = []; + if (n > ls.length) { + throw "Can't take " + n + " from list of length " + ls.length; + } + if (n === 1) { + r = ls.map(function(e) { + return [e]; + }); + return r; + } + for (i = j = 0, ref = ls.length - n; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) { + r = List.cmb(ls.slice(i + 1), n - 1); + r.forEach(function(l) { + return l.unshift(ls[i]); + }); + result = result.concat(r); + } + return result; + }, + window: function(ls, n, proc) { + var i, j, ref, results; + if (ls.length < n) { + throw "Window of " + n + " too large for list of " + ls.length + " elements"; + } + results = []; + for (i = j = 0, ref = ls.length - n; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) { + results.push(proc.apply({}, ls.slice(i, i + n))); + } + return results; + }, + intersect: function(ls, proc) { + var g_index, group, index, j, k, key, len, len1, listcount, m, ref, ref1, set, value; + if (proc == null) { + proc = function(x) { + return x; + }; + } + set = {}; + listcount = 0; + for (g_index in ls) { + if (!hasProp.call(ls, g_index)) continue; + group = ls[g_index]; + listcount++; + for (index in group) { + if (!hasProp.call(group, index)) continue; + value = group[index]; + key = proc(value, index); + if (set[key] == null) { + set[key] = { + count: 0, + items: [] + }; + } + set[key].count++; + set[key].items.push(value); + } + } + ref = Object.keys(set); + for (j = 0, len = ref.length; j < len; j++) { + k = ref[j]; + if (set[k].count < listcount) { + delete set[k]; + } + } + set; + ref1 = Object.keys(set); + for (m = 0, len1 = ref1.length; m < len1; m++) { + k = ref1[m]; + if (set[k].count < listcount) { + delete set[k]; + } + } + return set; + }, + select: function(data, indexes) { + var index, j, len, results; + results = []; + for (j = 0, len = indexes.length; j < len; j++) { + index = indexes[j]; + if (index in data) { + results.push(data[index]); + } + } + return results; + } +}; + +List.fold = List.foldr; + +List.unzip = List.zip; + +module.exports = List; + +if ((typeof window) === 'undefined') { + console.log(List.cmb([1, 2, 3, 4], 2)); +} + + +},{"./utils":58}],55:[function(require,module,exports){ +var Error, Ok, Result, ResultPromise, Utils, err, unwrap, wrap, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + hasProp = {}.hasOwnProperty; + +Utils = require('./utils'); + +err = function(x) { + return new Result.Error(x); +}; + +wrap = function(x) { + return new Result.Ok(x); +}; + +unwrap = function(x) { + return x.content; +}; + +Result = { + err: err, + wrap: wrap, + unwrap: unwrap, + Ok: Ok = (function() { + function Ok(content1) { + this.content = content1; + } + + Ok.prototype.map = function(fn) { + var res; + res = fn(this.content); + if (res instanceof Result.Ok || res instanceof Result.Error || res instanceof ResultPromise) { + throw "Invalid map call! Please send the command you entered to ejlee@sandia.gov for a bug fix"; + } + return wrap(res); + }; + + Ok.prototype.and_then = function(fn) { + var res; + res = fn(this.content); + if (!(res instanceof Result.Ok || res instanceof Result.Error || res instanceof ResultPromise)) { + throw "Invalid and_then call! Please send the command you entered to ejlee@sandia.gov for a bug fix"; + } + return res; + }; + + Ok.prototype.err_and_then = function(fn) { + return this; + }; + + Ok.prototype.map_err = function() { + return this; + }; + + Ok.prototype.is_ok = function() { + return true; + }; + + Ok.prototype.is_err = function() { + return false; + }; + + Ok.prototype.as_promise = function() { + return ResultPromise.fulfilled(this.content); + }; + + return Ok; + + })(), + Error: Error = (function() { + function Error(content1) { + this.content = content1; + } + + Error.prototype.map = function() { + return this; + }; + + Error.prototype.and_then = function() { + return this; + }; + + Error.prototype.map_err = function(fn) { + return err(fn(this.content)); + }; + + Error.prototype.err_and_then = function(fn) { + return fn(this.content); + }; + + Error.prototype.is_ok = function() { + return false; + }; + + Error.prototype.is_err = function() { + return true; + }; + + Error.prototype.as_promise = function() { + return ResultPromise.failed(this.content); + }; + + return Error; + + })() +}; + +ResultPromise = ResultPromise = (function() { + function ResultPromise() { + this.__defaultfailure = bind(this.__defaultfailure, this); + this.__defaultsuccess = bind(this.__defaultsuccess, this); + this.complete = false; + this.error = false; + this.content = void 0; + this.next = void 0; + this.success = this.__defaultsuccess; + this.failure = this.__defaultfailure; + } + + ResultPromise.prototype.as_promise = function() { + return this; + }; + + ResultPromise.prototype.fulfill = function(content) { + if (this.complete || this.error) { + return this; + } + this.complete = true; + this.content = content; + this.success(content); + this.onProgress(1, 1); + return this; + }; + + ResultPromise.prototype.fail = function(content) { + if (this.complete || this.error) { + return this; + } + this.error = true; + this.content = content; + this.failure(content); + return this; + }; + + ResultPromise.prototype.progress = function(handler) { + this.progressHandler = handler; + this.onProgress(0, 1); + return this; + }; + + ResultPromise.prototype.__defaultsuccess = function(content) { + var ref; + return (ref = this.next) != null ? ref.fulfill(content) : void 0; + }; + + ResultPromise.prototype.__defaultfailure = function(content) { + var ref; + return (ref = this.next) != null ? ref.fail(content) : void 0; + }; + + ResultPromise.prototype.onProgress = function(done, total) { + var ref; + if (typeof this.progressHandler === "function") { + this.progressHandler(done, total); + } + return (ref = this.next) != null ? ref.onProgress(done, total) : void 0; + }; + + ResultPromise.failed = function(result) { + return (new ResultPromise()).fail(result); + }; + + ResultPromise.fulfilled = function(result) { + return (new ResultPromise()).fulfill(result); + }; + + ResultPromise.prototype.map = function(fn) { + this.next = new ResultPromise; + this.success = (function(_this) { + return function(result) { + return _this.next.fulfill(fn(result)); + }; + })(this); + this.failure = (function(_this) { + return function(result) { + return _this.next.fail(result); + }; + })(this); + if (this.complete) { + this.success(this.content); + } else if (this.error) { + this.failure(this.content); + } + return this.next; + }; + + ResultPromise.prototype.and_then = function(fn) { + this.next = new ResultPromise(); + this.success = (function(_this) { + return function(result) { + return (fn(result)).as_promise().map(function(r) { + return _this.next.fulfill(r); + }).map_err(function(e) { + return _this.next.fail(e); + }); + }; + })(this); + this.failure = (function(_this) { + return function(result) { + return _this.next.fail(result); + }; + })(this); + if (this.complete) { + this.success(this.content); + } else if (this.error) { + this.failure(this.content); + } + return this.next; + }; + + ResultPromise.prototype.map_err = function(fn) { + this.next = new ResultPromise(); + this.failure = (function(_this) { + return function(result) { + return _this.next.fail(fn(result)); + }; + })(this); + this.success = (function(_this) { + return function(result) { + return _this.next.fulfill(result); + }; + })(this); + if (this.error) { + this.failure(this.content); + } else if (this.complete) { + this.success(this.content); + } + return this.next; + }; + + ResultPromise.prototype.err_and_then = function(fn) { + this.next = new ResultPromise(); + this.failure = (function(_this) { + return function(result) { + console.log("failing in err_and_then"); + return (fn(result)).as_promise().map_err(function(e) { + console.log("err_and_then..map_err"); + return _this.next.fail(e); + }).map(function(r) { + console.log("err_and_then..map"); + return _this.next.fulfill(r); + }); + }; + })(this); + this.success = (function(_this) { + return function(result) { + return _this.next.fulfill(result); + }; + })(this); + if (this.error) { + this.failure(this.content); + } else if (this.complete) { + this.success(this.content); + } + return this.next; + }; + + ResultPromise.prototype.wait = function(timeout) { + if (timeout == null) { + timeout = 60; + } + return ResultPromise.wait(this, timeout); + }; + + ResultPromise.wait = function(p, timeout) { + if (timeout == null) { + timeout = 60; + } + Utils = require('./utils'); + if (p instanceof ResultPromise) { + return p; + } else { + return ResultPromise.waitreplace(p, timeout); + } + }; + + ResultPromise.waitall = function(ps, timeout) { + var count, i, j, n, p, ref, resetTimeout, result, timer, update, updatemaker, values; + result = new ResultPromise; + values = (function() { + var j, len, results; + results = []; + for (j = 0, len = ps.length; j < len; j++) { + p = ps[j]; + results.push(null); + } + return results; + })(); + count = ps.length; + timer = void 0; + resetTimeout = function() { + clearTimeout(timer); + return timer = setTimeout((function() { + console.log("Fulfilling promise with partial result. Last result was more than 10 seconds ago."); + return result.fulfill(values.filter(function(v) { + return v !== null; + })); + }), timeout * 1000); + }; + update = function(d, n) { + console.log("Assign promised result number " + n); + values[n] = d; + count--; + if (count === 0) { + clearTimeout(timer); + return result.fulfill(values); + } + }; + updatemaker = function(n) { + return function(d) { + update(d, n); + return resetTimeout(); + }; + }; + for (i = j = 0, ref = ps.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) { + n = i + 0; + ps[i].map(updatemaker(n)); + } + return result; + }; + + ResultPromise.waitreplace = function(mixed, timeout) { + var cancel, cancelmaker, holes, replacer, resetTimeout, result, timer, totalholes, update, updatemaker; + result = new ResultPromise; + totalholes = 0; + holes = 0; + timer = void 0; + cancel = false; + resetTimeout = function() { + clearTimeout(timer); + return timer = setTimeout((function() { + console.log("Promise timed out, making partial fulfillment"); + return result.fulfill(mixed); + }), timeout * 1000); + }; + update = function(object, key, value, hole) { + console.log("filled hole " + hole + ", " + holes + " remaining"); + object[key] = value; + holes--; + result.onProgress(totalholes - holes, totalholes); + if (holes === 0) { + clearTimeout(timer); + return result.fulfill(mixed); + } + }; + updatemaker = function(object, key, hole) { + return function(val) { + update(object, key, val, hole); + return resetTimeout(); + }; + }; + cancelmaker = function(object, key, hole) { + return function(err) { + resetTimeout(); + console.log("Error: ", err, " Cancelling slot " + hole + " in waitreplace"); + object[key] = void 0; + holes--; + return result.onProgress(totalholes - holes, totalholes); + }; + }; + replacer = function(subitem) { + var part, promise; + for (part in subitem) { + if (!hasProp.call(subitem, part)) continue; + promise = subitem[part]; + if (promise instanceof ResultPromise) { + promise.map(updatemaker(subitem, part, holes++)).map_err(cancelmaker(subitem, part, holes - 1)); + totalholes++; + } else if ((Utils.isArray(promise)) || (Utils.isObject(promise))) { + replacer(promise); + } + } + return console.log("Replacing " + totalholes + " promises in waitreplace"); + }; + replacer(mixed); + if (holes === 0) { + result.fulfill(mixed); + } + return result; + }; + + ResultPromise.commands = { + help__wait: function() { + return "wait [timeout]\n\nIf you have run a command that will return a set of\npromises, this command will wait until all of them have\nbeen fulfilled, then continue the command pipeline with a\nlist of the resulting values.\n\nTimeout is an optional number of seconds to wait before\nreturning an incomplete result. The timer will be reset to\nthe full timeout after each successful completion, so\nthink of this as saying \"Wait as long as it takes while\nstuff is happening, but when there has been a long lag\nbetween updates, go ahead and just call it done.\" Note\nthat this result will have unfulfilled promise instances\nsprinkled through it, so you will have to filter them out\nif later pipeline elements can't deal with them.\n\nExample:\n $ get \"https://a.com/event_ids\" \\ (id)->Http.asyncjson \"GET\",(\"https://a.com/event/\"+id) \\ wait\n [list of events]\n\nHttp.asyncjson returns a promise that will be fulfilled\nwhen the server responds to the query. This command will\nwait on one promise or a list of promises, and fulfill its\nown promise when they are all completed."; + }, + wait: function(argv, data, ctx) { + if (argv.length > 0) { + return Utils.parsevalue(argv.join(' '), ctx).map_err(function(e) { + return Result.err('ResultPromise: ' + e); + }).map(function(timeout) { + return ResultPromise.wait(data, timeout); + }); + } else { + return ResultPromise.wait(data); + } + } + }; + + return ResultPromise; + +})(); + +module.exports = { + Result: Result, + ResultPromise: ResultPromise +}; + + +},{"./utils":58}],56:[function(require,module,exports){ +var Result, Strings, Utils; + +Utils = require('./utils'); + +Result = require('./result').Result; + +Strings = { + pat: { + ip: /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/, + hostname: /([a-zA-Z0-9_\-]\.)+[a-zA-Z0-9_\-]+/, + unixtime: /1[0-9]{9}\.[0-9]{6}/, + hms: /([0-9]{2}):([0-9]{2}):([0-9]{2})/, + timedate: /(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]+) ([0-9]+):([0-9+):([0-9]+) ([0-9]+)/, + email: /[^ ]+@([a-zA-Z0-9_\-]+\.)+[a-zA-Z0-9_\-]+/ + }, + pick: function(rx, str) { + var match, re, result; + re = new RegExp(rx.source, 'g'); + result = []; + match = null; + while ((match = re.exec(str))) { + result.push(match); + } + return result; + }, + commands: { + help__pick: function() { + return "pick \n\nScan the piped in string for instances of regex, and\nreturn a list of all matches. Each element of the list\nwill be the full match object from the regex match, so you\ncan access the index and the input from each match.\n\nThis function is also available inside your pipeline\nfunctions under the name Strings.pick. If you call it\ndirectly, pass the regular expression as the first\nargument and the string to pick from as the second\nargument\n\nExample:\n $ \"abcdefghi\" \\ pick /[a-z]{3}\n [[\"abc\",index:0,input:\"abcdefghi\"],\n [\"def\",index:3,input:\"abcdefghi\"],\n [\"ghi\",index:6,input:\"abcdefghi\"]]\n\n $ [\"abc\",\"def\",\"ghi\"] \\ (s)->Strings.pick /[a-z]{2}/, s\n [[\"ab\",index:0,input:\"abc\"],[\"de\",index:0,input:\"def\"],[\"gh\",index:0,input\"ghi\"]]"; + }, + pick: function(argv, d, ctx) { + return (Utils.parsevalue(argv[0], ctx)).map(function(re) { + if (!re instanceof RegExp) { + return Result.err("Please supply a regular expression on the command line"); + } + return Result.wrap(Strings.pick(re, d)); + }).map_err(function(e) { + return "pick: " + e; + }); + } + } +}; + +module.exports = Strings; + + +},{"./result":55,"./utils":58}],57:[function(require,module,exports){ +var Result, Struct, Utils, + hasProp = {}.hasOwnProperty; + +Utils = require('./utils'); + +Result = require('./result').Result; + +Struct = { + bfs: function(s, proc) { + var item, k, n, q, result; + result = []; + q = (function() { + var results; + results = []; + for (k in s) { + if (!hasProp.call(s, k)) continue; + results.push([[k], s[k]]); + } + return results; + })(); + n = 0; + while (q.length > 0) { + item = q.shift(); + if (Utils.isObject(item[1])) { + [].push.apply(q, (function() { + var results; + results = []; + for (k in item[1]) { + results.push([item[0].concat([k]), item[1][k]]); + } + return results; + })()); + } else { + result.push(proc(item[1], item[0], n)); + n = n + 1; + } + } + return result; + }, + map: function(s, proc) { + var key, result, value; + result = {}; + for (key in s) { + if (!hasProp.call(s, key)) continue; + value = s[key]; + result[key] = proc(value, key); + } + return result; + }, + deepmap: function(s, proc) { + var key, result, value; + result = {}; + for (key in s) { + if (!hasProp.call(s, key)) continue; + value = s[key]; + if (Utils.isObject(value)) { + result[key] = Struct.deepmap(value, proc); + } else { + result[key] = proc(value); + } + } + return result; + }, + filter: function(s, proc) { + var key, result, value; + result = {}; + for (key in s) { + if (!hasProp.call(s, key)) continue; + value = s[key]; + if (proc(value, key)) { + result[key] = value; + } + } + return result; + }, + tolist: function(s) { + var key, results; + results = []; + for (key in s) { + if (!hasProp.call(s, key)) continue; + results.push([key, s[key]]); + } + return results; + }, + select: function(s, keys) { + var i, k, len, r; + r = {}; + for (i = 0, len = keys.length; i < len; i++) { + k = keys[i]; + if (k in s) { + r[k] = s[k]; + } + } + return r; + } +}; + +module.exports = Struct; + + +},{"./result":55,"./utils":58}],58:[function(require,module,exports){ +var Context, Result, Utils; + +Result = require('./result').Result; + +Context = require('../ui/context'); + +Utils = { + isArray: Array.isArray || function(value) { + return {}.toString.call(value) === '[object Array]'; + }, + isObject: function(ob) { + return (typeof ob) === "object" && (ob instanceof Object) && (!Utils.isArray(ob)); + }, + isNumber: function(val) { + return typeof val === 'number'; + }, + smartcmp: function(a, b) { + switch (false) { + case !((Utils.isNumber(a)) && Utils.isNumber(b)): + return a - b; + case !((Utils.isNumber(a)) && !Utils.isNumber(b)): + return -1; + case !((Utils.isNumber(b)) && !Utils.isNumber(a)): + return 1; + case !(a < b): + return -1; + case a !== b: + return 0; + default: + return 1; + } + }, + parsefunction: function(txt, ctx) { + var e, names, proc, src; + try { + names = Context.argnames(ctx); + src = "(" + (names.join(',')) + ')-> ' + txt; + proc = (CoffeeScript["eval"](src)).apply(ctx, Context.argvals(ctx, names)); + if ((typeof proc) !== "function") { + return Result.err("Expected a function, got \"" + txt + "\""); + } else { + return Result.wrap(proc); + } + } catch (error) { + e = error; + return Result.err("" + e); + } + }, + parsevalue: function(txt, ctx) { + var e, exp, names, src; + try { + names = Context.argnames(ctx); + src = "((" + (names.join(',')) + ')->' + txt + ')'; + exp = (CoffeeScript["eval"](src)).apply(ctx, Context.argvals(ctx, names)); + if (typeof exp === "undefined") { + return Result.err("Expected a value, got nothing"); + } else { + return Result.wrap(exp); + } + } catch (error) { + e = error; + return Result.err("Parse error: " + e); + } + }, + hsv2rgb: function(h, s, v) { + var ff, hh, i, p, q, t; + if (s <= 0) { + return { + r: v, + g: v, + b: v + }; + } + hh = h * 6; + if (hh >= 6) { + hh = 0; + } + i = Math.floor(hh); + ff = hh - i; + p = v * (1 - s); + q = v * (1 - (s * ff)); + t = v * (1 - (s * (1 - ff))); + switch (i) { + case 0: + return { + r: v, + g: t, + b: p + }; + case 1: + return { + r: q, + g: v, + b: p + }; + case 2: + return { + r: p, + g: v, + b: t + }; + case 3: + return { + r: p, + g: q, + b: v + }; + case 4: + return { + r: t, + g: p, + b: v + }; + case 5: + return { + r: v, + g: p, + b: q + }; + default: + return { + r: v, + g: p, + b: q + }; + } + }, + pickColor: function(index, max) { + var rgb; + if (max == null) { + max = 20; + } + if (index >= max) { + max = index + 1; + } + if (max < 5) { + max = 5; + } + rgb = Utils.hsv2rgb(index / max, 0.7, 0.6); + return '#' + ([rgb.r, rgb.g, rgb.b].map(function(c) { + return (Math.floor(c * 256)).toString(16); + }).join('')); + }, + heatColor: function(index, max) { + var colors, colorscale, datascale; + if (max == null) { + max = 100; + } + colors = ["#800", "#f80", "#ff0"]; + colorscale = d3.scaleLinear().domain([0, colors.length - 1]).range(colors); + datascale = d3.scaleLinear().domain([0, max]).range([0, colors.length - 1]); + return colorscale(datascale(index)); + } +}; + +module.exports = Utils; + + +},{"../ui/context":41,"./result":55}],59:[function(require,module,exports){ +var Barchart, Result; + +Result = require('../utils/result').Result; + +Barchart = (function() { + Barchart.commands = { + help__barchart: function() { + return "barchart\n\nbarchart produces a bar chart in the visualization pane\nbased on the input. Input should be formatted as an\nobject, where the keys will be the chart labels and the\nvalues will be the heights of the bars. The chart is\nautomatically scaled so that all bars fit and the tallest\nbar is the height of the full chart. You can also just\npass in a list of numbers, and the labels will be the\nindexes.\n\nExamples:\n $ {cheezburgers: 50, cats: 1} \\ barchart\n\n $ [1,2,3,4,5] \\ barchart\n\nThe first example command produces a chart with two\nbars. The first is labeled \"cheezburgers\" and has height\n50, and the second is labeled \"cats\" and has height 1.\n\nThe second example produces a bar chart with five bars,\nlabeled 0 through 4, with heights given in the list.\n\nThe input will be passed through this command so you can\npipe other commands after it if needed"; + }, + barchart: function(argv, d) { + var chart; + chart = new Barchart(argv, d); + chart.render("#revl-vizbox"); + return Result.wrap(d); + } + }; + + function Barchart(argv, data) { + var k, ref, v; + this.data = data; + this.maxdata = void 0; + this.pairs = []; + ref = this.data; + for (k in ref) { + v = ref[k]; + if (this.maxdata == null) { + this.maxdata = v; + } + this.pairs.push([k, +v]); + if (this.maxdata < v) { + this.maxdata = v; + } + } + } + + Barchart.prototype.render = function(target) { + var g, height, margin, svg, width, x, y; + svg = d3.select(target).html("").append("svg").attr("class", "viz"); + margin = { + top: 20, + right: 20, + bottom: 30, + left: 40 + }; + width = +document.querySelector(target).offsetWidth - margin.left - margin.right; + height = +document.querySelector(target).offsetHeight - margin.top - margin.bottom; + console.log("width: " + width); + console.log("height: " + height); + x = d3.scaleBand().rangeRound([0, width]).padding(0.1).domain(this.pairs.map(function(p) { + return p[0]; + })); + y = d3.scaleLinear().rangeRound([height, 0]).domain([ + 0, d3.max(this.pairs.map(function(p) { + return p[1]; + })) + ]); + g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + console.log("bar width: " + x.bandwidth()); + g.append("g").attr("class", "axis barchart-axis--x").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x)); + g.append("g").attr("class", "axis barchart-axis--y").call((d3.axisLeft(y)).ticks(10)).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", "0.71em").attr("text-anchor", "end").text("Value"); + return g.selectAll(".barchart-bar").data(this.pairs).enter().append("rect").attr("class", "barchart-bar").attr("x", function(d) { + return x(d[0]); + }).attr("y", function(d) { + return y(d[1]); + }).attr("width", x.bandwidth()).attr("height", function(d) { + return height - y(d[1]); + }); + }; + + return Barchart; + +})(); + +module.exports = Barchart; + + +},{"../utils/result":55}],60:[function(require,module,exports){ +var Dotchart, Result, Utils, fzero; + +Utils = require('../utils/utils'); + +Result = require('../utils/result').Result; + +fzero = require('../geometry/eps').fzero; + +Dotchart = (function() { + function Dotchart(pts) { + this.pts = pts; + } + + Dotchart.prototype.draw = function(target) { + var height, margin, svg, width, x, xAxis, xExt, xpad, y, yAxis, yExt, ypad; + margin = { + top: 20, + right: 20, + bottom: 30, + left: 50 + }; + width = target.offsetWidth - margin.left - margin.right; + height = target.offsetHeight - margin.top - margin.bottom; + x = d3.scaleLinear().range([0, width]); + y = d3.scaleLinear().range([height, 0]); + xAxis = d3.axisBottom().scale(x); + yAxis = d3.axisLeft().scale(y); + xExt = d3.extent(this.pts.map(function(p) { + return p[0]; + })); + yExt = d3.extent(this.pts.map(function(p) { + return p[1]; + })); + xpad = (xExt[1] - xExt[0]) * 0.05; + ypad = (yExt[1] - yExt[0]) * 0.05; + if (fzero(xpad)) { + xpad = 0.001; + } + if (fzero(ypad)) { + ypad = 0.001; + } + x.domain([xExt[0] - xpad, xExt[1] + xpad]); + y.domain([yExt[0] - ypad, yExt[1] + ypad]); + svg = d3.select(target).html("").append("svg").attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); + svg.append("g").attr("class", "linechart-x axis").attr("transform", "translate(0," + height + ")").call(xAxis); + svg.append("g").attr("class", "linechart-y-axis axis").call(yAxis); + svg.selectAll(".dot").data(this.pts).enter().append("circle").attr("class", "dot").attr("r", 1.5).attr("cx", function(d) { + return x(d[0]); + }).attr("cy", function(d) { + return y(d[1]); + }).style("fill", function(d) { + return Utils.pickColor(d[0], xExt[1]); + }); + return Result.wrap(this.pts); + }; + + Dotchart.commands = { + help__dotchart: function() { + return "dotchart\n\nDotchart makes a scatter plot, with one dot for each data\npoint in a 2D data set.\n\nExample:\n $ get \"https://localhost/scot/api/v2/alertgroup/1512214/alert?limit=100\" \\\n .. (r)->map r.records,(rec)->rec.data._time \\\n .. pick Strings.pat.hms \\\n .. (ls)->(parseInt ls[1])*3600 + (parseInt ls[2])*60 + parseInt ls[3] \\\n .. sort \\\n .. (t,i)->[t,i] \\\n .. dotchart\n\n This command retreives the alerts in alertgroup\n 1512214, picks out all of the timestamps, converts\n them to a number of seconds (assuming the day is all\n the same), sorts them in ascending order,then makes a\n dotchart with the x coordinate being the timestamp and\n the y coordinate being the position of the event in\n the set. This makes it easy to see timing patterns\n (they look like tall spikes of dots)."; + }, + dotchart: function(argv, d, ctx) { + var chart; + chart = new Dotchart(d); + return chart.draw(document.querySelector("#revl-vizbox")); + } + }; + + return Dotchart; + +})(); + +module.exports = Dotchart; + + +},{"../geometry/eps":34,"../utils/result":55,"../utils/utils":58}],61:[function(require,module,exports){ +var Forcegraph, Result, Utils, + hasProp = {}.hasOwnProperty; + +Result = require('../utils/result').Result; + +Utils = require('../utils/utils'); + +Forcegraph = (function() { + Forcegraph.commands = { + help__forcegraph: function() { + return "forcegraph [naming proc]\n\nforcegraph produces a nodes-and-links graph from the data\nprovided. It expects either an object with a key for each\nnode (kind of, see below), or a list of links. If you\nspecify the naming proc, it will be called on each node to\nprovide a unique name for the node (this is how a node is\nrecognized across multiple links). If you have complex\nobjects, provide a name function that reduces them to\nsomething simple that can work as the key in a javascript\nobject. By default, the entire node will just be turned\ninto a string.\n\nThe object works like an association list. You give the\nnode name as the key, and a list of nodes it connects with\nas the value. The list of nodes can either be just a\nsimple flat list of link specifiers (see below), or an\nobject with your own metadata and a member named 'links'\nwith the list of link specifiers.\n\nThe list format simply specifies the graph by calling out\neach link. To use this, just pass in a flat list with all\nof the links given as link specifiers. Node names will be\ncollected from the link endpoints automatically. If you\nneed to draw a node with no links, just pass in a link\nspecifier with an endpoint missing.\n\nLink specifiers are either just a pair of node names, or\nan object with a 'from' and 'to' field in addition to\nwhatever metadata you want to add. If you use the object\nformat for specifying nodes, you can leave out the 'from'\nfield for the link specifiers as it will be taken from the\nnode name being processed instead.\n\nExamples:\n $ [['foo','bar'],['bar',bla'],['foo','bla']] \\ forcegraph\n\n $ {foo: ['bar','bla'], bar: ['bla']} \\ forcegraph\n\n $ [{from: 'foo', to: 'bar', counter:97},\n {from: 'foo',to:'bla', counter:8},\n {from: 'bar',to:'bla',counter:1000}] \\ forcegraph\n\n $ {foo: {links: [{to: 'bar', counter: 97}\n {to: 'bla', counter: 8}]\n coolness: 0},\n bar: {links: [{to: 'bla', counter: 1000}]\n coolness: 99},\n bla: {links: [],\n coolness: 22}} \\ forcegraph\n \nAll three examples produce the same graph with three nodes\nconnected by three links in a triangle.\n\nThe input will be passed through this command so you can\npipe other commands after it if needed"; + }, + forcegraph: function(argv, d, ctx) { + var chart; + chart = new Forcegraph(argv, d, ctx); + chart.render("#revl-vizbox"); + return Result.wrap(d); + } + }; + + function Forcegraph(argv, data, ctx) { + this.graph = { + links: [], + nodes: {} + }; + this.maxdata = void 0; + this.namer = function(n) { + return n; + }; + if (argv.length > 0) { + Utils.parsefunction(argv.join(' '), ctx).map((function(_this) { + return function(proc) { + return _this.namer = proc; + }; + })(this)).map_err(e)(function() { + throw e; + }); + } + this.pairs = []; + this.ingest(data); + window.fg = this; + } + + Forcegraph.prototype.ingest = function(data) { + var d, i, len, results; + this.graph = { + links: {}, + nodes: {} + }; + if (Utils.isArray(data)) { + results = []; + for (i = 0, len = data.length; i < len; i++) { + d = data[i]; + results.push(this.ingest_link(d)); + } + return results; + } + }; + + Forcegraph.prototype.ingest_link = function(link, insrc) { + var base, base1, clone, data, l, src, to; + if (insrc == null) { + insrc = void 0; + } + if (Utils.isArray(link)) { + clone = (function() { + var i, len, results; + results = []; + for (i = 0, len = link.length; i < len; i++) { + l = link[i]; + results.push(l); + } + return results; + })(); + src = void 0; + if (clone.length > 1 && (typeof clone[1] !== "object")) { + src = clone.shift(); + } + to = '' + clone.shift(); + if (src == null) { + src = '' + insrc; + } + data = clone.shift() || null; + this.ensure_node(to); + this.ensure_node(src); + if ((base = this.graph.links)[src] == null) { + base[src] = {}; + } + return (base1 = this.graph.links[src])[to] != null ? base1[to] : base1[to] = data; + } + }; + + Forcegraph.prototype.ensure_node = function(node) { + var base, name; + if (!node) { + return; + } + return (base = this.graph.nodes)[name = '' + (this.namer(node))] != null ? base[name] : base[name] = { + id: '' + (this.namer(node)), + data: {} + }; + }; + + Forcegraph.prototype.links = function() { + var ref, ref1, result, src, to; + result = []; + ref = this.graph.links; + for (src in ref) { + if (!hasProp.call(ref, src)) continue; + ref1 = this.graph.links[src]; + for (to in ref1) { + if (!hasProp.call(ref1, to)) continue; + result.push({ + source: src, + target: to, + data: this.graph.links[src][to] + }); + } + } + return result; + }; + + Forcegraph.prototype.render = function(target) { + var height, link, links, margin, node, nodes, simulation, svg, width; + svg = d3.select(target).html("").append("svg").attr("class", "viz"); + margin = { + top: 20, + right: 20, + bottom: 30, + left: 40 + }; + width = +document.querySelector(target).offsetWidth - margin.left - margin.right; + height = +document.querySelector(target).offsetHeight - margin.top - margin.bottom; + nodes = (Object.keys(this.graph.nodes)).map((function(_this) { + return function(n) { + return _this.graph.nodes[n]; + }; + })(this)); + links = this.links(); + window.fgraph = { + nodes: nodes, + links: links + }; + console.log(JSON.stringify(nodes)); + console.log(JSON.stringify(links)); + simulation = d3.forceSimulation().force("link", d3.forceLink().id(function(d) { + return d.id; + })).force("charge", d3.forceManyBody()).force("center", d3.forceCenter(width / 2, height / 2)); + link = svg.append("g").attr("class", "forcegraph-links").selectAll("line").data(links).enter().append("line").attr("stroke-width", 2); + node = svg.append("g").attr("class", "forcegraph-nodes").selectAll("circle").data(nodes).enter().append("circle").attr("r", 5).attr("fill", Utils.pickColor(1)); + node.append("title").text(function(d) { + return d.id; + }); + simulation.nodes(nodes).on("tick", function() { + link.attr("x1", function(d) { + return d.source.x; + }).attr("y1", function(d) { + return d.source.y; + }).attr("x2", function(d) { + return d.target.x; + }).attr("y2", function(d) { + return d.target.y; + }); + return node.attr("cx", function(d) { + return d.x; + }).attr("cy", function(d) { + return d.y; + }); + }); + return simulation.force("link").links(links); + }; + + return Forcegraph; + +})(); + +module.exports = Forcegraph; + + +},{"../utils/result":55,"../utils/utils":58}],62:[function(require,module,exports){ +var Linechart, Result, Utils, feq, fzero, ref; + +Utils = require('../utils/utils'); + +Result = require('../utils/result').Result; + +ref = require('../geometry/eps'), fzero = ref.fzero, feq = ref.feq; + +Linechart = (function() { + function Linechart(target) { + this.target = target; + } + + Linechart.commands = { + help__linechart: function() { + return "linechart\n \nlinechart produces a chart with lines tracing data series. It\nexpects data in the form of either lists of points, or objects\nthat have data members as follows:\n \nList form:\n [[[x1,y1],[x2,y2],...], [[x1,y1],[x2,y2]...], ...]\n \n The outer list contains a bunch of series. The inner lists\n are each single series, which are lists of point pairs. If\n you only want to chart a single data series, you can just\n pass in the list of point pairs and the linechart command\n will figure it out.\n \nObject form:\n[{\n points: [[x1,y1],[x2,y2]...]\n name: 'optional label for this series'\n color: 'optional html color name'\n style: 'optional line style'\n } ...]\n \n \n Examples:\n $ [[1,1],[2,4],[3,9]] \\ linechart\n # plots a linechart with y = x^2\n \n $ [[[1,1],[2,4],[3,9]],[[1,1],[2,2],[3,3]]] \\ linechart\n # plots a chart with two lines, one for y=x^2 and the other for y=x\n \n $ [{ points: [[1,1],[2,4],[3,9]],\n name: 'y=x^2',\n color: 'red'},\n { points: [[1,1],[2,2],[3,3]],\n name: 'y=x',\n color: 'blue'}] \\ linechart\n #plots two traces, labeled and colored as given"; + }, + linechart: function(argv, d, ctx) { + return Linechart.formatData(d).map(function(data) { + var lc; + lc = new Linechart(document.querySelector("#revl-vizbox")); + return lc.render(data); + }).map_err(function(e) { + return "linechart: " + e; + }); + } + }; + + Linechart.formatData = function(d) { + var i, len, series; + switch (false) { + case !((Utils.isArray(d)) && (Utils.isArray(d[0])) && (Utils.isArray(d[0][0]))): + return Result.wrap(d.map(function(series, idx) { + return { + points: series, + name: 'series ' + (idx + 1), + color: Utils.pickColor(idx, d.length), + style: '1px solid' + }; + })); + case !((Utils.isArray(d)) && (Utils.isArray(d[0]))): + return Result.wrap([ + { + points: d, + name: 'series 1', + color: Utils.pickColor(0), + style: '1px solid' + } + ]); + case !((Utils.isArray(d)) && (Utils.isObject(d[0]))): + for (i = 0, len = d.length; i < len; i++) { + series = d[i]; + if (!Utils.isArray(series.points)) { + return Result.err("series must have a 'points' member when objects are used"); + } + } + return Result.wrap(d.map(function(series, idx) { + if (series.color == null) { + series.color = Utils.pickColor(idx, d.length); + } + if (series.style == null) { + series.style = '1px solid'; + } + return series; + })); + case !Utils.isObject(d): + if (!Utils.isArray(d.points)) { + return Result.err("series must have a 'points' member when objects are used"); + } else { + if (d.color == null) { + d.color = Utils.pickColor(0); + } + if (d.style == null) { + d.style = '1px solid'; + } + return Result.wrap([d]); + } + break; + default: + return Result.err("Unrecognized data format, see 'help linechart' for details"); + } + }; + + Linechart.prototype.render = function(data) { + var height, i, len, line, margin, ref1, ref2, series, svg, width, x, xAxis, xExt, xpad, y, yAxis, yExt, ypad; + margin = { + top: 20, + right: 20, + bottom: 30, + left: 50 + }; + width = this.target.offsetWidth - margin.left - margin.right; + height = this.target.offsetHeight - margin.top - margin.bottom; + x = d3.scaleLinear().range([0, width]); + y = d3.scaleLinear().range([height, 0]); + xAxis = d3.axisBottom().scale(x); + yAxis = d3.axisLeft().scale(y); + xExt = d3.extent((ref1 = []).concat.apply(ref1, (function() { + var i, len, results; + results = []; + for (i = 0, len = data.length; i < len; i++) { + series = data[i]; + results.push(series.points.map(function(p) { + return p[0]; + })); + } + return results; + })())); + yExt = d3.extent((ref2 = []).concat.apply(ref2, (function() { + var i, len, results; + results = []; + for (i = 0, len = data.length; i < len; i++) { + series = data[i]; + results.push(series.points.map(function(p) { + return p[1]; + })); + } + return results; + })())); + xpad = (xExt[1] - xExt[0]) * 0.05; + ypad = (yExt[1] - yExt[0]) * 0.05; + if (fzero(xpad)) { + xpad = 0.001; + } + if (fzero(ypad)) { + ypad = 0.001; + } + x.domain([xExt[0] - xpad, xExt[1] + xpad]); + y.domain([yExt[0] - ypad, yExt[1] + ypad]); + svg = d3.select(this.target).html("").append("svg").attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom).append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); + svg.append("g").attr("class", "linechart-x axis").attr("transform", "translate(0," + height + ")").call(xAxis); + svg.append("g").attr("class", "linechart-y-axis axis").call(yAxis); + for (i = 0, len = data.length; i < len; i++) { + series = data[i]; + line = d3.line().x(function(d) { + return x(d[0]); + }).y(function(d) { + return y(d[1]); + }); + svg.append("path").datum(series.points).attr("class", "linechart-line").attr("d", line).attr('stroke', series.color); + } + return Result.wrap(data); + }; + + return Linechart; + +})(); + +module.exports = Linechart; + + +},{"../geometry/eps":34,"../utils/result":55,"../utils/utils":58}],63:[function(require,module,exports){ +var BoundingBox, Poly, Polygon, Result, Utils, Vec, Voronoi, fgt, polygon, ref, + hasProp = {}.hasOwnProperty; + +Result = require('../utils/result').Result; + +ref = require('../geometry/polygon'), polygon = ref.polygon, Polygon = ref.Polygon; + +Utils = require('../utils/utils'); + +Vec = require('../geometry/vec'); + +BoundingBox = require('../geometry/boundingbox'); + +Voronoi = require('../geometry/voronoi'); + +fgt = require('../geometry/eps').fgt; + +Poly = { + drawPolygons: function(pgons, svg, w, h) { + var container; + container = svg.selectAll("g").data(pgons).enter().append("g").attr("transform", "translate(" + (w * 0.1) + ',' + (h * 0.1) + ')'); + container.append("polygon").attr("points", function(pgon) { + return (pgon.verts.map(function(pt) { + return pt.x() + ',' + pt.y(); + })).join(' '); + }).attr("fill", function(pgon, n) { + if ('color' in pgon) { + return pgon.color; + } else { + return Utils.pickColor(n, pgons.length + 1); + } + }).attr("stroke-width", "1").attr("stroke", function(pgon) { + return "black"; + }); + return container.append("text").attr("transform", function(pgon) { + var cm; + cm = pgon.center(); + return "translate(" + cm.x() + ',' + cm.y() + ')'; + }).text(function(d) { + if (d.label) { + return JSON.stringify(d.label); + } else { + return ""; + } + }).attr("y", "0.35em").style("text-anchor", "middle"); + }, + drawImage: function(img, svg, w, h) {}, + grid: function(data) { + var cellAt, cellh, cells, cellw, col, cols, h, padding, ref1, row, rows, w, x, y; + rows = (Object.keys(data)).length; + cols = Math.max.apply({}, (function() { + var results; + results = []; + for (x in data) { + if (!hasProp.call(data, x)) continue; + results.push((Object.keys(data[x])).length); + } + return results; + })()); + w = (document.getElementById("revl-vizbox")).offsetWidth * 0.8; + h = (document.getElementById("revl-vizbox")).offsetHeight * 0.8; + padding = 2; + if ((w / cols < 10) || (h / rows < 10)) { + padding = 0; + } + cellw = (w / cols) - padding; + cellh = (h / rows) - padding; + cellAt = function(x, y, data) { + var p; + p = polygon([[x, y + cellh], [x, y], [x + cellw, y], [x + cellw, y + cellh]]); + p.input = data; + return p; + }; + cells = []; + y = 0; + for (row in data) { + if (!hasProp.call(data, row)) continue; + x = 0; + ref1 = data[row]; + for (col in ref1) { + if (!hasProp.call(ref1, col)) continue; + cells.push(cellAt(x * (cellw + padding), y * (cellh + padding), data[row][col])); + x++; + } + y++; + } + return { + data: data, + polygons: cells + }; + }, + eachpoly: function(data, proc) { + var k, len, poly, ref1; + ref1 = data.polygons; + for (k = 0, len = ref1.length; k < len; k++) { + poly = ref1[k]; + proc(poly); + } + return data; + }, + mappoly: function(data, proc) { + var k, len, p, poly, r, ref1; + r = []; + ref1 = data.polygons; + for (k = 0, len = ref1.length; k < len; k++) { + poly = ref1[k]; + p = proc(poly); + if ((typeof p) !== 'undefined') { + if (Utils.isArray(p)) { + r.push.apply(r, p); + } else { + r.push(p); + } + } + } + data.polygons = r; + return data; + }, + genpoints: function(count, boundary) { + var bbox, i, j, k, mkpt, points, pt, ref1, v; + bbox = boundary.bbox(); + points = []; + pt = void 0; + mkpt = function() { + return new Vec([Math.random() * bbox.w + bbox.left(), Math.random() * bbox.h + bbox.top()]); + }; + for (i = k = 0, ref1 = count; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) { + pt = mkpt(); + j = 0; + while (j < 10 && !boundary.contains(pt)) { + j++; + pt = mkpt(); + } + if (j >= 10) { + console.log("polygon(" + (JSON.stringify((function() { + var l, len, ref2, results; + ref2 = boundary.verts; + results = []; + for (l = 0, len = ref2.length; l < len; l++) { + v = ref2[l]; + results.push([v.x(), v.y()]); + } + return results; + })())) + ")"); + throw "Error: Couldn't make a point fit in the boundary for polygon " + (JSON.stringify(boundary)); + } + points.push(pt); + } + return points; + }, + voronoi: function(data, bbox, boundary) { + var bound, i, k, polys, pts, ref1; + if (boundary == null) { + boundary = void 0; + } + bound = boundary || bbox; + pts = Poly.genpoints(data.length, bound); + polys = (new Voronoi(pts, bound)).layout().drawable(); + polys.input = data; + for (i = k = 0, ref1 = data.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) { + polys.polygons[i].input = data[i]; + } + return polys; + }, + commands: { + help__draw: function() { + return "draw\n\nDraw a graphic object. This command is designed to take\nthe output from numerous other commands such as grid,\nvoronoi, treemap, and others, and render them on\nscreen. You can also hand-code your own graphics objects\nif you're up for some pain.\n\nGraphic objects are simple objects with up to two\nfields: 'image' and 'polygons'\n\n'image' is something that can be interpreted as an image\n(either a URL or an array with bitmap values)\n\n'polygons' is a list of polygons. They must be in the\nformat accepted by PolyBoolJS, which is a structure with\ntwo fields, one named 'regions' and the other named\n'inverted'.\n\nThe 'regions' field should be a list of lists of\ntwo-element lists, where the innermost lists represent\nvertices of a polygon. Be careful with the ordering of the\nvertices in this case. If you don't want funky\nself-intersecting polygons, the vertices need to follow an\norderly route around the perimeter. the 'inverted' field\nshould just be false (unless you want a polygon the size\nof the universe with a hole in it specified by the\nvertices).\n\nGraphics objects also have a few other fields you can\ntinker with:\n* color - specifies the color of the field\n* input - this is the data that should be associated with\n the polygon\n* stroke - the width of the border in pixels, can be zero\n* textcolor - color of text...\n\nExample:\n $ $ [1..10] \\ (n)->[1..10].map (i)->[i,n] \\ grid \\\n .. into (g)->g.polygons.forEach ((p)->p.color = Utils.pickColor p.input[0]*p.input[1], 100); g\\\n .. draw\n {\n polygons: [\n {\n color: '#99342e',\n input: [1, 1],\n inverted: false,\n regions: [[[0, 30.240], [0, 0], [50.64, 0], [50.64, 30.240]]]\n },\n {\n color: '#993a2e',\n input: [1, 2],\n inverted: false,\n regions: [\n [[0, 62.480], [0, 32.24], [50.64, 32.24], [50.64, 62.480]]\n ]\n },...\n }\n \nThat command makes a 10x10 list of lists, each of which\nhas its offset coordinates as the final level. It then\nuses the grid command to make a 2d array of rectangular\ncells, one for each set of offset coordinates. Finally, it\nalters the color so that it's determined by the magnitude\nof the product of the two coordinates. The result is\npassed to draw so that it shows up on screen.\n\nThis command passes the input data through to its output\nwithout modification"; + }, + draw: function(argv, data, ctx) { + var e, height, margin, svg, width; + try { + svg = d3.select("#revl-vizbox").html("").append("svg").attr("class", "viz"); + margin = { + top: 20, + right: 20, + bottom: 30, + left: 40 + }; + width = +document.querySelector("#revl-vizbox").offsetWidth - margin.left - margin.right; + height = +document.querySelector("#revl-vizbox").offsetHeight - margin.top - margin.bottom; + if ('image' in data) { + Poly.drawImage(element, svg, width, height); + } + if ('polygons' in data) { + Poly.drawPolygons(data.polygons, svg, width, height); + } + return Result.wrap(data); + } catch (error) { + e = error; + return Result.err("polydraw: " + e); + } + }, + help__grid: function() { + return "grid\n\nThis command takes a list of lists of data items, and\ncreates a graphic item containing an array of rectangular\ncells, one for each data item. The array mimics the\nstructure of the list, so if you have a 10x4 list, you'll\nhave 10 cells per row and 4 rows in the output graphic.\n\nThe 'input' field of each cell will hold its corresponding\ndata item so that further calculations can be done to\nalter things like color and whatnot. See the example for\nthe 'draw' command for an example of using this command\n(it's a long example)."; + }, + grid: function(argv, data, ctx) { + var e; + try { + return Result.wrap(Poly.grid(data)); + } catch (error) { + e = error; + return Result.err("grid: " + e); + } + }, + help__eachpoly: function() { + return "eachpoly <func(poly,data,global_data)>\n\neachpoly takes a function and calls it on every polygon in\na graphics object. The function is given the polygon\nitself, the cell's input data, and the original data (if\nany) that was used to create the whole graphics object.\n\nExample:\n $ [1..10] \\ (n)->[1..10].map (i)->[i,n] \\ grid \\\n .. eachpoly (p)->p.color = Utils.heatColor p.input[0]*p.input[1],100 \\ draw\n\nThe example creates a heatmap with 100 cells, where the\nheat value is computed by multipling the row and column of\nthe cell in question "; + }, + eachpoly: function(argv, data, ctx) { + var e; + try { + return Utils.parsefunction(argv.join(' '), ctx).map(function(proc) { + return Result.wrap(Poly.eachpoly(data, proc)); + }); + } catch (error) { + e = error; + return Result.err("eachpoly: " + e); + } + }, + help__mappoly: function() { + return "mappoly <(poly)->newpoly>\n\nmappoly applies a function to each polygon in a drawable,\ngenerating a new drawable that replaces the original\npolygons with the result of calling the function on them."; + }, + mappoly: function(argv, data, ctx) { + var e; + try { + return Utils.parsefunction(argv.join(' '), ctx).map(function(proc) { + return Result.wrap(Poly.mappoly(data, proc)); + }); + } catch (error) { + e = error; + return Result.err("mappoly: " + e); + } + }, + help__voronoi: function() { + return "voronoi\n\nCreate a voronoi diagram to display data from the\npipeline. Voronoi diagrams are 2d space-filling diagrams\nthat allocate polygonal cells to each data element. This\ntool expects a list of items from the pipeline, and will\ncreate a diagram with a cell for each item. The result is\na drawable object that can be piped directly to the draw\ncommand, or can be further processed to give custom colors\nor make recursive treemaps.\n\nExample:\n $ [1..100] \\ voronoi \\ draw\n\nThis makes a voronoi diagram with 100 cells and draws it\nusing the default color scheme and rectangular border."; + }, + voronoi: function(argv, data, ctx) { + var bbox, e, h, target, w; + try { + target = document.getElementById("revl-vizbox"); + w = target.offsetWidth * 0.8; + h = target.offsetHeight * 0.8; + bbox = new BoundingBox(0, 0, w, h); + return Result.wrap(Poly.voronoi(data, bbox)); + } catch (error) { + e = error; + return Result.err("voronoi: " + e); + } + }, + help__voronoitree: function() { + return " "; + }, + voronoitree: function(argv, data, ctx) {} + } +}; + +module.exports = Poly; + + +},{"../geometry/boundingbox":32,"../geometry/eps":34,"../geometry/polygon":35,"../geometry/vec":36,"../geometry/voronoi":37,"../utils/result":55,"../utils/utils":58}],64:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Notificationactivemq = require('../../../node_modules/react-notification-system'); +var Store = require('../activemq/store.jsx'); + +var notificationStyle = { + Containers: { + DefaultStyle: { + height: '85vh', width: '98%', overflowY: 'auto', left: 'null', marginLeft: 'null', position: 'relative' + } + }, + NotificationItem: { + DefaultStyle: { + width: '98%' + } + } +}; + +module.exports = React.createClass({ + displayName: 'exports', + + componentDidMount: function componentDidMount() { + Store.storeKey('amqdebug'); + Store.addChangeListener(this.reloadactive); + amqdebug = true; + }, + //Callback for AMQ updates + reloadactive: function reloadactive() { + var level = 'info'; + switch (activemqaction) { + case 'updated': + level = 'info'; + break; + case 'created': + level = 'success'; + break; + case 'deleted': + level = 'error'; + break; + case 'views': + level = 'warning'; + break; + case 'unlinked': + level: 'error'; + break; + } + var notification = this.refs.notificationSystem; + notification.addNotification({ + message: 'action: ' + activemqaction + ' | id: ' + activemqid + ' | type: ' + activemqtype + ' | who: ' + activemqwho + ' | guid: ' + activemqguid + ' | hostname: ' + activemqhostname + ' | pid: ' + activemqpid, + level: level, + autoDismiss: 0, + position: 'bc', + dismissable: false, + action: { + label: 'View', + callback: function callback() { + window.open('#/' + activemqtype + '/' + activemqid); + } + } + }); + }, + render: function render() { + return React.createElement( + 'div', + { className: 'allComponents', style: { 'margin-left': '17px' } }, + React.createElement( + 'div', + null, + React.createElement( + 'div', + { className: 'main-header-info-null' }, + React.createElement( + 'div', + { className: 'main-header-info-child' }, + React.createElement( + 'h2', + { style: { 'font-size': '30px' } }, + 'AMQ Debugging' + ) + ) + ), + React.createElement( + 'div', + { className: 'mainview' }, + React.createElement(Notificationactivemq, { ref: 'notificationSystem', style: notificationStyle }) + ) + ) + ); + } +}); + +},{"../../../node_modules/react-notification-system":842,"../activemq/store.jsx":5,"react":983}],65:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); + +module.exports = React.createClass({ + displayName: 'exports', + + getInitialState: function getInitialState() { + return { + wallMessage: '', + buttonStatus: 'primary', + buttonText: 'Send', + buttonLoading: false + }; + }, + sendWallMessage: function sendWallMessage() { + if (this.state.wallMessage == '') { + alert('Please enter text'); + this.setState({ buttonStatus: 'warning' }); + } else { + this.setState({ buttonText: 'Loading', buttonLoading: true }); + var data = { msg: this.state.wallMessage }; + $.ajax({ + type: 'post', + url: 'scot/api/v2/wall', + data: data, + traditional: true, + success: function () { + this.setState({ buttonStatus: 'success', buttonText: 'Sent', buttonLoading: false }); + }.bind(this), + error: function (data) { + this.setState({ buttonStatus: 'danger', buttonText: 'Failed - Try Again?', buttonLoading: false }); + this.props.errorToggle('Failed to send message', data); + }.bind(this) + }); + } + }, + inputChange: function inputChange(input) { + this.setState({ wallMessage: input.target.value }); + }, + render: function render() { + return React.createElement( + 'div', + { className: 'allComponents', style: { 'margin-left': '17px' } }, + React.createElement( + 'div', + null, + React.createElement( + 'div', + null, + React.createElement( + 'div', + { className: 'main-header-info-child' }, + React.createElement( + 'h2', + { 'for': 'message' }, + 'Message to all SCOT users:' + ), + React.createElement('input', { id: 'message', style: { width: '700px' }, placeholder: 'Enter message to be displayed to everyone using SCOT', value: this.state.wallMessage, onChange: this.inputChange }), + React.createElement( + Button, + { onClick: this.sendWallMessage, bsStyle: this.state.buttonStatus, disabled: this.state.buttonLoading }, + this.state.buttonText + ) + ) + ) + ) + ); + } +}); + +},{"react":983,"react-bootstrap/lib/Button":527}],66:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var SelectedHeader = require('./selected_header.jsx'); + +var SelectedContainer = React.createClass({ + displayName: 'SelectedContainer', + + render: function render() { + var datarows = []; + datarows.push(React.createElement(SelectedHeader, { key: this.props.id, id: this.props.id, type: this.props.type, toggleEventDisplay: this.props.viewEvent, taskid: this.props.taskid, alertPreSelectedId: this.props.alertPreSelectedId, handleFilter: this.props.handleFilter, errorToggle: this.props.errorToggle, history: this.props.history })); + //var width = this.state.width; + var width = '100%'; + if ($('#list-view')[0] != undefined) { + width = 'calc(100% ' + '- ' + $('#list-view').width() + 'px)'; + } + return React.createElement( + 'div', + { id: 'main-detail-container', className: 'entry-container', style: { width: width, position: 'relative' }, tabIndex: '3' }, + datarows + ); + } +}); + +module.exports = SelectedContainer; + +},{"./selected_header.jsx":68,"react":983}],67:[function(require,module,exports){ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var React = require('react'); +var ReactDOM = require('react-dom'); +var ReactTime = require('react-time').default; +var SplitButton = require('react-bootstrap/lib/SplitButton.js'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton.js'); +var MenuItem = require('react-bootstrap/lib/MenuItem.js'); +var Button = require('react-bootstrap/lib/Button.js'); +var AddEntry = require('../components/add_entry.jsx'); +var FileUpload = require('../components/file_upload.jsx'); +var DeleteEntry = require('../modal/delete.jsx').DeleteEntry; +var Summary = require('../components/summary.jsx'); +var Task = require('../components/task.jsx'); +var SelectedPermission = require('../components/permission.jsx'); +var Frame = require('react-frame'); +var Store = require('../activemq/store.jsx'); +var AddFlair = require('../components/add_flair.jsx').AddFlair; +var EntityDetail = require('../modal/entity_detail.jsx'); +var LinkWarning = require('../modal/link_warning.jsx'); +var Link = require('react-router-dom').Link; +var IncidentTable = require('../components/incident_table.jsx'); +var SignatureTable = require('../components/signature_table.jsx'); +var TrafficLightProtocol = require('../components/traffic_light_protocol.jsx'); +var Marker = require('../components/marker.jsx').default; +var EntityCreateModal = require('../modal/entity_create.jsx').default; + +var SelectedEntry = React.createClass({ + displayName: 'SelectedEntry', + + getInitialState: function getInitialState() { + var entityDetailKey = Math.floor(Math.random() * 1000); + return { + showEntryData: this.props.showEntryData, + showEntityData: this.props.showEntityData, + entryData: this.props.entryData, + entityData: this.props.entityData, + entityid: null, + entitytype: null, + entityoffset: null, + entityobj: null, + key: this.props.id, + flairToolbar: false, + notificationType: null, + notificationMessage: '', + height: null, + entityDetailKey: entityDetailKey + }; + }, + componentDidMount: function componentDidMount() { + if (this.props.type == 'alert' || this.props.type == 'entity' || this.props.isPopUp == 1) { + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entry', + success: function (result) { + var entryResult = result.records; + if (this.isMounted()) { + this.setState({ showEntryData: true, entryData: entryResult }); + for (var i = 0; i < result.records.length; i++) { + Store.storeKey(result.records[i].id); + Store.addChangeListener(this.updatedCB); + } + this.Watcher(); + } + }.bind(this), + error: function (result) { + if (this.isMounted()) { + this.setState({ showEntryData: true }); + this.props.errorToggle("Failed to load entry data.", result); + } + }.bind(this) + }); + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entity', + success: function (result) { + var entityResult = result.records; + if (this.isMounted()) { + this.setState({ showEntityData: true, entityData: entityResult }); + var waitForEntry = { + waitEntry: function () { + if (this.state.showEntryData == false) { + setTimeout(waitForEntry.waitEntry, 50); + } else { + setTimeout(function () { + AddFlair.entityUpdate(entityResult, this.flairToolbarToggle, this.props.type, this.linkWarningToggle, this.props.id); + }.bind(this)); + } + }.bind(this) + }; + waitForEntry.waitEntry(); + } + }.bind(this), + error: function (result) { + if (this.isMounted()) { + this.setState({ showEntityData: true }); + this.props.errorToggle("Failed to load entity data.", result); + } + }.bind(this) + }); + Store.storeKey(this.props.id); + Store.addChangeListener(this.updatedCB); + } + this.containerHeightAdjust(); + window.addEventListener('resize', this.containerHeightAdjust); + $("#ReactTable").resize(function () { + this.containerHeightAdjust; + }.bind(this)); + }, + componentWillReceiveProps: function componentWillReceiveProps() { + this.containerHeightAdjust(); + }, + componentDidUpdate: function componentDidUpdate() { + if (this.state.runWatcher == true) { + this.Watcher(); + } + }, + updatedCB: function updatedCB() { + if (this.props.type == 'alert' || this.props.type == 'entity' || this.props.isPopUp == 1) { + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entry', + success: function (result) { + var entryResult = result.records; + if (this.isMounted()) { + this.setState({ showEntryData: true, entryData: entryResult }); + for (var i = 0; i < result.records.length; i++) { + Store.storeKey(result.records[i].id); + Store.addChangeListener(this.updatedCB); + } + this.Watcher(); + } + }.bind(this), + error: function (result) { + if (this.isMounted()) { + this.setState({ showEntryData: true }); + this.props.errorToggle("Failed to load entry data ", result); + } + }.bind(this) + }); + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entity', + success: function (result) { + var entityResult = result.records; + if (this.isMounted()) { + this.setState({ showEntityData: true, entityData: entityResult }); + var waitForEntry = { + waitEntry: function () { + if (this.state.showEntryData == false) { + setTimeout(waitForEntry.waitEntry, 50); + } else { + setTimeout(function () { + AddFlair.entityUpdate(entityResult, this.flairToolbarToggle, this.props.type, this.linkWarningToggle, this.props.id); + }.bind(this)); + } + }.bind(this) + }; + waitForEntry.waitEntry(); + } + }.bind(this), + error: function (result) { + if (this.isMounted()) { + this.setState({ showEntityData: true }); + this.props.errorToggle("Failed to load entity data", result); + } + }.bind(this) + }); + } + }, + + flairToolbarToggle: function flairToolbarToggle(id, value, type, entityoffset, entityobj) { + if (this.isMounted()) { + this.setState({ flairToolbar: true, entityid: id, entityvalue: value, entitytype: type, entityoffset: entityoffset, entityobj: entityobj }); + } + }, + + flairToolbarOff: function flairToolbarOff() { + if (this.isMounted()) { + var newEntityDetailKey = this.state.entityDetailKey + 1; + this.setState({ flairToolbar: false, entityDetailKey: newEntityDetailKey }); + } + }, + + linkWarningToggle: function linkWarningToggle(href) { + if (this.isMounted()) { + if (this.state.linkWarningToolbar == false) { + this.setState({ linkWarningToolbar: true, link: href }); + } else { + this.setState({ linkWarningToolbar: false }); + } + } + }, + + Watcher: function Watcher() { + var containerid = '#' + this.props.type + '-detail-container'; + if (this.props.type != 'alertgroup') { + + $(containerid).find('iframe').each(function (index, ifr) { + //requestAnimationFrame waits for the frame to be rendered (allowing the iframe to fully render before excuting the next bit of code!!! + ifr.contentWindow.requestAnimationFrame(function () { + if (ifr.contentDocument != null) { + var arr = []; + //arr.push(this.props.type); + arr.push(this.checkFlairHover); + $(ifr).off('mouseenter'); + $(ifr).off('mouseleave'); + $(ifr).on('mouseenter', function (v, type) { + var intervalID = setInterval(this[0], 50, ifr); // this.flairToolbarToggle, type, this.props.linkWarningToggle, this.props.id); + $(ifr).data('intervalID', intervalID); + console.log('Now watching iframe ' + intervalID); + }.bind(arr)); + $(ifr).on('mouseleave', function () { + var intervalID = $(ifr).data('intervalID'); + window.clearInterval(intervalID); + console.log('No longer watching iframe ' + intervalID); + }); + } + }.bind(this)); + }.bind(this)); + } else { + $(containerid).find('a, .entity').not('.not_selectable').each(function (index, tr) { + $(tr).off('mousedown'); + $(tr).on('mousedown', function (index) { + var thing = index.target; + if ($(thing)[0].className == 'extras') { + thing = $(thing)[0].parentNode; + }; //if an extra is clicked reference the parent element + if ($(thing).attr('url')) { + //link clicked + var url = $(thing).attr('url'); + this.linkWarningToggle(url); + } else { + //entity clicked + var entityid = $(thing).attr('data-entity-id'); + var entityvalue = $(thing).attr('data-entity-value'); + var entityoffset = $(thing).offset(); + var entityobj = $(thing); + this.flairToolbarToggle(entityid, entityvalue, 'entity', entityoffset, entityobj); + } + }.bind(this)); + }.bind(this)); + } + }, + + checkFlairHover: function checkFlairHover(ifr) { + function returnifr() { + return ifr; + } + if (this.props.type != 'alertgroup') { + if (ifr.contentDocument != null) { + $(ifr).contents().find('.entity').each(function (index, entity) { + if ($(entity).css('background-color') == 'rgb(255, 0, 0)') { + $(entity).data('state', 'down'); + } else if ($(entity).data('state') == 'down') { + $(entity).data('state', 'up'); + var entityid = $(entity).attr('data-entity-id'); + var entityvalue = $(entity).attr('data-entity-value'); + var entityobj = $(entity); + var ifr = returnifr(); + var entityoffset = { top: $(entity).offset().top + $(ifr).offset().top, left: $(entity).offset().left + $(ifr).offset().left }; + this.flairToolbarToggle(entityid, entityvalue, 'entity', entityoffset, entityobj); + } + }.bind(this)); + } + if (ifr.contentDocument != null) { + $(ifr).contents().find('a').each(function (index, a) { + if ($(a).css('color') == 'rgb(255, 0, 0)') { + $(a).data('state', 'down'); + } else if ($(a).data('state') == 'down') { + $(a).data('state', 'up'); + var url = $(a).attr('url'); + this.linkWarningToggle(url); + } + }.bind(this)); + } + } + }, + + containerHeightAdjust: function containerHeightAdjust() { + //Using setTimeout so full screen toggle animation has time to finish before resizing detail section + setTimeout(function () { + var scrollHeight; + var ListViewTableHeight = parseInt(document.defaultView.getComputedStyle(document.getElementsByClassName('ReactTable')[0]).height, 10); + if (ListViewTableHeight !== 0) { + scrollHeight = $(window).height() - ListViewTableHeight - $('#header').height() - 78; + scrollHeight = scrollHeight + 'px'; + } else { + scrollHeight = $(window).height() - $('#header').height() - 78; + scrollHeight = scrollHeight + 'px'; + } + //$('#detail-container').css('height',scrollHeight); + if (this.isMounted()) { + this.setState({ height: scrollHeight }); + } + }.bind(this), 500); + }, + + render: function render() { + var divid = 'detail-container'; + var height = this.state.height; + var data = this.props.entryData; + var type = this.props.type; + var id = this.props.id; + var showEntryData = this.props.showEntryData; + var divClass = 'row-fluid entry-wrapper entry-wrapper-main'; + if (type == 'alert') { + //divClass = 'row-fluid entry-wrapper entry-wrapper-main-300' + divClass = 'row-fluid entry-wrapper entry-wrapper-main-nh'; + data = this.state.entryData; + showEntryData = this.state.showEntryData; + } else if (type == 'alertgroup') { + divClass = 'row-fluid alert-wrapper entry-wrapper-main'; + } else if (type == 'entity' || this.props.isPopUp == 1) { + divClass = 'row-fluid entry-wrapper-entity'; + data = this.state.entryData; + showEntryData = this.state.showEntryData; + } + //lazy loading flair - this needs to be done here because it is not initialized when this function is called by itself (alerts and entities) + var EntityDetail = require('../modal/entity_detail.jsx'); + if (type == 'alert' || this.props.isPopUp == 1) { + divid = this.props.type + '-detail-container'; + height = null; + } + return React.createElement( + 'div', + { id: divid, key: id, className: divClass, style: { height: height } }, + type == 'incident' && this.props.headerData != null ? React.createElement(IncidentTable, { type: type, id: id, headerData: this.props.headerData, errorToggle: this.props.errorToggle }) : null, + type == 'signature' && this.props.headerData != null ? React.createElement(SignatureTable, { type: type, id: id, headerData: this.props.headerData, errorToggle: this.props.errorToggle, showSignatureOptions: this.props.showSignatureOptions }) : null, + showEntryData ? React.createElement(EntryIterator, { data: data, type: type, id: id, alertSelected: this.props.alertSelected, headerData: this.props.headerData, alertPreSelectedId: this.props.alertPreSelectedId, isPopUp: this.props.isPopUp, entryToggle: this.props.entryToggle, updated: this.updatedCB, aType: this.props.aType, aID: this.props.aID, entryToolbar: this.props.entryToolbar, errorToggle: this.props.errorToggle, fileUploadToggle: this.props.fileUploadToggle, fileUploadToolbar: this.props.fileUploadToolbar, flairOff: this.props.flairOff }) : React.createElement( + 'span', + null, + 'Loading...' + ), + this.props.entryToolbar ? React.createElement( + 'div', + null, + this.props.isAlertSelected == false ? React.createElement(AddEntry, { entryAction: 'Add', type: this.props.type, targetid: this.props.id, id: null, addedentry: this.props.entryToggle, updated: this.updatedCB, errorToggle: this.props.errorToggle }) : null + ) : null, + this.props.fileUploadToolbar ? React.createElement( + 'div', + null, + this.props.isAlertSelected == false ? React.createElement(FileUpload, { type: this.props.type, targetid: this.props.id, id: 'file_upload', fileUploadToggle: this.props.fileUploadToggle, updated: this.updatedCB, errorToggle: this.props.errorToggle }) : null + ) : null, + this.state.flairToolbar ? React.createElement(EntityDetail, { key: this.state.entityDetailKey, flairToolbarToggle: this.flairToolbarToggle, flairToolbarOff: this.flairToolbarOff, entityid: this.state.entityid, entityvalue: this.state.entityvalue, entitytype: this.state.entitytype, type: this.props.type, id: this.props.id, aID: this.props.aID, aType: this.props.aType, entityoffset: this.state.entityoffset, entityobj: this.state.entityobj, linkWarningToggle: this.linkWarningToggle, errorToggle: this.props.errorToggle }) : null, + this.state.linkWarningToolbar ? React.createElement(LinkWarning, { linkWarningToggle: this.linkWarningToggle, link: this.state.link }) : null + ); + } +}); + +var EntryIterator = React.createClass({ + displayName: 'EntryIterator', + + render: function render() { + var rows = []; + var data = this.props.data; + var type = this.props.type; + var id = this.props.id; + if (data[0] == undefined) { + if (type != 'alertgroup') { + return React.createElement( + 'div', + null, + React.createElement( + 'div', + { style: { color: 'blue' } }, + 'No entries found. Would you like to create one?' + ) + ); + } else { + return React.createElement( + 'div', + null, + React.createElement( + 'div', + { style: { color: 'blue' } }, + 'No alerts found or they are unable to be rendered. Please check the source and correct the formatting of the alert if necessary' + ) + ); + } + } else { + if (type != 'alertgroup') { + data.forEach(function (data) { + rows.push(React.createElement(EntryParent, { key: data.id, items: data, type: type, id: id, isPopUp: this.props.isPopUp, errorToggle: this.props.errorToggle })); + }.bind(this)); + } else { + rows.push(React.createElement(AlertParent, { key: id, items: data, type: type, id: id, headerData: this.props.headerData, alertSelected: this.props.alertSelected, alertPreSelectedId: this.props.alertPreSelectedId, aType: this.props.aType, aID: this.props.aID, entryToolbar: this.props.entryToolbar, entryToggle: this.props.entryToggle, updated: this.props.updated, fileUploadToggle: this.props.fileUploadToggle, fileUploadToolbar: this.props.fileUploadToolbar, errorToggle: this.props.errorToggle, flairOff: this.props.flairOff })); + } + return React.createElement( + 'div', + null, + rows + ); + } + } +}); + +var AlertParent = React.createClass({ + displayName: 'AlertParent', + + getInitialState: function getInitialState() { + var arr = []; + return { + activeIndex: arr, + lastIndex: null, + allSelected: false, + lastId: null, + activeId: arr + }; + }, + componentDidMount: function componentDidMount() { + var filterOption = false; + var widgetOption = ['sortTbody']; + if (this.props.items.length > 1) { + filterOption = true;widgetOption = ['sortTbody', 'filter']; + } + $('#sortabletable').tablesorter({ + widgets: widgetOption, + widgetOptions: { + sortTbody_primaryRow: '.main', + sortTbody_sortRows: false, + sortTbody_noSort: 'tablesorter-no-sort-tbody', + + // include child row content while filtering the second demo table + filter_childRows: filterOption + } + }); + + //Ctrl + A to select all alerts + $('#main-detail-container').keydown(function (event) { + //prevent from working when in input + if ($('input').is(':focus')) { + return; + }; + //check for ctrl + a with keyCode + if (event.keyCode == 65 && (event.ctrlKey == true || event.metaKey == true)) { + this.rowClicked(null, null, 'all', null); + event.preventDefault(); + } + }.bind(this)); + }, + componentWillUnmount: function componentWillUnmount() { + $('#main-detail-container').unbind('keydown'); + }, + + componentDidUpdate: function componentDidUpdate() { + //update the table, but not if a tinymce editor window is open as it will break the editing window + if (!$('.mce-tinymce')[0] && window.getSelection().toString() == '') { + $('#sortabletable').trigger('update'); + } + }, + + rowClicked: function rowClicked(id, index, clickType, status) { + var array = this.state.activeIndex.slice(); + var activeIdArray = this.state.activeId.slice(); + var selected = true; + this.setState({ allSelected: false }); + if (clickType == 'ctrl') { + for (var i = 0; i < activeIdArray.length; i++) { + if (activeIdArray[i] === id) { + activeIdArray.splice(i, 1); + this.setState({ activeId: activeIdArray }); + selected = false; + } + } + if (selected == true) { + activeIdArray.push(id); + this.setState({ activeId: activeIdArray }); + } + } else if (clickType == 'shift') { + var keyObj = {}; + var i = 0; + $('.alertTableHorizontal').find('tr').not('.not_selectable').each(function (index, x) { + var id = $(x).attr('id'); + keyObj[id] = i; + i++; + }.bind(this)); + if (this.state.lastId != undefined) { + var min = Math.min(keyObj[this.state.lastId], keyObj[id]); + var max = Math.max(keyObj[this.state.lastId], keyObj[id]); + //var min = max - min + 1; + var range = []; + /*while (min--) { + range[min]=max--; + }*/ + for (var q = min; q <= max; q++) { + range.push(q); + } + for (var i = 0; i < range.length; i++) { + for (var prop in keyObj) { + if (keyObj[prop] == range[i]) { + activeIdArray.push(parseInt(prop)); + } + } + } + this.setState({ activeId: activeIdArray }); + } + } else if (clickType == 'all') { + activeIdArray = []; + for (var i = 0; i < this.props.items.length; i++) { + activeIdArray.push(this.props.items[i].id); + } + this.setState({ activeId: activeIdArray, allSelected: true }); + } else { + activeIdArray = []; + activeIdArray.push(id); + this.setState({ activeId: activeIdArray }); + } + this.setState({ lastIndex: index, lastId: id }); + if (activeIdArray.length == 1) { + this.props.alertSelected('oneactive', activeIdArray[0], 'alert'); + } else if (activeIdArray.length == 0) { + this.props.alertSelected(null, null, 'alert'); + } else { + this.props.alertSelected('showall', null, 'alert'); + } + }, + render: function render() { + //var z = 0; + var items = this.props.items; + var body = []; + var header = []; + var columns = false; + var dataColumns = false; + var linkToSearch = []; + if (items[0] != undefined) { + var col_names; + //checking two locations for columns. Will make this a single location in future revision + + if (col_names == undefined) { + if (items[0].columns != undefined) { + if (items[0].columns.length != 0) { + col_names = items[0].columns.slice(0); //slices forces a copy of array + } + } + } + + if (col_names == undefined) { + if (items[0].data != undefined) { + if (items[0].data.columns != undefined) { + if (items[0].data.columns.length != 0) { + col_names = items[0].data.columns.slice(0); + } + } + } + } + if (col_names == undefined) { + if (this.props.headerData != undefined) { + if (this.props.headerData.columns != undefined) { + if (this.props.headerData.columns.length != 0) { + col_names = this.props.headerData.columns.slice(0); + } + } + } + } + if (col_names == undefined) { + console.log('Error finding columns in JSON'); + if (this.props.headerData != undefined) { + if (this.props.headerData.body != undefined) { + return React.createElement( + 'div', + null, + React.createElement( + 'div', + { style: { color: 'red' } }, + 'If you see this message, please notify your SCOT admin. Parsing failed on the message below. The raw alert is displayed.' + ), + React.createElement('div', { className: 'alertTableHorizontal', dangerouslySetInnerHTML: { __html: this.props.headerData.body } }) + ); + } + } + } + col_names.unshift('entries'); //Add entries to 3rd column + col_names.unshift('status'); //Add status to 2nd column + col_names.unshift('id'); //Add entries number to 1st column + for (var i = 0; i < col_names.length; i++) { + header.push(React.createElement(AlertHeader, { colName: col_names[i], key: i })); + } + for (var z = 0; z < items.length; z++) { + var dataFlair = null; + if (Object.getOwnPropertyNames(items[z].data_with_flair).length != 0 && !this.props.flairOff) { + dataFlair = items[z].data_with_flair; + } else { + dataFlair = items[z].data; + } + + body.push(React.createElement(AlertBody, { key: z, index: z, data: items[z], dataFlair: dataFlair, headerData: this.props.headerData, activeIndex: this.state.activeIndex, rowClicked: this.rowClicked, alertSelected: this.props.alertSelected, allSelected: this.state.allSelected, alertPreSelectedId: this.props.alertPreSelectedId, activeId: this.state.activeId, aID: this.props.aID, aType: this.props.aType, entryToggle: this.props.entryToggle, entryToolbar: this.props.entryToolbar, updated: this.props.updated, fileUploadToggle: this.props.fileUploadToggle, fileUploadToolbar: this.props.fileUploadToolbar, errorToggle: this.props.errorToggle })); + } + + var search = null; + if (items[0].data_with_flair != undefined && !this.props.flairOff) { + search = items[0].data_with_flair.search; + } else { + search = items[0].data.search; + } + + for (var y = 0; y < this.props.headerData.ahrefs.length; y++) { + linkToSearch.push(React.createElement( + 'a', + { href: this.props.headerData.ahrefs[y].link }, + this.props.headerData.ahrefs[y].subject + )); + linkToSearch.push(React.createElement('br', null)); + } + } else if (this.props.headerData != undefined) { + if (this.props.headerData.body != undefined) { + return React.createElement( + 'div', + null, + React.createElement( + 'div', + { style: { color: 'red' } }, + 'If you see this message, please notify your SCOT admin. Parsing failed on the message below. The raw alert is displayed.' + ), + React.createElement('div', { className: 'alertTableHorizontal', dangerouslySetInnerHTML: { __html: this.props.headerData.body } }) + ); + } + } + return React.createElement( + 'div', + null, + React.createElement( + 'div', + null, + React.createElement( + 'table', + { className: 'tablesorter alertTableHorizontal', id: 'sortabletable', width: '100%' }, + React.createElement( + 'thead', + null, + React.createElement( + 'tr', + null, + header + ) + ), + body + ) + ), + search != undefined ? React.createElement( + 'div', + { className: 'alertTableHorizontal' }, + linkToSearch, + React.createElement('div', { dangerouslySetInnerHTML: { __html: search } }) + ) : null + ); + } +}); +var AlertHeader = React.createClass({ + displayName: 'AlertHeader', + + render: function render() { + return React.createElement( + 'th', + null, + this.props.colName + ); + } +}); +var AlertBody = React.createClass({ + displayName: 'AlertBody', + + getInitialState: function getInitialState() { + return { + selected: 'un-selected', + promotedNumber: null, + showEntry: false, + promoteFetch: false, + showAddEntryToolbar: false, + showFileUpload: false, + showFileUploadToolbar: false + }; + }, + onClick: function onClick(event) { + if (event.shiftKey == true) { + this.props.rowClicked(this.props.data.id, this.props.index, 'shift', null); + } else if (event.ctrlKey == true || event.metaKey == true) { + this.props.rowClicked(this.props.data.id, this.props.index, 'ctrl', this.props.data.status); + } else { + this.props.rowClicked(this.props.data.id, this.props.index, '', this.props.data.status); + } + }, + toggleEntry: function toggleEntry() { + if (this.state.showEntry == false) { + this.setState({ showEntry: true }); + } else { + this.setState({ showEntry: false }); + } + }, + toggleOnAddEntry: function toggleOnAddEntry() { + if (this.state.showAddEntryToolbar == false) { + this.setState({ showAddEntryToolbar: true, showEntry: true }); + } + }, + toggleOffAddEntry: function toggleOffAddEntry() { + if (this.state.showAddEntryToolbar == true) { + this.setState({ showAddEntryToolbar: false }); + this.props.entryToggle(); + } + }, + toggleFileUpload: function toggleFileUpload() { + if (this.state.showFileUpload == false) { + this.setState({ showFileUpload: true }); + } else { + this.setState({ showFileUpload: false }); + } + }, + toggleOnFileUpload: function toggleOnFileUpload() { + if (this.state.showFileUploadToolbar == false) { + this.setState({ showFileUploadToolbar: true, showEntry: true }); + } + }, + toggleOffFileUpload: function toggleOffFileUpload() { + if (this.state.showFileUploadToolbar == true) { + this.setState({ showFileUploadToolbar: false }); + this.props.fileUploadToggle(); + } + }, + navigateTo: function navigateTo() { + window.open('#/event/' + this.state.promotedNumber); + }, + componentDidMount: function componentDidMount() { + if (this.props.data.status == 'promoted') { + $.ajax({ + type: 'GET', + url: '/scot/api/v2/alert/' + this.props.data.id + '/event', + success: function (response) { + if (this.isMounted()) { + this.setState({ promotedNumber: response.records[0].id }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get promoted id', data); + }.bind(this) + }); + + if (this.isMounted()) { + this.setState({ promoteFetch: true }); + } + } + //Pre Selects the alert in an alertgroup if alertPreSelectedId is passed to the component + if (this.props.alertPreSelectedId != null) { + if (this.props.alertPreSelectedId == this.props.data.id) { + this.props.rowClicked(this.props.data.id, this.props.index, '', this.props.data.status); + } + } + }, + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + if (this.state.promoteFetch == false) { + if (this.props.data.status == 'promoted') { + $.ajax({ + type: 'GET', + url: '/scot/api/v2/alert/' + this.props.data.id + '/event', + success: function (response) { + if (this.isMounted()) { + this.setState({ promotedNumber: response.records[0].id }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get promoted id', data); + }.bind(this) + }); + + if (this.isMounted()) { + this.setState({ promoteFetch: true }); + } + } + } + if (this.props.data.id == this.props.aID && nextProps.entryToolbar == true && this.state.showAddEntryToolbar == false) { + this.toggleOnAddEntry(); + } else if (this.props.data.id != nextProps.aID && nextProps.entryToolbar == true && this.state.showAddEntryToolbar == true) { + this.toggleOffAddEntry(); + } + if (this.props.data.id == this.props.aID && nextProps.fileUploadToolbar == true && this.state.showFileUploadToolbar == false) { + this.toggleOnFileUpload(); + } else if (this.props.data.id != nextProps.aID && nextProps.fileUploadToolbar == true && this.state.showFileUploadToolbar == true) { + this.toggleOffFileUpload(); + } + }, + render: function render() { + var data = this.props.data; + var headerData = this.props.headerData; + var dataFlair = this.props.dataFlair; + var index = this.props.index; + var columns; + var selected = 'un-selected'; + var rowReturn = []; + var buttonStyle = ''; + var open = ''; + var closed = ''; + var promoted = ''; + if (data.status == 'open') { + buttonStyle = 'red'; + } else if (data.status == 'closed') { + buttonStyle = 'green'; + } else if (data.status == 'promoted') { + buttonStyle = 'warning'; + } + + if (columns == undefined) { + if (data.columns != undefined) { + if (data.columns.length != 0) { + columns = data.columns; + } + } + } + if (columns == undefined) { + if (data.data != undefined) { + if (data.data.columns != undefined) { + if (data.data.columns.length != 0) { + columns = data.data.columns; + } + } + } + } + if (columns == undefined) { + if (this.props.headerData != undefined) { + if (this.props.headerData.length != 0) { + columns = this.props.headerData.columns; + } else { + console.log('Error finding columns in JSON'); + } + } + } + + for (var i = 0; i < columns.length; i++) { + var value = columns[i]; + rowReturn.push(React.createElement(AlertRow, { data: data, dataFlair: dataFlair, value: value })); + } + if (this.props.allSelected == false) { + for (var j = 0; j < this.props.activeId.length; j++) { + if (this.props.activeId[j] === data.id) { + selected = 'selected'; + } + } + } else { + selected = 'selected'; + } + var id = 'alert_' + data.id + '_status'; + return React.createElement( + 'tbody', + null, + React.createElement( + 'tr', + { id: data.id, className: 'main ' + selected, style: { cursor: 'pointer' }, onMouseDown: this.onClick }, + React.createElement( + 'td', + { style: { marginRight: '4px' } }, + data.id + ), + React.createElement( + 'td', + { style: { marginRight: '4px' } }, + data.status != 'promoted' ? React.createElement( + 'span', + { style: { color: buttonStyle } }, + data.status + ) : React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: buttonStyle, id: id, onMouseDown: this.navigateTo, style: { lineHeight: '12pt', fontSize: '10pt', marginLeft: 'auto' } }, + data.status + ) + ), + data.entry_count == 0 ? React.createElement( + 'td', + { style: { marginRight: '4px' } }, + data.entry_count + ) : React.createElement( + 'td', + { style: { marginRight: '4px' } }, + React.createElement( + 'span', + { style: { color: 'blue', textDecoration: 'underline', cursor: 'pointer' }, onMouseDown: this.toggleEntry }, + data.entry_count + ) + ), + rowReturn + ), + React.createElement(AlertRowBlank, { id: data.id, type: 'alert', showEntry: this.state.showEntry, aID: this.props.aID, aType: this.props.aType, updated: this.props.updated, showAddEntryToolbar: this.state.showAddEntryToolbar, toggleOffAddEntry: this.toggleOffAddEntry, showFileUploadToolbar: this.state.showFileUploadToolbar, toggleOffFileUpload: this.toggleOffFileUpload, errorToggle: this.props.errorToggle }) + ); + } +}); +var AlertRow = React.createClass({ + displayName: 'AlertRow', + + render: function render() { + var data = this.props.data; + var dataFlair = this.props.dataFlair; + var value = this.props.value; + + var rowContent = dataFlair[value]; + + if (Array.isArray(dataFlair[value])) { + for (var i = 0; i < dataFlair[value].length; i++) { + rowContent = $('
').text(dataFlair[value][i]).html(); + } + }; + + return React.createElement( + 'td', + { style: { marginRight: '4px' } }, + React.createElement('div', { className: 'alert_data_cell', dangerouslySetInnerHTML: { __html: rowContent } }) + ); + } +}); +var AlertRowBlank = React.createClass({ + displayName: 'AlertRowBlank', + + render: function render() { + var id = this.props.id; + var showEntry = this.props.showEntry; + var showAddEntryToolbar = this.props.showAddEntryToolbar; + var showFileUploadToolbar = this.props.showFileUploadToolbar; + var DisplayValue = 'none'; + var arr = []; + arr.push(React.createElement(SelectedEntry, { type: this.props.type, id: this.props.id, errorToggle: this.props.errorToggle })); + if (showEntry == true) { + DisplayValue = 'table-row'; + } + return React.createElement( + 'tr', + { className: 'not_selectable', style: { display: DisplayValue } }, + React.createElement( + 'td', + { colSpan: '50' }, + showEntry ? React.createElement( + 'div', + null, + React.createElement(SelectedEntry, { type: this.props.type, id: this.props.id, errorToggle: this.props.errorToggle }) + ) : null, + showAddEntryToolbar ? React.createElement(AddEntry, { entryAction: 'Add', type: this.props.type, targetid: this.props.id, id: null, addedentry: this.props.toggleOffAddEntry, updated: this.props.updated, errorToggle: this.props.errorToggle }) : null, + showFileUploadToolbar ? React.createElement(FileUpload, { type: this.props.aType, targetid: this.props.id, errorToggle: this.props.errorToggle, fileUploadToggle: this.props.toggleOffFileUpload }) : null + ) + ); + } +}); +var EntryParent = React.createClass({ + displayName: 'EntryParent', + + getInitialState: function getInitialState() { + return { + editEntryToolbar: false, + replyEntryToolbar: false, + deleteToolbar: false, + permissionsToolbar: false, + fileUploadToolbar: false, + showEntityCreateModal: false, + highlightedText: null + }; + }, + componentDidMount: function componentDidMount() { + Store.storeKey(this.props.items.id); + Store.addChangeListener(this.refreshButton); + }, + //TODO modify manual entry refresh to be done on automatically based on STOMP single entry update. This works for now. + refreshButton: function refreshButton() { + if ($('#refresh-detail')) { + $('#refresh-detail').click(); + } + }, + editEntryToggle: function editEntryToggle() { + if (this.state.editEntryToolbar == false) { + this.setState({ editEntryToolbar: true }); + } else { + this.setState({ editEntryToolbar: false }); + } + }, + replyEntryToggle: function replyEntryToggle() { + if (this.state.replyEntryToolbar == false) { + this.setState({ replyEntryToolbar: true }); + } else { + this.setState({ replyEntryToolbar: false }); + } + }, + deleteToggle: function deleteToggle() { + if (this.state.deleteToolbar == false) { + this.setState({ deleteToolbar: true }); + } else { + this.setState({ deleteToolbar: false }); + } + }, + permissionsToggle: function permissionsToggle() { + if (this.state.permissionsToolbar == false) { + this.setState({ permissionsToolbar: true }); + } else { + this.setState({ permissionsToolbar: false }); + } + }, + reparseFlair: function reparseFlair() { + $.ajax({ + type: 'put', + url: '/scot/api/v2/entry/' + this.props.items.id, + data: JSON.stringify({ parsed: 0 }), + contentType: 'application/json; charset=UTF-8', + success: function (response) { + console.log('reparsing started'); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to start reparsing of data', data); + }.bind(this) + }); + }, + fileUploadToggle: function fileUploadToggle() { + if (this.state.fileUploadToolbar == false) { + this.setState({ fileUploadToolbar: true }); + } else { + this.setState({ fileUploadToolbar: false }); + } + }, + render: function render() { + var itemarr = []; + var subitemarr = []; + var items = this.props.items; + var type = this.props.type; + var id = this.props.id; + var isPopUp = this.props.isPopUp; + var itemsClass = this.props.items.class; + var summary = 0; //define Summary as false unless itemsClass is "summary" + var editEntryToolbar = this.state.editEntryToolbar; + var editEntryToggle = this.editEntryToggle; + var errorToggle = this.props.errorToggle; + var outerClassName = 'row-fluid entry-outer'; + var innerClassName = 'row-fluid entry-header'; + var taskOwner = ''; + if (itemsClass == 'summary') { + outerClassName += ' summary_entry'; + summary = 1; + } + if (itemsClass == 'task') { + if (items.metadata.task.status == 'open' || items.metadata.task.status == 'assigned') { + taskOwner = '-- Task Owner ' + items.metadata.task.who + ' '; + outerClassName += ' todo_open_outer'; + innerClassName += ' todo_open'; + } else if ((items.metadata.task.status == 'closed' || items.metadata.task.status == 'completed') && items.metadata.task.who != null) { + taskOwner = '-- Task Owner ' + items.metadata.task.who + ' '; + outerClassName += ' todo_completed_outer'; + innerClassName += ' todo_completed'; + } else if (items.metadata.task.status == 'closed' || items.metadata.task.status == 'completed') { + outerClassName += ' todo_undefined_outer'; + innerClassName += ' todo_undefined'; + } + } + if (itemsClass == 'alert') { + outerClassName += ' event_entry_container_alert'; + } + itemarr.push(React.createElement(EntryData, { id: items.id, key: items.id, subitem: items, type: type, targetid: id, editEntryToolbar: editEntryToolbar, editEntryToggle: editEntryToggle, isPopUp: isPopUp, errorToggle: this.props.errorToggle })); + for (var prop in items) { + var childfunc = function childfunc(prop) { + if (prop == "children") { + var childobj = items[prop]; + items[prop].forEach(function (childobj) { + subitemarr.push(new Array(React.createElement(EntryParent, { items: childobj, id: id, type: type, editEntryToolbar: editEntryToolbar, editEntryToggle: editEntryToggle, isPopUp: isPopUp, errorToggle: errorToggle }))); + }); + } + }; + + childfunc(prop); + }; + itemarr.push(subitemarr); + + var entryActions = []; + if (this.props.items) { + if (this.props.items.actions) { + for (var i = 0; i < this.props.items.actions.length; i++) { + if (this.props.items.actions[i].send_to_name && this.props.items.actions[i].send_to_url) { + entryActions.push(React.createElement(EntryAction, { + id: this.props.items.actions[i].send_to_name, + datahref: this.props.items.actions[i].send_to_url, + errorToggle: this.props.errorToggle + })); + } + } + } + } + + var header1 = '[' + items.id + '] '; + var header2 = ' by ' + items.owner + ' ' + taskOwner + '(updated on '; + var header3 = ')'; + var createdTime = items.created; + var updatedTime = items.updated; + var entryHeaderInnerId = 'entry-header-inner-' + this.props.id + ' entry-header-inner'; + + return React.createElement( + 'div', + null, + this.state.showEntityCreateModal ? React.createElement(EntityCreateModal, { match: this.state.highlightedText, modalActive: this.state.showEntityCreateModal, ToggleCreateEntity: this.ToggleCreateEntity, errorToggle: this.props.errorToggle }) : null, + React.createElement( + 'div', + { className: outerClassName, style: { marginLeft: 'auto', marginRight: 'auto', width: '99.3%' } }, + React.createElement('span', { className: 'anchor', id: "/" + type + '/' + id + '/' + items.id }), + React.createElement( + 'div', + { className: innerClassName }, + React.createElement( + 'div', + { id: entryHeaderInnerId, className: entryHeaderInnerId }, + '[', + React.createElement( + Link, + { style: { color: 'black' }, to: '/' + type + '/' + id + '/' + items.id }, + items.id + ), + '] ', + React.createElement(ReactTime, { value: items.created * 1000, format: 'MM/DD/YYYY hh:mm:ss a' }), + ' by ', + items.owner, + ' ', + taskOwner, + '(updated on ', + React.createElement(ReactTime, { value: items.updated * 1000, format: 'MM/DD/YYYY hh:mm:ss a' }), + ')', + this.state.highlightedText != '' && this.state.highlightedText != null ? React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'success', onClick: this.ToggleCreateEntity }, + 'Create Entity' + ) : null, + this.props.items.body_flair != '' && this.props.items.parsed == 0 ? React.createElement( + 'span', + { style: { color: 'green', fontWeight: 'bold' } }, + ' Entry awaiting flair engine. Content may be inaccurate.' + ) : null, + React.createElement( + 'span', + { className: 'pull-right', style: { display: 'inline-flex', paddingRight: '3px' } }, + this.state.permissionsToolbar ? React.createElement(SelectedPermission, { updateid: id, id: items.id, type: 'entry', permissionData: items, permissionsToggle: this.permissionsToggle }) : null, + React.createElement( + SplitButton, + { bsSize: 'xsmall', title: 'Reply', key: items.id, id: 'Reply ' + items.id, onClick: this.replyEntryToggle, pullRight: true }, + type != 'entity' ? React.createElement( + MenuItem, + { eventKey: '1', onClick: this.fileUploadToggle }, + 'Upload File' + ) : null, + entryActions, + React.createElement( + MenuItem, + { eventKey: '3' }, + React.createElement(Summary, { type: type, id: id, entryid: items.id, summary: summary, errorToggle: this.props.errorToggle }) + ), + React.createElement( + MenuItem, + { eventKey: '4' }, + React.createElement(Task, { type: type, id: id, entryid: items.id, taskData: items, errorToggle: this.props.errorToggle }) + ), + React.createElement(Marker, { type: 'entry', id: items.id, string: items.body_plain }), + React.createElement( + MenuItem, + { onClick: this.permissionsToggle }, + 'Permissions' + ), + React.createElement( + MenuItem, + { onClick: this.reparseFlair }, + 'Reparse Flair' + ), + React.createElement(TrafficLightProtocol, { type: 'entry', id: items.id, tlp: items.tlp, errorToggle: this.props.errorToggle }), + React.createElement(MenuItem, { divider: true }), + React.createElement( + MenuItem, + { eventKey: '2', onClick: this.deleteToggle }, + 'Delete' + ) + ), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.editEntryToggle }, + 'Edit' + ) + ) + ) + ), + itemarr, + this.state.replyEntryToolbar ? React.createElement(AddEntry, { entryAction: 'Reply', type: type, header1: header1, header2: header2, header3: header3, createdTime: createdTime, updatedTime: updatedTime, targetid: id, id: items.id, addedentry: this.replyEntryToggle, errorToggle: this.props.errorToggle }) : null, + this.state.fileUploadToolbar ? React.createElement(FileUpload, { type: this.props.type, targetid: this.props.id, entryid: this.props.items.id, fileUploadToggle: this.fileUploadToggle, errorToggle: this.props.errorToggle }) : null + ), + this.state.deleteToolbar ? React.createElement(DeleteEntry, { type: type, id: id, deleteToggle: this.deleteToggle, entryid: items.id, errorToggle: this.props.errorToggle }) : null + ); + }, + + componentWillReceiveProps: function componentWillReceiveProps() { + this.checkHighlight(); + }, + + checkHighlight: function checkHighlight() { + var content = void 0; + var iframe = document.getElementById('iframe_' + this.props.items.id); + if (iframe) { + content = iframe.contentWindow.getSelection().toString(); + if (this.state.highlightedText != content) { + console.log(iframe + ' has highlighted text: ' + content); + this.setState({ highlightedText: content }); + } else { + return; + } + } + }, + + ToggleCreateEntity: function ToggleCreateEntity() { + this.setState({ showEntityCreateModal: !this.state.showEntityCreateModal }); + } + +}); + +var EntryAction = React.createClass({ + displayName: 'EntryAction', + + getInitialState: function getInitialState() { + var _ref; + + return _ref = {}, _defineProperty(_ref, this.props.id, false), _defineProperty(_ref, 'disabled', false), _ref; + }, + + submit: function submit() { + var url = this.props.datahref; + var id = this.props.id; + + $.ajax({ + type: 'post', + url: url, + success: function (response) { + var _setState; + + this.setState((_setState = {}, _defineProperty(_setState, id, true), _defineProperty(_setState, 'disabled', false), _setState)); + console.log('submitted the entry action'); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to submit the entry action', data); + this.setState({ disabled: false }); + }.bind(this) + }); + this.setState({ disabled: true }); + }, + + render: function render() { + return React.createElement( + MenuItem, + { disabled: this.state.disabled }, + React.createElement( + 'span', + { id: this.props.id, 'data-href': this.props.datahref, onClick: this.submit, style: { display: 'block' } }, + this.props.id, + ' ', + this.state[this.props.id] ? React.createElement( + 'span', + { style: { color: 'green' } }, + 'success' + ) : null + ) + ); + } +}); + +var EntryData = React.createClass({ + displayName: 'EntryData', + + getInitialState: function getInitialState() { + /*if (this.props.type == 'entity' || this.props.isPopUp == 1) { + return { + height: '250px', + } + }*/ + return { + height: '1px' + }; + }, + onLoad: function onLoad() { + if (document.getElementById('iframe_' + this.props.id) != undefined) { + if (document.getElementById('iframe_' + this.props.id).contentDocument.readyState === 'complete') { + var ifr = $('#iframe_' + this.props.id); + var ifrContents = $(ifr).contents(); + var ifrContentsHead = $(ifrContents).find('head'); + if (ifrContentsHead) { + if (!$(ifrContentsHead).find('link')) { + ifrContentsHead.append($("", { rel: "stylesheet", href: 'css/sandbox.css', type: "text/css" })); + } + } + //if (this.props.type != 'entity') { + setTimeout(function () { + if (document.getElementById('iframe_' + this.props.id) != undefined) { + document.getElementById('iframe_' + this.props.id).contentWindow.requestAnimationFrame(function () { + var newheight; + newheight = document.getElementById('iframe_' + this.props.id).contentWindow.document.body.scrollHeight; + newheight = newheight + 'px'; + if (this.state.height != newheight) { + this.setState({ height: newheight }); + } + }.bind(this)); + } + }.bind(this), 250); + //} + } else { + setTimeout(this.onLoad, 0); + } + } + }, + componentWillReceiveProps: function componentWillReceiveProps() { + this.onLoad(); + }, + render: function render() { + var rawMarkup = this.props.subitem.body_flair; + if (this.props.subitem.body_flair == '') { + rawMarkup = this.props.subitem.body; + } + var id = this.props.id; + var entry_body_id = 'entry-body-' + this.props.id; + var entry_body_inner_id = 'entry-body-inner-' + this.props.id; + return React.createElement( + 'div', + { id: entry_body_id, key: this.props.id, className: 'row-fluid entry-body' }, + React.createElement( + 'div', + { id: entry_body_inner_id, className: 'row-fluid entry-body-inner', style: { marginLeft: 'auto', marginRight: 'auto', width: '99.3%' } }, + this.props.editEntryToolbar ? React.createElement(AddEntry, { entryAction: 'Edit', type: this.props.type, targetid: this.props.targetid, id: id, addedentry: this.props.editEntryToggle, parent: this.props.subitem.parent, errorToggle: this.props.errorToggle }) : React.createElement( + Frame, + { frameBorder: '0', id: 'iframe_' + id, sandbox: 'allow-same-origin', styleSheets: ['/css/sandbox.css'], style: { width: '100%', height: this.state.height } }, + React.createElement('div', { dangerouslySetInnerHTML: { __html: rawMarkup } }) + ) + ) + ); + }, + componentDidMount: function componentDidMount() { + this.onLoad(); + } +}); +module.exports = SelectedEntry; + +},{"../activemq/store.jsx":5,"../components/add_entry.jsx":7,"../components/add_flair.jsx":8,"../components/file_upload.jsx":21,"../components/incident_table.jsx":22,"../components/marker.jsx":23,"../components/permission.jsx":24,"../components/signature_table.jsx":26,"../components/summary.jsx":28,"../components/task.jsx":30,"../components/traffic_light_protocol.jsx":31,"../modal/delete.jsx":75,"../modal/entity_create.jsx":77,"../modal/entity_detail.jsx":78,"../modal/link_warning.jsx":79,"react":983,"react-bootstrap/lib/Button.js":527,"react-bootstrap/lib/DropdownButton.js":539,"react-bootstrap/lib/MenuItem.js":566,"react-bootstrap/lib/SplitButton.js":597,"react-dom":677,"react-frame":807,"react-router-dom":878,"react-time":905}],68:[function(require,module,exports){ +'use strict'; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var React = require('react'); +var ReactTime = require('react-time').default; +var SelectedHeaderOptions = require('./selected_header_options.jsx'); +var DeleteEvent = require('../modal/delete.jsx').DeleteEvent; +var Owner = require('../modal/owner.jsx'); +var Entities = require('../modal/entities.jsx'); +var ChangeHistory = require('../modal/change_history.jsx'); +var ViewedByHistory = require('../modal/viewed_by_history.jsx'); +var SelectedPermission = require('../components/permission.jsx'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var ButtonToolbar = require('react-bootstrap/lib/ButtonToolbar'); +var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger'); +var Popover = require('react-bootstrap/lib/Popover'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton'); +var MenuItem = require('react-bootstrap/lib/MenuItem'); +var DebounceInput = require('react-debounce-input'); +var SelectedEntry = require('./selected_entry.jsx'); +var Tag = require('../components/tag.jsx'); +var Source = require('../components/source.jsx'); +var Store = require('../activemq/store.jsx'); +var Notification = require('react-notification-system'); +var AddFlair = require('../components/add_flair.jsx').AddFlair; +var EntityDetail = require('../modal/entity_detail.jsx'); +var LinkWarning = require('../modal/link_warning.jsx'); +var Link = require('react-router-dom').Link; +var Links = require('../modal/links.jsx').default; +var DetailDataStatus = require('../components/detail_data_status.jsx'); +var Mark = require('../modal/mark.jsx').default; +var DetailHeaderMoreOptions = require('../components/detail_header_more_options').default; +var PromotedData = require('../modal/promoted_data.jsx').default; +var InitialAjaxLoad; + +var SelectedHeader = React.createClass({ + displayName: 'SelectedHeader', + + getInitialState: function getInitialState() { + var entityDetailKey = Math.floor(Math.random() * 1000); + return { + showEventData: false, + headerData: {}, + sourceData: '', + tagData: '', + permissionsToolbar: false, + entitiesToolbar: false, + changeHistoryToolbar: false, + viewedByHistoryToolbar: false, + entryToolbar: false, + deleteToolbar: false, + promoteToolbar: false, + notificationType: null, + notificationMessage: null, + key: this.props.id, + showEntryData: false, + entryData: '', + showEntityData: false, + entityData: '', + entityid: null, + entitytype: null, + entityoffset: null, + entityobj: null, + flairToolbar: false, + linkWarningToolbar: false, + refreshing: false, + loading: false, + eventLoaded: false, + entryLoaded: false, + entityLoaded: false, + alertSelected: false, + aIndex: null, + aType: null, + aStatus: null, + aID: 0, + guideID: null, + fileUploadToolbar: false, + isNotFound: false, + runWatcher: false, + entityDetailKey: entityDetailKey, + processing: false, + showSignatureOptions: false, + showMarkModal: false, + showLinksModal: false, + isDeleted: false, + flairOff: false, + highlightedText: '' + }; + }, + componentWillMount: function componentWillMount() { + this.setState({ loading: true }); + }, + componentDidMount: function componentDidMount() { + var delayFunction = { + delay: function () { + var entryType = 'entry'; + if (this.props.type == 'alertgroup') { + entryType = 'alert'; + }; + //Main Type Load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + success: function (result) { + if (this.isMounted()) { + var eventResult = result; + this.setState({ headerData: eventResult, showEventData: true, isNotFound: false, tagData: eventResult.tag, sourceData: eventResult.source }); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (result) { + this.setState({ showEventData: true, isNotFound: true }); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + this.props.errorToggle("Error: Failed to load detail data. Error message: " + result.responseText, result); + }.bind(this) + }); + //entry load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/' + entryType, + success: function (result) { + if (this.isMounted()) { + var entryResult = result.records; + this.setState({ showEntryData: true, entryData: entryResult, runWatcher: true }); + this.Watcher(); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function error(result) { + this.setState({ showEntryData: true }); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + this.props.errorToggle("Error: Failed to load entry data. Error message: " + result.responseText, result); + } + }); + //entity load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entity', + success: function (result) { + if (this.isMounted()) { + var entityResult = result.records; + this.setState({ showEntityData: true, entityData: entityResult }); + var waitForEntry = { + waitEntry: function () { + if (this.state.showEntryData == false) { + setTimeout(waitForEntry.waitEntry, 50); + } else { + setTimeout(function () { + AddFlair.entityUpdate(entityResult, this.flairToolbarToggle, this.props.type, this.linkWarningToggle, this.props.id, this.scrollTo); + }.bind(this)); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + } + }.bind(this) + }; + waitForEntry.waitEntry(); + } + }.bind(this), + error: function (result) { + this.setState({ showEntityData: true }); + if (this.state.showEventData == true && this.state.showEntryData == true && this.state.showEntityData == true) { + this.setState({ loading: false }); + } + this.props.errorToggle("Error: Failed to load entity data.", result); + }.bind(this) + }); + //guide load + if (this.props.type == 'alertgroup') { + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/guide', + success: function (result) { + if (this.isMounted()) { + if (result.records[0] != undefined) { + var guideID = result.records[0].id; + this.setState({ guideID: guideID }); + } else { + this.setState({ guideID: 0 }); + } + } + }.bind(this), + error: function (result) { + this.setState({ guideID: null }); + this.props.errorToggle("Error: Failed to load guide data. Error message:" + result.responseText, result); + }.bind(this) + }); + } + Store.storeKey(this.props.id); + Store.addChangeListener(this.updated); + }.bind(this) + }; + InitialAjaxLoad = setTimeout(delayFunction.delay, 400); + }, + componentWillUnmount: function componentWillUnmount() { + clearTimeout(InitialAjaxLoad); + }, + componentDidUpdate: function componentDidUpdate() { + //This runs the watcher which handles the entity popup and link warning. + if (this.state.runWatcher == true) { + this.Watcher(); + } + }, + componentWillReceiveProps: function componentWillReceiveProps() { + //resets the watcher flag to false. This will only get set to true if a call for entries is made. + this.setState({ runWatcher: false }); + }, + updated: function updated(_type, _message) { + if (!this.state.isDeleted) { + this.setState({ refreshing: true, eventLoaded: false, entryLoaded: false, entityLoaded: false }); + var entryType = 'entry'; + if (this.props.type == 'alertgroup') { + entryType = 'alert'; + }; + //main type load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + success: function (result) { + if (this.isMounted()) { + var eventResult = result; + this.setState({ headerData: eventResult, showEventData: true, eventLoaded: true, isNotFound: false, tagData: eventResult.tag, sourceData: eventResult.source }); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + } + }.bind(this), + error: function (result) { + this.setState({ showEventData: true, eventLoaded: true, isNotFound: true }); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + this.props.errorToggle("Error: Failed to reload detail data. Error message: " + result.responseText, result); + }.bind(this) + }); + //entry load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/' + entryType, + success: function (result) { + if (this.isMounted()) { + var entryResult = result.records; + this.setState({ showEntryData: true, entryLoaded: true, entryData: entryResult, runWatcher: true }); + this.Watcher(); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + } + }.bind(this), + error: function error(result) { + this.setState({ showEntryData: true, entryLoaded: true }); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + this.props.errorToggle("Error: Failed to reload entry data. Error message: " + result.responseText, result); + } + }); + //entity load + $.ajax({ + type: 'get', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id + '/entity', + success: function (result) { + if (this.isMounted()) { + var entityResult = result.records; + this.setState({ showEntityData: true, entityLoaded: true, entityData: entityResult }); + var waitForEntry = { + waitEntry: function () { + if (this.state.entryLoaded == false) { + setTimeout(waitForEntry.waitEntry, 50); + } else { + setTimeout(function () { + AddFlair.entityUpdate(entityResult, this.flairToolbarToggle, this.props.type, this.linkWarningToggle, this.props.id); + }.bind(this)); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + } + }.bind(this) + }; + waitForEntry.waitEntry(); + } + }.bind(this), + error: function (result) { + this.setState({ showEntityData: true }); + if (this.state.eventLoaded == true && this.state.entryLoaded == true && this.state.entityLoaded == true) { + this.setState({ refreshing: false }); + } + this.props.errorToggle("Error: Failed to reload entity data.", result); + }.bind(this) + }); + //error popup if an error occurs + if (_type != undefined && _message != undefined) { + this.props.errorToggle(_message); + } + } + }, + flairToolbarToggle: function flairToolbarToggle(id, value, type, entityoffset, entityobj) { + this.setState({ flairToolbar: true, entityid: id, entityvalue: value, entitytype: type, entityoffset: entityoffset, entityobj: entityobj }); + }, + flairToolbarOff: function flairToolbarOff() { + if (this.isMounted()) { + var newEntityDetailKey = this.state.entityDetailKey + 1; + this.setState({ flairToolbar: false, entityDetailKey: newEntityDetailKey }); + } + }, + linkWarningToggle: function linkWarningToggle(href) { + if (this.state.linkWarningToolbar == false) { + this.setState({ linkWarningToolbar: true, link: href }); + } else { + this.setState({ linkWarningToolbar: false }); + } + }, + viewedbyfunc: function viewedbyfunc(headerData) { + var viewedbyarr = []; + if (headerData != null) { + for (var prop in headerData.view_history) { + viewedbyarr.push(prop); + }; + } + return viewedbyarr; + }, + entryToggle: function entryToggle() { + if (this.state.entryToolbar == false) { + this.setState({ entryToolbar: true }); + } else { + this.setState({ entryToolbar: false }); + //click refresh detail button on screen to refresh data while the tinymce window was open since it held back updates of the DOM + //hold off on refresh as the tinymce preventing update is currently commented out + /*if ($('#refresh-detail')) { + $('#refresh-detail').click(); + }*/ + } + }, + deleteToggle: function deleteToggle(isDeleted) { + if (this.state.deleteToolbar == false) { + this.setState({ deleteToolbar: true }); + } else { + this.setState({ deleteToolbar: false }); + } + //set isDeleted to true so notifications won't fire + if (isDeleted) { + this.setState({ isDeleted: true }); + } + }, + changeHistoryToggle: function changeHistoryToggle() { + if (this.state.changeHistoryToolbar == false) { + this.setState({ changeHistoryToolbar: true }); + } else { + this.setState({ changeHistoryToolbar: false }); + } + }, + viewedByHistoryToggle: function viewedByHistoryToggle() { + if (this.state.viewedByHistoryToolbar == false) { + this.setState({ viewedByHistoryToolbar: true }); + } else { + this.setState({ viewedByHistoryToolbar: false }); + } + }, + permissionsToggle: function permissionsToggle() { + if (this.state.permissionsToolbar == false) { + this.setState({ permissionsToolbar: true }); + } else { + this.setState({ permissionsToolbar: false }); + } + }, + entitiesToggle: function entitiesToggle() { + if (this.state.entitiesToolbar == false) { + this.setState({ entitiesToolbar: true }); + } else { + this.setState({ entitiesToolbar: false }); + } + }, + promoteToggle: function promoteToggle() { + if (this.state.promoteToolbar == false) { + this.setState({ promoteToolbar: true }); + } else { + this.setState({ promoteToolbar: false }); + } + }, + guideToggle: function guideToggle() { + window.open('#/guide/' + this.state.guideID); + }, + fileUploadToggle: function fileUploadToggle() { + if (this.state.fileUploadToolbar == false) { + this.setState({ fileUploadToolbar: true }); + } else { + this.setState({ fileUploadToolbar: false }); + } + }, + titleCase: function titleCase(string) { + var newstring = string.charAt(0).toUpperCase() + string.slice(1); + return newstring; + }, + alertSelected: function alertSelected(aIndex, aID, aType, aStatus) { + this.setState({ alertSelected: true, aIndex: aIndex, aID: aID, aType: aType, aStatus: aStatus }); + }, + sourceToggle: function sourceToggle() { + $.ajax({ + type: 'GET', + url: '/scot/api/v2/alertgroup/' + this.props.id, + success: function (response) { + var win = window.open('/libs/viewSource.html'); //, '_blank') + var html = response.body; + var plain = response.body_plain; + win.onload = function () { + if (html != undefined) { + $(win.document).find('#html').text(html); + } else { + $(win.document).find('.html').remove(); + } + if (plain != undefined) { + $(win.document).find('#plain').text(plain); + } else { + $(win.document).find('.plain').remove(); + } + }; + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get data for source popup', data); + }.bind(this) + }); + }, + Watcher: function Watcher() { + if (this.props.type != 'alertgroup') { + $('iframe').each(function (index, ifr) { + //requestAnimationFrame waits for the frame to be rendered (allowing the iframe to fully render before excuting the next bit of code!!! + ifr.contentWindow.requestAnimationFrame(function () { + if (ifr.contentDocument != null) { + var arr = []; + //arr.push(this.props.type); + arr.push(this.checkFlairHover); + arr.push(this.checkHighlight); + $(ifr).off('mouseenter'); + $(ifr).off('mouseleave'); + $(ifr).on('mouseenter', function (v, type) { + var intervalID = setInterval(this[0], 50, ifr); // this.flairToolbarToggle, type, this.props.linkWarningToggle, this.props.id); + var intervalID1 = setInterval(this[1], 50, ifr); // this.flairToolbarToggle, type, this.props.linkWarningToggle, this.props.id); + $(ifr).data('intervalID', intervalID); + $(ifr).data('intervalID1', intervalID1); + console.log('Now watching iframe ' + intervalID); + }.bind(arr)); + $(ifr).on('mouseleave', function () { + var intervalID = $(ifr).data('intervalID'); + var intervalID1 = $(ifr).data('intervalID1'); + window.clearInterval(intervalID); + window.clearInterval(intervalID1); + console.log('No longer watching iframe ' + intervalID); + }); + } + }.bind(this)); + }.bind(this)); + } else { + $('#detail-container').find('a, .entity').not('.not_selectable').each(function (index, tr) { + $(tr).off('mousedown'); + $(tr).on('mousedown', function (index) { + var thing = index.target; + if ($(thing)[0].className == 'extras') { + thing = $(thing)[0].parentNode; + }; //if an extra is clicked reference the parent element + if ($(thing).attr('url')) { + //link clicked + var url = $(thing).attr('url'); + this.linkWarningToggle(url); + } else { + //entity clicked + var entityid = $(thing).attr('data-entity-id'); + var entityvalue = $(thing).attr('data-entity-value'); + var entityoffset = $(thing).offset(); + var entityobj = $(thing); + this.flairToolbarToggle(entityid, entityvalue, 'entity', entityoffset, entityobj); + } + }.bind(this)); + }.bind(this)); + }; + }, + + checkHighlight: function checkHighlight(ifr) { + var content = void 0; + if (ifr) { + content = ifr.contentWindow.getSelection().toString(); + if (this.state.highlightedText != content) { + //this only tells the lower components to run their componentWIllReceiveProps methods to check for highlighted text. + this.setState({ highlightedText: content }); + } else { + return; + } + } + }, + + checkFlairHover: function checkFlairHover(ifr) { + function returnifr() { + return ifr; + } + if (this.props.type != 'alertgroup') { + if (ifr.contentDocument != null) { + $(ifr).contents().find('.entity').each(function (index, entity) { + if ($(entity).css('background-color') == 'rgb(255, 0, 0)') { + $(entity).data('state', 'down'); + } else if ($(entity).data('state') == 'down') { + $(entity).data('state', 'up'); + var entityid = $(entity).attr('data-entity-id'); + var entityvalue = $(entity).attr('data-entity-value'); + var entityobj = $(entity); + var ifr = returnifr(); + var entityoffset = { top: $(entity).offset().top + $(ifr).offset().top, left: $(entity).offset().left + $(ifr).offset().left }; + this.flairToolbarToggle(entityid, entityvalue, 'entity', entityoffset, entityobj); + } + }.bind(this)); + } + if (ifr.contentDocument != null) { + $(ifr).contents().find('a').each(function (index, a) { + if ($(a).css('color') == 'rgb(255, 0, 0)') { + $(a).data('state', 'down'); + } else if ($(a).data('state') == 'down') { + $(a).data('state', 'up'); + var url = $(a).attr('url'); + this.linkWarningToggle(url); + } + }.bind(this)); + } + } + }, + + summaryUpdate: function summaryUpdate() { + this.forceUpdate(); + }, + + scrollTo: function scrollTo() { + if (this.props.taskid != undefined) { + $('.entry-wrapper').scrollTop($('.entry-wrapper').scrollTop() + $('#iframe_' + this.props.taskid).position().top - 30); + } + }, + guideRedirectToAlertListWithFilter: function guideRedirectToAlertListWithFilter() { + RegExp.escape = function (text) { + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + }; + //column, string, clearall (bool), type + this.props.handleFilter(null, null, true, 'alertgroup'); + this.props.handleFilter([{ id: 'subject', value: RegExp.escape(this.state.headerData.applies_to[0]) }], null, false, "alertgroup"); + window.open('#/alertgroup/'); + }, + showSignatureOptionsToggle: function showSignatureOptionsToggle() { + if (this.state.showSignatureOptions == false) { + this.setState({ showSignatureOptions: true }); + } else { + this.setState({ showSignatureOptions: false }); + } + }, + markModalToggle: function markModalToggle() { + if (this.state.showMarkModal == false) { + this.setState({ showMarkModal: true }); + } else { + this.setState({ showMarkModal: false }); + } + }, + ToggleProcessingMessage: function ToggleProcessingMessage(status) { + this.setState({ processing: status }); + }, + + linksModalToggle: function linksModalToggle() { + var showLinksModal = !this.state.showLinksModal; + this.setState({ showLinksModal: showLinksModal }); + }, + + toggleFlair: function toggleFlair() { + if (this.state.flairOff) { + this.setState({ flairOff: false }); + setTimeout(function () { + AddFlair.entityUpdate(this.state.entityData, this.flairToolbarToggle, this.props.type, this.linkWarningToggle, this.props.id); + }.bind(this)); + } else { + this.setState({ flairOff: true }); + } + }, + + render: function render() { + var headerData = this.state.headerData; + var viewedby = this.viewedbyfunc(headerData); + var type = this.props.type; + var subjectType = this.titleCase(this.props.type); //in signatures we're using the key "name" + var id = this.props.id; + var string = ''; + + if (this.state.headerData.subject) { + string = this.state.headerData.subject; + } else if (this.state.headerData.value) { + string = this.state.headerData.value; + } else if (this.state.headerData.name) { + string = this.state.headerData.name; + } else if (this.state.headerData.body) { + string = this.state.headerData.body; + } + + return React.createElement( + 'div', + null, + ' ', + this.state.isNotFound ? React.createElement( + 'h1', + null, + 'No record found.' + ) : React.createElement( + 'div', + null, + React.createElement( + 'div', + { id: 'header' }, + React.createElement( + 'div', + { id: 'NewEventInfo', className: 'entry-header-info-null' }, + React.createElement( + 'div', + { className: 'details-subject', style: { display: 'inline-flex', paddingLeft: '5px' } }, + this.state.showEventData ? React.createElement(EntryDataSubject, { data: this.state.headerData, subjectType: subjectType, type: type, id: this.props.id, errorToggle: this.props.errorToggle }) : null, + this.state.refreshing ? React.createElement( + 'span', + { style: { color: 'lightblue' } }, + 'Refreshing Data...' + ) : null, + this.state.loading ? React.createElement( + 'span', + { style: { color: 'lightblue' } }, + 'Loading...' + ) : null, + this.state.processing ? React.createElement( + 'span', + { style: { color: 'lightblue' } }, + 'Processing Actions...' + ) : null + ), + type != 'entity' ? React.createElement( + 'div', + { className: 'details-table toolbar', style: { display: 'flex' } }, + React.createElement( + 'table', + null, + React.createElement( + 'tbody', + null, + React.createElement( + 'tr', + null, + React.createElement('th', null), + React.createElement( + 'td', + null, + React.createElement( + 'div', + { style: { marginLeft: '5px' } }, + this.state.showEventData ? React.createElement(DetailDataStatus, { data: this.state.headerData, status: this.state.headerData.status, id: id, type: type, errorToggle: this.props.errorToggle }) : null + ) + ), + type != 'entity' ? React.createElement( + 'th', + null, + 'Owner: ' + ) : null, + type != 'entity' ? React.createElement( + 'td', + null, + React.createElement( + 'span', + null, + this.state.showEventData ? React.createElement(Owner, { key: id, data: this.state.headerData.owner, type: type, id: id, updated: this.updated, errorToggle: this.props.errorToggle }) : null + ) + ) : null, + type != 'entity' ? React.createElement( + 'th', + null, + 'Updated: ' + ) : null, + type != 'entity' ? React.createElement( + 'td', + null, + React.createElement( + 'span', + { id: 'event_updated' }, + this.state.showEventData ? React.createElement(EntryDataUpdated, { data: this.state.headerData.updated }) : null + ) + ) : null, + (type == 'event' || type == 'incident') && this.state.showEventData && this.state.headerData.promoted_from.length > 0 ? React.createElement( + 'th', + null, + 'Promoted From:' + ) : null, + (type == 'event' || type == 'incident') && this.state.showEventData && this.state.headerData.promoted_from.length > 0 ? React.createElement(PromotedData, { data: this.state.headerData.promoted_from, type: type, id: id }) : null, + type != 'entity' && this.state.showEventData ? React.createElement(Tag, { data: this.state.tagData, id: id, type: type, updated: this.updated, errorToggle: this.props.errorToggle }) : null, + type != 'entity' && this.state.showEventData ? React.createElement(Source, { data: this.state.sourceData, id: id, type: type, updated: this.updated, errorToggle: this.props.errorToggle }) : null + ) + ) + ) + ) : null + ), + React.createElement(Notification, { ref: 'notificationSystem' }), + this.state.linkWarningToolbar ? React.createElement(LinkWarning, { linkWarningToggle: this.linkWarningToggle, link: this.state.link }) : null, + this.state.viewedByHistoryToolbar ? React.createElement(ViewedByHistory, { viewedByHistoryToggle: this.viewedByHistoryToggle, id: id, type: type, subjectType: subjectType, viewedby: viewedby, errorToggle: this.props.errorToggle }) : null, + this.state.changeHistoryToolbar ? React.createElement(ChangeHistory, { changeHistoryToggle: this.changeHistoryToggle, id: id, type: type, subjectType: subjectType, errorToggle: this.props.errorToggle }) : null, + this.state.entitiesToolbar ? React.createElement(Entities, { entitiesToggle: this.entitiesToggle, entityData: this.state.entityData, flairToolbarToggle: this.flairToolbarToggle, flairToolbarOff: this.flairToolbarOff }) : null, + this.state.deleteToolbar ? React.createElement(DeleteEvent, { subjectType: subjectType, type: type, id: id, deleteToggle: this.deleteToggle, updated: this.updated, errorToggle: this.props.errorToggle, history: this.props.history }) : null, + this.state.showMarkModal ? React.createElement(Mark, { modalActive: true, type: type, id: id, string: string, errorToggle: this.props.errorToggle, markModalToggle: this.markModalToggle }) : null, + this.state.showLinksModal ? React.createElement(Links, { modalActive: true, type: type, id: id, errorToggle: this.props.errorToggle, linksModalToggle: this.linksModalToggle }) : null, + this.state.showEventData ? React.createElement(SelectedHeaderOptions, { type: type, subjectType: subjectType, id: id, headerData: this.state.headerData, status: this.state.headerData.status, promoteToggle: this.promoteToggle, permissionsToggle: this.permissionsToggle, entryToggle: this.entryToggle, entitiesToggle: this.entitiesToggle, changeHistoryToggle: this.changeHistoryToggle, viewedByHistoryToggle: this.viewedByHistoryToggle, deleteToggle: this.deleteToggle, updated: this.updated, alertSelected: this.state.alertSelected, aIndex: this.state.aIndex, aType: this.state.aType, aStatus: this.state.aStatus, flairToolbarToggle: this.flairToolbarToggle, flairToolbarOff: this.flairToolbarOff, sourceToggle: this.sourceToggle, guideID: this.state.guideID, subjectName: this.state.headerData.subject, fileUploadToggle: this.fileUploadToggle, fileUploadToolbar: this.state.fileUploadToolbar, guideRedirectToAlertListWithFilter: this.guideRedirectToAlertListWithFilter, showSignatureOptionsToggle: this.showSignatureOptionsToggle, markModalToggle: this.markModalToggle, linksModalToggle: this.linksModalToggle, ToggleProcessingMessage: this.ToggleProcessingMessage, errorToggle: this.props.errorToggle, toggleFlair: this.toggleFlair }) : null, + this.state.permissionsToolbar ? React.createElement(SelectedPermission, { updateid: id, id: id, type: type, permissionData: this.state.headerData, permissionsToggle: this.permissionsToggle, updated: this.updated, errorToggle: this.props.errorToggle }) : null + ), + this.state.showEventData && type != 'entity' ? React.createElement(SelectedEntry, { id: id, type: type, entryToggle: this.entryToggle, updated: this.updated, entryData: this.state.entryData, entityData: this.state.entityData, headerData: this.state.headerData, showEntryData: this.state.showEntryData, showEntityData: this.state.showEntityData, alertSelected: this.alertSelected, summaryUpdate: this.summaryUpdate, flairToolbarToggle: this.flairToolbarToggle, flairToolbarOff: this.flairToolbarOff, linkWarningToggle: this.linkWarningToggle, entryToolbar: this.state.entryToolbar, isAlertSelected: this.state.alertSelected, aType: this.state.aType, aID: this.state.aID, alertPreSelectedId: this.props.alertPreSelectedId, errorToggle: this.props.errorToggle, fileUploadToggle: this.fileUploadToggle, fileUploadToolbar: this.state.fileUploadToolbar, showSignatureOptions: this.state.showSignatureOptions, flairOff: this.state.flairOff, highlightedText: this.state.highlightedText }) : null, + this.state.showEventData && type == 'entity' ? React.createElement(EntityDetail, { entityid: id, entitytype: 'entity', id: id, type: 'entity', fullScreen: true, errorToggle: this.props.errorToggle, linkWarningToggle: this.linkWarningToggle }) : null, + this.state.flairToolbar ? React.createElement(EntityDetail, { key: this.state.entityDetailKey, flairToolbarToggle: this.flairToolbarToggle, flairToolbarOff: this.flairToolbarOff, entityid: this.state.entityid, entityvalue: this.state.entityvalue, entitytype: this.state.entitytype, type: this.props.type, id: this.props.id, errorToggle: this.props.errorToggle, entityoffset: this.state.entityoffset, entityobj: this.state.entityobj, linkWarningToggle: this.linkWarningToggle }) : null + ) + ); + } +}); + +var EntryDataUpdated = React.createClass({ + displayName: 'EntryDataUpdated', + + render: function render() { + var data = this.props.data; + return React.createElement( + 'div', + null, + React.createElement(ReactTime, { value: data * 1000, format: 'MM/DD/YY hh:mm:ss a' }) + ); + } +}); + +var EntryDataSubject = React.createClass({ + displayName: 'EntryDataSubject', + + getInitialState: function getInitialState() { + var keyName = 'subject'; + var value = this.props.data.subject; + if (this.props.type == 'signature') { + keyName = 'name'; + value = this.props.data.name; + } else if (this.props.type == 'entity') { + keyName = 'value'; + value = this.props.data.value; + } + return { + value: value, + width: '', + keyName: keyName + }; + }, + handleChange: function handleChange(event) { + if (event != null) { + var keyName = this.state.keyName; + var json = _defineProperty({}, keyName, event.target.value); + var newValue = event.target.value; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + this.setState({ value: newValue }); + this.calculateWidth(newValue); + }.bind(this), + error: function (result) { + this.props.errorToggle('error: Failed to update the subject/name', result); + }.bind(this) + }); + } + }, + componentDidMount: function componentDidMount() { + this.calculateWidth(this.state.value); + }, + handleEnterKey: function handleEnterKey(e) { + if (e.key == 'Enter') { + this.handleChange(e); + } + }, + calculateWidth: function calculateWidth(input) { + var newWidth; + $('#invisible').html($('').text(input)); + newWidth = $('#invisible').width() + 25 + 'px'; + this.setState({ width: newWidth }); + }, + render: function render() { + //only disable the subject editor on an entity with a non-blank subject as editing it could damage flair. + var isDisabled = false; + if (this.props.type == 'entity' && this.state.value != '') { + isDisabled = true; + } + return React.createElement( + 'div', + null, + this.props.subjectType, + ' ', + this.props.id, + ': ', + React.createElement('input', { type: 'text', defaultValue: this.state.value, onKeyPress: this.handleEnterKey, onBlur: this.handleChange, style: { width: this.state.width, lineHeight: 'normal' }, className: 'detail-header-input', disabled: isDisabled }) + ); + } +}); + +module.exports = SelectedHeader; + +},{"../activemq/store.jsx":5,"../components/add_flair.jsx":8,"../components/detail_data_status.jsx":18,"../components/detail_header_more_options":19,"../components/permission.jsx":24,"../components/source.jsx":27,"../components/tag.jsx":29,"../modal/change_history.jsx":74,"../modal/delete.jsx":75,"../modal/entities.jsx":76,"../modal/entity_detail.jsx":78,"../modal/link_warning.jsx":79,"../modal/links.jsx":80,"../modal/mark.jsx":82,"../modal/owner.jsx":83,"../modal/promoted_data.jsx":84,"../modal/viewed_by_history.jsx":85,"./selected_entry.jsx":67,"./selected_header_options.jsx":69,"react":983,"react-bootstrap/lib/Button":527,"react-bootstrap/lib/ButtonToolbar":529,"react-bootstrap/lib/DropdownButton":539,"react-bootstrap/lib/MenuItem":566,"react-bootstrap/lib/OverlayTrigger":582,"react-bootstrap/lib/Popover":591,"react-debounce-input":644,"react-modal":839,"react-notification-system":842,"react-router-dom":878,"react-time":905}],69:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var ButtonGroup = require('react-bootstrap/lib/ButtonGroup.js'); +var Button = require('react-bootstrap/lib/Button.js'); +var MenuItem = require('react-bootstrap/lib/MenuItem.js'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton.js'); +var Promote = require('../components/promote.jsx'); +var Marker = require('../components/marker.jsx').default; +var TrafficLightProtocol = require('../components/traffic_light_protocol.jsx'); + +var SelectedHeaderOptions = React.createClass({ + displayName: 'SelectedHeaderOptions', + + getInitialState: function getInitialState() { + return { + globalFlairState: true, + promoteRemaining: null + }; + }, + toggleFlair: function toggleFlair() { + this.props.toggleFlair(); + $('iframe').each(function (index, ifr) { + if (ifr.contentDocument != null) { + var ifrContents = $(ifr).contents(); + var off = ifrContents.find('.entity-off'); + var on = ifrContents.find('.entity'); + if (this.state.globalFlairState == false) { + ifrContents.find('.extras').show(); + ifrContents.find('.flair-off').hide(); + off.each(function (index, entity) { + $(entity).addClass('entity'); + $(entity).removeClass('entity-off'); + }); + this.setState({ globalFlairState: true }); + } else { + ifrContents.find('.extras').hide(); + ifrContents.find('.flair-off').show(); + on.each(function (index, entity) { + $(entity).addClass('entity-off'); + $(entity).removeClass('entity'); + }); + this.setState({ globalFlairState: false }); + } + } + }.bind(this)); + /*var off = $('.entity-off'); + var on = $('.entity'); + if (!this.state.globalFlairState) { + this.setState({globalFlairState:true}); + $('.extras').show(); + $('.flair-off').hide(); + off.each(function(index, entity) { + $(entity).addClass('entity'); + $(entity).removeClass('entity-off'); + }); + } else { + $('.extras').hide(); + $('.flair-off').show(); + this.setState({globalFlairState:false}); + on.each(function(index, entity) { + $(entity).addClass('entity-off'); + $(entity).removeClass('entity'); + }); + }*/ + }, + //All methods containing alert are only used by selected_entry when viewing an alertgroupand interacting with an alert. + alertOpenSelected: function alertOpenSelected() { + var array = []; + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push({ id: id, status: 'open' }); + }.bind(this)); + var data = JSON.stringify({ alerts: array }); + + this.props.ToggleProcessingMessage(true); + + $.ajax({ + type: 'put', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id, + data: data, + contentType: 'application/json; charset=UTF-8', + success: function (response) { + console.log('success'); + this.props.ToggleProcessingMessage(false); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to open selected alerts', data); + this.props.ToggleProcessingMessage(false); + }.bind(this) + }); + }, + + alertCloseSelected: function alertCloseSelected() { + var time = Math.round(new Date().getTime() / 1000); + var array = []; + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push({ id: id, status: 'closed', closed: time }); + }.bind(this)); + var data = JSON.stringify({ alerts: array }); + + this.props.ToggleProcessingMessage(true); + + $.ajax({ + type: 'put', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id, + data: data, + contentType: 'application/json; charset=UTF-8', + success: function (response) { + console.log('success'); + this.props.ToggleProcessingMessage(false); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to close selected alerts', data); + this.props.ToggleProcessingMessage(false); + }.bind(this) + }); + }, + + alertPromoteSelected: function alertPromoteSelected() { + var data = JSON.stringify({ promote: 'new' }); + var array = []; + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push(id); + }.bind(this)); + + this.props.ToggleProcessingMessage(true); + + //Start by promoting the first one in the array + $.ajax({ + type: 'put', + url: '/scot/api/v2/alert/' + array[0], + data: data, + contentType: 'application/json; charset=UTF-8', + success: function (response) { + //With the entry number, promote the others into the existing event + var promoteTo = { + promote: response.pid + }; + + this.setState({ promoteRemaining: array.length - 1 }); + + for (var i = 1; i < array.length; i++) { + + $.ajax({ + type: 'put', + url: '/scot/api/v2/alert/' + array[i], + data: JSON.stringify(promoteTo), + contentType: 'application/json; charset=UTF-8', + success: function (response) { + console.log('success'); + this.setState({ promoteRemaining: this.state.promoteRemaining - 1 }); + + if (this.state.promoteRemaining == 0) { + this.props.ToggleProcessingMessage(false); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to promoted selected alerts', data); + this.setState({ promoteRemaining: this.state.promoteRemaining - 1 }); + }.bind(this) + }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to promoted selected alerts', data); + }.bind(this) + }); + }, + /*Future use? + alertUnpromoteSelected: function() { + var data = JSON.stringify({unpromote:this.props.aIndex}) + var array = []; + $('tr.selected').each(function(index,tr) { + var id = $(tr).attr('id'); + array.push(id); + }.bind(this)); + for (i=0; i < array.length; i++) { + $.ajax({ + type:'put', + url: '/scot/api/v2/alert/'+array[i], + data: data, + contentType: 'application/json; charset=UTF-8', + success: function(response){ + console.log('success'); + }.bind(this), + error: function() { + console.log('failure'); + }.bind(this) + }) + } + },*/ + alertSelectExisting: function alertSelectExisting() { + var text = prompt("Please Enter Event ID to promote into"); + var array = []; + if (text != '' && text != null) { + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push(id); + }.bind(this)); + for (var i = 0; i < array.length; i++) { + if ($.isNumeric(text)) { + var data = { + promote: parseInt(text) + }; + $.ajax({ + type: 'PUT', + url: '/scot/api/v2/alert/' + array[i], + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + success: function (response) { + if ($.isNumeric(text)) { + window.location = '#/event/' + text; + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to promote into existing event', data); + }.bind(this) + }); + } else { + prompt("Please use numbers only"); + this.selectExisting(); + } + } + } + }, + alertExportCSV: function alertExportCSV() { + var keys = []; + $('.alertTableHorizontal').find('th').each(function (key, value) { + var obj = $(value).text(); + keys.push(obj); + }); + var csv = ''; + $('tr.selected').each(function (x, y) { + var storearray = []; + $(y).find('td').each(function (x, y) { + var copy = $(y).clone(false); + $(copy).find('.extras').remove(); + var value = $(copy).text(); + value = value.replace(/,/g, '|'); + storearray.push(value); + }); + csv += storearray.join() + '\n'; + }); + var result = keys.join() + "\n"; + csv = result + csv; + var data_uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv); + window.open(data_uri); + }, + alertDeleteSelected: function alertDeleteSelected() { + if (confirm("Are you sure you want to Delete? This action can not be undone.")) { + var array = []; + $('tr.selected').each(function (index, tr) { + var id = $(tr).attr('id'); + array.push(id); + }.bind(this)); + for (var i = 0; i < array.length; i++) { + $.ajax({ + type: 'delete', + url: '/scot/api/v2/alert/' + array[i], + success: function (response) { + console.log('success'); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to delete selected alerts', data); + }.bind(this) + }); + } + } + }, + + componentDidMount: function componentDidMount() { + //open, close SELECTED alerts + if (this.props.type == 'alertgroup' || this.props.type == 'alert') { + $('#main-detail-container').keydown(function (event) { + if ($('input').is(':focus')) { + return; + } + if (event.keyCode == 79 && event.ctrlKey != true && event.metaKey != true) { + this.alertOpenSelected(); + } + if (event.keyCode == 67 && event.ctrlKey != true && event.metaKey != true) { + this.alertCloseSelected(); + } + }.bind(this)); + } + $('#main-detail-container').keydown(function (event) { + if ($('input').is(':focus')) { + return; + } + if (event.keyCode == 84 && event.ctrlKey != true && event.metaKey != true) { + this.toggleFlair(); + } + }.bind(this)); + }, + + componentWillUnmount: function componentWillUnmount() { + $('#main-detail-container').unbind('keydown'); + }, + + guideToggle: function guideToggle() { + var entityoffset = { top: 0, left: 0 //set to 0 so it appears in a default location. + };this.props.flairToolbarToggle(this.props.guideID, null, 'guide', entityoffset, null); + }, + + createGuide: function createGuide() { + var data = JSON.stringify({ subject: 'ENTER A GUIDE NAME', applies_to: [this.props.subjectName] }); + $.ajax({ + type: 'POST', + url: '/scot/api/v2/guide', + data: data, + contentType: 'application/json; charset=UTF-8', + success: function (response) { + window.open('/#/guide/' + response.id); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to create a new guide', data); + }.bind(this) + }); + }, + reparseFlair: function reparseFlair() { + $.ajax({ + type: 'put', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify({ parsed: 0 }), + contentType: 'application/json; charset=UTF-8', + success: function (response) { + console.log('reparsing started'); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to reparse flair', data); + }.bind(this) + }); + }, + + createLinkSignature: function createLinkSignature() { + $.ajax({ + type: 'POST', + url: '/scot/api/v2/signature', + data: JSON.stringify({ target: { id: this.props.id, type: this.props.type }, name: 'Name your Signature', status: 'disabled' }), + contentType: 'application/json; charset=UTF-8', + success: function (response) { + var url = '/#/signature/' + response.id; + window.open(url, '_blank'); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to create a signature', data); + }.bind(this) + }); + }, + + manualUpdate: function manualUpdate() { + this.props.updated(null, null); + }, + render: function render() { + var subjectType = this.props.subjectType; + var type = this.props.type; + var id = this.props.id; + var status = this.props.status; + + var string = ''; + + if (this.props.headerData.subject) { + string = this.props.headerData.subject; + } else if (this.props.headerData.value) { + string = this.props.headerData.value; + } else if (this.props.headerData.name) { + string = this.props.headerData.name; + } else if (this.props.headerData.body) { + string = this.props.headerData.body; + } + + if (type != 'alertgroup') { + var newType = null; + var showPromote = true; + var showAddEntry = true; + if (status != 'promoted') { + if (type == "alert") { + newType = "Event"; + } else if (type == "event") { + newType = "Incident"; + } else if (type == "incident" || type == "guide" || type == 'intel' || type == 'signature' || type == 'entity') { + showPromote = false; + } + } else { + showPromote = false; + } + return React.createElement( + 'div', + { className: 'entry-header detail-buttons' }, + type != 'entity' ? React.createElement( + Button, + { eventKey: '1', bsStyle: 'success', onClick: this.props.entryToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-plus-circle', 'aria-hidden': 'true' }), + ' Add Entry' + ) : null, + type != 'entity' ? React.createElement( + Button, + { eventKey: '2', onClick: this.props.fileUploadToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-upload', 'aria-hidden': 'true' }), + ' Upload File' + ) : null, + React.createElement( + Button, + { eventKey: '3', onClick: this.toggleFlair, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-eye-slash', 'aria-hidden': 'true' }), + ' Toggle Flair' + ), + type == 'alertgroup' || type == 'event' || type == 'intel' ? React.createElement( + Button, + { eventKey: '4', onClick: this.props.viewedByHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' Viewed By History' + ) : null, + React.createElement( + Button, + { eventKey: '5', onClick: this.props.changeHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' ', + subjectType, + ' History' + ), + type != 'entity' ? React.createElement( + Button, + { eventKey: '6', onClick: this.props.permissionsToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-users', 'aria-hidden': 'true' }), + ' Permissions' + ) : null, + React.createElement(TrafficLightProtocol, { type: type, id: id, tlp: this.props.headerData.tlp }), + React.createElement( + Button, + { eventKey: '7', onClick: this.props.entitiesToggle, bsSize: 'xsmall' }, + React.createElement( + 'span', + { className: 'entity' }, + '__' + ), + ' View Entities' + ), + type == 'guide' ? React.createElement( + Button, + { eventKey: '8', onClick: this.props.guideRedirectToAlertListWithFilter, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-table', 'aria-hidden': 'true' }), + ' View Related Alerts' + ) : null, + React.createElement( + Button, + { onClick: this.props.linksModalToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-link', 'aria-hidden': 'true' }), + ' Links' + ), + showPromote ? React.createElement(Promote, { type: type, id: id, updated: this.props.updated, errorToggle: this.props.errorToggle }) : null, + type != 'signature' ? React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.createLinkSignature }, + React.createElement('i', { className: 'fa fa-pencil', 'aria-hidden': 'true' }), + ' Create & Link Signature' + ) : null, + type == 'signature' ? React.createElement( + Button, + { eventKey: '11', onClick: this.props.showSignatureOptionsToggle, bsSize: 'xsmall', bsStyle: 'warning' }, + 'View Custom Options' + ) : null, + React.createElement( + Button, + { bsStyle: 'danger', eventKey: '9', onClick: this.props.deleteToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-trash', 'aria-hidden': 'true' }), + ' Delete ', + subjectType + ), + React.createElement( + ButtonGroup, + { style: { float: 'right' } }, + React.createElement(Marker, { type: type, id: id, string: string }), + React.createElement( + Button, + { onClick: this.props.markModalToggle, bsSize: 'xsmall' }, + 'Marked Objects' + ), + React.createElement( + Button, + { id: 'refresh-detail', bsStyle: 'info', eventKey: '10', onClick: this.manualUpdate, bsSize: 'xsmall', style: { float: 'right' } }, + React.createElement('i', { className: 'fa fa-refresh', 'aria-hidden': 'true' }) + ) + ) + ); + } else { + if (this.props.aIndex != undefined) { + return React.createElement( + 'div', + { className: 'entry-header second-menu detail-buttons' }, + React.createElement( + Button, + { eventKey: '1', onClick: this.toggleFlair, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-eye-slash', 'aria-hidden': 'true' }), + ' Toggle Flair' + ), + React.createElement( + Button, + { eventKey: '2', onClick: this.reparseFlair, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-refresh', 'aria-hidden': 'true' }), + ' Reparse Flair' + ), + this.props.guideID == null ? null : React.createElement( + 'span', + null, + this.props.guideID != 0 ? React.createElement( + Button, + { eventKey: '3', onClick: this.guideToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/guide.png' }), + ' Guide' + ) : React.createElement( + Button, + { eventKey: '3', onClick: this.createGuide, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/guide.png' }), + ' Create Guide' + ) + ), + React.createElement( + Button, + { eventKey: '4', onClick: this.props.sourceToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/code.png' }), + ' View Source' + ), + React.createElement( + Button, + { eventKey: '5', onClick: this.props.entitiesToggle, bsSize: 'xsmall' }, + React.createElement( + 'span', + { className: 'entity' }, + '__' + ), + ' View Entities' + ), + type == 'alertgroup' || type == 'event' || type == 'intel' ? React.createElement( + Button, + { eventKey: '6', onClick: this.props.viewedByHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' Viewed By History' + ) : null, + React.createElement( + Button, + { eventKey: '7', onClick: this.props.changeHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' ', + subjectType, + ' History' + ), + React.createElement(TrafficLightProtocol, { type: type, id: id, tlp: this.props.headerData.tlp }), + React.createElement( + Button, + { eventKey: '8', onClick: this.alertOpenSelected, bsSize: 'xsmall', bsStyle: 'danger' }, + React.createElement('img', { src: '/images/open.png' }), + ' Open Selected' + ), + React.createElement( + Button, + { eventKey: '9', onClick: this.alertCloseSelected, bsSize: 'xsmall', bsStyle: 'success' }, + React.createElement('i', { className: 'fa fa-flag-checkered', 'aria-hidden': 'true' }), + ' Close Selected' + ), + React.createElement( + Button, + { eventKey: '10', onClick: this.alertPromoteSelected, bsSize: 'xsmall', bsStyle: 'warning' }, + React.createElement('img', { src: '/images/megaphone.png' }), + ' Promote Selected' + ), + React.createElement( + Button, + { eventKey: '11', onClick: this.alertSelectExisting, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/megaphone_plus.png' }), + ' Add Selected to ', + React.createElement( + 'b', + null, + 'Existing Event' + ) + ), + React.createElement( + Button, + { eventKey: '12', onClick: this.props.entryToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-plus-circle', 'aria-hidden': 'true' }), + ' Add Entry' + ), + React.createElement( + Button, + { eventKey: '13', onClick: this.props.fileUploadToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-upload', 'aria-hidden': 'true' }), + ' Upload File' + ), + React.createElement( + Button, + { eventKey: '14', onClick: this.alertExportCSV, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/csv_text.png' }), + ' Export to CSV' + ), + React.createElement( + Button, + { onClick: this.props.linksModalToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-link', 'aria-hidden': 'true' }), + ' Links' + ), + React.createElement(Marker, { type: type, id: id, string: string, isAlert: true, getSelectedAlerts: this.getSelectedAlerts }), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.createLinkSignature }, + React.createElement('i', { className: 'fa fa-pencil', 'aria-hidden': 'true' }), + ' Create & Link Signature' + ), + React.createElement( + Button, + { eventKey: '15', onClick: this.alertDeleteSelected, bsSize: 'xsmall', bsStyle: 'danger' }, + React.createElement('i', { className: 'fa fa-trash', 'aria-hidden': 'true' }), + ' Delete Selected' + ), + React.createElement( + Button, + { bsStyle: 'danger', eventKey: '17', onClick: this.props.deleteToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-trash', 'aria-hidden': 'true' }), + ' Delete ', + subjectType + ), + React.createElement( + ButtonGroup, + { style: { float: 'right' } }, + React.createElement(Marker, { type: type, id: id, string: string }), + React.createElement( + Button, + { onClick: this.props.markModalToggle, bsSize: 'xsmall' }, + 'Marked Actions' + ), + React.createElement( + Button, + { bsStyle: 'info', eventKey: '16', onClick: this.manualUpdate, bsSize: 'xsmall', style: { float: 'right' } }, + React.createElement('i', { className: 'fa fa-refresh', 'aria-hidden': 'true' }) + ) + ) + ); + } else { + return React.createElement( + 'div', + { className: 'entry-header detail-buttons' }, + React.createElement( + Button, + { eventKey: '1', onClick: this.toggleFlair, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-eye-slash', 'aria-hidden': 'true' }), + ' Toggle Flair' + ), + React.createElement( + Button, + { eventKey: '2', onClick: this.reparseFlair, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-refresh', 'aria-hidden': 'true' }), + ' Reparse Flair' + ), + this.props.guideID == null ? null : React.createElement( + 'span', + null, + this.props.guideID != 0 ? React.createElement( + Button, + { eventKey: '3', onClick: this.guideToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/guide.png' }), + ' Guide' + ) : React.createElement( + Button, + { eventKey: '3', onClick: this.createGuide, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/guide.png' }), + ' Create Guide' + ) + ), + React.createElement( + Button, + { eventKey: '4', onClick: this.props.sourceToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/code.png' }), + ' View Source' + ), + React.createElement( + Button, + { eventKey: '5', onClick: this.props.entitiesToggle, bsSize: 'xsmall' }, + React.createElement( + 'span', + { className: 'entity' }, + '__' + ), + ' View Entities' + ), + type == 'alertgroup' || type == 'event' || type == 'intel' ? React.createElement( + Button, + { eventKey: '6', onClick: this.props.viewedByHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' Viewed By History' + ) : null, + React.createElement( + Button, + { eventKey: '7', onClick: this.props.changeHistoryToggle, bsSize: 'xsmall' }, + React.createElement('img', { src: '/images/clock.png' }), + ' ', + subjectType, + ' History' + ), + React.createElement(TrafficLightProtocol, { type: type, id: id, tlp: this.props.headerData.tlp }), + React.createElement( + Button, + { onClick: this.props.linksModalToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-link', 'aria-hidden': 'true' }), + ' Links' + ), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.createLinkSignature }, + React.createElement('i', { className: 'fa fa-pencil', 'aria-hidden': 'true' }), + ' Create & Link Signature' + ), + React.createElement( + Button, + { bsStyle: 'danger', eventKey: '8', onClick: this.props.deleteToggle, bsSize: 'xsmall' }, + React.createElement('i', { className: 'fa fa-trash', 'aria-hidden': 'true' }), + ' Delete ', + subjectType + ), + React.createElement( + ButtonGroup, + { style: { float: 'right' } }, + React.createElement(Marker, { type: type, id: id, string: string }), + React.createElement( + Button, + { onClick: this.props.markModalToggle, bsSize: 'xsmall' }, + 'Marked Actions' + ), + React.createElement( + Button, + { bsStyle: 'info', eventKey: '9', onClick: this.manualUpdate, bsSize: 'xsmall', style: { float: 'right' } }, + React.createElement('i', { className: 'fa fa-refresh', 'aria-hidden': 'true' }) + ) + ) + ); + } + } + } +}); + +module.exports = SelectedHeaderOptions; + +},{"../components/marker.jsx":23,"../components/promote.jsx":25,"../components/traffic_light_protocol.jsx":31,"react":983,"react-bootstrap/lib/Button.js":527,"react-bootstrap/lib/ButtonGroup.js":528,"react-bootstrap/lib/DropdownButton.js":539,"react-bootstrap/lib/MenuItem.js":566}],70:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactTransitionGroup = require('react-transition-group'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var LoadingContainer = function (_PureComponent) { + _inherits(LoadingContainer, _PureComponent); + + function LoadingContainer() { + _classCallCheck(this, LoadingContainer); + + return _possibleConstructorReturn(this, (LoadingContainer.__proto__ || Object.getPrototypeOf(LoadingContainer)).apply(this, arguments)); + } + + _createClass(LoadingContainer, [{ + key: 'render', + value: function render() { + return _react2.default.createElement( + 'div', + { className: 'LoadingContainer' }, + this.props.loading ? _react2.default.createElement('i', { className: 'fa fa-spinner fa-spin fa-2x', 'aria-hidden': 'true' }) : null + ); + } + }]); + + return LoadingContainer; +}(_react.PureComponent); + +LoadingContainer.propTypes = { + loading: _propTypes2.default.bool +}; +exports.default = LoadingContainer; + +},{"prop-types":512,"react":983,"react-transition-group":953}],71:[function(require,module,exports){ +'use strict'; + +var _reactTable = require('react-table'); + +var _reactTable2 = _interopRequireDefault(_reactTable); + +var _tableConfig = require('./tableConfig'); + +var _tableConfig2 = _interopRequireDefault(_tableConfig); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var React = require('react'); +var SelectedContainer = require('../detail/selected_container.jsx'); +var Store = require('../activemq/store.jsx'); +var Popover = require('react-bootstrap/lib/Popover'); +var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger'); +var ButtonToolbar = require('react-bootstrap/lib/ButtonToolbar'); +var DateRangePicker = require('../../../node_modules/react-daterange-picker'); +var Button = require('react-bootstrap/lib/Button'); +var SplitButton = require('react-bootstrap/lib/SplitButton.js'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton.js'); +var MenuItem = require('react-bootstrap/lib/MenuItem.js'); + +var LoadingContainer = require('./LoadingContainer/index.jsx').default; +var EntityCreateModal = require('../modal/entity_create.jsx').default; +var datasource; +var height; +var width; +var listStartX; +var listStartY; +var listStartWidth; +var listStartHeight; +var listQuery = void 0; + +module.exports = React.createClass({ + displayName: 'exports', + + + getInitialState: function getInitialState() { + var type = this.props.type; + var id = this.props.id; + var queryType = this.props.type; + var alertPreSelectedId = null; + var scrollHeight = $(window).height() - 170 + 'px'; + var scrollWidth = '650px'; + var columnsDisplay = []; + var columns = []; + var columnsClassName = []; + var showSelectedContainer = false; + var sort = [{ id: 'id', desc: true }]; + var activepage = { page: 0, limit: 50 }; + var filter = []; + width = 650; + + columnsDisplay = listColumnsJSON.columnsDisplay[this.props.type]; + columns = listColumnsJSON.columns[this.props.type]; + columnsClassName = listColumnsJSON.columnsClassName[this.props.type]; + + if (this.props.listViewSort != null) { + sort = JSON.parse(this.props.listViewSort); + } + + if (this.props.listViewPage != null) { + activepage = JSON.parse(this.props.listViewPage); + } + + if (this.props.listViewFilter != null) { + filter = JSON.parse(this.props.listViewFilter); + } + + if (this.props.type == 'alert') { + showSelectedContainer = false;typeCapitalized = 'Alertgroup';type = 'alertgroup';queryType = 'alertgroup';alertPreSelectedId = id; + }; + + if (this.props.type === 'task') { + type = 'task';queryType = this.props.queryType; + } + + var typeCapitalized = this.titleCase(this.props.type); + return { + splitter: true, + selectedColor: '#AEDAFF', + sourcetags: [], tags: [], startepoch: '', endepoch: '', idtext: '', totalCount: 0, activepage: activepage, + statustext: '', subjecttext: '', idsarray: [], classname: [' ', ' ', ' ', ' '], + alldetail: true, viewsarrow: [0, 0], idarrow: [-1, -1], subjectarrow: [0, 0], statusarrow: [0, 0], + resize: 'horizontal', createdarrow: [0, 0], sourcearrow: [0, 0], tagsarrow: [0, 0], + viewstext: '', entriestext: '', scrollheight: scrollHeight, display: 'flex', + differentviews: '', maxwidth: '915px', maxheight: scrollHeight, minwidth: '650px', + suggestiontags: [], suggestionssource: [], sourcetext: '', tagstext: '', scrollwidth: scrollWidth, reload: false, + viewfilter: false, viewevent: false, showevent: true, objectarray: [], csv: true, fsearch: '', listViewOrientation: 'landscape-list-view', columns: columns, columnsDisplay: columnsDisplay, columnsClassName: columnsClassName, typeCapitalized: typeCapitalized, type: type, queryType: queryType, id: id, showSelectedContainer: showSelectedContainer, listViewContainerDisplay: null, viewMode: this.props.viewMode, offset: 0, sort: sort, filter: filter, match: null, alertPreSelectedId: alertPreSelectedId, entryid: this.props.id2, listViewKey: 1, loading: true, initialAutoScrollToId: false, manualScrollHeight: null, showEntityCreateModal: false }; + }, + + componentWillMount: function componentWillMount() { + if (this.props.viewMode == undefined || this.props.viewMode == 'default') { + this.Landscape(); + } else if (this.props.viewMode == 'landscape') { + this.Landscape(); + } else if (this.props.viewMode == 'portrait') { + this.Portrait(); + } + //If alert id is passed, convert the id to its alertgroup id. + this.ConvertAlertIdToAlertgroupId(this.props.id); + + //if the type is entry, convert the id and type to the actual type and id + this.ConvertEntryIdToType(this.props.id); + }, + + componentDidMount: function componentDidMount() { + var height = this.state.scrollheight; + var sortBy = this.state.sort; + var filterBy = this.state.filter; + var pageLimit = this.state.activepage.limit; + var pageNumber = this.state.activepage.page; + var idsarray = []; + var newPage; + if (this.props.id != undefined) { + if (this.props.id.length > 0) { + array = this.props.id; + //scrolled = $('.container-fluid2').scrollTop() + if (this.state.viewMode == 'landscape') { + height = '30vh'; + } + } + } + + var array = []; + var finalarray = []; + //register for creation + var storeKey = this.props.type + 'listview'; + Store.storeKey(storeKey); + Store.addChangeListener(this.reloadactive); + //List View code + var url = '/scot/api/v2/' + this.state.type; + if (this.props.type == 'alert') { + url = '/scot/api/v2/alertgroup'; + } + + //get page number + newPage = pageNumber * pageLimit; + var data = { limit: pageLimit, offset: newPage + + //add sort to the data object + };if (sortBy != undefined) { + var sortObj = {}; + $.each(sortBy, function (key, value) { + var sortInt = -1; + if (!value.desc) { + sortInt = 1; + }; + sortObj[value.id] = sortInt; + }); + data['sort'] = JSON.stringify(sortObj); + } + + //add filter to the data object + if (this.state.filter != undefined) { + $.each(filterBy, function (key, value) { + if (value.id == 'source' || value.id == 'tag') { + var stringArr = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = value.value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var each = _step.value; + + stringArr.push(each.name); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + data[value.id] = JSON.stringify(stringArr); + } else if (value.id == 'created' || value.id == 'updated') { + var arr = []; + arr.push(value.value.start); + arr.push(value.value.end); + data[value.id] = JSON.stringify(arr); + } else { + data[value.id] = JSON.stringify(value.value); + } + }); + } + + listQuery = $.ajax({ + type: 'GET', + url: url, + data: data, + traditional: true, + success: function (response) { + datasource = response; + $.each(datasource.records, function (key, value) { + finalarray[key] = {}; + $.each(value, function (num, item) { + if (num == 'sources' || num == 'source') { + if (item != undefined) { + var sourcearr = item.join(', '); + finalarray[key]["source"] = sourcearr; + } + } else if (num == 'tags' || num == 'tag') { + if (item != undefined) { + var tagarr = item.join(', '); + finalarray[key]["tag"] = tagarr; + } + } else { + finalarray[key][num] = item; + } + if (num == 'id') { + Store.storeKey(item); + Store.addChangeListener(this.reloadactive); + idsarray.push(item); + } + }.bind(this)); + if (key % 2 == 0) { + finalarray[key]["classname"] = 'table-row roweven'; + } else { + finalarray[key]["classname"] = 'table-row rowodd'; + } + }.bind(this)); + + var totalPages = this.getPages(response.totalRecordCount); //get pages for list view + + this.setState({ scrollheight: height, objectarray: finalarray, totalCount: response.totalRecordCount, loading: false, idsarray: idsarray, totalPages: totalPages }); + if (this.props.type == 'alert' && this.state.showSelectedContainer == false) { + this.setState({ showSelectedContainer: false }); + } else if (this.state.id == undefined) { + this.setState({ showSelectedContainer: false }); + } else { + this.setState({ showSelectedContainer: true }); + }; + }.bind(this), + error: function (data) { + if (!data.statusText == 'abort') { + this.props.errorToggle('failed to get list data', data); + } + }.bind(this) + }); + + $('#list-view-container').keydown(this.keyNavigate); + + $(document.body).keydown(function (e) { + if ($('input').is(':focus')) { + return; + }; + if ($('textarea').is(':focus')) { + return; + }; + if (e.keyCode == 70 && e.ctrlKey != true && e.metaKey != true) { + this.toggleView(); + } + }.bind(this)); + }, + + componentWillUnmount: function componentWillUnmount() { + document.removeEventListener('keydown', this.keyNavigate); + }, + + keyNavigate: function keyNavigate(event) { + if (event.type !== 'click') { + if (!['j', 'k', 'ArrowUp', 'ArrowDown'].includes(event.key)) { + return; + } + + var target = event.target || event.srcElement; + var targetType = target.tagName.toLowerCase(); + if (targetType === 'input' || targetType === 'textarea') { + return; + } + } + + var curRow = document.querySelector('.ReactTable .rt-tbody .rt-tr.selected'); + if (!curRow) { + return; + } + var nextRow = null; + + switch (event.key) { + case 'j': + case 'ArrowDown': + default: + nextRow = curRow.parentElement.nextElementSibling; + break; + case 'k': + case 'ArrowUp': + nextRow = curRow.parentElement.previousElementSibling; + break; + } + + if (!nextRow) { + return; + } + var nextId = nextRow.children[0].children[0].innerHTML; + + this.props.history.push('/' + this.state.type + '/' + nextId); + + event.preventDefault(); + event.stopPropagation(); + }, + + //Callback for AMQ updates + reloadactive: function reloadactive() { + this.getNewData(); + }, + + ToggleCreateEntity: function ToggleCreateEntity() { + this.setState({ showEntityCreateModal: !this.state.showEntityCreateModal }); + }, + + render: function render() { + var listViewContainerHeight; + var showClearFilter = false; + var scrollheight = this.state.scrollheight; + + if (this.state.listViewContainerDisplay == null) { + listViewContainerHeight = null; + } else { + listViewContainerHeight = '0px'; + } + + if (this.state.id != null && this.state.typeCapitalized != null) { + document.title = this.state.typeCapitalized.charAt(0) + '-' + this.state.id; + } + + if (checkCookie('listViewFilter' + this.props.type) != null || checkCookie('listViewSort' + this.props.type) != null || checkCookie('listViewPage' + this.props.type) != null) { + showClearFilter = true; + } + + /*if ( this.state.manualScrollHeight ) { + scrollheight = this.state.manualScrollHeight; + }*/ + + var columns = (0, _tableConfig.buildTypeColumns)(this.props.type); + + return React.createElement( + 'div', + null, + this.state.type != 'entry' ? React.createElement( + 'div', + { key: this.state.listViewKey, className: 'allComponents' }, + React.createElement( + 'div', + { className: 'black-border-line' }, + React.createElement( + 'div', + { className: 'mainview' }, + React.createElement( + 'div', + null, + React.createElement( + 'div', + { className: 'list-buttons', style: { display: 'inline-flex' } }, + this.props.notificationSetting == 'on' ? React.createElement( + Button, + { eventKey: '1', onClick: this.props.notificationToggle, bsSize: 'xsmall' }, + 'Mute Notifications' + ) : React.createElement( + Button, + { eventKey: '2', onClick: this.props.notificationToggle, bsSize: 'xsmall' }, + 'Turn On Notifications' + ), + this.props.type == 'event' || this.props.type == 'intel' || this.props.type == 'incident' || this.props.type == 'signature' || this.props.type == 'guide' || this.props.type == 'entity' ? React.createElement( + Button, + { onClick: this.createNewThing, eventKey: '6', bsSize: 'xsmall' }, + 'Create ', + this.state.typeCapitalized + ) : null, + React.createElement( + Button, + { eventKey: '5', bsSize: 'xsmall', onClick: this.exportCSV }, + 'Export to CSV' + ), + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.toggleView }, + 'Full Screen Toggle (f)' + ), + showClearFilter ? React.createElement( + Button, + { onClick: this.clearAll, eventKey: '3', bsSize: 'xsmall', bsStyle: 'info' }, + 'Clear All Filters' + ) : null + ), + React.createElement( + 'div', + { id: 'list-view-container', tabIndex: '1' }, + React.createElement( + 'div', + { id: 'list-view', tabIndex: '2' }, + React.createElement(_reactTable2.default, { + columns: columns, + data: this.state.objectarray, + style: { + height: scrollheight + }, + page: this.state.activepage.page, + pages: this.state.totalPages, + defaultPageSize: 50, + onPageChange: this.handlePageChange, + onPageSizeChange: this.handlePageSizeChange, + pageSize: this.state.activepage.limit, + onFilteredChange: this.handleFilter, + filtered: this.state.filter, + onSortedChange: this.handleSort, + sorted: this.state.sort, + manual: true, + sortable: true, + filterable: true, + resizable: true, + styleName: 'styles.ReactTable', + className: '-striped -highlight', + minRows: 0, + LoadingComponent: this.CustomTableLoader, + loading: this.state.loading, + getTrProps: this.handleRowSelection + }) + ) + ), + React.createElement('div', { onMouseDown: this.dragdiv, className: 'splitter', style: { display: 'block', height: '5px', backgroundColor: 'black', borderTop: '1px solid #AAA', borderBottom: '1px solid #AAA', cursor: 'row-resize', overflow: 'hidden' } }), + this.state.showSelectedContainer ? React.createElement(SelectedContainer, { id: this.state.id, type: this.state.queryType, alertPreSelectedId: this.state.alertPreSelectedId, taskid: this.state.entryid, handleFilter: this.handleFilter, errorToggle: this.props.errorToggle, history: this.props.history }) : null, + this.state.showEntityCreateModal ? React.createElement(EntityCreateModal, { match: '', modalActive: this.state.showEntityCreateModal, ToggleCreateEntity: this.ToggleCreateEntity, errorToggle: this.props.errorToggle }) : null + ) + ) + ) + ) : null + ); + }, + + CustomTableLoader: function CustomTableLoader() { + return React.createElement( + 'div', + { className: '-loading' + (this.state.loading ? ' -active' : '') }, + React.createElement(LoadingContainer, { loading: this.state.loading }) + ); + }, + + AutoScrollToId: function AutoScrollToId() { + //auto scrolls to selected id + var row = document.querySelector('.ReactTable .rt-tbody .rt-tr.selected'); + var tbody = document.querySelector('.ReactTable .rt-tbody'); + + if (!row) { + tbody.scrollTop = 0; + return; + } + + if (tbody.scrollTop + tbody.offsetHeight - row.offsetHeight < row.offsetTop || row.offsetTop < tbody.scrollTop) { + tbody.scrollTop = row.offsetTop - tbody.offsetHeight / 2 + row.offsetHeight / 2; + } + + this.setState({ initialAutoScrollToId: true }); + }, + + componentDidUpdate: function componentDidUpdate(prevProps, prevState) { + //auto scrolls to selected id + for (var i = 0; i < this.state.objectarray.length; i++) { + //Iterate through all of the items in the list to verify that the current id still matches the rows in the list. If not, don't scroll + var idReference = this.state.objectarray[i].id; + if (this.state.id != null && this.state.id == idReference && this.state.id != prevState.id || this.state.id != null && this.state.id == idReference && prevState.initialAutoScrollToId == false) { + //Checks that the id is present, is on the screen, and will not be kicked off again if its already been scrolled to before. The || statement handles the initial load since the id hasn't been scrolled to before. + setTimeout(this.AutoScrollToId, 300); + } + } + }, + + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + if (nextProps.id == undefined) { + this.setState({ type: nextProps.type, id: null, showSelectedContainer: false, scrollheight: $(window).height() - 170 + 'px' }); + } else if (nextProps.id != this.props.id) { + if (this.props.type == 'alert') { + this.ConvertAlertIdToAlertgroupId(nextProps.id); + this.ConvertEntryIdToType(nextProps.id); + this.setState({ type: nextProps.type, alertPreSelectedId: nextProps.id }); + } else if (this.props.type == 'task') { + this.setState({ type: nextProps.type, queryType: nextProps.queryType, id: nextProps.id, entryid: nextProps.id2 }); + } else { + this.setState({ type: nextProps.type, id: nextProps.id }); + } + } + }, + + ConvertAlertIdToAlertgroupId: function ConvertAlertIdToAlertgroupId(id) { + //if the type is alert, convert the id to the alertgroup id + if (this.props.type == 'alert') { + $.ajax({ + type: 'get', + url: 'scot/api/v2/alert/' + id, + success: function (response1) { + var newresponse = response1; + this.setState({ id: newresponse.alertgroup, showSelectedContainer: true }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to convert alert id to alertgroup id', data); + }.bind(this) + }); + }; + }, + + ConvertEntryIdToType: function ConvertEntryIdToType(id) { + //if the type is alert, convert the id to the alertgroup id + if (this.props.type == 'entry') { + $.ajax({ + type: 'get', + url: 'scot/api/v2/entry/' + id, + async: false, + success: function (response) { + this.selected(response.target.type, response.target.id, this.props.id); + //this.setState({id: response.target.id, type: response.target.type, showSelectedContainer:true}); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to convert alert id to alertgroup id', data); + }.bind(this) + }); + }; + }, + + //This is used for the dragging portrait and landscape views + startdrag: function startdrag(e) { + $('iframe').each(function (index, ifr) { + $(ifr).addClass('pointerEventsOff'); + }); + + this.setState({ manualScrollHeight: listStartHeight + e.clientY - listStartY + 'px', scrollheight: listStartHeight + e.clientY - listStartY + 'px' }); + }, + + stopdrag: function stopdrag(e) { + $('iframe').each(function (index, ifr) { + $(ifr).removeClass('pointerEventsOff'); + }); + document.onmousemove = null; + }, + + dragdiv: function dragdiv(e) { + if (e.preventDefault) { + e.preventDefault(); + } + if (e.stopPropagation) { + e.stopPropagation(); + } + var elem = document.getElementsByClassName('ReactTable'); + listStartX = e.clientX; + listStartY = e.clientY; + listStartWidth = parseInt(document.defaultView.getComputedStyle(elem[0]).width, 10); + listStartHeight = parseInt(document.defaultView.getComputedStyle(elem[0]).height, 10); + document.onmousemove = this.startdrag; + document.onmouseup = this.stopdrag; + }, + + toggleView: function toggleView() { + if (this.state.id.length != 0 && this.state.showSelectedContainer == true && this.state.listViewContainerDisplay != 'none') { + this.setState({ listViewContainerDisplay: 'none', scrollheight: '0px' }); + } else { + this.setState({ listViewContainerDisplay: null, scrollheight: '30vh' }); + } + }, + + Portrait: function Portrait() { + document.onmousemove = null; + document.onmousedown = null; + document.onmouseup = null; + $('.container-fluid2').css('width', '650px'); + width = 650; + $('.splitter').css('width', '5px'); + $('.mainview').show(); + var array = []; + array = ['dates-small', 'status-owner-small', 'module-reporter-small']; + this.setState({ splitter: true, display: 'flex', alldetail: true, scrollheight: $(window).height() - 170 + 'px', maxheight: $(window).height() - 170 + 'px', resize: 'horizontal', differentviews: '', + maxwidth: '', minwidth: '', scrollwidth: '650px', sizearray: array }); + this.setState({ listViewOrientation: 'portrait-list-view' }); + setCookie('viewMode', "portrait", 1000); + }, + + Landscape: function Landscape() { + document.onmousemove = null; + document.onmousedown = null; + document.onmouseup = null; + width = 650; + $('.splitter').css('width', '100%'); + $('.mainview').show(); + this.setState({ classname: [' ', ' ', ' ', ' '], splitter: false, display: 'block', maxheight: '', alldetail: true, differentviews: '100%', + scrollheight: this.state.id != null ? '300px' : $(window).height() - 170 + 'px', maxwidth: '', minwidth: '', scrollwidth: '100%', resize: 'vertical' }); + this.setState({ listViewOrientation: 'landscape-list-view' }); + setCookie('viewMode', "landscape", 1000); + }, + + clearAll: function clearAll() { + var newListViewKey = this.state.listViewKey + 1; + this.setState({ listViewKey: newListViewKey, activepage: { page: 0, limit: this.state.activepage.limit }, sort: [{ id: 'id', desc: true }], filter: [] }); + this.getNewData({ page: 0 }, [{ id: 'id', desc: true }], {}); + deleteCookie('listViewFilter' + this.props.type); //clear filter cookie + deleteCookie('listViewSort' + this.props.type); //clear sort cookie + deleteCookie('listViewPage' + this.props.type); //clear page cookie + }, + + selected: function selected(type, rowid, subid, taskid) { + var scrollheight = void 0; + if (taskid == null && subid == null) { + //window.history.pushState('Page', 'SCOT', '/#/' + type +'/'+rowid) + this.props.history.push('/' + type + '/' + rowid); + } else if (taskid == null && subid != null) { + this.props.history.push('/' + type + '/' + rowid + '/' + subid); + } else { + //If a task, swap the rowid and the taskid + //window.history.pushState('Page', 'SCOT', '/#/' + type + '/' + taskid + '/' + rowid) + this.props.history.push('/' + type + '/' + taskid + '/' + rowid + '/'); + } + + if (this.state.display == 'block') { + scrollheight = '30vh'; + } + + this.setState({ alertPreSelectedId: 0, scrollheight: scrollheight, showSelectedContainer: true }); + }, + + getNewData: function getNewData(page, sort, filter) { + this.setState({ loading: true }); //display loading opacity + var sortBy = sort; + var filterBy = filter; + var pageLimit; + var pageNumber; + var idsarray = this.state.idsarray; + var newidsarray = []; + + //if the type is alert, convert the id to the alertgroup id + this.ConvertAlertIdToAlertgroupId(this.props.id); + + //if the type is entry, convert the id and type to the actual type and id + this.ConvertEntryIdToType(this.props.id); + + //defaultpage = page.page + if (page == undefined) { + pageNumber = this.state.activepage.page; + pageLimit = this.state.activepage.limit; + } else { + if (page.page == undefined) { + pageNumber = this.state.activepage.page; + } else { + pageNumber = page.page; + } + if (page.limit == undefined) { + pageLimit = this.state.activepage.limit; + } else { + pageLimit = page.limit; + } + } + var newPage; + newPage = pageNumber * pageLimit; + //sort check + if (sortBy == undefined) { + sortBy = this.state.sort; + } + //filter check + if (filterBy == undefined) { + filterBy = this.state.filter; + } + var data = { limit: pageLimit, offset: newPage + + //add sort to the data object + };if (sortBy != undefined) { + var sortObj = {}; + $.each(sortBy, function (key, value) { + var sortInt = -1; + if (!value.desc) { + sortInt = 1; + }; + sortObj[value.id] = sortInt; + }); + data['sort'] = JSON.stringify(sortObj); + } + + //add filter to the data object + if (filterBy != undefined) { + $.each(filterBy, function (key, value) { + if (value.id == 'source' || value.id == 'tag') { + var stringArr = []; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = value.value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var each = _step2.value; + + stringArr.push(each.name); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + data[value.id] = JSON.stringify(stringArr); + } else if (value.id == 'created' || value.id == 'updated' || value.id == 'occurred') { + var arr = []; + arr.push(value.value.start); + arr.push(value.value.end); + data[value.id] = JSON.stringify(arr); + } else { + data[value.id] = JSON.stringify(value.value); + } + }); + } + + var newarray = []; + + if (this.state.loading == true) { + listQuery.abort(); + } + + listQuery = $.ajax({ + type: 'GET', + url: '/scot/api/v2/' + this.state.type, + data: data, + traditional: true, + success: function (response) { + datasource = response; + $.each(datasource.records, function (key, value) { + newarray[key] = {}; + $.each(value, function (num, item) { + if (num == 'sources' || num == 'source') { + if (item != undefined) { + var sourcearr = item.join(', '); + newarray[key]["source"] = sourcearr; + } + } else if (num == 'tags' || num == 'tag') { + if (item != undefined) { + var tagarr = item.join(', '); + newarray[key]["tag"] = tagarr; + } + } else { + newarray[key][num] = item; + } + if (num == 'id') { + var idalreadyadded = false; + for (var i = 0; i < idsarray.length; i++) { + if (item == idsarray[i]) { + idalreadyadded = true; + } + } + if (idalreadyadded == false) { + Store.storeKey(item); + Store.addChangeListener(this.reloadactive); + } + newidsarray.push(item); + } + }.bind(this)); + if (key % 2 == 0) { + newarray[key]['classname'] = 'table-row roweven'; + } else { + newarray[key]['classname'] = 'table-row rowodd'; + } + }.bind(this)); + + var totalPages = this.getPages(response.totalRecordCount); //get pages for list view + + this.setState({ totalCount: response.totalRecordCount, activepage: { page: pageNumber, limit: pageLimit }, objectarray: newarray, loading: false, idsarray: newidsarray, totalPages: totalPages }); + }.bind(this), + error: function (data) { + if (!data.statusText == 'abort') { + this.props.errorToggle('failed to get list data', data); + } + }.bind(this) + }); + }, + + exportCSV: function exportCSV() { + var keys = []; + var columns = this.state.columns; + $.each(columns, function (key, value) { + keys.push(value); + }); + var csv = ''; + $('.rt-tbody').find('.rt-tr').each(function (key, value) { + var storearray = []; + $(value).find('.rt-td').each(function (x, y) { + var obj = $(y).text(); + obj = obj.replace(/,/g, '|'); + storearray.push(obj); + }); + csv += storearray.join() + '\n'; + }); + var result = keys.join() + "\n"; + csv = result + csv; + var data_uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv); + window.open(data_uri); + }, + + handleSort: function handleSort(sortArr, clearall) { + var currentSort = this.state.sort; + var newSortArr = []; + + if (clearall === true) { + this.setState({ sort: [{ id: 'id', desc: true }] }); + } else { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = sortArr[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var sortEach = _step3.value; + + if (sortEach.id) { + newSortArr.push(sortEach); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + this.setState({ sort: newSortArr }); + this.getNewData(null, newSortArr, null); + var cookieName = 'listViewSort' + this.props.type; + setCookie(cookieName, JSON.stringify(newSortArr), 1000); + }, + + handleFilter: function handleFilter(filterObj, string, clearall, type) { + var currentFilter = this.state.filter; + var newFilterArr = []; + var _type = this.props.type; + + if (type != undefined) { + _type = type; + } + + if (clearall === true) { + + this.setState({ filter: newFilterArr }); + return; + } else { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + + for (var _iterator4 = filterObj[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var filterEach = _step4.value; + + if (filterEach.id) { + newFilterArr.push(filterEach); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + + this.setState({ filter: newFilterArr }); + + if (type == this.props.type || type == undefined) { + //Check if the type passed in matches the type displayed. If not, it's updating the filter for a future query in a different type. Undefined implies its the same type, so update + this.getNewData({ page: 0 }, null, newFilterArr); + } + + var cookieName = 'listViewFilter' + _type; + setCookie(cookieName, JSON.stringify(newFilterArr), 1000); + } + }, + + titleCase: function titleCase(string) { + var newstring = string.charAt(0).toUpperCase() + string.slice(1); + return newstring; + }, + + createNewThing: function createNewThing() { + var data; + + if (this.props.type == 'signature') { + data = JSON.stringify({ name: 'Name your Signature', status: 'disabled' }); + } else if (this.props.type == 'guide') { + data = JSON.stringify({ subject: 'ENTER A GUIDE NAME', applies_to: ['documentation'] }); + } else if (this.props.type == 'entity') { + this.ToggleCreateEntity(); + return; + } else { + data = JSON.stringify({ subject: 'No Subject' }); + } + + $.ajax({ + type: 'POST', + url: '/scot/api/v2/' + this.props.type, + data: data, + success: function (response) { + this.selected(this.props.type, response.id); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to create new thing', data); + }.bind(this) + }); + }, + + handlePageChange: function handlePageChange(pageIndex) { + this.getNewData({ page: pageIndex }); + var cookieName = 'listViewPage' + this.props.type; + setCookie(cookieName, JSON.stringify({ page: pageIndex, limit: this.state.activepage.limit })); + }, + + handlePageSizeChange: function handlePageSizeChange(pageSize, pageIndex) { + this.getNewData({ limit: pageSize, page: pageIndex }); + var cookieName = 'listViewPage' + this.props.type; + setCookie(cookieName, JSON.stringify({ page: pageIndex, limit: pageSize })); + }, + + getPages: function getPages(count) { + var totalPages = Math.ceil((count || 1) / this.state.activepage.limit); + return totalPages; + }, + + handleRowSelection: function handleRowSelection(state, rowInfo, column, instance) { + var _this = this; + + return { + onClick: function onClick(event) { + if (_this.state.id === rowInfo.row.id) { + return; + } + + var scrollheight = _this.state.scrollheight; + if (_this.state.display == 'block') { + scrollheight = '30vh'; + } + + if (_this.state.type === 'task') { + _this.props.history.push('/task/' + rowInfo.row.target_type + '/' + rowInfo.row.target_id + '/' + rowInfo.row.id); + } else { + _this.props.history.push('/' + _this.state.type + '/' + rowInfo.row.id); + } + _this.setState({ alertPreSelectedId: 0, scrollheight: scrollheight, showSelectedContainer: true }); + return; + }, + className: rowInfo.row.id === parseInt(this.props.id) ? 'selected' : null + }; + } +}); + +},{"../../../node_modules/react-daterange-picker":619,"../activemq/store.jsx":5,"../detail/selected_container.jsx":66,"../modal/entity_create.jsx":77,"./LoadingContainer/index.jsx":70,"./tableConfig":72,"react":983,"react-bootstrap/lib/Button":527,"react-bootstrap/lib/ButtonToolbar":529,"react-bootstrap/lib/DropdownButton.js":539,"react-bootstrap/lib/MenuItem.js":566,"react-bootstrap/lib/OverlayTrigger":582,"react-bootstrap/lib/Popover":591,"react-bootstrap/lib/SplitButton.js":597,"react-table":891}],72:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildTypeColumns = exports.defaultTypeTableSettings = undefined; + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactDaterangePicker = require('react-daterange-picker'); + +var _reactDaterangePicker2 = _interopRequireDefault(_reactDaterangePicker); + +var _reactDebounceInput = require('react-debounce-input'); + +var _reactDebounceInput2 = _interopRequireDefault(_reactDebounceInput); + +var _time = require('../utils/time'); + +var _constants = require('../utils/constants'); + +var constants = _interopRequireWildcard(_constants); + +var _LoadingContainer = require('./LoadingContainer'); + +var _LoadingContainer2 = _interopRequireDefault(_LoadingContainer); + +var _TagInput = require('../components/TagInput'); + +var _TagInput2 = _interopRequireDefault(_TagInput); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var customFilters = { + numberFilter: function numberFilter(_ref) { + var filter = _ref.filter, + _onChange = _ref.onChange; + return _react2.default.createElement(_reactDebounceInput2.default, { + debounceTimeout: 200, + type: 'number', + minLength: 1, + min: 0, + value: filter ? filter.value : '', + onChange: function onChange(e) { + return _onChange(e.target.value); + }, + style: { width: '100%' } + }); + }, + stringFilter: function stringFilter(_ref2) { + var filter = _ref2.filter, + _onChange2 = _ref2.onChange; + return _react2.default.createElement(_reactDebounceInput2.default, { + debounceTimeout: 200, + minLength: 1, + value: filter ? filter.value : '', + onChange: function onChange(e) { + return _onChange2(e.target.value); + }, + style: { width: '100%' } + }); + }, + dropdownFilter: function dropdownFilter() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['open', 'closed', 'promoted']; + var align = arguments[1]; + return function (_ref3) { + var filter = _ref3.filter, + onChange = _ref3.onChange; + return _react2.default.createElement( + _reactBootstrap.OverlayTrigger, + { trigger: 'focus', placement: 'bottom', overlay: _react2.default.createElement( + _reactBootstrap.Popover, + { id: 'status_popover', style: { maxWidth: '400px' } }, + _react2.default.createElement( + _reactBootstrap.ButtonGroup, + { vertical: true, style: { maxHeight: '50vh', overflowY: 'auto', position: 'relative' } }, + options.map(function (option) { + return _react2.default.createElement( + _reactBootstrap.Button, + { + key: option, + onClick: function onClick() { + return onChange(option); + }, + active: filter && filter.value === option, + style: { textTransform: 'capitalize', textAlign: align ? align : null } + }, + option + ); + }) + ), + filter && _react2.default.createElement( + _reactBootstrap.Button, + { + block: true, + onClick: function onClick() { + return onChange(''); + }, + bsStyle: 'primary', + style: { marginTop: '3px' } + }, + 'Clear' + ) + ) }, + _react2.default.createElement('input', { type: 'text', value: filter ? filter.value : '', readOnly: true, style: { width: '100%', cursor: 'pointer' } }) + ); + }; + }, + dateRange: function dateRange(_ref4) { + var filter = _ref4.filter, + onChange = _ref4.onChange; + return _react2.default.createElement( + _reactBootstrap.OverlayTrigger, + { trigger: 'click', rootClose: true, placement: 'bottom', overlay: _react2.default.createElement( + _reactBootstrap.Popover, + { id: 'daterange_popover', style: { maxWidth: '350px' } }, + _react2.default.createElement(_reactDaterangePicker2.default, { numberOfCalendars: 2, selectionType: 'range', showLegend: false, singleDateRange: true, onSelect: function onSelect(range, states) { + onChange((0, _time.momentRangeToEpoch)(range)); + }, value: filter ? (0, _time.epochRangeToMoment)(filter.value) : null }), + filter && _react2.default.createElement( + _reactBootstrap.Button, + { block: true, onClick: function onClick() { + onChange(''); + document.dispatchEvent(new MouseEvent('click')); + }, bsStyle: 'primary' }, + 'Clear' + ) + ) }, + _react2.default.createElement('input', { type: 'text', value: filter ? (0, _time.epochRangeToString)(filter.value) : '', readOnly: true, style: { width: '100%', cursor: 'pointer' } }) + ); + }, + tagFilter: function tagFilter() { + var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'tag'; + return function (_ref5) { + var filter = _ref5.filter, + onChange = _ref5.onChange; + return _react2.default.createElement(_TagInput2.default, { type: type, onChange: onChange, value: filter ? filter.value : [] }); + }; + } +}; + +var customCellRenderers = { + dateFormater: function dateFormater(row) { + var date = new Date(row.value * 1000); + return _react2.default.createElement( + 'span', + null, + date.toLocaleString() + ); + }, + alertStatus: function alertStatus(row) { + var _row$value$split$map = row.value.split('/').map(function (value) { + return parseInt(value.trim(), 10); + }), + _row$value$split$map2 = _slicedToArray(_row$value$split$map, 3), + open = _row$value$split$map2[0], + closed = _row$value$split$map2[1], + promoted = _row$value$split$map2[2]; + + var className = 'open btn-danger'; + if (promoted) { + className = 'promoted btn-warning'; + } else if (closed) { + if (!open) { + className = 'closed btn-success'; + } + } + + return _react2.default.createElement( + 'div', + { className: 'alertStatusCell ' + className }, + row.value + ); + }, + textStatus: function textStatus(row) { + var color = 'green'; + if (row.value === 'open' || row.value === 'disabled' || row.value === 'assigned') { + color = 'red'; + } else if (row.value === 'promoted') { + color = 'orange'; + } + + return _react2.default.createElement( + 'span', + { style: { color: color } }, + row.value + ); + } +}; + +var customTableComponents = { + loading: function loading(_ref6) { + var _loading = _ref6.loading; + return _react2.default.createElement( + 'div', + { className: '-loading' + (_loading ? ' -active' : '') }, + _react2.default.createElement(_LoadingContainer2.default, { loading: _loading }) + ); + } +}; + +var columnDefinitions = { + Id: { + Header: 'ID', + accessor: 'id', + maxWidth: 100, + Filter: customFilters.numberFilter + }, + + AlertStatus: { + Header: 'Status', + accessor: function accessor(d) { + return d.open_count + ' / ' + d.closed_count + ' / ' + d.promoted_count; + }, + column: ['open_count', 'closed_count', 'promoted_count'], + id: 'status', + maxWidth: 150, + Filter: customFilters.dropdownFilter(), + Cell: customCellRenderers.alertStatus, + style: { + padding: 0 + } + }, + + EventStatus: { + Header: 'Status', + accessor: 'status', + maxWidth: 100, + Cell: customCellRenderers.textStatus, + Filter: customFilters.dropdownFilter() + }, + + IncidentStatus: { + Header: 'Status', + accessor: 'status', + maxWidth: 100, + Cell: customCellRenderers.textStatus, + Filter: customFilters.dropdownFilter(['open', 'closed']) + }, + + SigStatus: { + Header: 'Status', + accessor: 'status', + maxWidth: 100, + Cell: customCellRenderers.textStatus, + Filter: customFilters.dropdownFilter(['enabled', 'disabled']) + }, + + TaskStatus: { + Header: 'Task Status', + accessor: function accessor(d) { + return d.metadata.task.status; + }, + id: 'status', + column: 'metadata', + Cell: customCellRenderers.textStatus, + Filter: customFilters.dropdownFilter(['open', 'assigned', 'closed']) + }, + + TaskSummary: { + Header: 'Task Summary', + accessor: function accessor(d) { + return d.body_plain.length > 200 ? d.body_plain.substr(0, 200) + '...' : d.body_plain; + }, + id: 'summary', + minWidth: 400, + maxWidth: 5000, + Filter: customFilters.stringFilter + }, + + Subject: { + Header: 'Subject', + accessor: 'subject', + minWidth: 400, + maxWidth: 5000, + Filter: customFilters.stringFilter + }, + + Created: { + Header: 'Created', + accessor: 'created', + minWidth: 100, + maxWidth: 180, + Filter: customFilters.dateRange, + Cell: customCellRenderers.dateFormater + }, + + Updated: { + Header: 'Updated', + accessor: 'updated', + minWidth: 100, + maxWidth: 180, + Filter: customFilters.dateRange, + Cell: customCellRenderers.dateFormater + }, + + Occurred: { + Header: 'Occurred', + accessor: 'occurred', + minWidth: 100, + maxWidth: 180, + Filter: customFilters.dateRange, + Cell: customCellRenderers.dateFormater + }, + + Sources: { + Header: 'Sources', + accessor: 'source', //d => d.source ? d.source.join( ', ' ) : '', + column: 'source', + id: 'source', + minWidth: 120, + //maxWidth: 150, + Filter: customFilters.tagFilter('source') + }, + + Tags: { + Header: 'Tags', + accessor: 'tag', //d => d.tag ? d.tag.join( ', ' ) : '', + column: 'tag', + id: 'tag', + minWidth: 120, + //maxWidth: 150, + Filter: customFilters.tagFilter('tag') + }, + + TaskOwner: { + Header: 'Task Owner', + accessor: 'owner', + maxWidth: 80, + Filter: customFilters.stringFilter + }, + + Owner: { + Header: 'Owner', + accessor: 'owner', + maxWidth: 80, + Filter: customFilters.stringFilter + }, + + Entries: { + Header: 'Entries', + accessor: 'entry_count', + maxWidth: 70, + Filter: customFilters.numberFilter + }, + + Views: { + Header: 'Views', + accessor: 'views', + maxWidth: 70, + Filter: customFilters.numberFilter + }, + + DOE: { + Header: 'DOE', + accessor: 'doe_report_id', + maxWidth: 100, + Filter: customFilters.stringFilter + }, + + IncidentType: { + Header: 'Type', + accessor: 'type', + minWidth: 200, + maxWidth: 250, + Filter: customFilters.dropdownFilter(constants.INCIDENT_TYPES, 'left') + }, + + AppliesTo: { + Header: 'Applies To', + accessor: 'applies_to', + Filter: customFilters.stringFilter, + minWidth: 400, + maxWidth: 5000 + }, + + Value: { + Header: 'Value', + accessor: 'value', + Filter: customFilters.stringFilter, + minWidth: 400, + maxWidth: 5000 + }, + + Name: { + Header: 'Name', + accessor: 'name', + Filter: customFilters.stringFilter, + minWidth: 200, + maxWidth: 300 + }, + + Group: { + Header: 'Group', + accessor: function accessor(d) { + return d.signature_group ? d.signature_group.join(', ') : ''; + }, + column: 'signature_group', + id: 'group', + Filter: customFilters.stringFilter + }, + + Type: { + Header: 'Type', + accessor: 'type', + Filter: customFilters.stringFilter, + minWidth: 100, + maxWidth: 150 + }, + + Description: { + Header: 'Description', + accessor: 'description', + Filter: customFilters.stringFilter, + minWidth: 400, + maxWidth: 5000 + }, + + TargetType: { + Header: 'Type', + accessor: function accessor(d) { + return d.target.type; + }, + column: 'target', + id: 'target_type', + Filter: customFilters.stringFilter + }, + + TargetId: { + Header: 'Target Id', + accessor: function accessor(d) { + return d.target.id; + }, + column: 'target', + id: 'target_id', + Filter: customFilters.numberFilter + }, + + OpenTasks: { + Header: 'Open Tasks', + accessor: 'has_tasks', + Filter: customFilters.numberFilter, + maxWidth: 90, + filterable: false + } +}; + +var defaultTableSettings = { + manual: true, + sortable: true, + filterable: true, + resizable: true, + styleName: 'styles.ReactTable', + className: '-striped -highlight', + minRows: 0, + + LoadingComponent: customTableComponents.loading + +}; + +var defaultTypeTableSettings = exports.defaultTypeTableSettings = { + page: 0, + pageSize: 50, + sorted: [{ + id: 'id', + desc: true + }], + filtered: [] +}; + +var defaultColumnSettings = { + style: { + padding: '5px 5px' + } +}; + +var typeColumns = { + alertgroup: ['Id', 'AlertStatus', 'Subject', 'Created', 'Sources', 'Tags', 'Views', 'OpenTasks'], + event: ['Id', 'EventStatus', 'Subject', 'Created', 'Updated', 'Sources', 'Tags', 'Owner', 'Entries', 'Views', 'OpenTasks'], + incident: ['Id', 'DOE', 'IncidentStatus', 'Owner', 'Subject', 'Occurred', 'IncidentType', { + title: 'Tags', + options: { minWidth: 100, maxWidth: 150 } + }, { + title: 'Sources', + options: { minWidth: 100, maxWidth: 150 } + }], + intel: ['Id', 'Subject', 'Created', 'Updated', 'Sources', { + title: 'Tags', + options: { minWidth: 200, maxWidth: 250 } + }, 'Owner', 'Entries', 'Views'], + task: ['Id', 'TargetType', 'TargetId', { + title: 'TaskOwner', + options: { minWidth: 150, maxWidth: 500 } + }, 'TaskStatus', 'TaskSummary', { + title: 'Updated', + options: { minWidth: 150, maxWidth: 500 } + }], + signature: ['Id', 'Name', 'Type', 'SigStatus', 'Group', 'Description', 'Owner', 'Tags', 'Sources', 'Updated'], + guide: ['Id', 'Subject', 'AppliesTo'], + entity: ['Id', 'Value', 'Type', 'Entries'], + default: ['Id', 'AlertStatus', 'Subject', 'Created', 'Sources', 'Tags', 'Views'] +}; + +var buildTypeColumns = exports.buildTypeColumns = function buildTypeColumns(type) { + if (!typeColumns.hasOwnProperty(type)) { + // throw new Error( 'No columns defined for type: '+ type ); + type = 'default'; + } + + var columns = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = typeColumns[type][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var col = _step.value; + + var colOptions = {}; + + if ((typeof col === 'undefined' ? 'undefined' : _typeof(col)) === 'object') { + colOptions = _extends({}, columnDefinitions[col.title], col.options); + } else if (typeof col === 'string') { + colOptions = columnDefinitions[col]; + } + + columns.push(_extends({}, defaultColumnSettings, colOptions)); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return columns; +}; + +exports.default = defaultTableSettings; + +},{"../components/TagInput":6,"../utils/constants":86,"../utils/time":88,"./LoadingContainer":70,"react":983,"react-bootstrap":608,"react-daterange-picker":619,"react-debounce-input":644}],73:[function(require,module,exports){ +'use strict'; + +var _report = require('../components/dashboard/report'); + +var ReactDOM = require('react-dom'); +var React = require('react'); +var Navbar = require('react-bootstrap/lib/Navbar.js'); +var Nav = require('react-bootstrap/lib/Nav.js'); +var NavItem = require('react-bootstrap/lib/NavItem.js'); +var NavDropdown = require('react-bootstrap/lib/NavDropdown.js'); +var MenuItem = require('react-bootstrap/lib/MenuItem.js'); +var LinkContainer = require('react-router-bootstrap/lib/LinkContainer.js'); +var ListView = require('../list/list-view.jsx'); +//var ListView = require('../ListView/index.jsx').default; +var Router = require('react-router-dom').Router; +var Route = require('react-router-dom').Route; +var Link = require('react-router-dom').Link; +var customHistory = require('history').createBrowserHistory; +var Switch = require('react-router-dom').Switch; +var HashRouter = require('react-router-dom').HashRouter; +var BrowserRouter = require('react-router-dom').BrowserRouter; +var Listener = require('../activemq/listener.jsx'); +var Store = require('../activemq/store.jsx'); +var SelectedContainer = require('../detail/selected_container.jsx'); +var AMQ = require('../debug-components/amq.jsx'); +var Wall = require('../debug-components/wall.jsx'); +var Search = require('../components/esearch.jsx'); +var Revl = require('../components/visualization/revl.coffee'); +var Gamification = require('../components/dashboard/gamification.jsx'); +var Status = require('../components/dashboard/status.jsx'); +var Online = require('../components/dashboard/online.jsx'); + +var Notification = require('react-notification-system'); +var Login = require('../modal/login.jsx').default; + +{ + window.React = React; + var $ = window.$; +} + +var App = React.createClass({ + displayName: 'App', + + + getInitialState: function getInitialState() { + Listener.activeMq(); //register for amq updates + return { handler: undefined, viewMode: 'default', notificationSetting: 'on', eestring: '', login: false, csrf: '', origurl: '', sensitivity: '', whoami: undefined }; + }, + + componentDidMount: function componentDidMount() { + this.GetHandler(); + this.WhoAmIQuery(); + + Store.storeKey('wall'); + Store.addChangeListener(this.wall); + Store.storeKey('notification'); + Store.addChangeListener(this.notification); + + //ee + if (this.props.match.url == '/') { + $(document.body).keydown(function (e) { + this.ee(e); + }.bind(this)); + } + }, + + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + var viewModeSetting = checkCookie('viewMode'); + var notificationSetting = checkCookie('notification'); + if (nextProps.match.params.value) { + var listViewFilterSetting = checkCookie('listViewFilter' + nextProps.match.params.value.toLowerCase()); + var listViewSortSetting = checkCookie('listViewSort' + nextProps.match.params.value.toLowerCase()); + var listViewPageSetting = checkCookie('listViewPage' + nextProps.match.params.value.toLowerCase()); + } + if (notificationSetting == undefined) { + notificationSetting = 'on'; + } + + if (!this.state.handler) { + this.GetHandler(); + } + + if (!this.state.whoami) { + this.WhoAmIQuery(); + } + + this.setState({ viewMode: viewModeSetting, notificationSetting: notificationSetting, listViewFilter: listViewFilterSetting, listViewSort: listViewSortSetting, listViewPage: listViewPageSetting }); + }, + + ee: function ee(e) { + var ee = '837279877769847269697171'; + if (ee.includes(this.state.eestring)) { + if (this.state.eestring + e.keyCode == ee) { + this.eedraw(); + setTimeout(this.eeremove, 2000); + } else { + if ($('input').is(':focus')) { + return; + }; + if (e.ctrlKey != true && e.metaKey != true) { + var eestring = this.state.eestring + e.keyCode; + this.setState({ eestring: eestring }); + } + } + } else { + this.setState({ eestring: '' }); + } + }, + + eedraw: function eedraw() { + $('#content').css('transform', 'rotateX(20deg)'); + $(document.body).prepend('Lbh sbhaq gur rtt. Cbfg gb gur jnyy "V sbhaq gur rtt, pna lbh?"'); + }, + + eeremove: function eeremove() { + $('#content').css('transform', 'rotateX(0deg)'); + $('#ee').remove(); + }, + + componentWillUnmount: function componentWillUnmount() { + removeSessionStorage('whoami'); + }, + + componentWillMount: function componentWillMount() { + //Get landscape/portrait view if the cookie exists + var viewModeSetting = checkCookie('viewMode'); + var notificationSetting = checkCookie('notification'); + if (this.props.match.params.value) { + var listViewFilterSetting = checkCookie('listViewFilter' + this.props.match.params.value.toLowerCase()); + var listViewSortSetting = checkCookie('listViewSort' + this.props.match.params.value.toLowerCase()); + var listViewPageSetting = checkCookie('listViewPage' + this.props.match.params.value.toLowerCase()); + globalFilter = listViewFilterSetting; + globalPage = listViewPageSetting; + globalSort = listViewSortSetting; + } + if (notificationSetting == undefined) { + notificationSetting = 'on'; + } + this.setState({ viewMode: viewModeSetting, notificationSetting: notificationSetting, listViewFilter: listViewFilterSetting, listViewSort: listViewSortSetting, listViewPage: listViewPageSetting }); + }, + notification: function notification() { + //Notification display in update as it will run on every amq message matching 'main'. + var notification = this.refs.notificationSystem; + //not showing notificaiton on entity due to "flooding" on an entry update that has many entities causing a storm of AMQ messages + if (activemqwho != 'scot-alerts' && activemqwho != 'scot-admin' && activemqwho != 'scot-flair' && notification != undefined && activemqwho != this.state.whoami && activemqwho != "" && activemqwho != 'api' && activemqwall != true && activemqtype != 'entity' && this.state.notificationSetting == 'on') { + notification.addNotification({ + message: activemqwho + activemqmessage + activemqid, + level: 'info', + autoDismiss: 5, + action: activemqstate != 'delete' ? { + label: 'View', + callback: function callback() { + window.open('/#/' + activemqtype + '/' + activemqid); + } + } : null + }); + } + }, + wall: function wall() { + var notification = this.refs.notificationSystem; + var date = new Date(activemqwhen * 1000); + date = date.toLocaleString(); + if (activemqwall == true) { + notification.addNotification({ + message: date + ' ' + activemqwho + ': ' + activemqmessage, + level: 'warning', + autoDismiss: 0 + }); + activemqwall = false; + } + }, + errorToggle: function errorToggle(string, result) { + var errorString = string; + if (result) { + if (result.responseJSON) { + if (result.responseJSON.error === 'Authentication Required') { + this.setState({ csrf: result.responseJSON.csrf }); //set csrf here since it can change after the login prompt loads + this.loginToggle(result.responseJSON.csrf); + return; + } + } else if (result.statusText == 'Service Unavailable') { + errorString = result.statusText; //Use server error message if available. + } + } + + var notification = this.refs.notificationSystem; + notification.addNotification({ + message: errorString, + level: 'error', + autoDismiss: 0 + }); + }, + notificationToggle: function notificationToggle() { + if (this.state.notificationSetting == 'off') { + this.setState({ notificationSetting: 'on' }); + setCookie('notification', 'on', 1000); + } else { + this.setState({ notificationSetting: 'off' }); + setCookie('notification', 'off', 1000); + } + }, + + loginToggle: function loginToggle(csrf, loggedin) { + //Only open modal once - if other requests come in to open the modal just bypass since the login page is active + if (!this.state.login && loggedin != true) { + var origurl = this.props.location.pathname;; + this.props.history.push('/'); + this.setState({ login: true, origurl: origurl }); + } else if (this.state.login && loggedin == true) { + this.setState({ login: false }); + this.props.history.push(this.state.origurl); + } + }, + + LogOut: function LogOut() { + //Logs out of SCOT + $.ajax({ + type: 'get', + url: '/logout', + success: function (data) { + this.setState({ login: true }); + console.log('Successfully logged out'); + }.bind(this), + error: function (data) { + this.error('Failed to log out', data); + }.bind(this) + }); + }, + + WhoAmIQuery: function WhoAmIQuery() { + + $.ajax({ + type: 'get', + url: 'scot/api/v2/whoami', + success: function (result) { + setSessionStorage('whoami', result.user); + if (result.data) { + this.setState({ sensitivity: result.data.sensitivity, whoami: result.user }); + } + }.bind(this), + error: function (data) { + this.errorToggle('Failed to get current user', data); + }.bind(this) + }); + }, + + GetHandler: function GetHandler() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/handler?current=1' + }).success(function (response) { + this.setState({ handler: response.records[0].username }); + }.bind(this)); + }, + + render: function render() { + var IH = 'Incident Handler: ' + this.state.handler; + var type = void 0; + + if (this.props.match.params.value) { + type = this.props.match.params.value.toLowerCase(); + } + + return React.createElement( + 'div', + null, + React.createElement( + Navbar, + { inverse: true, fixedTop: true, fluid: true }, + React.createElement( + Navbar.Header, + null, + React.createElement( + Navbar.Brand, + null, + React.createElement( + Link, + { to: '/', style: { margin: '0', padding: '0' } }, + React.createElement('img', { src: '/images/scot.png', style: { width: '50px' } }) + ) + ), + React.createElement(Navbar.Toggle, null) + ), + React.createElement( + Navbar.Collapse, + null, + React.createElement( + Nav, + null, + React.createElement( + LinkContainer, + { to: '/alertgroup', activeClassName: 'active' }, + React.createElement( + NavItem, + null, + 'Alert' + ) + ), + React.createElement( + LinkContainer, + { to: '/event', activeClassName: 'active' }, + React.createElement( + NavItem, + null, + 'Event' + ) + ), + React.createElement( + LinkContainer, + { to: '/incident', activeClassName: 'active' }, + React.createElement( + NavItem, + null, + 'Incident' + ) + ), + React.createElement( + LinkContainer, + { to: '/intel', activeClassName: 'active' }, + React.createElement( + NavItem, + null, + 'Intel' + ) + ), + React.createElement( + NavDropdown, + { id: 'nav-dropdown', title: 'More' }, + React.createElement( + LinkContainer, + { to: '/task', activeClassName: 'active' }, + React.createElement( + MenuItem, + null, + 'Task' + ) + ), + React.createElement( + LinkContainer, + { to: '/guide', activeClassName: 'active' }, + React.createElement( + MenuItem, + null, + 'Guide' + ) + ), + React.createElement( + MenuItem, + { href: '/revl.html#/visualization' }, + 'Visualization' + ), + React.createElement( + LinkContainer, + { to: '/signature', activeClassName: 'active' }, + React.createElement( + MenuItem, + null, + 'Signature' + ) + ), + React.createElement( + LinkContainer, + { to: '/entity', activeClassName: 'active' }, + React.createElement( + MenuItem, + null, + 'Entity' + ) + ), + React.createElement( + LinkContainer, + { to: '/reports', activeClassName: 'active' }, + React.createElement( + MenuItem, + null, + 'Reports' + ) + ), + React.createElement(MenuItem, { divider: true }), + React.createElement( + MenuItem, + { href: '/admin/index.html' }, + 'Administration' + ), + React.createElement( + MenuItem, + { href: '/docs/index.html' }, + 'Documentation' + ), + React.createElement(MenuItem, { divider: true }), + React.createElement( + MenuItem, + { href: '/cyberchef.htm' }, + 'Cyber Chef' + ), + React.createElement(MenuItem, { divider: true }), + React.createElement( + MenuItem, + { href: '/#/', onClick: this.LogOut }, + 'Log Out' + ) + ), + React.createElement( + NavItem, + { href: '/incident_handler.html' }, + IH + ) + ), + React.createElement( + 'span', + { id: 'ouo_warning', className: 'ouo-warning' }, + this.state.sensitivity + ), + React.createElement(Search, { errorToggle: this.errorToggle }) + ) + ), + React.createElement( + 'div', + { className: 'mainNavPadding' }, + React.createElement(Login, { csrf: this.state.csrf, modalActive: this.state.login, loginToggle: this.loginToggle, WhoAmIQuery: this.WhoAmIQuery, GetHandler: this.GetHandler, errorToggle: this.errorToggle }), + React.createElement(Notification, { ref: 'notificationSystem' }), + !type || type == 'home' ? React.createElement( + 'div', + { className: 'homePageDisplay' }, + React.createElement( + 'div', + { className: 'col-md-4' }, + React.createElement('img', { src: '/images/scot-600h.png', style: { maxWidth: '350px', width: '100%', marginLeft: 'auto', marginRight: 'auto', display: 'block' } }), + React.createElement( + 'h1', + null, + 'Sandia Cyber Omni Tracker 3.5' + ), + React.createElement( + 'h1', + null, + this.state.sensitivity + ), + !this.state.login ? React.createElement(Status, { errorToggle: this.errorToggle }) : null + ), + !this.state.login ? React.createElement( + 'div', + null, + React.createElement(Gamification, { errorToggle: this.errorToggle }), + React.createElement(Online, { errorToggle: this.errorToggle }), + React.createElement(_report.ReportDashboard, null) + ) : null + ) : null, + type == 'alert' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'alertgroup' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'entry' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'event' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'incident' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'task' ? React.createElement(ListView, { isTask: true, queryType: this.props.match.params.type, viewMode: this.state.viewMode, type: this.props.match.params.value, id: this.props.match.params.id, id2: this.props.match.params.id2, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'guide' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'intel' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'signature' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'entity' ? React.createElement(ListView, { id: this.props.match.params.id, id2: this.props.match.params.id2, viewMode: this.state.viewMode, type: type, notificationToggle: this.notificationToggle, notificationSetting: this.state.notificationSetting, listViewFilter: this.state.listViewFilter, listViewSort: this.state.listViewSort, listViewPage: this.state.listViewPage, errorToggle: this.errorToggle, history: this.props.history }) : null, + type == 'visualization' ? React.createElement(Revl, { value: type, type: this.props.match.params.type, id: this.props.match.params.id, depth: this.props.match.params.id2, viewMode: this.state.viewMode, Notification: this.state.Notification }) : null, + type === 'reports' && !this.props.match.params.id && React.createElement(_report.ReportPage, null), + type === 'reports' && this.props.match.params.id && React.createElement(_report.SingleReport, { reportType: this.props.match.params.id }), + type == 'amq' ? React.createElement(AMQ, { type: 'amq', errorToggle: this.errorToggle }) : null, + type == 'wall' ? React.createElement(Wall, { errorToggle: this.errorToggle }) : null + ) + ); + } +}); + +ReactDOM.render(React.createElement( + HashRouter, + { history: customHistory() }, + React.createElement( + Switch, + null, + React.createElement(Route, { exact: true, path: '/', component: App }), + React.createElement(Route, { exact: true, path: '/:value', component: App }), + React.createElement(Route, { exact: true, path: '/:value/:id', component: App }), + React.createElement(Route, { exact: true, path: '/:value/:id/:id2', component: App }), + React.createElement(Route, { path: '/:value/:type/:id/:id2', component: App }) + ) +), document.getElementById('content')); + +},{"../activemq/listener.jsx":4,"../activemq/store.jsx":5,"../components/dashboard/gamification.jsx":10,"../components/dashboard/online.jsx":11,"../components/dashboard/report":12,"../components/dashboard/status.jsx":17,"../components/esearch.jsx":20,"../components/visualization/revl.coffee":38,"../debug-components/amq.jsx":64,"../debug-components/wall.jsx":65,"../detail/selected_container.jsx":66,"../list/list-view.jsx":71,"../modal/login.jsx":81,"history":333,"react":983,"react-bootstrap/lib/MenuItem.js":566,"react-bootstrap/lib/Nav.js":573,"react-bootstrap/lib/NavDropdown.js":574,"react-bootstrap/lib/NavItem.js":575,"react-bootstrap/lib/Navbar.js":576,"react-dom":677,"react-notification-system":842,"react-router-bootstrap/lib/LinkContainer.js":866,"react-router-dom":878}],74:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var ReactTime = require('react-time').default; +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var type; +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var ChangeHistory = React.createClass({ + displayName: 'ChangeHistory', + + getInitialState: function getInitialState() { + return { + historyBody: false, + data: '' + }; + }, + componentDidMount: function componentDidMount() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id + '/history', + success: function (result) { + var result = result.records; + this.setState({ historyBody: true, data: result }); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to get change history', data); + }.bind(this) + }); + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { + isOpen: true, + onRequestClose: this.props.changeHistoryToggle, + style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: '/images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.changeHistoryToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + this.props.subjectType, + ' Change History' + ) + ), + React.createElement( + 'div', + { className: 'modal-body', style: { maxHeight: '30vh', width: '700px', overflowY: 'auto' } }, + this.state.historyBody ? React.createElement(ChangeHistoryData, { data: this.state.data }) : null + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { onClick: this.props.changeHistoryToggle }, + 'Done' + ) + ) + ) + ); + } +}); + +var ChangeHistoryData = React.createClass({ + displayName: 'ChangeHistoryData', + + render: function render() { + var rows = []; + var data = this.props.data; + for (var prop in data) { + rows.push(React.createElement(ChangeHistoryDataIterator, { data: data[prop] })); + } + return React.createElement( + 'div', + null, + rows + ); + } +}); + +var ChangeHistoryDataIterator = React.createClass({ + displayName: 'ChangeHistoryDataIterator', + + render: function render() { + var data = this.props.data; + return React.createElement( + 'div', + null, + 'ID: ', + data.id, + ' - ', + React.createElement(ReactTime, { value: data.when * 1000, format: 'MM/DD/YYYY hh:mm:ss a' }), + ' - ', + data.who, + ' - ', + data.what + ); + } +}); + +module.exports = ChangeHistory; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839,"react-time":905}],75:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var Link = require('react-router-dom').Link; + +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + }, + overlay: { + zIndex: '101' + } +}; + +var DeleteEvent = React.createClass({ + displayName: 'DeleteEvent', + + getInitialState: function getInitialState() { + return { + key: this.props.id + }; + }, + toggle: function toggle() { + $.ajax({ + type: 'delete', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + success: function (data) { + console.log('success: ' + data); + this.props.deleteToggle(true); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to delete', data); + this.props.deleteToggle(); + }.bind(this) + }); + this.props.history.push('/' + this.props.type); + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { isOpen: true, onRequestClose: this.props.deleteToggle, style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: 'images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.deleteToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + 'Are you sure you want to delete ', + this.props.subjectType, + ': ', + this.props.id, + '?' + ) + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { id: 'cancel-delete', onClick: this.props.deleteToggle }, + 'Cancel' + ), + React.createElement( + Button, + { bsStyle: 'danger', id: 'delete', onClick: this.toggle }, + 'Delete' + ) + ) + ) + ); + } +}); + +var DeleteEntry = React.createClass({ + displayName: 'DeleteEntry', + + getInitialState: function getInitialState() { + return { + key: this.props.id + }; + }, + toggle: function toggle() { + $.ajax({ + type: 'delete', + url: 'scot/api/v2/entry/' + this.props.entryid, + success: function (data) { + console.log('success: ' + data); + var key = this.state.key; + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to delete entry', data); + }.bind(this) + }); + this.props.deleteToggle(); + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { isOpen: true, onRequestClose: this.props.deleteToggle, style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: 'images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.deleteToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + 'Are you sure you want to delete Entry: ', + this.props.entryid, + '?' + ) + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { id: 'cancel-delete', onClick: this.props.deleteToggle }, + 'Cancel' + ), + React.createElement( + Button, + { bsStyle: 'danger', id: 'delete', onClick: this.toggle }, + 'Delete' + ) + ) + ) + ); + } +}); + +module.exports = { + DeleteEvent: DeleteEvent, + DeleteEntry: DeleteEntry +}; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839,"react-router-dom":878}],76:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var Entities = React.createClass({ + displayName: 'Entities', + + getInitialState: function getInitialState() { + return { + entitiesBody: true + }; + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { + isOpen: true, + onRequestClose: this.props.entitiesToggle, + style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: '/images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.entitiesToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + 'List of Entities' + ) + ), + React.createElement( + 'div', + { className: 'modal-body', style: { maxHeight: '50vh', overflowY: 'auto' } }, + this.state.entitiesBody ? React.createElement(EntitiesData, { data: this.props.entityData, flairToolbarToggle: this.props.flairToolbarToggle }) : null + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { onClick: this.props.entitiesToggle }, + 'Done' + ) + ) + ) + ); + } +}); + +var EntitiesData = React.createClass({ + displayName: 'EntitiesData', + + render: function render() { + var rows = []; + var data = this.props.data; + var originalobj = {}; + originalobj['entities'] = {}; + var obj = originalobj.entities; + for (var prop in data) { + var subobj = {}; + var type = data[prop].type; + var id = data[prop].id; + var value = prop; + subobj[id] = value; + if (obj.hasOwnProperty(type)) { + obj[type].push(subobj); + } else { + var arr = []; + arr.push(subobj); + obj[type] = arr; + } + } + for (var prop in obj) { + var type = prop; + var value = obj[prop]; + rows.push(React.createElement(EntitiesDataHeaderIterator, { type: type, value: value, flairToolbarToggle: this.props.flairToolbarToggle })); + } + return React.createElement( + 'div', + null, + rows + ); + } +}); + +var EntitiesDataHeaderIterator = React.createClass({ + displayName: 'EntitiesDataHeaderIterator', + + render: function render() { + var rows = []; + var type = this.props.type; + var value = this.props.value; + for (var i = 0; i < value.length; i++) { + var eachValue = value[i]; + var entityId = null; + var entityValue = null; + for (var prop in eachValue) { + entityId = prop; + entityValue = eachValue[prop]; + } + rows.push(React.createElement(EntitiesDataValueIterator, { entityValue: entityValue, entityId: entityId, flairToolbarToggle: this.props.flairToolbarToggle })); + } + return React.createElement( + 'div', + { style: { border: '1px solid black', width: '500px' } }, + React.createElement( + 'h3', + null, + type + ), + React.createElement( + 'div', + { style: { fontWeight: 'normal', maxHeight: '300px', overflowY: 'auto' } }, + rows + ) + ); + } +}); + +var EntitiesDataValueIterator = React.createClass({ + displayName: 'EntitiesDataValueIterator', + + toggle: function toggle() { + this.props.flairToolbarToggle(this.props.entityId, this.props.entityValue, 'entity'); + }, + render: function render() { + var entityValue = this.props.entityValue; + return React.createElement( + 'a', + { href: 'javascript: void(0)', onClick: this.toggle }, + entityValue, + React.createElement('br', null) + ); + } +}); +module.exports = Entities; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839}],77:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _autocomplete_input = require('../components/autocomplete_input.jsx'); + +var _autocomplete_input2 = _interopRequireDefault(_autocomplete_input); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } +//import TagInput from '../components/TagInput'; + + +var EntityCreateModal = function (_Component) { + _inherits(EntityCreateModal, _Component); + + function EntityCreateModal(props) { + _classCallCheck(this, EntityCreateModal); + + var _this = _possibleConstructorReturn(this, (EntityCreateModal.__proto__ || Object.getPrototypeOf(EntityCreateModal)).call(this, props)); + + _this.state = { + value: '', + match: '', + userdef: true, + status: 'tracked', + multiword: 'yes', + confirmation: false, + countLoading: false + }; + + _this.Submit = _this.Submit.bind(_this); + _this.HasSpacesCheck = _this.HasSpacesCheck.bind(_this); + _this.Confirmation = _this.Confirmation.bind(_this); + _this.OnChangeValue = _this.OnChangeValue.bind(_this); + _this.OnChangeMatch = _this.OnChangeMatch.bind(_this); + return _this; + } + + _createClass(EntityCreateModal, [{ + key: 'componentWillMount', + value: function componentWillMount() { + if (this.props.match) { + this.setState({ match: this.props.match }); + } + + this.mounted = true; + } + }, { + key: 'componentDidMount', + value: function componentDidMount() { + $(document).keypress(function (event) { + if ($('input').is(':focus')) { + return; + } + + if (event.keyCode == 13 && this.state.match.length >= 1 && this.state.value >= 1) { + if (this.state.confirmation == false) { + this.Confirmation(); + } else { + this.Submit(); + } + } + return; + }.bind(this)).bind(this); + + this.HasSpacesCheck(this.props.match); + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + $(document).unbind('keypress'); + this.mounted = false; + } + }, { + key: 'HasSpacesCheck', + value: function HasSpacesCheck(match) { + if (/\s/g.test(match) == true) { + + this.setState({ multiword: 'yes' }); + } else { + this.setState({ multiword: 'no' }); + } + } + }, { + key: 'GetCount', + value: function GetCount() { + this.setState({ countLoading: true }); + var match = encodeURIComponent(this.state.match); + $.ajax({ + type: 'get', + url: '/scot/api/v2/hitsearch?match=' + match, + success: function (data) { + this.setState({ count: data.count, countLoading: false }); + }.bind(this), + error: function (data) { + this.setState({ count: 'unable to get count', countLoading: false }); + }.bind(this) + }); + } + }, { + key: 'Confirmation', + value: function Confirmation() { + if (this.state.confirmation == false) { + this.GetCount(); + this.setState({ confirmation: true }); + } else { + this.setState({ confirmation: false, value: '' }); + } + } + }, { + key: 'Submit', + value: function Submit() { + var json = { 'value': this.state.value, 'match': this.state.match, 'status': 'active', 'options': { 'multiword': this.state.multiword } }; + $.ajax({ + type: 'POST', + url: '/scot/api/v2/entitytype', + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + console.log('success: ' + data); + this.props.ToggleCreateEntity(); + }.bind(this), + error: function (data) { + if (data.responseJSON.error_msg) { + this.props.errorToggle('failed to create user defined entity: error_message: ' + data.responseJSON.error_msg, data); + } else { + this.props.errorToggle('failed to create user defined entity', data); + } + }.bind(this) + }); + } + }, { + key: 'OnChangeMatch', + value: function OnChangeMatch(e) { + this.setState({ match: e.target.value }); + this.HasSpacesCheck(e.target.value); + } + }, { + key: 'OnChangeValue', + value: function OnChangeValue(e) { + this.setState({ value: e }); + } + }, { + key: 'render', + value: function render() { + + return _react2.default.createElement( + _reactBootstrap.Modal, + { dialogClassName: 'entity-create-modal', show: this.props.modalActive, onHide: this.props.ToggleCreateEntity }, + _react2.default.createElement( + _reactBootstrap.Modal.Header, + { closeButton: true }, + _react2.default.createElement( + _reactBootstrap.Modal.Title, + null, + !this.state.confirmation ? _react2.default.createElement( + 'span', + null, + 'Create a user defined entity' + ) : _react2.default.createElement( + 'span', + null, + 'Confirm and submit user defined entity' + ) + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Body, + null, + !this.state.confirmation ? _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + 'span', + { style: { display: 'flex' } }, + _react2.default.createElement( + 'span', + { style: { width: '150px' } }, + _react2.default.createElement( + 'b', + null, + 'New Entity Name:' + ) + ), + _react2.default.createElement( + 'span', + { style: { width: '300px' } }, + _react2.default.createElement('input', { type: 'tag', onChange: this.OnChangeMatch, value: this.state.match, style: { width: '100%' } }) + ) + ), + _react2.default.createElement( + 'span', + { style: { display: 'flex' } }, + _react2.default.createElement( + 'span', + { style: { width: '150px' } }, + _react2.default.createElement( + 'b', + null, + 'Entity Type:' + ) + ), + _react2.default.createElement( + 'span', + null, + _react2.default.createElement(_autocomplete_input2.default, { type: 'entitytype', OnChange: this.OnChangeValue, value: this.state.value }) + ) + ) + ) : _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + 'div', + null, + 'Entity Name: ', + _react2.default.createElement( + 'b', + null, + this.state.match + ) + ), + _react2.default.createElement( + 'div', + null, + 'Entity Type: ', + _react2.default.createElement( + 'b', + null, + this.state.value + ) + ), + _react2.default.createElement( + 'div', + null, + 'Multiword: ', + _react2.default.createElement( + 'b', + null, + this.state.multiword + ) + ) + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Footer, + null, + !this.state.confirmation ? _react2.default.createElement( + 'span', + null, + this.state.value.length >= 1 && this.state.match.length >= 1 ? _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.Confirmation, bsStyle: 'primary', type: 'submit', active: true }, + 'Continue' + ) : null, + _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.props.ToggleCreateEntity }, + 'Cancel' + ) + ) : _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + 'span', + { style: { color: 'red', float: 'left' } }, + this.state.countLoading ? _react2.default.createElement( + 'span', + null, + 'Count: is loading...' + ) : _react2.default.createElement( + 'span', + null, + 'Count: ', + this.state.count + ) + ), + _react2.default.createElement( + 'span', + null, + _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.Submit, bsStyle: 'success' }, + 'Submit' + ), + _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.Confirmation }, + 'Go Back' + ) + ) + ) + ) + ); + } + }]); + + return EntityCreateModal; +}(_react.Component); + +exports.default = EntityCreateModal; + +},{"../components/autocomplete_input.jsx":9,"prop-types":512,"react":983,"react-bootstrap":608}],78:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Button = require('react-bootstrap/lib/Button'); +var ButtonGroup = require('react-bootstrap/lib/ButtonGroup'); +var Popover = require('react-bootstrap/lib/Popover'); +var Tabs = require('react-bootstrap/lib/Tabs'); +var Tab = require('react-bootstrap/lib/Tab'); +var Inspector = require('react-inspector'); +var SelectedEntry = require('../detail/selected_entry.jsx'); +var AddEntry = require('../components/add_entry.jsx'); +var Draggable = require('react-draggable'); +var DetailDataStatus = require('../components/detail_data_status.jsx'); +var Link = require('react-router-dom').Link; +var Store = require('../activemq/store.jsx'); +var Marker = require('../components/marker.jsx').default; + +var startX; +var startY; +var startWidth; +var startHeight; + +var EntityDetail = React.createClass({ + displayName: 'EntityDetail', + + getInitialState: function getInitialState() { + var tabs = []; + var processedIdsArray = []; + var entityHeight = '100%'; //test + var entityWidthint = 700; + var entityWidth = entityWidthint + 'px'; + var entityMaxHeight = '70vh'; + if (this.props.fullScreen == true) { + entityHeight = '95vh'; + entityWidth = '95%'; + entityMaxHeight = '95vh'; + } + return { + entityData: null, + entityid: this.props.entityid, + entityHeight: entityHeight, + entityWidth: entityWidth, + entityWidthint: entityWidthint, + entityMaxHeight: entityMaxHeight, + tabs: tabs, + initialLoad: false, + processedIds: processedIdsArray, + valueClicked: '', + defaultEntityOffset: this.props.entityoffset, + entityobj: this.props.entityobj, + height: null + }; + }, + componentDidMount: function componentDidMount() { + var currentTabArray = this.state.tabs; + var valueClicked = this.props.entityvalue; + if (this.props.entityid == undefined) { + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + this.props.entitytype + '/byname', + data: { name: valueClicked }, + success: function (result) { + var entityid = result.id; + if (this.isMounted()) { + this.setState({ entityid: entityid }); + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + this.props.entitytype + '/' + entityid, + success: function (result) { + //this.setState({entityData:result}) + var newTab = { data: result, entityid: entityid, entitytype: this.props.entitytype, valueClicked: result.value }; + currentTabArray.push(newTab); + if (this.isMounted()) { + var entityidsarray = []; + entityidsarray.push(entityid); + this.setState({ tabs: currentTabArray, currentKey: entityid, initialLoad: true, processedIds: entityidsarray }); + Store.storeKey(entityid); + Store.addChangeListener(this.updated); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity detail information', data); + }.bind(this) + }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity detail id information ', data); + }.bind(this) + }); + } else { + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + this.props.entitytype + '/' + this.state.entityid, + success: function (result) { + //this.setState({entityData:result}) + var newTab = { data: result, entityid: result.id, entitytype: this.props.entitytype, valueClicked: result.value }; + currentTabArray.push(newTab); + if (this.isMounted()) { + var entityidsarray = []; + entityidsarray.push(result.id); + this.setState({ tabs: currentTabArray, currentKey: result.id, initialLoad: true, processedIds: entityidsarray }); + Store.storeKey(this.props.entityid); + Store.addChangeListener(this.updated); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity detail information', data); + }.bind(this) + }); + } + //Esc key closes popup + function escHandler(event) { + //prevent from working when in input + if ($('input').is(':focus')) { + return; + }; + if ($('#main-search-results')[0] != undefined) { + return; + }; //close search results before closing entity div + //check for esc with keyCode + if (event.keyCode == 27) { + this.props.flairToolbarOff(); + event.preventDefault(); + } + } + + $(document).keydown(escHandler.bind(this)); + this.containerHeightAdjust(); + window.addEventListener('resize', this.containerHeightAdjust); + }, + componentWillUnmount: function componentWillUnmount() { + //removes escHandler bind + $(document).off('keydown'); + //This makes the size that was last used hold for future entities + /*var height = $('#dragme').height(); + var width = $('#dragme').width(); + entityPopUpHeight = height; + entityPopUpWidth = width;*/ + }, + componentWillReceiveProps: function componentWillReceiveProps(nextProps) { + var checkForInitialLoadComplete = { + checkForInitialLoadComplete: function () { + var addNewEntity = { //Initializing Function for adding an entry to be used later. + addNewEntity: function () { + var currentTabArray = this.state.tabs; + if (nextProps.entityid == undefined) { + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + nextProps.entitytype + '/byname', + data: { name: nextProps.entityvalue }, + success: function (result) { + var entityid = result.id; + if (this.isMounted()) { + this.setState({ entityid: entityid }); + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + nextProps.entitytype + '/' + entityid, + success: function (result) { + var newTab = { data: result, entityid: entityid, entitytype: nextProps.entitytype, valueClicked: nextProps.entityvalue }; + currentTabArray.push(newTab); + if (this.isMounted()) { + this.setState({ tabs: currentTabArray, currentKey: nextProps.entityid }); + Store.storeKey(nextProps.entityid); + Store.addChangeListener(this.updated); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity detail information', data); + }.bind(this) + }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity id detail information', data); + }.bind(this) + }); + } else { + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + nextProps.entitytype + '/' + nextProps.entityid, + success: function (result) { + var newTab = { data: result, entityid: nextProps.entityid, entitytype: nextProps.entitytype, valueClicked: nextProps.entityvalue }; + currentTabArray.push(newTab); + if (this.isMounted()) { + this.setState({ tabs: currentTabArray, currentKey: nextProps.entityid }); + Store.storeKey(nextProps.entityid); + Store.addChangeListener(this.updated); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity detail information', data); + }.bind(this) + }); + } + }.bind(this) + }; + if (this.state.initialLoad == false) { + setTimeout(checkForInitialLoadComplete.checkForInitialLoadComplete, 50); + } else { + if (nextProps != undefined) { + //TODO Fix next conditional for undefined that prevents multiple calls for the same ID at load time on a nested entity + if (nextProps.entitytype != null && nextProps.entityid != undefined) { + var nextPropsEntityIdInt = parseInt(nextProps.entityid); + for (var i = 0; i < this.state.tabs.length; i++) { + if (nextPropsEntityIdInt == this.state.tabs[i].entityid || this.state.tabs[i].entitytype == 'guide' && nextProps.entitytype == 'guide') { + if (this.isMounted()) { + this.setState({ currentKey: nextPropsEntityIdInt }); + } + return; + } else { + var array = this.state.processedIds; + var addEntity = true; + for (var i = 0; i < array.length; i++) { + if (array[i] == nextPropsEntityIdInt) { + // Check if entity is already being processed so we don't show it twice + addEntity = false; + } + } + if (addEntity) { + addNewEntity.addNewEntity(); + array.push(nextPropsEntityIdInt); + this.setState({ processedIds: array }); + } + } + } + } + } + } + }.bind(this) + }; + checkForInitialLoadComplete.checkForInitialLoadComplete(); + this.containerHeightAdjust(); + }, + updated: function updated() { + var currentTabArray = this.state.tabs; + var valueClicked = this.props.entityvalue; + for (var j = 0; j < currentTabArray.length; j++) { + if (activemqid == currentTabArray[j].entityid) { + var currentTabArrayIndex = j; + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + this.props.entitytype + '/' + currentTabArray[j].entityid, + success: function (result) { + //this.setState({entityData:result}) + var newTab = { data: result, entityid: result.id, entitytype: this.props.entitytype, valueClicked: result.value }; + currentTabArray[currentTabArrayIndex] = newTab; + if (this.isMounted()) { + var entityidsarray = []; + entityidsarray.push(result.id); + this.setState({ tabs: currentTabArray, currentKey: result.id, initialLoad: true, processedIds: entityidsarray }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get updated entity detail information', data); + }.bind(this) + }); + } + } + }, + initDrag: function initDrag(e) { + //remove the entityPopUpMaxSizeDefault class so it can be resized. + if ($('#dragme').hasClass('entityPopUpMaxSizeDefault')) { + var height = $('#dragme').height() + 'px'; + $('#dragme').css('height', height); + $('#dragme').removeClass('entityPopUpMaxSizeDefault'); + } + var elem = document.getElementById('dragme'); + startX = e.clientX; + startY = e.clientY; + startWidth = parseInt(document.defaultView.getComputedStyle(elem).width, 10); + startHeight = parseInt(document.defaultView.getComputedStyle(elem).height, 10); + document.documentElement.addEventListener('mousemove', this.doDrag, false); + document.documentElement.addEventListener('mouseup', this.stopDrag, false); + this.blockiFrameMouseEvent(); + }, + doDrag: function doDrag(e) { + var elem = document.getElementById('dragme'); + elem.style.width = startWidth + e.clientX - startX + 'px'; + elem.style.height = startHeight + e.clientY - startY + 'px'; + }, + stopDrag: function stopDrag(e) { + document.documentElement.removeEventListener('mousemove', this.doDrag, false);document.documentElement.removeEventListener('mouseup', this.stopDrag, false); + this.allowiFrameMouseEvent(); + }, + moveDivInit: function moveDivInit(e) { + document.documentElement.addEventListener('mouseup', this.moveDivStop, false); + this.blockiFrameMouseEvent(); + }, + moveDivStop: function moveDivStop(e) { + document.documentElement.removeEventListener('mouseup', this.moveDivStop, false); + this.allowiFrameMouseEvent(); + }, + blockiFrameMouseEvent: function blockiFrameMouseEvent() { + $('iframe').each(function (index, ifr) { + $(ifr).addClass('pointerEventsOff'); + }); + }, + allowiFrameMouseEvent: function allowiFrameMouseEvent() { + $('iframe').each(function (index, ifr) { + $(ifr).removeClass('pointerEventsOff'); + }); + }, + handleSelectTab: function handleSelectTab(key) { + this.setState({ currentKey: key }); + }, + + positionRightBoundsCheck: function positionRightBoundsCheck(e) { + if (!e) { + return $(document).width() - this.state.defaultEntityOffset.left - this.state.entityWidthint; + } else { + return $(document).width() - (this.state.defaultEntityOffset.left + e) - this.state.entityWidthint; + } + }, + containerHeightAdjust: function containerHeightAdjust() { + //only run this if we're in /#/entity and not as a popup + if (this.props.fullScreen == true) { + var scrollHeight; + if ($('#list-view-container')[0]) { + scrollHeight = $(window).height() - $('#list-view-container').height() - $('#header').height() - 70; + scrollHeight = scrollHeight + 'px'; + } else { + scrollHeight = $(window).height() - $('#header').height() - 70; + scrollHeight = scrollHeight + 'px'; + } + //$('#detail-container').css('height',scrollHeight); + if (this.isMounted()) { + this.setState({ height: scrollHeight }); + } + } + }, + render: function render() { + //This makes the size that was last used hold for future entities + /*if (entityPopUpHeight && entityPopUpWidth) { + entityHeight = entityPopUpHeight; + entityWidth = entityPopUpWidth; + }*/ + var defaultOffsetY; + var defaultOffsetX; + var tabsArr = []; + var DragmeClass = 'box react-draggable entityPopUp entityPopUpMaxSizeDefault'; + if (this.props.fullScreen == true || $('react-draggable-dragged')) { + //Don't readd entityPopUpMaxSizeDefault if full screen or if the box has been dragged + DragmeClass = 'box react-draggable entityPopUp'; + } + if (this.props.fullScreen == true) { + DragmeClass = DragmeClass + ' height100percent'; + } + for (var i = 0; i < this.state.tabs.length; i++) { + var z = i + 1; + var title = 'tab'; + if (this.state.tabs[i].entitytype == 'guide') { + title = 'guide'; + } else { + if (this.state.tabs[i].valueClicked != undefined) { + title = this.state.tabs[i].valueClicked.slice(0, 15); + } else { + title = ''; + } + } + tabsArr.push(React.createElement( + Tab, + { className: 'tab-content', eventKey: this.state.tabs[i].entityid, title: title }, + React.createElement(TabContents, { data: this.state.tabs[i].data, type: this.props.type, id: this.props.id, entityid: this.state.tabs[i].entityid, entitytype: this.state.tabs[i].entitytype, valueClicked: this.state.tabs[i].valueClicked, i: z, key: z, errorToggle: this.props.errorToggle, linkWarningToggle: this.props.linkWarningToggle }) + )); + } + if (this.state.defaultEntityOffset && this.state.entityobj) { + var positionRightBoundsValue = this.positionRightBoundsCheck(); + if (this.positionRightBoundsCheck($(this.state.entityobj).width()) < 0) { + defaultOffsetX = this.state.defaultEntityOffset.left - this.state.entityWidthint; + } else { + defaultOffsetX = this.state.defaultEntityOffset.left + $(this.state.entityobj).width(); + } + } else { + defaultOffsetY = 50; + defaultOffsetX = 0; + } + if (this.props.fullScreen == true) { + //entity detail is full screen mode + return React.createElement( + 'div', + { id: 'popup-flex-container', style: { height: this.state.height }, className: 'entity-full-screen' }, + React.createElement( + 'div', + { id: 'entity_detail_container', style: { flexFlow: 'column', display: 'flex', width: '100%' } }, + React.createElement( + Tabs, + { className: 'tab-content', defaultActiveKey: this.props.entityid, activeKey: this.state.currentKey, onSelect: this.handleSelectTab, bsStyle: 'pills' }, + tabsArr + ) + ) + ); + } else { + return React.createElement( + Draggable, + { handle: '#handle', onMouseDown: this.moveDivInit }, + React.createElement( + 'div', + { id: 'dragme', className: DragmeClass, style: { width: this.state.entityWidth, left: defaultOffsetX, maxHeight: '90vh' } }, + React.createElement( + 'div', + { id: 'popup-flex-container', style: { height: '100%', display: 'flex', flexFlow: 'row' } }, + React.createElement( + 'div', + { id: 'entity_detail_container', style: { flexFlow: 'column', display: 'flex', width: '100%' } }, + React.createElement( + 'div', + { id: 'handle', style: { width: '100%', background: '#292929', color: 'white', fontWeight: '900', fontSize: 'large', textAlign: 'center', cursor: 'move', flex: '0 1 auto' } }, + React.createElement( + 'div', + null, + React.createElement( + 'span', + { className: 'pull-left', style: { paddingLeft: '5px' } }, + React.createElement('i', { className: 'fa fa-arrows', 'aria-hidden': 'true' }) + ), + React.createElement( + 'span', + { className: 'pull-right', style: { cursor: 'pointer', paddingRight: '5px' } }, + React.createElement('i', { className: 'fa fa-times', style: { color: 'red' }, onClick: this.props.flairToolbarOff }) + ) + ) + ), + React.createElement( + Tabs, + { className: 'tab-content', defaultActiveKey: this.props.entityid, activeKey: this.state.currentKey, onSelect: this.handleSelectTab, bsStyle: 'pills' }, + tabsArr + ) + ), + React.createElement('div', { id: 'sidebar', onMouseDown: this.initDrag, style: { flex: '0 1 auto', backgroundColor: 'black', borderTop: '2px solid black', borderBottom: '2px solid black', cursor: 'nwse-resize', overflow: 'hidden', width: '5px' } }) + ), + React.createElement('div', { id: 'footer', onMouseDown: this.initDrag, style: { display: 'block', height: '5px', backgroundColor: 'black', borderTop: '2px solid black', borderBottom: '2px solid black', cursor: 'nwse-resize', overflow: 'hidden' } }) + ) + ); + } + } + +}); + +var TabContents = React.createClass({ + displayName: 'TabContents', + + render: function render() { + if (this.props.entitytype == 'entity') { + + return React.createElement( + 'div', + { className: 'tab-content' }, + React.createElement( + 'div', + { style: { flex: '0 1 auto', marginLeft: '10px' } }, + React.createElement( + 'h4', + { id: 'myModalLabel' }, + this.props.data != null ? React.createElement(EntityValue, { value: this.props.valueClicked, data: this.props.data, errorToggle: this.props.errorToggle }) : React.createElement( + 'div', + { style: { display: 'inline-flex', position: 'relative' } }, + 'Loading...' + ) + ) + ), + React.createElement( + 'div', + { style: { height: '100%', display: 'flex', flex: '1 1 auto', marginLeft: '10px', flexFlow: 'inherit', minHeight: '1px' } }, + this.props.data != null ? React.createElement(EntityBody, { data: this.props.data, entityid: this.props.entityid, type: this.props.type, id: this.props.id, errorToggle: this.props.errorToggle, linkWarningToggle: this.props.linkWarningToggle }) : React.createElement( + 'div', + null, + 'Loading...' + ) + ) + ); + } else if (this.props.entitytype == 'guide') { + var guideurl = '/' + 'guide/' + this.props.entityid; + return React.createElement( + 'div', + { className: 'tab-content' }, + React.createElement( + 'div', + { style: { flex: '0 1 auto', marginLeft: '10px' } }, + React.createElement( + Link, + { to: guideurl, target: '_blank' }, + React.createElement( + 'h4', + { id: 'myModalLabel' }, + this.props.data != null ? React.createElement( + 'span', + null, + React.createElement( + 'span', + null, + React.createElement(EntityValue, { value: this.props.entityid, errorToggle: this.props.errorToggle }) + ), + React.createElement( + 'div', + null, + React.createElement(EntityValue, { value: this.props.data.applies_to, errorToggle: this.props.errorToggle }) + ) + ) : React.createElement( + 'div', + { style: { display: 'inline-flex', position: 'relative' } }, + 'Loading...' + ) + ) + ) + ), + React.createElement( + 'div', + { style: { overflow: 'auto', flex: '1 1 auto', marginLeft: '10px' } }, + this.props.data != null ? React.createElement(GuideBody, { entityid: this.props.entityid, entitytype: this.props.entitytype }) : React.createElement( + 'div', + null, + 'Loading...' + ) + ) + ); + } + } +}); + +var EntityValue = React.createClass({ + displayName: 'EntityValue', + + render: function render() { + if (this.props.data != undefined) { + //Entity Detail Popup showing the entity type + var entityurl = '/' + 'entity/' + this.props.data.id; + + return React.createElement( + 'div', + { className: 'flair_header' }, + React.createElement( + 'div', + null, + React.createElement( + Link, + { to: entityurl, target: '_blank' }, + 'Entity ', + this.props.data.id + ), + React.createElement( + 'span', + null, + '\xA0' + ), + React.createElement(DetailDataStatus, { status: this.props.data.status, id: this.props.data.id, type: 'entity', errorToggle: this.props.errorToggle }), + React.createElement( + 'span', + null, + '\xA0' + ), + React.createElement(Marker, { type: 'entity', id: this.props.data.id, string: this.props.value }) + ), + React.createElement( + 'div', + null, + React.createElement( + 'span', + null, + this.props.data.type, + ':' + ), + '\xA0', + React.createElement( + 'span', + null, + this.props.value + ) + ) + ); + } else { + //Guide Detail Popup showing the name of the guide that is being applied to + return React.createElement( + 'div', + { className: 'flair_header' }, + this.props.value + ); + } + } +}); + +var EntityBody = React.createClass({ + displayName: 'EntityBody', + + getInitialState: function getInitialState() { + return { + loading: "Loading Entries", + entryToolbar: false, + appearances: 0, + showFullEntityButton: false + }; + }, + updateAppearances: function updateAppearances(appearancesNumber) { + if (appearancesNumber != null) { + if (appearancesNumber != 0) { + var newAppearancesNumber = this.state.appearances + appearancesNumber; + if (this.isMounted()) { + this.setState({ appearances: newAppearancesNumber }); + } + } + } + }, + entryToggle: function entryToggle() { + if (this.state.entryToolbar == false) { + this.setState({ entryToolbar: true }); + } else { + this.setState({ entryToolbar: false }); + } + }, + showFullEntityButton: function showFullEntityButton() { + //don't show the button if in full screen entity view. + if (this.props.type != 'entity') { + this.setState({ showFullEntityButton: true }); + } + }, + linkOnClickIntercept: function linkOnClickIntercept(e) { + this.props.linkWarningToggle(e.target.id); + }, + render: function render() { + var entityEnrichmentDataArr = []; + var entityEnrichmentLinkArr = []; + var entityEnrichmentGeoArr = []; + var enrichmentEventKey = 4; + if (this.props.data != undefined) { + var entityData = this.props.data['data']; + for (var prop in entityData) { + if (entityData[prop] != undefined) { + if (prop == 'geoip') { + entityEnrichmentGeoArr.push(React.createElement( + Tab, + { eventKey: enrichmentEventKey, className: 'entityPopUpButtons', style: { overflow: 'auto' }, title: prop }, + React.createElement(GeoView, { data: entityData[prop].data, type: this.props.type, id: this.props.id, entityData: this.props.data, errorToggle: this.props.errorToggle }) + )); + enrichmentEventKey++; + } else if (entityData[prop].type == 'data') { + entityEnrichmentDataArr.push(React.createElement( + Tab, + { eventKey: enrichmentEventKey, className: 'entityPopUpButtons', style: { overflow: 'auto' }, title: prop }, + React.createElement(EntityEnrichmentButtons, { dataSource: entityData[prop], type: this.props.type, id: this.props.id, errorToggle: this.props.errorToggle }) + )); + enrichmentEventKey++; + } else if (entityData[prop].type == 'link') { + entityEnrichmentLinkArr.push(React.createElement( + Button, + { bsSize: 'xsmall', target: '_blank', id: entityData[prop].data.url, onMouseDown: this.linkOnClickIntercept }, + entityData[prop].data.title + )); + enrichmentEventKey++; + } + } + } + } + //Lazy Loading SelectedEntry as it is not actually loaded when placed at the top of the page due to the calling order. + var SelectedEntry = require('../detail/selected_entry.jsx'); + //PopOut available + //var href = '/#/entity/' + this.props.entityid + '/' + this.props.type + '/' + this.props.id; + var href = '/' + 'entity/' + this.props.entityid; + return React.createElement( + Tabs, + { className: 'tab-content', defaultActiveKey: 1, bsStyle: 'tabs' }, + React.createElement( + Tab, + { eventKey: 1, className: 'entityPopUpButtons', title: this.state.appearances, style: { height: '100%' } }, + React.createElement( + 'div', + null, + entityEnrichmentLinkArr + ), + React.createElement( + 'div', + { style: { maxHeight: '30vh', overflowY: 'auto' } }, + React.createElement( + 'span', + null, + React.createElement( + 'b', + null, + 'Appears: ', + this.state.appearances, + ' times' + ) + ), + this.state.showFullEntityButton == true ? React.createElement( + 'span', + { style: { paddingLeft: '5px' } }, + React.createElement( + Link, + { to: href, style: { color: '#c400ff' }, target: '_blank' }, + 'List truncated due to large amount of references. Click to view the whole entity' + ) + ) : null, + React.createElement('br', null), + React.createElement(EntityReferences, { entityid: this.props.entityid, updateAppearances: this.updateAppearances, type: this.props.type, showFullEntityButton: this.showFullEntityButton, errorToggle: this.props.errorToggle }), + React.createElement('br', null) + ), + React.createElement('hr', { style: { marginTop: '.5em', marginBottom: '.5em' } }), + React.createElement( + 'div', + { style: { maxHeight: '50vh', overflowY: 'auto' } }, + React.createElement( + 'div', + null, + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.entryToggle }, + 'Add Entry' + ), + React.createElement('br', null) + ), + this.state.entryToolbar ? React.createElement(AddEntry, { entryAction: 'Add', type: 'entity', targetid: this.props.entityid, id: 'add_entry', addedentry: this.entryToggle, errorToggle: this.props.errorToggle }) : null, + React.createElement(SelectedEntry, { type: 'entity', id: this.props.entityid, isPopUp: 1, errorToggle: this.props.errorToggle }) + ) + ), + entityEnrichmentGeoArr, + entityEnrichmentDataArr + ); + } + +}); + +var GeoView = React.createClass({ + displayName: 'GeoView', + + getInitialState: function getInitialState() { + return { + copyToEntryToolbar: false, + copyToEntityToolbar: false + }; + }, + copyToEntry: function copyToEntry() { + if (this.state.copyToEntryToolbar == false) { + this.setState({ copyToEntryToolbar: true }); + } else { + this.setState({ copyToEntryToolbar: false }); + } + }, + copyToEntity: function copyToEntity() { + if (this.state.copyToEntityToolbar == false) { + this.setState({ copyToEntityToolbar: true }); + } else { + this.setState({ copyToEntityToolbar: false }); + } + }, + render: function render() { + var trArr = []; + var copyArr = []; + copyArr.push(''); + for (var prop in this.props.data) { + var keyProp = prop; + var value = this.props.data[prop]; + trArr.push(React.createElement( + 'tr', + null, + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px' } }, + React.createElement( + 'b', + null, + prop + ) + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px' } }, + this.props.data[prop] + ) + )); + copyArr.push(''); + } + copyArr.push('
' + prop + '' + value + '
'); + var copy = copyArr.join(''); + return React.createElement( + 'div', + null, + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.copyToEntity }, + 'Copy to ', + React.createElement( + 'b', + null, + "entity" + ), + ' entry' + ), + this.props.type != 'alertgroup' ? React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.copyToEntry }, + 'Copy to ', + React.createElement( + 'b', + null, + this.props.type, + ' ', + this.props.id + ), + ' entry' + ) : null, + this.state.copyToEntryToolbar ? React.createElement(AddEntry, { entryAction: 'Copy To Entry', type: this.props.type, targetid: this.props.id, id: this.props.id, addedentry: this.copyToEntry, content: copy, errorToggle: this.props.errorToggle }) : null, + this.state.copyToEntityToolbar ? React.createElement(AddEntry, { entryAction: 'Copy To Entry', type: 'entity', targetid: this.props.entityData.id, id: this.props.entityData.id, addedentry: this.copyToEntity, content: copy, errorToggle: this.props.errorToggle }) : null, + React.createElement( + 'div', + { className: 'entityTableWrapper' }, + React.createElement( + 'table', + { className: 'tablesorter entityTableHorizontal', id: 'sortableentitytable', width: '100%' }, + trArr + ) + ) + ); + } +}); + +var EntityEnrichmentButtons = React.createClass({ + displayName: 'EntityEnrichmentButtons', + + render: function render() { + var dataSource = this.props.dataSource; + return React.createElement( + 'div', + { style: { overflowY: 'auto', maxHeight: '70vh' } }, + React.createElement( + 'div', + null, + React.createElement(Inspector.default, { data: dataSource, expandLevel: 4 }) + ) + ); + } +}); + +var EntityReferences = React.createClass({ + displayName: 'EntityReferences', + + getInitialState: function getInitialState() { + var maxRecords = 100; + //if type == entity then the url is looking for a full screen entity view with all records. + if (this.props.type == 'entity') { + maxRecords = undefined; + } + return { + entityDataAlertGroup: null, + entityDataEvent: null, + entityDataIncident: null, + entityDataIntel: null, + entityDataSignature: null, + maxRecords: maxRecords, + loadingAlerts: true, + loadingEvents: true, + loadingIncidents: true, + loadingIntel: true, + loadingSignature: true, + loading: true + }; + }, + componentDidMount: function componentDidMount() { + this.alertRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/alert', + data: { sort: JSON.stringify({ 'id': -1 }) }, + traditional: true, + success: function (result) { + var result = result.records; + var recordNumber = result.length; + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + if (this.state.maxRecords) { + recordNumber = this.state.maxRecords; + } + for (var i = 0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted') { + arrPromoted.push(React.createElement(ReferencesBody, { type: 'alert', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else if (result[i].status == 'closed') { + arrClosed.push(React.createElement(ReferencesBody, { type: 'alert', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else { + arrOpen.push(React.createElement(ReferencesBody, { type: 'alert', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({ entityDataAlertGroup: arr, loadingAlerts: false }); + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false && this.state.loadingSignature == false) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity references for alerts', data); + }.bind(this) + }); + + this.eventRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/event', + data: { sort: JSON.stringify({ 'id': -1 }) }, + traditional: true, + success: function (result) { + var result = result.records; + var recordNumber = result.length; + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + if (this.state.maxRecords) { + recordNumber = this.state.maxRecords; + } + for (var i = 0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted') { + arrPromoted.push(React.createElement(ReferencesBody, { type: 'event', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else if (result[i].status == 'closed') { + arrClosed.push(React.createElement(ReferencesBody, { type: 'event', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else { + arrOpen.push(React.createElement(ReferencesBody, { type: 'event', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({ entityDataEvent: arr, loadingEvents: false }); + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false && this.state.loadingSignature) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity reference for events', data); + }.bind(this) + }); + + this.incidentRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/incident', + data: { sort: JSON.stringify({ 'id': -1 }) }, + traditional: true, + success: function (result) { + var result = result.records; + var recordNumber = result.length; + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + if (this.state.maxRecords) { + recordNumber = this.state.maxRecords; + } + for (var i = 0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted') { + arrPromoted.push(React.createElement(ReferencesBody, { type: 'incident', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else if (result[i].status == 'closed') { + arrClosed.push(React.createElement(ReferencesBody, { type: 'incident', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else { + arrOpen.push(React.createElement(ReferencesBody, { type: 'incident', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({ entityDataIncident: arr, loadingIncidents: false }); + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false && this.state.loadingSignature == false) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity references for incidents', data); + }.bind(this) + }); + + this.intelRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/intel', + data: { sort: JSON.stringify({ 'id': -1 }) }, + traditional: true, + success: function (result) { + var result = result.records; + var recordNumber = result.length; + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + if (this.state.maxRecords) { + recordNumber = this.state.maxRecords; + } + for (var i = 0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted') { + arrPromoted.push(React.createElement(ReferencesBody, { type: 'intel', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else if (result[i].status == 'closed') { + arrClosed.push(React.createElement(ReferencesBody, { type: 'intel', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else { + arrOpen.push(React.createElement(ReferencesBody, { type: 'intel', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({ entityDataIntel: arr, loadingIntel: false }); + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false && this.state.loadingSignature == false) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity references for intel'); + }.bind(this) + }); + + this.signatureRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/signature', + data: { sort: JSON.stringify({ 'id': -1 }) }, + traditional: true, + success: function (result) { + var result = result.records; + var recordNumber = result.length; + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + if (this.state.maxRecords) { + recordNumber = this.state.maxRecords; + } + for (var i = 0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted') { + arrPromoted.push(React.createElement(ReferencesBody, { type: 'signature', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else if (result[i].status == 'closed') { + arrClosed.push(React.createElement(ReferencesBody, { type: 'signature', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } else { + arrOpen.push(React.createElement(ReferencesBody, { type: 'signature', data: result[i], index: i, errorToggle: this.props.errorToggle })); + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({ entityDataSignature: arr, loadingSignature: false }); + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false && this.state.loadingSignature == false) { + this.setState({ loading: false }); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entity references for signature'); + }.bind(this) + }); + /* + this.entityRequest = $.ajax({ + type: 'get', + url: 'scot/api/v2/entity/' + this.props.entityid + '/entity', + data: {sort:JSON.stringify({'id':-1})}, + traditional: true, + success: function(result) { + var result = result.records + var arr = []; + var arrPromoted = []; + var arrClosed = []; + var arrOpen = []; + var recordNumber = this.state.maxRecords; + if (isNaN(this.state.maxRecords) == true) { recordNumber = eval(this.state.maxRecords) } + for(var i=0; i < recordNumber; i++) { + if (result[i] != null) { + if (result[i].status == 'promoted'){ + arrPromoted.push() + } else if (result[i].status == 'closed') { + arrClosed.push() + } else { + arrOpen.push() + } + } + } + arr.push(arrPromoted); + arr.push(arrClosed); + arr.push(arrOpen); + if (this.isMounted()) { + if (result.length >= 100) { + this.props.showFullEntityButton(); + } + this.props.updateAppearances(result.length); + this.setState({entityDataIntel:arr, loadingIntel:false}) + if (this.state.loadingAlerts == false && this.state.loadingEvents == false && this.state.loadingIncidents == false && this.state.loadingIntel == false) { + this.setState({loading:false}); + } + } + }.bind(this), + error: function(data) { + this.props.errorToggle('failed to get entity references for entity') + }.bind(this) + })*/ + $('#sortableentitytable' + this.props.entityid).tablesorter(); + }, + componentDidUpdate: function componentDidUpdate() { + var config = $('#sortableentitytable' + this.props.entityid)[0].config, + + // applies or reapplies a sort to the table; use false to not update the sort + resort = true; // or [ [0,0], [1,0] ] etc + $.tablesorter.updateAll(config, resort); + }, + render: function render() { + var id = 'sortableentitytable' + this.props.entityid; + return React.createElement( + 'div', + { className: 'entityTableWrapper' }, + this.state.loading ? React.createElement( + 'span', + null, + 'Loading: ', + this.state.loadingAlerts ? React.createElement( + 'span', + null, + 'Alerts ' + ) : null, + this.state.loadingEvents ? React.createElement( + 'span', + null, + 'Events ' + ) : null, + this.state.loadingIncidents ? React.createElement( + 'span', + null, + 'Incidents ' + ) : null, + this.state.loadingIntel ? React.createElement( + 'span', + null, + 'Intel ' + ) : null, + this.state.loadingSignature ? React.createElement( + 'span', + null, + 'Signature ' + ) : null + ) : null, + React.createElement( + 'table', + { className: 'tablesorter entityTableHorizontal', id: id, width: '100%' }, + React.createElement( + 'thead', + null, + React.createElement( + 'tr', + null, + React.createElement( + 'th', + null, + 'peek' + ), + React.createElement( + 'th', + null, + 'status' + ), + React.createElement( + 'th', + null, + 'id' + ), + React.createElement( + 'th', + null, + 'type' + ), + React.createElement( + 'th', + null, + 'entries' + ), + React.createElement( + 'th', + null, + 'subject' + ), + React.createElement( + 'th', + null, + 'last updated' + ) + ) + ), + React.createElement( + 'tbody', + null, + this.state.entityDataSignature, + this.state.entityDataIntel, + this.state.entityDataIncident, + this.state.entityDataEvent, + this.state.entityDataAlertGroup + ) + ) + ); + } +}); + +var ReferencesBody = React.createClass({ + displayName: 'ReferencesBody', + + getIntialState: function getIntialState() { + return { + showSummary: false, + summaryExists: true + }; + }, + onClick: function onClick() { + $.ajax({ + type: 'GET', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.data.id + '/entry', + success: function (result) { + var entryResult = result.records; + var summary = false; + for (var i = 0; i < entryResult.length; i++) { + if (entryResult[i].class == 'summary') { + summary = true; + if (this.isMounted) { + this.setState({ showSummary: true, summaryData: entryResult[i].body_plain }); + $('#entityTable' + this.props.data.id).qtip({ + content: { text: entryResult[i].body_plain }, + style: { classes: 'qtip-scot' }, + hide: 'unfocus', + position: { my: 'top left', at: 'right', target: $('#entitySummaryRow' + this.props.data.id) }, //[position.left,position.top] }, + show: { ready: true, event: 'click' } + }); + break; + } + } + } + if (summary == false) { + $('#entityTable' + this.props.data.id).qtip({ + content: { text: 'No Summary Found' }, + style: { classes: 'qtip-scot' }, + hide: 'unfocus', + position: { my: 'top left', at: 'right', target: $('#entitySummaryRow' + this.props.data.id) }, + show: { ready: true, event: 'click' } + }); + } + }.bind(this), + error: function (data) { + this.props.errorToggle('Summary Query failed for: ' + this.props.type + ':' + this.props.data.id, data); + }.bind(this) + }); + }, + render: function render() { + var id = this.props.data.id; + var trId = 'entityTable' + this.props.data.id; + var tdId = 'entitySummaryRow' + this.props.data.id; + var aHref = null; + var promotedHref = null; + var statusColor = null; + var daysSince = null; + var subject = this.props.data.subject; + var updatedTime = this.props.data.updated; + var updatedTimeHumanReadable = ''; + if (this.props.data.status == 'promoted') { + statusColor = 'orange'; + } else if (this.props.data.status == 'closed') { + statusColor = 'green'; + } else if (this.props.data.status == 'open') { + statusColor = 'red'; + } else { + statusColor = 'black'; + } + if (this.props.type == 'alert') { + aHref = '/' + this.props.type + '/' + this.props.data.id; + //aHref = '/#/alertgroup/' + this.props.data.alertgroup; + promotedHref = '/#/event/' + this.props.data.promotion_id; + } else if (this.props.type == 'event') { + promotedHref = '/#/incident/' + this.props.data.promotion_id; + aHref = '/' + this.props.type + '/' + this.props.data.id; + } else { + aHref = '/' + this.props.type + '/' + this.props.data.id; + } + if (subject == undefined) { + if (this.props.data.data != undefined) { + if (this.props.data.data.alert_name != undefined) { + subject = this.props.data.data.alert_name; + } else { + subject = ''; + } + } else { + subject = ''; + } + } + if (updatedTime != undefined) { + daysSince = Math.floor((Math.round(new Date().getTime() / 1000) - updatedTime) / 86400); + updatedTimeHumanReadable = new Date(1000 * updatedTime).toLocaleString(); + } + return React.createElement( + 'tr', + { id: trId }, + React.createElement( + 'td', + { style: { textAlign: 'center', cursor: 'pointer', verticalAlign: 'top' }, onClick: this.onClick, id: tdId }, + React.createElement('i', { className: 'fa fa-eye fa-1', 'aria-hidden': 'true' }) + ), + this.props.data.status == 'promoted' ? React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' } }, + React.createElement( + Button, + { bsSize: 'xsmall', bsStyle: 'warning', id: this.props.data.id, href: promotedHref, target: '_blank', style: { lineHeight: '12pt', fontSize: '10pt', marginLeft: 'auto' } }, + this.props.data.status + ) + ) : React.createElement( + 'td', + { style: { color: statusColor, paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' } }, + this.props.data.status + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' } }, + React.createElement( + Link, + { to: aHref, target: '_blank' }, + this.props.data.id + ) + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' } }, + this.props.type + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', textAlign: 'center', verticalAlign: 'top' } }, + this.props.data.entry_count + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' } }, + subject + ), + React.createElement( + 'td', + { style: { paddingRight: '4px', paddingLeft: '4px', verticalAlign: 'top' }, title: updatedTimeHumanReadable }, + daysSince, + ' days ago' + ) + ); + } +}); + +var GuideBody = React.createClass({ + displayName: 'GuideBody', + + getInitialState: function getInitialState() { + return { + entryToolbar: false + }; + }, + entryToggle: function entryToggle() { + if (this.state.entryToolbar == false) { + this.setState({ entryToolbar: true }); + } else { + this.setState({ entryToolbar: false }); + } + }, + render: function render() { + //Lazy Loading SelectedEntry as it is not actually loaded when placed at the top of the page due to the calling order. + var SelectedEntry = require('../detail/selected_entry.jsx'); + return React.createElement( + Tabs, + { className: 'tab-content', defaultActiveKey: 1, bsStyle: 'pills' }, + React.createElement( + Tab, + { eventKey: 1, style: { overflow: 'auto', maxHeight: '70vh' } }, + React.createElement( + 'div', + null, + React.createElement( + Button, + { bsSize: 'xsmall', onClick: this.entryToggle }, + 'Add Entry' + ), + React.createElement('br', null) + ), + this.state.entryToolbar ? React.createElement(AddEntry, { entryAction: 'Add', type: 'guide', targetid: this.props.entityid, id: 'add_entry', addedentry: this.entryToggle, errorToggle: this.props.errorToggle }) : null, + React.createElement(SelectedEntry, { type: 'guide', id: this.props.entityid, isPopUp: 1, errorToggle: this.props.errorToggle }) + ) + ); + } +}); + +module.exports = EntityDetail; + +},{"../activemq/store.jsx":5,"../components/add_entry.jsx":7,"../components/detail_data_status.jsx":18,"../components/marker.jsx":23,"../detail/selected_entry.jsx":67,"react":983,"react-bootstrap/lib/Button":527,"react-bootstrap/lib/ButtonGroup":528,"react-bootstrap/lib/Popover":591,"react-bootstrap/lib/Tab":599,"react-bootstrap/lib/Tabs":604,"react-draggable":804,"react-inspector":811,"react-router-dom":878}],79:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); + +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var LinkWarning = React.createClass({ + displayName: 'LinkWarning', + + proceed: function proceed() { + window.open(this.props.link); + this.props.linkWarningToggle(); + }, + componentWillMount: function componentWillMount() { + var myDomain = window.location.href; + var reg = new RegExp(/((https?|ftp):\/\/[a-zA-Z0-9\-_\.]+\.)?([a-zA-Z0-9\-_\.]+\.([a-zA-Z]{1,63}))/, 'i'); + var linkRegResult = this.props.link.match(reg); + var myDomainRegResult = myDomain.match(reg); + if (linkRegResult != undefined && myDomainRegResult != undefined) { + var linkDomain = linkRegResult[3]; + var myDomain = myDomainRegResult[3]; + if (linkDomain == myDomain) { + this.proceed(); + } + } else if (linkRegResult == undefined) { + this.proceed(); + } + /* + if ($.isUrlInternal(this.props.link)) { + this.proceed(); + }*/ + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { + isOpen: true, + onRequestClose: this.props.linkWarningToggle, + style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: '/images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.linkWarningToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + 'Browse to site?' + ) + ), + React.createElement( + 'div', + { className: 'modal-body' }, + 'The link you clicked may take you to a site outside SCOT. If this is a link an attacker controls you may be tipping your hand.', + React.createElement('br', null), + React.createElement( + 'b', + null, + this.props.link + ) + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { id: 'cancel-delete', onClick: this.props.linkWarningToggle }, + 'Cancel' + ), + React.createElement( + Button, + { bsStyle: 'info', id: 'proceed', onClick: this.proceed }, + 'Proceed' + ) + ) + ) + ); + } +}); +module.exports = LinkWarning; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839}],80:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactTable = require('react-table'); + +var _reactTable2 = _interopRequireDefault(_reactTable); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Links = function (_Component) { + _inherits(Links, _Component); + + function Links(props) { + _classCallCheck(this, Links); + + var _this = _possibleConstructorReturn(this, (Links.__proto__ || Object.getPrototypeOf(Links)).call(this, props)); + + _this.state = { + data: [], + allSelected: false, + loading: false + }; + + _this.getLinks = _this.getLinks.bind(_this); + _this.handleTHeadCheckboxSelection = _this.handleTHeadCheckboxSelection.bind(_this); + _this.handleRowSelection = _this.handleRowSelection.bind(_this); + _this.handleCheckboxSelection = _this.handleCheckboxSelection.bind(_this); + return _this; + } + + _createClass(Links, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.getLinks(); + this.mounted = true; + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'render', + value: function render() { + var _this2 = this; + + var columns = [{ + Header: function Header(cell) { + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { className: 'links-checkbox' }, + _react2.default.createElement('i', { className: 'fa fa' + (_this2.state.allSelected ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }) + ) + ); + }, + id: 'selected', + accessor: function accessor(d) { + return d.selected; + }, + Cell: function Cell(row) { + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { className: 'links-checkbox' }, + _react2.default.createElement('i', { className: 'fa fa' + (row.row.selected ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }) + ) + ); + }, + maxWidth: 100, + filterable: false + }, { + Header: 'Type', + accessor: 'type', + maxWidth: 150, + sortable: true + }, { Header: 'ID', + accessor: 'id', + maxWidth: 100, + sortable: true + }, { + Header: 'Context', + accessor: 'context', + minWidth: 100, + maxWidth: 800, + sortable: true + }, { + Header: 'Memo', + accessor: 'memo', + minWidth: 100, + maxWidth: 800, + sortable: true + }, { Header: 'Link ID', + accessor: 'linkid', + maxWidth: 100, + sortable: true + }]; + + return _react2.default.createElement( + _reactBootstrap.Modal, + { dialogClassName: 'links-modal', show: this.props.modalActive, onHide: this.props.linksModalToggle }, + _react2.default.createElement( + _reactBootstrap.Modal.Header, + { closeButton: true }, + _react2.default.createElement( + _reactBootstrap.Modal.Title, + null, + this.state.data.length, + ' items linked to ', + this.props.type, + ' ', + this.props.id + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Body, + null, + _react2.default.createElement(_reactTable2.default, { + columns: columns, + data: this.state.data, + defaultPageSize: 10, + getTdProps: this.handleCheckboxSelection, + getTheadThProps: this.handleTHeadCheckboxSelection, + getTrProps: this.handleRowSelection, + minRows: 0, + noDataText: 'No items Linked.', + loading: this.state.loading, + style: { + maxHeight: "60vh" + }, + filterable: true + }) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Footer, + null, + _react2.default.createElement(Actions, { data: this.state.data, id: this.props.id, type: this.props.type, getLinks: this.getLinks, errorToggle: this.props.errorToggle }) + ) + ); + } + }, { + key: 'getLinks', + value: function getLinks() { + this.setState({ loading: true }); + + $.ajax({ + type: 'get', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id + '/link', + success: function (data) { + var arr = []; + + for (var i = 0; i < data.records.length; i++) { + var verticeObject = {}; + verticeObject.linkid = data.records[i].id; + verticeObject.context = data.records[i].context; + for (var j = 0; j < data.records[i].vertices.length; j++) { + //if ids are equal, check if the type is equal. If so, it's what is displayed so don't show it. + if (data.records[i].vertices[j].id == this.props.id) { + if (data.records[i].vertices[j].type != this.props.type) { + verticeObject.id = data.records[i].vertices[j].id; + verticeObject.type = data.records[i].vertices[j].type; + verticeObject.memo = data.records[i].memo[j]; + arr.push(verticeObject); + } else { + continue; + } + } else { + verticeObject.id = data.records[i].vertices[j].id; + verticeObject.type = data.records[i].vertices[j].type; + verticeObject.memo = data.records[i].memo[j]; + arr.push(verticeObject); + } + } + } + + this.setState({ data: arr, loading: false }); + }.bind(this), + error: function (data) { + this.setState({ loading: false }); + this.props.errorToggle('failed to get links', data); + }.bind(this) + }); + } + }, { + key: 'handleRowSelection', + value: function handleRowSelection(state, rowInfo, column) { + var _this3 = this; + + return { + onClick: function onClick(event) { + var data = _this3.state.data; + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var row = _step.value; + + if (rowInfo.row.id == row.id && rowInfo.row.type == row.type) { + row.selected = true; + } else { + row.selected = false; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + _this3.setState({ data: data, allSelected: false }); + return; + }, + style: { + background: rowInfo != undefined ? rowInfo.row.selected ? 'rgb(174, 218, 255)' : null : null + } + }; + } + }, { + key: 'handleCheckboxSelection', + value: function handleCheckboxSelection(state, rowInfo, column) { + var _this4 = this; + + if (column.id == 'selected') { + return { + onClick: function onClick(event) { + var data = _this4.state.data; + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var row = _step2.value; + + if (rowInfo.row.id == row.id && rowInfo.row.type == row.type) { + row.selected = !row.selected; + break; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + _this4.setState({ data: data, allSelected: _this4.checkAllSelected(data) }); + event.stopPropagation(); + return; + } + }; + } else { + return {}; + } + } + }, { + key: 'handleTHeadCheckboxSelection', + value: function handleTHeadCheckboxSelection(state, rowInfo, column, instance) { + var _this5 = this; + + if (column.id === 'selected') { + return { + onClick: function onClick(event) { + var data = _this5.state.data; + var allSelected = !_this5.state.allSelected; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var row = _step3.value; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = state.pageRows[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var pageRow = _step4.value; + + if (row.id == pageRow.id && row.type == pageRow.type) { + //compare displayed rows to rows in dataset and only select those + row.selected = allSelected; + break; + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + _this5.setState({ data: data, allSelected: allSelected }); + return; + } + }; + } else { + return {}; + } + } + }, { + key: 'checkAllSelected', + value: function checkAllSelected(data) { + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = data[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var row = _step5.value; + + if (!row.selected) { + return false; + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + return true; + } + }]); + + return Links; +}(_react.Component); + +var Actions = function (_Component2) { + _inherits(Actions, _Component2); + + function Actions(props) { + _classCallCheck(this, Actions); + + var _this6 = _possibleConstructorReturn(this, (Actions.__proto__ || Object.getPrototypeOf(Actions)).call(this, props)); + + _this6.state = { + entry: false, + thing: false, + actionSuccess: false + }; + + _this6.RemoveLink = _this6.RemoveLink.bind(_this6); + _this6.RemoveLinkAjax = _this6.RemoveLinkAjax.bind(_this6); + _this6.ToggleActionSuccess = _this6.ToggleActionSuccess.bind(_this6); + return _this6; + } + + _createClass(Actions, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.mounted = true; + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'render', + value: function render() { + var buttons = []; + var entry = false; + var thing = false; + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = this.props.data[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var key = _step6.value; + + if (key.type && key.selected) { + if (key.type == 'entry') { + entry = true; + } else { + thing = true; + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + + return _react2.default.createElement( + 'div', + null, + this.state.actionSuccess ? _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'span', + { bsStyle: { color: 'green' } }, + 'Action Successful!' + ) + ) : null, + _react2.default.createElement( + 'div', + null, + thing || entry ? _react2.default.createElement( + 'h4', + { style: { float: 'left' } }, + 'Actions' + ) : _react2.default.createElement( + 'div', + null, + ' ', + this.props.data.length > 0 ? _react2.default.createElement( + 'h4', + { style: { float: 'left' } }, + 'Select a link for options' + ) : null, + ' ' + ), + _react2.default.createElement( + _reactBootstrap.ButtonGroup, + { style: { float: 'right' } }, + thing || entry ? _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.RemoveLink }, + 'Remove Link' + ) : null + ) + ) + ); + } + }, { + key: 'RemoveLink', + value: function RemoveLink() { + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + + for (var _iterator7 = this.props.data[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var key = _step7.value; + + if (key.selected) { + this.RemoveLinkAjax(parseInt(key.linkid)); + } + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + }, { + key: 'RemoveLinkAjax', + value: function RemoveLinkAjax(id) { + + $.ajax({ + type: 'delete', + url: '/scot/api/v2/link/' + id, + success: function (response) { + console.log('successfully removed link'); + this.ToggleActionSuccess(); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to remove link', data); + }.bind(this) + }); + } + }, { + key: 'ToggleActionSuccess', + value: function ToggleActionSuccess() { + var newActionSuccess = !this.state.actionSuccess; + this.props.getLinks(); + this.setState({ actionSuccess: newActionSuccess }); + } + }]); + + return Actions; +}(_react.Component); + +exports.default = Links; + +},{"prop-types":512,"react":983,"react-bootstrap":608,"react-table":891}],81:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _actions = require('../activemq/actions'); + +var _actions2 = _interopRequireDefault(_actions); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Login = function (_Component) { + _inherits(Login, _Component); + + function Login(props) { + _classCallCheck(this, Login); + + var _this = _possibleConstructorReturn(this, (Login.__proto__ || Object.getPrototypeOf(Login)).call(this, props)); + + _this.state = { + user: '', + pass: '' + }; + _this.SSO = _this.SSO.bind(_this); + _this.NormalAuth = _this.NormalAuth.bind(_this); + _this.Reset = _this.Reset.bind(_this); + _this.isEnterPressed = _this.isEnterPressed.bind(_this); + return _this; + } + + _createClass(Login, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.mounted = true; + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'render', + value: function render() { + + return _react2.default.createElement( + _reactBootstrap.Modal, + { dialogClassName: 'login-modal', show: this.props.modalActive }, + _react2.default.createElement( + _reactBootstrap.Modal.Header, + null, + _react2.default.createElement( + _reactBootstrap.Modal.Title, + { style: { textAlign: 'center' } }, + _react2.default.createElement( + 'h1', + null, + ' SCOT Login ' + ) + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Body, + { style: { textAlign: 'center' } }, + _react2.default.createElement('img', { src: '/images/scot_logo_473x473.png', alt: 'SCOT Logo' }), + _react2.default.createElement('input', { type: 'submit', value: 'Sign in using SSO', onClick: this.SSO }), + _react2.default.createElement('br', null), + _react2.default.createElement('br', null), + _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'label', + null, + 'Username ' + ), + _react2.default.createElement('input', { id: 'user', type: 'user', ref: 'user', defaultValue: '' }) + ), + _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'label', + null, + 'Password ' + ), + _react2.default.createElement('input', { id: 'pass', type: 'password', ref: 'pass', defaultValue: '', onKeyPress: this.isEnterPressed }) + ), + _react2.default.createElement('input', { type: 'submit', onClick: this.NormalAuth }), + _react2.default.createElement('input', { type: 'reset', onClick: this.Reset }), + _react2.default.createElement('br', null) + ) + ); + } + }, { + key: 'isEnterPressed', + value: function isEnterPressed(e) { + if (e.key == 'Enter') { + this.NormalAuth(); + } + } + }, { + key: 'Reset', + value: function Reset() { + this.refs.user.value == ''; + this.refs.pass.value == ''; + } + }, { + key: 'SSO', + value: function SSO() { + var data = {}; + data['orig_url'] = '%2f'; + $.ajax({ + type: 'get', + url: 'sso', + data: data, + success: function (data) { + console.log('success logging in'); + _actions2.default.restartClient(); //restart the amq client after successful login + this.props.WhoAmIQuery(); //get new whoami after successful login + this.props.GetHandler(); //get new handler after succesful login + this.props.loginToggle(null, true); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to log in using SSO'); + }.bind(this) + }); + } + }, { + key: 'NormalAuth', + value: function NormalAuth() { + var data = {}; + data['user'] = this.refs.user.value; + data['pass'] = this.refs.pass.value; + data['csrf_token'] = this.props.csrf; + + $.ajax({ + type: 'post', + url: 'auth', + data: data, + success: function () { + console.log('success logging in'); + _actions2.default.restartClient(); //restart the amq client after successful login + this.props.WhoAmIQuery(); //get new whoami after successful login + this.props.GetHandler(); //get new handler after succesful login + this.props.loginToggle(null, true); + }.bind(this), + error: function (data) { + if (data.responseText == 'Failed CSRF check') { + this.props.errorToggle('Failed to log in due to bad CSRF token. Please reload the page and then log in. Error: ' + data.responseText); + } else { + this.props.errorToggle('Failed to log in using normal auth: ' + data.responseText); + } + }.bind(this) + }); + } + }]); + + return Login; +}(_react.Component); + +Login.propTypes = { + modalActive: _propTypes2.default.bool +}; + +Login.defaultProps = { + modalActive: true +}; + +exports.default = Login; + +},{"../activemq/actions":1,"prop-types":512,"react":983,"react-bootstrap":608}],82:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactTable = require('react-table'); + +var _reactTable2 = _interopRequireDefault(_reactTable); + +var _marker = require('../components/marker'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Mark = function (_Component) { + _inherits(Mark, _Component); + + function Mark(props) { + _classCallCheck(this, Mark); + + var _this = _possibleConstructorReturn(this, (Mark.__proto__ || Object.getPrototypeOf(Mark)).call(this, props)); + + _this.state = { + data: [], + allSelected: false + }; + + _this.handleTHeadCheckboxSelection = _this.handleTHeadCheckboxSelection.bind(_this); + _this.handleRowSelection = _this.handleRowSelection.bind(_this); + _this.handleCheckboxSelection = _this.handleCheckboxSelection.bind(_this); + _this.getMarkedItems = _this.getMarkedItems.bind(_this); + return _this; + } + + _createClass(Mark, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.mounted = true; + + this.getMarkedItems(); + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'render', + value: function render() { + var _this2 = this; + + var columns = [{ + Header: function Header(cell) { + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { className: 'mark-checkbox' }, + _react2.default.createElement('i', { className: 'fa fa' + (_this2.state.allSelected ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }) + ) + ); + }, + id: 'selected', + accessor: function accessor(d) { + return d.selected; + }, + Cell: function Cell(row) { + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { className: 'mark-checkbox' }, + _react2.default.createElement('i', { className: 'fa fa' + (row.row.selected ? '-check' : '') + '-square-o', 'aria-hidden': 'true' }) + ) + ); + }, + maxWidth: 100, + filterable: false + }, { + Header: 'Type', + accessor: 'type', + maxWidth: 150, + sortable: true + }, { Header: 'ID', + accessor: 'id', + maxWidth: 100, + sortable: true + }, { Header: 'Subject', + accessor: 'subject', + maxWidth: '100%', + sortable: true + }]; + + return _react2.default.createElement( + _reactBootstrap.Modal, + { dialogClassName: 'mark-modal', show: this.props.modalActive, onHide: this.props.markModalToggle }, + _react2.default.createElement( + _reactBootstrap.Modal.Header, + { closeButton: true }, + _react2.default.createElement( + _reactBootstrap.Modal.Title, + null, + 'Marked Objects' + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Body, + null, + this.state.data.length > 0 ? _react2.default.createElement(_reactTable2.default, { + columns: columns, + data: this.state.data, + defaultPageSize: 10, + getTdProps: this.handleCheckboxSelection, + getTheadThProps: this.handleTHeadCheckboxSelection, + getTrProps: this.handleRowSelection, + minRows: 0, + noDataText: 'No items marked.', + style: { + maxHeight: "60vh" + }, + filterable: true + }) : _react2.default.createElement( + 'h3', + null, + 'No marked items detected.' + ) + ), + _react2.default.createElement( + _reactBootstrap.Modal.Footer, + null, + _react2.default.createElement(Actions, { data: this.state.data, id: this.props.id, type: this.props.type, getMarkedItems: this.getMarkedItems, errorToggle: this.props.errorToggle }) + ) + ); + } + }, { + key: 'handleRowSelection', + value: function handleRowSelection(state, rowInfo, column) { + var _this3 = this; + + return { + onClick: function onClick(event) { + var data = _this3.state.data; + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var row = _step.value; + + if (rowInfo.row.id == row.id && rowInfo.row.type == row.type) { + row.selected = true; + } else { + row.selected = false; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + _this3.setState({ data: data, allSelected: false }); + return; + }, + style: { + background: rowInfo != undefined ? rowInfo.row.selected ? 'rgb(174, 218, 255)' : null : null + } + }; + } + }, { + key: 'handleCheckboxSelection', + value: function handleCheckboxSelection(state, rowInfo, column) { + var _this4 = this; + + if (column.id == 'selected') { + return { + onClick: function onClick(event) { + var data = _this4.state.data; + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var row = _step2.value; + + if (rowInfo.row.id == row.id && rowInfo.row.type == row.type) { + row.selected = !row.selected; + break; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + _this4.setState({ data: data, allSelected: _this4.checkAllSelected(data) }); + event.stopPropagation(); + return; + } + }; + } else { + return {}; + } + } + }, { + key: 'handleTHeadCheckboxSelection', + value: function handleTHeadCheckboxSelection(state, rowInfo, column, instance) { + var _this5 = this; + + if (column.id === 'selected') { + return { + onClick: function onClick(event) { + var data = _this5.state.data; + var allSelected = !_this5.state.allSelected; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var row = _step3.value; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = state.pageRows[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var pageRow = _step4.value; + + if (row.id == pageRow.id && row.type == pageRow.type) { + //compare displayed rows to rows in dataset and only select those + row.selected = allSelected; + break; + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + _this5.setState({ data: data, allSelected: allSelected }); + return; + } + }; + } else { + return {}; + } + } + }, { + key: 'checkAllSelected', + value: function checkAllSelected(data) { + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = data[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var row = _step5.value; + + if (!row.selected) { + return false; + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + return true; + } + }, { + key: 'getMarkedItems', + value: function getMarkedItems() { + var markedItems = getLocalStorage('marked'); + var currentItem = { id: this.props.id, type: this.props.type, subject: this.props.string }; + + if (markedItems) { + markedItems = JSON.parse(markedItems); + markedItems.unshift(currentItem); //Add currently viewed item to the top of the list + this.setState({ data: markedItems }); + } else { + return; //return if no items are marked + } + } + }]); + + return Mark; +}(_react.Component); + +var Actions = function (_Component2) { + _inherits(Actions, _Component2); + + function Actions(props) { + _classCallCheck(this, Actions); + + var _this6 = _possibleConstructorReturn(this, (Actions.__proto__ || Object.getPrototypeOf(Actions)).call(this, props)); + + _this6.state = { + entry: false, + thing: false, + actionSuccess: false, + linkContextString: null, + linkPanel: false + }; + + _this6.RemoveSelected = _this6.RemoveSelected.bind(_this6); + _this6.MoveEntry = _this6.MoveEntry.bind(_this6); + _this6.CopyEntry = _this6.CopyEntry.bind(_this6); + _this6.EntryAjax = _this6.EntryAjax.bind(_this6); + _this6.Link = _this6.Link.bind(_this6); + _this6.LinkAjax = _this6.LinkAjax.bind(_this6); + _this6.ToggleActionSuccess = _this6.ToggleActionSuccess.bind(_this6); + _this6.ExpandLinkToggle = _this6.ExpandLinkToggle.bind(_this6); + _this6.LinkContextChange = _this6.LinkContextChange.bind(_this6); + return _this6; + } + + _createClass(Actions, [{ + key: 'componentWillMount', + value: function componentWillMount() { + this.mounted = true; + } + }, { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.mounted = false; + } + }, { + key: 'render', + value: function render() { + var buttons = []; + var entry = false; + var thing = false; + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = this.props.data[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var key = _step6.value; + + if (key.type && key.selected) { + if (key.type == 'entry') { + entry = true; + } else { + thing = true; + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + + return _react2.default.createElement( + 'div', + null, + this.state.actionSuccess ? _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + _reactBootstrap.Button, + { bsStyle: 'success', onClick: this.RemoveSelected }, + 'Action Successful! Remove Mark?' + ), + _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.ToggleActionSuccess }, + 'Keep Marked' + ) + ) : _react2.default.createElement( + 'div', + { style: { display: 'grid' } }, + _react2.default.createElement( + 'div', + null, + thing || entry ? _react2.default.createElement( + 'h4', + { style: { float: 'left' } }, + 'Actions' + ) : _react2.default.createElement( + 'div', + null, + ' ', + this.props.data.length > 0 ? _react2.default.createElement( + 'h4', + { style: { float: 'left' } }, + 'Select a Marked Object' + ) : null, + ' ' + ), + _react2.default.createElement( + _reactBootstrap.ButtonGroup, + { style: { float: 'right' } }, + entry && !thing && this.props.type != 'alertgroup' ? _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.MoveEntry }, + 'Move to ', + this.props.type, + ' ', + this.props.id + ) : null, + entry && !thing && this.props.type != 'alertgroup' ? _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.CopyEntry }, + 'Copy to ', + this.props.type, + ' ', + this.props.id + ) : null, + thing || entry ? _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.ExpandLinkToggle }, + 'Link to ', + this.props.type, + ' ', + this.props.id + ) : null, + thing || entry ? _react2.default.createElement( + _reactBootstrap.Button, + { bsStyle: 'danger', onClick: this.RemoveSelected }, + 'Unmark' + ) : null + ) + ), + this.state.linkPanel && (thing || entry) ? _react2.default.createElement( + _reactBootstrap.Panel, + { collapsible: true, expanded: this.state.linkPanel }, + _react2.default.createElement( + _reactBootstrap.Form, + { horizontal: true }, + _react2.default.createElement( + _reactBootstrap.Col, + { sm: 2 }, + 'Provide context to this link:' + ), + _react2.default.createElement( + _reactBootstrap.Col, + { sm: 9 }, + _react2.default.createElement(_reactBootstrap.FormControl, { + type: 'text', + value: this.state.linkContextString, + placeholder: 'optional', + onChange: this.LinkContextChange + }) + ), + _react2.default.createElement( + _reactBootstrap.Col, + { sm: 1 }, + _react2.default.createElement( + _reactBootstrap.Button, + { onClick: this.Link, bsStyle: 'success' }, + 'Submit' + ) + ) + ) + ) : null + ) + ); + } + }, { + key: 'LinkContextChange', + value: function LinkContextChange(e) { + this.setState({ linkContextString: e.target.value }); + } + }, { + key: 'ExpandLinkToggle', + value: function ExpandLinkToggle(newState) { + if (newState == true || newState == false) { + this.setState({ linkPanel: newState, linkContextString: '' }); + } else { + var linkPanel = !this.state.linkPanel; + this.setState({ linkPanel: linkPanel, linkContextString: '' }); + } + } + }, { + key: 'RemoveSelected', + value: function RemoveSelected() { + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = this.props.data[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var key = _step7.value; + + if (key.selected) { + (0, _marker.removeMarkedItems)(key.type, key.id); + } + } + + //update marked items after removal + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + this.props.getMarkedItems(); + + //turn off the action success buttons after removal + if (this.state.actionSuccess) { + this.setState({ actionSuccess: false }); + } + } + }, { + key: 'MoveEntry', + value: function MoveEntry() { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = this.props.data[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var key = _step8.value; + + if (key.selected && key.type == 'entry') { + this.EntryAjax(key.id, true); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + }, { + key: 'CopyEntry', + value: function CopyEntry() { + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = this.props.data[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var key = _step9.value; + + if (key.selected && key.type == 'entry') { + this.EntryAjax(key.id, false); + } + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } + }, { + key: 'Link', + value: function Link() { + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + + for (var _iterator10 = this.props.data[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var key = _step10.value; + + if (key.selected) { + + var arrayToLink = []; + var obj = {}; + var currentobj = {}; + + //assign new thing to link + obj.id = parseInt(key.id); + obj.type = key.type; + + //assign current thing to link to + currentobj.id = parseInt(this.props.id); + currentobj.type = this.props.type; + + arrayToLink.push(obj); + arrayToLink.push(currentobj); + + this.LinkAjax(arrayToLink); + } + + /* + if ( arrayToLink.length > 0 ) { + //add current thing to be linked to + let obj = {}; + obj.id = parseInt( this.props.id ); + obj.type = this.props.type; + arrayToLink.push( obj ); + this.LinkAjax( arrayToLink ); + }*/ + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + }, { + key: 'LinkAjax', + value: function LinkAjax(arrayToLink) { + var data = {}; + data.weight = 1; //passed in object + data.vertices = arrayToLink; //link to current thing + + if (this.state.linkContextString) { + //add context string if one was submitted + data.context = this.state.linkContextString; + } + + $.ajax({ + type: 'post', + url: '/scot/api/v2/link', + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + console.log('successfully linked'); + this.ExpandLinkToggle(false); //disable link panel + this.ToggleActionSuccess(true); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to link', data); + }.bind(this) + }); + } + }, { + key: 'EntryAjax', + value: function EntryAjax(id, removeOriginal) { + + $.ajax({ + type: 'get', + url: '/scot/api/v2/entry/' + id, + success: function (response) { + var data = {}; + data = { parent: 0, body: response.body, target_id: parseInt(this.props.id), target_type: this.props.type }; + $.ajax({ + type: 'post', + url: '/scot/api/v2/entry', + data: JSON.stringify(data), + contentType: 'application/json; charset=UTF-8', + dataType: 'json', + success: function (response) { + + if (removeOriginal) { + this.RemoveEntryAfterMove(id); + this.RemoveSelected(); + } else { + if (!this.state.actionSuccess) { + this.ToggleActionSuccess(true); + } + } + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to create new entry', data); + }.bind(this) + }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get entry data', data); + }.bind(this) + }); + } + }, { + key: 'RemoveEntryAfterMove', + value: function RemoveEntryAfterMove(id) { + $.ajax({ + type: 'delete', + url: '/scot/api/v2/entry/' + id, + success: function (response) { + console.log('removed original entry'); + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to remove original entry', data); + }.bind(this) + }); + } + }, { + key: 'ToggleActionSuccess', + value: function ToggleActionSuccess(status) { + + if (status == true || status == false) { + this.setState({ actionSuccess: status }); + } else { + var newActionSuccess = !this.state.actionSuccess; + this.setState({ actionSuccess: newActionSuccess }); + } + } + }]); + + return Actions; +}(_react.Component); + +Actions.propTypes = { + data: _propTypes2.default.object +}; + +Actions.defaultProps = { + data: {} +}; + +Mark.propTypes = { + modalActive: _propTypes2.default.bool +}; + +Mark.defaultProps = { + modalActive: true +}; + +exports.default = Mark; + +},{"../components/marker":23,"prop-types":512,"react":983,"react-bootstrap":608,"react-table":891}],83:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var DropdownButton = require('react-bootstrap/lib/DropdownButton'); +var MenuItem = require('react-bootstrap/lib/MenuItem'); + +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var Owner = React.createClass({ + displayName: 'Owner', + + getInitialState: function getInitialState() { + return { + currentOwner: this.props.data, + whoami: undefined, + ownerToolbar: false, + key: this.props.id + }; + }, + componentDidMount: function componentDidMount() { + var whoami = getSessionStorage('whoami'); + if (whoami) { + this.setState({ whoami: whoami }); + } + }, + componentWillReceiveProps: function componentWillReceiveProps() { + this.setState({ currentOwner: this.props.data }); + }, + toggle: function toggle() { + if (this.state.whoami != undefined) { + var json = { 'owner': this.state.whoami }; + $.ajax({ + type: 'put', + url: 'scot/api/v2/' + this.props.type + '/' + this.props.id, + data: JSON.stringify(json), + contentType: 'application/json; charset=UTF-8', + success: function (data) { + var key = this.state.key; + }.bind(this), + error: function (data) { + this.props.errorToggle('Failed to change owner', data); + }.bind(this) + }); + } else { + this.props.errorToggle('Failed to detect current user'); + } + this.ownerToggle(); + }, + ownerToggle: function ownerToggle() { + if (this.state.ownerToolbar == false) { + this.setState({ ownerToolbar: true }); + } else { + this.setState({ ownerToolbar: false }); + } + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + DropdownButton, + { bsSize: 'xsmall', id: 'event_owner', title: this.state.currentOwner }, + React.createElement( + MenuItem, + { eventKey: '1', onClick: this.ownerToggle }, + 'Take Ownership' + ) + ), + this.state.ownerToolbar ? React.createElement( + Modal, + { isOpen: true, onRequestClose: this.ownerToggle, style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: 'images/close_toolbar.png', className: 'close_toolbar', onClick: this.ownerToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + 'Take Ownership' + ) + ), + React.createElement( + 'div', + { className: 'modal-body' }, + 'Are you sure you want to take ownership of this event?' + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { id: 'cancel-ownership', onClick: this.ownerToggle }, + 'Cancel' + ), + React.createElement( + Button, + { bsStyle: 'info', id: 'take-ownership', onClick: this.toggle }, + 'Take Ownership' + ) + ) + ) : null + ); + } +}); + +module.exports = Owner; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-bootstrap/lib/DropdownButton":539,"react-bootstrap/lib/MenuItem":566,"react-modal":839}],84:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactBootstrap = require('react-bootstrap'); + +var _reactModal = require('react-modal'); + +var _reactModal2 = _interopRequireDefault(_reactModal); + +var _reactRouterDom = require('react-router-dom'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var PromotedData = function (_Component) { + _inherits(PromotedData, _Component); + + function PromotedData(props) { + _classCallCheck(this, PromotedData); + + var _this = _possibleConstructorReturn(this, (PromotedData.__proto__ || Object.getPrototypeOf(PromotedData)).call(this, props)); + + _this.state = { + showAllPromotedDataToolbar: false + }; + + _this.showAllPromotedDataToggle = _this.showAllPromotedDataToggle.bind(_this); + return _this; + } + + _createClass(PromotedData, [{ + key: 'showAllPromotedDataToggle', + value: function showAllPromotedDataToggle() { + if (this.state.showAllPromotedDataToolbar == false) { + this.setState({ showAllPromotedDataToolbar: true }); + } else { + this.setState({ showAllPromotedDataToolbar: false }); + } + } + }, { + key: 'render', + value: function render() { + var promotedFromType = null; + var fullarr = []; + var shortarr = []; + var shortforlength = 3; + if (this.props.type == 'event') { + promotedFromType = 'alert'; + } else if (this.props.type == 'incident') { + promotedFromType = 'event'; + } + //makes large array for modal + for (var i = 0; i < this.props.data.length; i++) { + if (i > 0) { + fullarr.push(_react2.default.createElement( + 'span', + null, + ' , ' + )); + } + var link = '/' + promotedFromType + '/' + this.props.data[i]; + fullarr.push(_react2.default.createElement( + 'span', + { key: this.props.data[i] }, + _react2.default.createElement( + _reactRouterDom.Link, + { to: link }, + this.props.data[i] + ) + )); + } + //makes small array for quick display in header + if (this.props.data.length < 3) { + shortforlength = this.props.data.length; + } + for (var _i = 0; _i < shortforlength; _i++) { + if (_i > 0) { + shortarr.push(_react2.default.createElement( + 'div', + null, + ' , ' + )); + } + var _link = '/' + promotedFromType + '/' + this.props.data[_i]; + shortarr.push(_react2.default.createElement( + 'div', + { key: this.props.data[_i] }, + _react2.default.createElement( + _reactRouterDom.Link, + { to: _link }, + this.props.data[_i] + ) + )); + } + if (this.props.data.length > 3) { + shortarr.push(_react2.default.createElement( + 'div', + { onClick: this.showAllPromotedDataToggle }, + ',', + _react2.default.createElement( + 'a', + { href: 'javascript:;' }, + '...more' + ) + )); + } + return _react2.default.createElement( + 'td', + null, + _react2.default.createElement( + 'span', + { id: 'promoted_from', style: { display: 'flex' } }, + shortarr + ), + this.state.showAllPromotedDataToolbar ? _react2.default.createElement( + _reactModal2.default, + { isOpen: true, onRequestClose: this.showAllPromotedDataToggle, style: customStyles }, + _react2.default.createElement( + 'div', + { className: 'modal-header' }, + _react2.default.createElement('img', { src: 'images/close_toolbar.png', className: 'close_toolbar', onClick: this.showAllPromotedDataToggle }), + _react2.default.createElement( + 'h3', + { id: 'myModalLabel' }, + 'Promoted From' + ) + ), + _react2.default.createElement( + 'div', + { className: 'modal-body promoted-from-full' }, + fullarr + ), + _react2.default.createElement( + 'div', + { className: 'modal-footer' }, + _react2.default.createElement( + _reactBootstrap.Button, + { id: 'cancel-modal', onClick: this.showAllPromotedDataToggle }, + 'Close' + ) + ) + ) : null + ); + } + }]); + + return PromotedData; +}(_react.Component); + +; + +exports.default = PromotedData; + +},{"prop-types":512,"react":983,"react-bootstrap":608,"react-modal":839,"react-router-dom":878}],85:[function(require,module,exports){ +'use strict'; + +var React = require('react'); +var ReactTime = require('react-time').default; +var Modal = require('react-modal'); +var Button = require('react-bootstrap/lib/Button'); +var type; +var customStyles = { + content: { + top: '50%', + left: '50%', + right: 'auto', + bottom: 'auto', + marginRight: '-50%', + transform: 'translate(-50%, -50%)' + } +}; + +var ViewedByHistory = React.createClass({ + displayName: 'ViewedByHistory', + + getInitialState: function getInitialState() { + return { + historyBody: false, + data: '' + }; + }, + componentDidMount: function componentDidMount() { + $.ajax({ + type: 'get', + url: '/scot/api/v2/' + this.props.type + '/' + this.props.id, + success: function (result) { + this.setState({ historyBody: true, data: result }); + }.bind(this), + error: function (data) { + this.props.errorToggle('failed to get user change history', data); + }.bind(this) + }); + }, + render: function render() { + return React.createElement( + 'div', + null, + React.createElement( + Modal, + { + isOpen: true, + onRequestClose: this.props.viewedByHistoryToggle, + style: customStyles }, + React.createElement( + 'div', + { className: 'modal-header' }, + React.createElement('img', { src: '/images/close_toolbar.png', className: 'close_toolbar', onClick: this.props.viewedByHistoryToggle }), + React.createElement( + 'h3', + { id: 'myModalLabel' }, + this.props.subjectType, + ' Viewed By' + ) + ), + React.createElement( + 'div', + { className: 'modal-body', style: { maxHeight: '30vh', overflowY: 'auto' } }, + this.state.historyBody ? React.createElement(ViewedByHistoryData, { data: this.state.data }) : null + ), + React.createElement( + 'div', + { className: 'modal-footer' }, + React.createElement( + Button, + { onClick: this.props.viewedByHistoryToggle }, + 'Done' + ) + ) + ) + ); + } +}); + +var ViewedByHistoryData = React.createClass({ + displayName: 'ViewedByHistoryData', + + render: function render() { + var rows = []; + var data = this.props.data; + for (var prop in data.view_history) { + rows.push(React.createElement(ViewedByHistoryDataIterator, { data: data.view_history[prop], prop: prop })); + } + return React.createElement( + 'div', + null, + rows + ); + } +}); + +var ViewedByHistoryDataIterator = React.createClass({ + displayName: 'ViewedByHistoryDataIterator', + + render: function render() { + var data = this.props.data; + var prop = this.props.prop; + return React.createElement( + 'div', + null, + React.createElement( + 'b', + null, + prop + ), + ' at ', + React.createElement(ReactTime, { value: data.when * 1000, format: 'MM/DD/YYYY hh:mm:ss a' }), + ' from IP: ', + data.where + ); + } +}); + +module.exports = ViewedByHistory; + +},{"react":983,"react-bootstrap/lib/Button":527,"react-modal":839,"react-time":905}],86:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +/*****************************************************/ +/*************** Table Options *****************/ +/***************************************************/ +var INCIDENT_TYPES = exports.INCIDENT_TYPES = ['Type 1 : Root Compromise', 'Type 1 : User Compromise', 'Type 1 : Loss/Theft/Missing Desktop', 'Type 1 : Loss/Theft/Missing Laptop', 'Type 1 : Loss/Theft/Missing Media', 'Type 1 : Loss/Theft/Missing Other', 'Type 1 : Malicious Code Trojan', 'Type 1 : Malicious Code Virus', 'Type 1 : Malicious Code Worm', 'Type 1 : Malicious Code Other', 'Type 1 : Web Site Defacement', 'Type 1 : Denial of Service', 'Type 1 : Critical Infrastructure Protection', 'Type 1 : Unauthorized Use', 'Type 1 : Information Compromise', 'Type 2 : Attempted Intrusion', 'Type 2 : Reconnaissance Activity']; + +},{}],87:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = debounce; +function debounce(callback) { + var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; + var immediate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + var timeout = void 0; + + return function () { + var _this = this; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + clearTimeout(timeout); + + timeout = setTimeout(function () { + timeout = null; + if (!immediate) callback.apply(_this, args); + }, wait); + + if (immediate && !timeout) callback.apply(this, [].concat(args)); + }; +} + +},{}],88:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.momentRangeToEpoch = exports.epochRangeToMoment = exports.epochRangeToString = exports.isExpired = exports.timeOlderThan = undefined; + +var _moment = require('moment'); + +var _moment2 = _interopRequireDefault(_moment); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +require('moment-range'); + +/** + * Calculate if a timestamp is older than a number of seconds + * + * timestamp: Date() object to test against + * secondsAgo: Number of seconds to test against + */ +var timeOlderThan = exports.timeOlderThan = function timeOlderThan(timestamp, secondsAgo) { + if (!timestamp) { + return true; + } + + return Date.now() - timestamp > secondsAgo * 1000; +}; + +/** + * Calculate if a timestamp is in the past and therefore data is expired + * + * expires: time data expires + */ +var isExpired = exports.isExpired = function isExpired(expires) { + return !expires || Date.now() >= expires; +}; + +/** + * Conversion Functions for DateRangeFilter + * + * epochRangeToString: stringify an epoch range + * epochRangeToMoment: convert epoch range into MomentRange object + * momentRangeToEpoch: convert MomentRange object to epoch range + * + * epoch range: { start: _epoch_, end: _epoch_ } + */ +var epochRangeToString = exports.epochRangeToString = function epochRangeToString(range) { + return range.start + ', ' + range.end; +}; + +var epochRangeToMoment = exports.epochRangeToMoment = function epochRangeToMoment(range) { + return _moment2.default.range(range.start * 1000, range.end * 1000); +}; + +var momentRangeToEpoch = exports.momentRangeToEpoch = function momentRangeToEpoch(range) { + return { + start: Math.round(range.start) / 1000, + end: Math.round(range.end) / 1000 + }; +}; + +},{"moment":503,"moment-range":502}],89:[function(require,module,exports){ +"use strict"; + +// rawAsap provides everything we need except exception management. +var rawAsap = require("./raw"); +// RawTasks are recycled to reduce GC churn. +var freeTasks = []; +// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors = []; +var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); + +function throwFirstError() { + if (pendingErrors.length) { + throw pendingErrors.shift(); + } +} + +/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawAsap(rawTask); +} + +// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask() { + this.task = null; +} + +// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call = function () { + try { + this.task.call(); + } catch (error) { + if (asap.onerror) { + // This hook exists purely for testing purposes. + // Its name will be periodically randomized to break any code that + // depends on its existence. + asap.onerror(error); + } else { + // In a web browser, exceptions are not fatal. However, to avoid + // slowing down the queue of pending tasks, we rethrow the error in a + // lower priority turn. + pendingErrors.push(error); + requestErrorThrow(); + } + } finally { + this.task = null; + freeTasks[freeTasks.length] = this; + } +}; + +},{"./raw":90}],90:[function(require,module,exports){ +(function (global){ +"use strict"; + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + // Equivalent to push, but avoids a function call. + queue[queue.length] = task; +} + +var queue = []; +// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing = false; +// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +// `requestFlush` is implemented using a strategy based on data collected from +// every available SauceLabs Selenium web driver worker at time of writing. +// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 + +// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that +// have WebKitMutationObserver but not un-prefixed MutationObserver. +// Must use `global` or `self` instead of `window` to work in both frames and web +// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. + +/* globals self */ +var scope = typeof global !== "undefined" ? global : self; +var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; + +// MutationObservers are desirable because they have high priority and work +// reliably everywhere they are implemented. +// They are implemented in all modern browsers. +// +// - Android 4-4.3 +// - Chrome 26-34 +// - Firefox 14-29 +// - Internet Explorer 11 +// - iPad Safari 6-7.1 +// - iPhone Safari 7-7.1 +// - Safari 6-7 +if (typeof BrowserMutationObserver === "function") { + requestFlush = makeRequestCallFromMutationObserver(flush); + +// MessageChannels are desirable because they give direct access to the HTML +// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera +// 11-12, and in web workers in many engines. +// Although message channels yield to any queued rendering and IO tasks, they +// would be better than imposing the 4ms delay of timers. +// However, they do not work reliably in Internet Explorer or Safari. + +// Internet Explorer 10 is the only browser that has setImmediate but does +// not have MutationObservers. +// Although setImmediate yields to the browser's renderer, it would be +// preferrable to falling back to setTimeout since it does not have +// the minimum 4ms penalty. +// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and +// Desktop to a lesser extent) that renders both setImmediate and +// MessageChannel useless for the purposes of ASAP. +// https://github.com/kriskowal/q/issues/396 + +// Timers are implemented universally. +// We fall back to timers in workers in most engines, and in foreground +// contexts in the following browsers. +// However, note that even this simple case requires nuances to operate in a +// broad spectrum of browsers. +// +// - Firefox 3-13 +// - Internet Explorer 6-9 +// - iPad Safari 4.3 +// - Lynx 2.8.7 +} else { + requestFlush = makeRequestCallFromTimer(flush); +} + +// `requestFlush` requests that the high priority event queue be flushed as +// soon as possible. +// This is useful to prevent an error thrown in a task from stalling the event +// queue if the exception handled by Node.js’s +// `process.on("uncaughtException")` or by a domain. +rawAsap.requestFlush = requestFlush; + +// To request a high priority event, we induce a mutation observer by toggling +// the text of a text node between "1" and "-1". +function makeRequestCallFromMutationObserver(callback) { + var toggle = 1; + var observer = new BrowserMutationObserver(callback); + var node = document.createTextNode(""); + observer.observe(node, {characterData: true}); + return function requestCall() { + toggle = -toggle; + node.data = toggle; + }; +} + +// The message channel technique was discovered by Malte Ubl and was the +// original foundation for this library. +// http://www.nonblocking.io/2011/06/windownexttick.html + +// Safari 6.0.5 (at least) intermittently fails to create message ports on a +// page's first load. Thankfully, this version of Safari supports +// MutationObservers, so we don't need to fall back in that case. + +// function makeRequestCallFromMessageChannel(callback) { +// var channel = new MessageChannel(); +// channel.port1.onmessage = callback; +// return function requestCall() { +// channel.port2.postMessage(0); +// }; +// } + +// For reasons explained above, we are also unable to use `setImmediate` +// under any circumstances. +// Even if we were, there is another bug in Internet Explorer 10. +// It is not sufficient to assign `setImmediate` to `requestFlush` because +// `setImmediate` must be called *by name* and therefore must be wrapped in a +// closure. +// Never forget. + +// function makeRequestCallFromSetImmediate(callback) { +// return function requestCall() { +// setImmediate(callback); +// }; +// } + +// Safari 6.0 has a problem where timers will get lost while the user is +// scrolling. This problem does not impact ASAP because Safari 6.0 supports +// mutation observers, so that implementation is used instead. +// However, if we ever elect to use timers in Safari, the prevalent work-around +// is to add a scroll event listener that calls for a flush. + +// `setTimeout` does not call the passed callback if the delay is less than +// approximately 7 in web workers in Firefox 8 through 18, and sometimes not +// even then. + +function makeRequestCallFromTimer(callback) { + return function requestCall() { + // We dispatch a timeout with a specified delay of 0 for engines that + // can reliably accommodate that request. This will usually be snapped + // to a 4 milisecond delay, but once we're flushing, there's no delay + // between events. + var timeoutHandle = setTimeout(handleTimer, 0); + // However, since this timer gets frequently dropped in Firefox + // workers, we enlist an interval handle that will try to fire + // an event 20 times per second until it succeeds. + var intervalHandle = setInterval(handleTimer, 50); + + function handleTimer() { + // Whichever timer succeeds will cancel both timers and + // execute the callback. + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + callback(); + } + }; +} + +// This is for `asap.js` only. +// Its name will be periodically randomized to break any code that depends on +// its existence. +rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; + +// ASAP was originally a nextTick shim included in Q. This was factored out +// into this ASAP package. It was later adapted to RSVP which made further +// amendments. These decisions, particularly to marginalize MessageChannel and +// to capture the MutationObserver implementation in a closure, were integrated +// back into ASAP proper. +// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],91:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/array/from"), __esModule: true }; +},{"core-js/library/fn/array/from":112}],92:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; +},{"core-js/library/fn/get-iterator":113}],93:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/is-iterable"), __esModule: true }; +},{"core-js/library/fn/is-iterable":114}],94:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; +},{"core-js/library/fn/object/assign":115}],95:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; +},{"core-js/library/fn/object/create":116}],96:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true }; +},{"core-js/library/fn/object/define-property":117}],97:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/entries"), __esModule: true }; +},{"core-js/library/fn/object/entries":118}],98:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; +},{"core-js/library/fn/object/set-prototype-of":119}],99:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/values"), __esModule: true }; +},{"core-js/library/fn/object/values":120}],100:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; +},{"core-js/library/fn/symbol":121}],101:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; +},{"core-js/library/fn/symbol/iterator":122}],102:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +},{}],103:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _defineProperty = require("../core-js/object/define-property"); + +var _defineProperty2 = _interopRequireDefault(_defineProperty); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + (0, _defineProperty2.default)(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +}(); +},{"../core-js/object/define-property":96}],104:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _defineProperty = require("../core-js/object/define-property"); + +var _defineProperty2 = _interopRequireDefault(_defineProperty); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (obj, key, value) { + if (key in obj) { + (0, _defineProperty2.default)(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +}; +},{"../core-js/object/define-property":96}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _assign = require("../core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = _assign2.default || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; +}; +},{"../core-js/object/assign":94}],106:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _setPrototypeOf = require("../core-js/object/set-prototype-of"); + +var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); + +var _create = require("../core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _typeof2 = require("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +},{"../core-js/object/create":95,"../core-js/object/set-prototype-of":98,"../helpers/typeof":111}],107:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (obj, keys) { + var target = {}; + + for (var i in obj) { + if (keys.indexOf(i) >= 0) continue; + if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; + target[i] = obj[i]; + } + + return target; +}; +},{}],108:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +},{"../helpers/typeof":111}],109:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _isIterable2 = require("../core-js/is-iterable"); + +var _isIterable3 = _interopRequireDefault(_isIterable2); + +var _getIterator2 = require("../core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if ((0, _isIterable3.default)(Object(arr))) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); +},{"../core-js/get-iterator":92,"../core-js/is-iterable":93}],110:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _from = require("../core-js/array/from"); + +var _from2 = _interopRequireDefault(_from); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } else { + return (0, _from2.default)(arr); + } +}; +},{"../core-js/array/from":91}],111:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _iterator = require("../core-js/symbol/iterator"); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _symbol = require("../core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +},{"../core-js/symbol":100,"../core-js/symbol/iterator":101}],112:[function(require,module,exports){ +require('../../modules/es6.string.iterator'); +require('../../modules/es6.array.from'); +module.exports = require('../../modules/_core').Array.from; + +},{"../../modules/_core":129,"../../modules/es6.array.from":189,"../../modules/es6.string.iterator":196}],113:[function(require,module,exports){ +require('../modules/web.dom.iterable'); +require('../modules/es6.string.iterator'); +module.exports = require('../modules/core.get-iterator'); + +},{"../modules/core.get-iterator":187,"../modules/es6.string.iterator":196,"../modules/web.dom.iterable":202}],114:[function(require,module,exports){ +require('../modules/web.dom.iterable'); +require('../modules/es6.string.iterator'); +module.exports = require('../modules/core.is-iterable'); + +},{"../modules/core.is-iterable":188,"../modules/es6.string.iterator":196,"../modules/web.dom.iterable":202}],115:[function(require,module,exports){ +require('../../modules/es6.object.assign'); +module.exports = require('../../modules/_core').Object.assign; + +},{"../../modules/_core":129,"../../modules/es6.object.assign":191}],116:[function(require,module,exports){ +require('../../modules/es6.object.create'); +var $Object = require('../../modules/_core').Object; +module.exports = function create(P, D) { + return $Object.create(P, D); +}; + +},{"../../modules/_core":129,"../../modules/es6.object.create":192}],117:[function(require,module,exports){ +require('../../modules/es6.object.define-property'); +var $Object = require('../../modules/_core').Object; +module.exports = function defineProperty(it, key, desc) { + return $Object.defineProperty(it, key, desc); +}; + +},{"../../modules/_core":129,"../../modules/es6.object.define-property":193}],118:[function(require,module,exports){ +require('../../modules/es7.object.entries'); +module.exports = require('../../modules/_core').Object.entries; + +},{"../../modules/_core":129,"../../modules/es7.object.entries":198}],119:[function(require,module,exports){ +require('../../modules/es6.object.set-prototype-of'); +module.exports = require('../../modules/_core').Object.setPrototypeOf; + +},{"../../modules/_core":129,"../../modules/es6.object.set-prototype-of":194}],120:[function(require,module,exports){ +require('../../modules/es7.object.values'); +module.exports = require('../../modules/_core').Object.values; + +},{"../../modules/_core":129,"../../modules/es7.object.values":199}],121:[function(require,module,exports){ +require('../../modules/es6.symbol'); +require('../../modules/es6.object.to-string'); +require('../../modules/es7.symbol.async-iterator'); +require('../../modules/es7.symbol.observable'); +module.exports = require('../../modules/_core').Symbol; + +},{"../../modules/_core":129,"../../modules/es6.object.to-string":195,"../../modules/es6.symbol":197,"../../modules/es7.symbol.async-iterator":200,"../../modules/es7.symbol.observable":201}],122:[function(require,module,exports){ +require('../../modules/es6.string.iterator'); +require('../../modules/web.dom.iterable'); +module.exports = require('../../modules/_wks-ext').f('iterator'); + +},{"../../modules/_wks-ext":184,"../../modules/es6.string.iterator":196,"../../modules/web.dom.iterable":202}],123:[function(require,module,exports){ +module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; +}; + +},{}],124:[function(require,module,exports){ +module.exports = function () { /* empty */ }; + +},{}],125:[function(require,module,exports){ +var isObject = require('./_is-object'); +module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; + +},{"./_is-object":147}],126:[function(require,module,exports){ +// false -> Array#indexOf +// true -> Array#includes +var toIObject = require('./_to-iobject'); +var toLength = require('./_to-length'); +var toAbsoluteIndex = require('./_to-absolute-index'); +module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +},{"./_to-absolute-index":176,"./_to-iobject":178,"./_to-length":179}],127:[function(require,module,exports){ +// getting tag from 19.1.3.6 Object.prototype.toString() +var cof = require('./_cof'); +var TAG = require('./_wks')('toStringTag'); +// ES3 wrong here +var ARG = cof(function () { return arguments; }()) == 'Arguments'; + +// fallback for IE11 Script Access Denied error +var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } +}; + +module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; + +},{"./_cof":128,"./_wks":185}],128:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = function (it) { + return toString.call(it).slice(8, -1); +}; + +},{}],129:[function(require,module,exports){ +var core = module.exports = { version: '2.5.3' }; +if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + +},{}],130:[function(require,module,exports){ +'use strict'; +var $defineProperty = require('./_object-dp'); +var createDesc = require('./_property-desc'); + +module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; +}; + +},{"./_object-dp":158,"./_property-desc":169}],131:[function(require,module,exports){ +// optional / simple context binding +var aFunction = require('./_a-function'); +module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +},{"./_a-function":123}],132:[function(require,module,exports){ +// 7.2.1 RequireObjectCoercible(argument) +module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +},{}],133:[function(require,module,exports){ +// Thank's IE8 for his funny defineProperty +module.exports = !require('./_fails')(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +},{"./_fails":138}],134:[function(require,module,exports){ +var isObject = require('./_is-object'); +var document = require('./_global').document; +// typeof document.createElement is 'object' in old IE +var is = isObject(document) && isObject(document.createElement); +module.exports = function (it) { + return is ? document.createElement(it) : {}; +}; + +},{"./_global":139,"./_is-object":147}],135:[function(require,module,exports){ +// IE 8- don't enum bug keys +module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); + +},{}],136:[function(require,module,exports){ +// all enumerable object keys, includes symbols +var getKeys = require('./_object-keys'); +var gOPS = require('./_object-gops'); +var pIE = require('./_object-pie'); +module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; +}; + +},{"./_object-gops":163,"./_object-keys":166,"./_object-pie":167}],137:[function(require,module,exports){ +var global = require('./_global'); +var core = require('./_core'); +var ctx = require('./_ctx'); +var hide = require('./_hide'); +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && key in exports) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); + } + } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; + +},{"./_core":129,"./_ctx":131,"./_global":139,"./_hide":141}],138:[function(require,module,exports){ +module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } +}; + +},{}],139:[function(require,module,exports){ +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); +if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + +},{}],140:[function(require,module,exports){ +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +},{}],141:[function(require,module,exports){ +var dP = require('./_object-dp'); +var createDesc = require('./_property-desc'); +module.exports = require('./_descriptors') ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +},{"./_descriptors":133,"./_object-dp":158,"./_property-desc":169}],142:[function(require,module,exports){ +var document = require('./_global').document; +module.exports = document && document.documentElement; + +},{"./_global":139}],143:[function(require,module,exports){ +module.exports = !require('./_descriptors') && !require('./_fails')(function () { + return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7; +}); + +},{"./_descriptors":133,"./_dom-create":134,"./_fails":138}],144:[function(require,module,exports){ +// fallback for non-array-like ES3 and non-enumerable old V8 strings +var cof = require('./_cof'); +// eslint-disable-next-line no-prototype-builtins +module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); +}; + +},{"./_cof":128}],145:[function(require,module,exports){ +// check on default Array iterator +var Iterators = require('./_iterators'); +var ITERATOR = require('./_wks')('iterator'); +var ArrayProto = Array.prototype; + +module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); +}; + +},{"./_iterators":153,"./_wks":185}],146:[function(require,module,exports){ +// 7.2.2 IsArray(argument) +var cof = require('./_cof'); +module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; +}; + +},{"./_cof":128}],147:[function(require,module,exports){ +module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +},{}],148:[function(require,module,exports){ +// call something on iterator step with safe closing on error +var anObject = require('./_an-object'); +module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } +}; + +},{"./_an-object":125}],149:[function(require,module,exports){ +'use strict'; +var create = require('./_object-create'); +var descriptor = require('./_property-desc'); +var setToStringTag = require('./_set-to-string-tag'); +var IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function () { return this; }); + +module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); +}; + +},{"./_hide":141,"./_object-create":157,"./_property-desc":169,"./_set-to-string-tag":172,"./_wks":185}],150:[function(require,module,exports){ +'use strict'; +var LIBRARY = require('./_library'); +var $export = require('./_export'); +var redefine = require('./_redefine'); +var hide = require('./_hide'); +var has = require('./_has'); +var Iterators = require('./_iterators'); +var $iterCreate = require('./_iter-create'); +var setToStringTag = require('./_set-to-string-tag'); +var getPrototypeOf = require('./_object-gpo'); +var ITERATOR = require('./_wks')('iterator'); +var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` +var FF_ITERATOR = '@@iterator'; +var KEYS = 'keys'; +var VALUES = 'values'; + +var returnThis = function () { return this; }; + +module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = (!BUGGY && $native) || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; +}; + +},{"./_export":137,"./_has":140,"./_hide":141,"./_iter-create":149,"./_iterators":153,"./_library":154,"./_object-gpo":164,"./_redefine":170,"./_set-to-string-tag":172,"./_wks":185}],151:[function(require,module,exports){ +var ITERATOR = require('./_wks')('iterator'); +var SAFE_CLOSING = false; + +try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); +} catch (e) { /* empty */ } + +module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; +}; + +},{"./_wks":185}],152:[function(require,module,exports){ +module.exports = function (done, value) { + return { value: value, done: !!done }; +}; + +},{}],153:[function(require,module,exports){ +module.exports = {}; + +},{}],154:[function(require,module,exports){ +module.exports = true; + +},{}],155:[function(require,module,exports){ +var META = require('./_uid')('meta'); +var isObject = require('./_is-object'); +var has = require('./_has'); +var setDesc = require('./_object-dp').f; +var id = 0; +var isExtensible = Object.isExtensible || function () { + return true; +}; +var FREEZE = !require('./_fails')(function () { + return isExtensible(Object.preventExtensions({})); +}); +var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); +}; +var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; +}; +var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; +}; +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; +}; +var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze +}; + +},{"./_fails":138,"./_has":140,"./_is-object":147,"./_object-dp":158,"./_uid":182}],156:[function(require,module,exports){ +'use strict'; +// 19.1.2.1 Object.assign(target, source, ...) +var getKeys = require('./_object-keys'); +var gOPS = require('./_object-gops'); +var pIE = require('./_object-pie'); +var toObject = require('./_to-object'); +var IObject = require('./_iobject'); +var $assign = Object.assign; + +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = !$assign || require('./_fails')(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; +} : $assign; + +},{"./_fails":138,"./_iobject":144,"./_object-gops":163,"./_object-keys":166,"./_object-pie":167,"./_to-object":180}],157:[function(require,module,exports){ +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +var anObject = require('./_an-object'); +var dPs = require('./_object-dps'); +var enumBugKeys = require('./_enum-bug-keys'); +var IE_PROTO = require('./_shared-key')('IE_PROTO'); +var Empty = function () { /* empty */ }; +var PROTOTYPE = 'prototype'; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = require('./_dom-create')('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + require('./_html').appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); +}; + +module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); +}; + +},{"./_an-object":125,"./_dom-create":134,"./_enum-bug-keys":135,"./_html":142,"./_object-dps":159,"./_shared-key":173}],158:[function(require,module,exports){ +var anObject = require('./_an-object'); +var IE8_DOM_DEFINE = require('./_ie8-dom-define'); +var toPrimitive = require('./_to-primitive'); +var dP = Object.defineProperty; + +exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +},{"./_an-object":125,"./_descriptors":133,"./_ie8-dom-define":143,"./_to-primitive":181}],159:[function(require,module,exports){ +var dP = require('./_object-dp'); +var anObject = require('./_an-object'); +var getKeys = require('./_object-keys'); + +module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; +}; + +},{"./_an-object":125,"./_descriptors":133,"./_object-dp":158,"./_object-keys":166}],160:[function(require,module,exports){ +var pIE = require('./_object-pie'); +var createDesc = require('./_property-desc'); +var toIObject = require('./_to-iobject'); +var toPrimitive = require('./_to-primitive'); +var has = require('./_has'); +var IE8_DOM_DEFINE = require('./_ie8-dom-define'); +var gOPD = Object.getOwnPropertyDescriptor; + +exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); +}; + +},{"./_descriptors":133,"./_has":140,"./_ie8-dom-define":143,"./_object-pie":167,"./_property-desc":169,"./_to-iobject":178,"./_to-primitive":181}],161:[function(require,module,exports){ +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +var toIObject = require('./_to-iobject'); +var gOPN = require('./_object-gopn').f; +var toString = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } +}; + +module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); +}; + +},{"./_object-gopn":162,"./_to-iobject":178}],162:[function(require,module,exports){ +// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) +var $keys = require('./_object-keys-internal'); +var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype'); + +exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); +}; + +},{"./_enum-bug-keys":135,"./_object-keys-internal":165}],163:[function(require,module,exports){ +exports.f = Object.getOwnPropertySymbols; + +},{}],164:[function(require,module,exports){ +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) +var has = require('./_has'); +var toObject = require('./_to-object'); +var IE_PROTO = require('./_shared-key')('IE_PROTO'); +var ObjectProto = Object.prototype; + +module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; +}; + +},{"./_has":140,"./_shared-key":173,"./_to-object":180}],165:[function(require,module,exports){ +var has = require('./_has'); +var toIObject = require('./_to-iobject'); +var arrayIndexOf = require('./_array-includes')(false); +var IE_PROTO = require('./_shared-key')('IE_PROTO'); + +module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; +}; + +},{"./_array-includes":126,"./_has":140,"./_shared-key":173,"./_to-iobject":178}],166:[function(require,module,exports){ +// 19.1.2.14 / 15.2.3.14 Object.keys(O) +var $keys = require('./_object-keys-internal'); +var enumBugKeys = require('./_enum-bug-keys'); + +module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); +}; + +},{"./_enum-bug-keys":135,"./_object-keys-internal":165}],167:[function(require,module,exports){ +exports.f = {}.propertyIsEnumerable; + +},{}],168:[function(require,module,exports){ +var getKeys = require('./_object-keys'); +var toIObject = require('./_to-iobject'); +var isEnum = require('./_object-pie').f; +module.exports = function (isEntries) { + return function (it) { + var O = toIObject(it); + var keys = getKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; +}; + +},{"./_object-keys":166,"./_object-pie":167,"./_to-iobject":178}],169:[function(require,module,exports){ +module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +},{}],170:[function(require,module,exports){ +module.exports = require('./_hide'); + +},{"./_hide":141}],171:[function(require,module,exports){ +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ +var isObject = require('./_is-object'); +var anObject = require('./_an-object'); +var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); +}; +module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check +}; + +},{"./_an-object":125,"./_ctx":131,"./_is-object":147,"./_object-gopd":160}],172:[function(require,module,exports){ +var def = require('./_object-dp').f; +var has = require('./_has'); +var TAG = require('./_wks')('toStringTag'); + +module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); +}; + +},{"./_has":140,"./_object-dp":158,"./_wks":185}],173:[function(require,module,exports){ +var shared = require('./_shared')('keys'); +var uid = require('./_uid'); +module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); +}; + +},{"./_shared":174,"./_uid":182}],174:[function(require,module,exports){ +var global = require('./_global'); +var SHARED = '__core-js_shared__'; +var store = global[SHARED] || (global[SHARED] = {}); +module.exports = function (key) { + return store[key] || (store[key] = {}); +}; + +},{"./_global":139}],175:[function(require,module,exports){ +var toInteger = require('./_to-integer'); +var defined = require('./_defined'); +// true -> String#at +// false -> String#codePointAt +module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; + +},{"./_defined":132,"./_to-integer":177}],176:[function(require,module,exports){ +var toInteger = require('./_to-integer'); +var max = Math.max; +var min = Math.min; +module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); +}; + +},{"./_to-integer":177}],177:[function(require,module,exports){ +// 7.1.4 ToInteger +var ceil = Math.ceil; +var floor = Math.floor; +module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; + +},{}],178:[function(require,module,exports){ +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = require('./_iobject'); +var defined = require('./_defined'); +module.exports = function (it) { + return IObject(defined(it)); +}; + +},{"./_defined":132,"./_iobject":144}],179:[function(require,module,exports){ +// 7.1.15 ToLength +var toInteger = require('./_to-integer'); +var min = Math.min; +module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; + +},{"./_to-integer":177}],180:[function(require,module,exports){ +// 7.1.13 ToObject(argument) +var defined = require('./_defined'); +module.exports = function (it) { + return Object(defined(it)); +}; + +},{"./_defined":132}],181:[function(require,module,exports){ +// 7.1.1 ToPrimitive(input [, PreferredType]) +var isObject = require('./_is-object'); +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +},{"./_is-object":147}],182:[function(require,module,exports){ +var id = 0; +var px = Math.random(); +module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; + +},{}],183:[function(require,module,exports){ +var global = require('./_global'); +var core = require('./_core'); +var LIBRARY = require('./_library'); +var wksExt = require('./_wks-ext'); +var defineProperty = require('./_object-dp').f; +module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); +}; + +},{"./_core":129,"./_global":139,"./_library":154,"./_object-dp":158,"./_wks-ext":184}],184:[function(require,module,exports){ +exports.f = require('./_wks'); + +},{"./_wks":185}],185:[function(require,module,exports){ +var store = require('./_shared')('wks'); +var uid = require('./_uid'); +var Symbol = require('./_global').Symbol; +var USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +$exports.store = store; + +},{"./_global":139,"./_shared":174,"./_uid":182}],186:[function(require,module,exports){ +var classof = require('./_classof'); +var ITERATOR = require('./_wks')('iterator'); +var Iterators = require('./_iterators'); +module.exports = require('./_core').getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; +}; + +},{"./_classof":127,"./_core":129,"./_iterators":153,"./_wks":185}],187:[function(require,module,exports){ +var anObject = require('./_an-object'); +var get = require('./core.get-iterator-method'); +module.exports = require('./_core').getIterator = function (it) { + var iterFn = get(it); + if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); + return anObject(iterFn.call(it)); +}; + +},{"./_an-object":125,"./_core":129,"./core.get-iterator-method":186}],188:[function(require,module,exports){ +var classof = require('./_classof'); +var ITERATOR = require('./_wks')('iterator'); +var Iterators = require('./_iterators'); +module.exports = require('./_core').isIterable = function (it) { + var O = Object(it); + return O[ITERATOR] !== undefined + || '@@iterator' in O + // eslint-disable-next-line no-prototype-builtins + || Iterators.hasOwnProperty(classof(O)); +}; + +},{"./_classof":127,"./_core":129,"./_iterators":153,"./_wks":185}],189:[function(require,module,exports){ +'use strict'; +var ctx = require('./_ctx'); +var $export = require('./_export'); +var toObject = require('./_to-object'); +var call = require('./_iter-call'); +var isArrayIter = require('./_is-array-iter'); +var toLength = require('./_to-length'); +var createProperty = require('./_create-property'); +var getIterFn = require('./core.get-iterator-method'); + +$export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } +}); + +},{"./_create-property":130,"./_ctx":131,"./_export":137,"./_is-array-iter":145,"./_iter-call":148,"./_iter-detect":151,"./_to-length":179,"./_to-object":180,"./core.get-iterator-method":186}],190:[function(require,module,exports){ +'use strict'; +var addToUnscopables = require('./_add-to-unscopables'); +var step = require('./_iter-step'); +var Iterators = require('./_iterators'); +var toIObject = require('./_to-iobject'); + +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +module.exports = require('./_iter-define')(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); +}, 'values'); + +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +Iterators.Arguments = Iterators.Array; + +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); + +},{"./_add-to-unscopables":124,"./_iter-define":150,"./_iter-step":152,"./_iterators":153,"./_to-iobject":178}],191:[function(require,module,exports){ +// 19.1.3.1 Object.assign(target, source) +var $export = require('./_export'); + +$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') }); + +},{"./_export":137,"./_object-assign":156}],192:[function(require,module,exports){ +var $export = require('./_export'); +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +$export($export.S, 'Object', { create: require('./_object-create') }); + +},{"./_export":137,"./_object-create":157}],193:[function(require,module,exports){ +var $export = require('./_export'); +// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) +$export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperty: require('./_object-dp').f }); + +},{"./_descriptors":133,"./_export":137,"./_object-dp":158}],194:[function(require,module,exports){ +// 19.1.3.19 Object.setPrototypeOf(O, proto) +var $export = require('./_export'); +$export($export.S, 'Object', { setPrototypeOf: require('./_set-proto').set }); + +},{"./_export":137,"./_set-proto":171}],195:[function(require,module,exports){ + +},{}],196:[function(require,module,exports){ +'use strict'; +var $at = require('./_string-at')(true); + +// 21.1.3.27 String.prototype[@@iterator]() +require('./_iter-define')(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; +}); + +},{"./_iter-define":150,"./_string-at":175}],197:[function(require,module,exports){ +'use strict'; +// ECMAScript 6 symbols shim +var global = require('./_global'); +var has = require('./_has'); +var DESCRIPTORS = require('./_descriptors'); +var $export = require('./_export'); +var redefine = require('./_redefine'); +var META = require('./_meta').KEY; +var $fails = require('./_fails'); +var shared = require('./_shared'); +var setToStringTag = require('./_set-to-string-tag'); +var uid = require('./_uid'); +var wks = require('./_wks'); +var wksExt = require('./_wks-ext'); +var wksDefine = require('./_wks-define'); +var enumKeys = require('./_enum-keys'); +var isArray = require('./_is-array'); +var anObject = require('./_an-object'); +var isObject = require('./_is-object'); +var toIObject = require('./_to-iobject'); +var toPrimitive = require('./_to-primitive'); +var createDesc = require('./_property-desc'); +var _create = require('./_object-create'); +var gOPNExt = require('./_object-gopn-ext'); +var $GOPD = require('./_object-gopd'); +var $DP = require('./_object-dp'); +var $keys = require('./_object-keys'); +var gOPD = $GOPD.f; +var dP = $DP.f; +var gOPN = gOPNExt.f; +var $Symbol = global.Symbol; +var $JSON = global.JSON; +var _stringify = $JSON && $JSON.stringify; +var PROTOTYPE = 'prototype'; +var HIDDEN = wks('_hidden'); +var TO_PRIMITIVE = wks('toPrimitive'); +var isEnum = {}.propertyIsEnumerable; +var SymbolRegistry = shared('symbol-registry'); +var AllSymbols = shared('symbols'); +var OPSymbols = shared('op-symbols'); +var ObjectProto = Object[PROTOTYPE]; +var USE_NATIVE = typeof $Symbol == 'function'; +var QObject = global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); +} : dP; + +var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; +}; + +var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return it instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); +}; +var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; +}; +var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); +}; +var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; +}; +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; +}; +var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; +}; +var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; +}; + +// 19.4.1.1 Symbol([description]) +if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames; + require('./_object-pie').f = $propertyIsEnumerable; + require('./_object-gops').f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !require('./_library')) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; +} + +$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + +for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' +).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + +for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + +$export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } +}); + +$export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// 24.3.2 JSON.stringify(value [, replacer [, space]]) +$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; +})), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } +}); + +// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) +$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); +// 19.4.3.5 Symbol.prototype[@@toStringTag] +setToStringTag($Symbol, 'Symbol'); +// 20.2.1.9 Math[@@toStringTag] +setToStringTag(Math, 'Math', true); +// 24.3.3 JSON[@@toStringTag] +setToStringTag(global.JSON, 'JSON', true); + +},{"./_an-object":125,"./_descriptors":133,"./_enum-keys":136,"./_export":137,"./_fails":138,"./_global":139,"./_has":140,"./_hide":141,"./_is-array":146,"./_is-object":147,"./_library":154,"./_meta":155,"./_object-create":157,"./_object-dp":158,"./_object-gopd":160,"./_object-gopn":162,"./_object-gopn-ext":161,"./_object-gops":163,"./_object-keys":166,"./_object-pie":167,"./_property-desc":169,"./_redefine":170,"./_set-to-string-tag":172,"./_shared":174,"./_to-iobject":178,"./_to-primitive":181,"./_uid":182,"./_wks":185,"./_wks-define":183,"./_wks-ext":184}],198:[function(require,module,exports){ +// https://github.com/tc39/proposal-object-values-entries +var $export = require('./_export'); +var $entries = require('./_object-to-array')(true); + +$export($export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } +}); + +},{"./_export":137,"./_object-to-array":168}],199:[function(require,module,exports){ +// https://github.com/tc39/proposal-object-values-entries +var $export = require('./_export'); +var $values = require('./_object-to-array')(false); + +$export($export.S, 'Object', { + values: function values(it) { + return $values(it); + } +}); + +},{"./_export":137,"./_object-to-array":168}],200:[function(require,module,exports){ +require('./_wks-define')('asyncIterator'); + +},{"./_wks-define":183}],201:[function(require,module,exports){ +require('./_wks-define')('observable'); + +},{"./_wks-define":183}],202:[function(require,module,exports){ +require('./es6.array.iterator'); +var global = require('./_global'); +var hide = require('./_hide'); +var Iterators = require('./_iterators'); +var TO_STRING_TAG = require('./_wks')('toStringTag'); + +var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + + 'TextTrackList,TouchList').split(','); + +for (var i = 0; i < DOMIterables.length; i++) { + var NAME = DOMIterables[i]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = Iterators.Array; +} + +},{"./_global":139,"./_hide":141,"./_iterators":153,"./_wks":185,"./es6.array.iterator":190}],203:[function(require,module,exports){ +module.exports = require("regenerator-runtime"); + +},{"regenerator-runtime":985}],204:[function(require,module,exports){ +module.exports = function blacklist (src) { + var copy = {} + var filter = arguments[1] + + if (typeof filter === 'string') { + filter = {} + for (var i = 1; i < arguments.length; i++) { + filter[arguments[i]] = true + } + } + + for (var key in src) { + // blacklist? + if (filter[key]) continue + + copy[key] = src[key] + } + + return copy +} + +},{}],205:[function(require,module,exports){ +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * Define a module along with a payload + * @param module a name for the payload + * @param payload a function to call with (acequire, exports, module) params + */ + +(function() { + +var ACE_NAMESPACE = "ace"; + +var global = (function() { return this; })(); +if (!global && typeof window != "undefined") global = window; // strict mode + + +if (!ACE_NAMESPACE && typeof acequirejs !== "undefined") + return; + + +var define = function(module, deps, payload) { + if (typeof module !== "string") { + if (define.original) + define.original.apply(this, arguments); + else { + console.error("dropping module because define wasn\'t a string."); + console.trace(); + } + return; + } + if (arguments.length == 2) + payload = deps; + if (!define.modules[module]) { + define.payloads[module] = payload; + define.modules[module] = null; + } +}; + +define.modules = {}; +define.payloads = {}; + +/** + * Get at functionality define()ed using the function above + */ +var _acequire = function(parentId, module, callback) { + if (typeof module === "string") { + var payload = lookup(parentId, module); + if (payload != undefined) { + callback && callback(); + return payload; + } + } else if (Object.prototype.toString.call(module) === "[object Array]") { + var params = []; + for (var i = 0, l = module.length; i < l; ++i) { + var dep = lookup(parentId, module[i]); + if (dep == undefined && acequire.original) + return; + params.push(dep); + } + return callback && callback.apply(null, params) || true; + } +}; + +var acequire = function(module, callback) { + var packagedModule = _acequire("", module, callback); + if (packagedModule == undefined && acequire.original) + return acequire.original.apply(this, arguments); + return packagedModule; +}; + +var normalizeModule = function(parentId, moduleName) { + // normalize plugin acequires + if (moduleName.indexOf("!") !== -1) { + var chunks = moduleName.split("!"); + return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); + } + // normalize relative acequires + if (moduleName.charAt(0) == ".") { + var base = parentId.split("/").slice(0, -1).join("/"); + moduleName = base + "/" + moduleName; + + while(moduleName.indexOf(".") !== -1 && previous != moduleName) { + var previous = moduleName; + moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); + } + } + return moduleName; +}; + +/** + * Internal function to lookup moduleNames and resolve them by calling the + * definition function if needed. + */ +var lookup = function(parentId, moduleName) { + moduleName = normalizeModule(parentId, moduleName); + + var module = define.modules[moduleName]; + if (!module) { + module = define.payloads[moduleName]; + if (typeof module === 'function') { + var exports = {}; + var mod = { + id: moduleName, + uri: '', + exports: exports, + packaged: true + }; + + var req = function(module, callback) { + return _acequire(moduleName, module, callback); + }; + + var returnValue = module(req, exports, mod); + exports = returnValue || mod.exports; + define.modules[moduleName] = exports; + delete define.payloads[moduleName]; + } + module = define.modules[moduleName] = exports || module; + } + return module; +}; + +function exportAce(ns) { + var root = global; + if (ns) { + if (!global[ns]) + global[ns] = {}; + root = global[ns]; + } + + if (!root.define || !root.define.packaged) { + define.original = root.define; + root.define = define; + root.define.packaged = true; + } + + if (!root.acequire || !root.acequire.packaged) { + acequire.original = root.acequire; + root.acequire = acequire; + root.acequire.packaged = true; + } +} + +exportAce(ACE_NAMESPACE); + +})(); + +ace.define("ace/lib/regexp",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + + var real = { + exec: RegExp.prototype.exec, + test: RegExp.prototype.test, + match: String.prototype.match, + replace: String.prototype.replace, + split: String.prototype.split + }, + compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups + compliantLastIndexIncrement = function () { + var x = /^/g; + real.test.call(x, ""); + return !x.lastIndex; + }(); + + if (compliantLastIndexIncrement && compliantExecNpcg) + return; + RegExp.prototype.exec = function (str) { + var match = real.exec.apply(this, arguments), + name, r2; + if ( typeof(str) == 'string' && match) { + if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { + r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); + real.replace.call(str.slice(match.index), r2, function () { + for (var i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) + match[i] = undefined; + } + }); + } + if (this._xregexp && this._xregexp.captureNames) { + for (var i = 1; i < match.length; i++) { + name = this._xregexp.captureNames[i - 1]; + if (name) + match[name] = match[i]; + } + } + if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + } + return match; + }; + if (!compliantLastIndexIncrement) { + RegExp.prototype.test = function (str) { + var match = real.exec.call(this, str); + if (match && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + return !!match; + }; + } + + function getNativeFlags (regex) { + return (regex.global ? "g" : "") + + (regex.ignoreCase ? "i" : "") + + (regex.multiline ? "m" : "") + + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 + (regex.sticky ? "y" : ""); + } + + function indexOf (array, item, from) { + if (Array.prototype.indexOf) // Use the native array method if available + return array.indexOf(item, from); + for (var i = from || 0; i < array.length; i++) { + if (array[i] === item) + return i; + } + return -1; + } + +}); + +ace.define("ace/lib/es5-shim",["require","exports","module"], function(acequire, exports, module) { + +function Empty() {} + +if (!Function.prototype.bind) { + Function.prototype.bind = function bind(that) { // .length is 1 + var target = this; + if (typeof target != "function") { + throw new TypeError("Function.prototype.bind called on incompatible " + target); + } + var args = slice.call(arguments, 1); // for normal call + var bound = function () { + + if (this instanceof bound) { + + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + + } + + }; + if(target.prototype) { + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; +} +var call = Function.prototype.call; +var prototypeOfArray = Array.prototype; +var prototypeOfObject = Object.prototype; +var slice = prototypeOfArray.slice; +var _toString = call.bind(prototypeOfObject.toString); +var owns = call.bind(prototypeOfObject.hasOwnProperty); +var defineGetter; +var defineSetter; +var lookupGetter; +var lookupSetter; +var supportsAccessors; +if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { + defineGetter = call.bind(prototypeOfObject.__defineGetter__); + defineSetter = call.bind(prototypeOfObject.__defineSetter__); + lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); + lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); +} +if ([1,2].splice(0).length != 2) { + if(function() { // test IE < 9 to splice bug - see issue #138 + function makeArray(l) { + var a = new Array(l+2); + a[0] = a[1] = 0; + return a; + } + var array = [], lengthBefore; + + array.splice.apply(array, makeArray(20)); + array.splice.apply(array, makeArray(26)); + + lengthBefore = array.length; //46 + array.splice(5, 0, "XXX"); // add one element + + lengthBefore + 1 == array.length + + if (lengthBefore + 1 == array.length) { + return true;// has right splice implementation without bugs + } + }()) {//IE 6/7 + var array_splice = Array.prototype.splice; + Array.prototype.splice = function(start, deleteCount) { + if (!arguments.length) { + return []; + } else { + return array_splice.apply(this, [ + start === void 0 ? 0 : start, + deleteCount === void 0 ? (this.length - start) : deleteCount + ].concat(slice.call(arguments, 2))) + } + }; + } else {//IE8 + Array.prototype.splice = function(pos, removeCount){ + var length = this.length; + if (pos > 0) { + if (pos > length) + pos = length; + } else if (pos == void 0) { + pos = 0; + } else if (pos < 0) { + pos = Math.max(length + pos, 0); + } + + if (!(pos+removeCount < length)) + removeCount = length - pos; + + var removed = this.slice(pos, pos+removeCount); + var insert = slice.call(arguments, 2); + var add = insert.length; + if (pos === length) { + if (add) { + this.push.apply(this, insert); + } + } else { + var remove = Math.min(removeCount, length - pos); + var tailOldPos = pos + remove; + var tailNewPos = tailOldPos + add - remove; + var tailCount = length - tailOldPos; + var lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { // case A + for (var i = 0; i < tailCount; ++i) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { // case B + for (i = tailCount; i--; ) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } // else, add == remove (nothing to do) + + if (add && pos === lengthAfterRemove) { + this.length = lengthAfterRemove; // truncate array + this.push.apply(this, insert); + } else { + this.length = lengthAfterRemove + add; // reserves space + for (i = 0; i < add; ++i) { + this[pos+i] = insert[i]; + } + } + } + return removed; + }; + } +} +if (!Array.isArray) { + Array.isArray = function isArray(obj) { + return _toString(obj) == "[object Array]"; + }; +} +var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + +if (!Array.prototype.forEach) { + Array.prototype.forEach = function forEach(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + thisp = arguments[1], + i = -1, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(); // TODO message + } + + while (++i < length) { + if (i in self) { + fun.call(thisp, self[i], i, object); + } + } + }; +} +if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; +} +if (!Array.prototype.filter) { + Array.prototype.filter = function filter(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = [], + value, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + value = self[i]; + if (fun.call(thisp, value, i, object)) { + result.push(value); + } + } + } + return result; + }; +} +if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; +} +if (!Array.prototype.some) { + Array.prototype.some = function some(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && fun.call(thisp, self[i], i, object)) { + return true; + } + } + return false; + }; +} +if (!Array.prototype.reduce) { + Array.prototype.reduce = function reduce(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduce of empty array with no initial value"); + } + + var i = 0; + var result; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i++]; + break; + } + if (++i >= length) { + throw new TypeError("reduce of empty array with no initial value"); + } + } while (true); + } + + for (; i < length; i++) { + if (i in self) { + result = fun.call(void 0, result, self[i], i, object); + } + } + + return result; + }; +} +if (!Array.prototype.reduceRight) { + Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + + var result, i = length - 1; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i--]; + break; + } + if (--i < 0) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + } while (true); + } + + do { + if (i in this) { + result = fun.call(void 0, result, self[i], i, object); + } + } while (i--); + + return result; + }; +} +if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { + Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + toObject(this), + length = self.length >>> 0; + + if (!length) { + return -1; + } + + var i = 0; + if (arguments.length > 1) { + i = toInteger(arguments[1]); + } + i = i >= 0 ? i : Math.max(0, length + i); + for (; i < length; i++) { + if (i in self && self[i] === sought) { + return i; + } + } + return -1; + }; +} +if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { + Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + toObject(this), + length = self.length >>> 0; + + if (!length) { + return -1; + } + var i = length - 1; + if (arguments.length > 1) { + i = Math.min(i, toInteger(arguments[1])); + } + i = i >= 0 ? i : length - Math.abs(i); + for (; i >= 0; i--) { + if (i in self && sought === self[i]) { + return i; + } + } + return -1; + }; +} +if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function getPrototypeOf(object) { + return object.__proto__ || ( + object.constructor ? + object.constructor.prototype : + prototypeOfObject + ); + }; +} +if (!Object.getOwnPropertyDescriptor) { + var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + + "non-object: "; + Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { + if ((typeof object != "object" && typeof object != "function") || object === null) + throw new TypeError(ERR_NON_OBJECT + object); + if (!owns(object, property)) + return; + + var descriptor, getter, setter; + descriptor = { enumerable: true, configurable: true }; + if (supportsAccessors) { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + + var getter = lookupGetter(object, property); + var setter = lookupSetter(object, property); + object.__proto__ = prototype; + + if (getter || setter) { + if (getter) descriptor.get = getter; + if (setter) descriptor.set = setter; + return descriptor; + } + } + descriptor.value = object[property]; + return descriptor; + }; +} +if (!Object.getOwnPropertyNames) { + Object.getOwnPropertyNames = function getOwnPropertyNames(object) { + return Object.keys(object); + }; +} +if (!Object.create) { + var createEmpty; + if (Object.prototype.__proto__ === null) { + createEmpty = function () { + return { "__proto__": null }; + }; + } else { + createEmpty = function () { + var empty = {}; + for (var i in empty) + empty[i] = null; + empty.constructor = + empty.hasOwnProperty = + empty.propertyIsEnumerable = + empty.isPrototypeOf = + empty.toLocaleString = + empty.toString = + empty.valueOf = + empty.__proto__ = null; + return empty; + } + } + + Object.create = function create(prototype, properties) { + var object; + if (prototype === null) { + object = createEmpty(); + } else { + if (typeof prototype != "object") + throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); + var Type = function () {}; + Type.prototype = prototype; + object = new Type(); + object.__proto__ = prototype; + } + if (properties !== void 0) + Object.defineProperties(object, properties); + return object; + }; +} + +function doesDefinePropertyWork(object) { + try { + Object.defineProperty(object, "sentinel", {}); + return "sentinel" in object; + } catch (exception) { + } +} +if (Object.defineProperty) { + var definePropertyWorksOnObject = doesDefinePropertyWork({}); + var definePropertyWorksOnDom = typeof document == "undefined" || + doesDefinePropertyWork(document.createElement("div")); + if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { + var definePropertyFallback = Object.defineProperty; + } +} + +if (!Object.defineProperty || definePropertyFallback) { + var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; + var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " + var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + + "on this javascript engine"; + + Object.defineProperty = function defineProperty(object, property, descriptor) { + if ((typeof object != "object" && typeof object != "function") || object === null) + throw new TypeError(ERR_NON_OBJECT_TARGET + object); + if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) + throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); + if (definePropertyFallback) { + try { + return definePropertyFallback.call(Object, object, property, descriptor); + } catch (exception) { + } + } + if (owns(descriptor, "value")) { + + if (supportsAccessors && (lookupGetter(object, property) || + lookupSetter(object, property))) + { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + delete object[property]; + object[property] = descriptor.value; + object.__proto__ = prototype; + } else { + object[property] = descriptor.value; + } + } else { + if (!supportsAccessors) + throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); + if (owns(descriptor, "get")) + defineGetter(object, property, descriptor.get); + if (owns(descriptor, "set")) + defineSetter(object, property, descriptor.set); + } + + return object; + }; +} +if (!Object.defineProperties) { + Object.defineProperties = function defineProperties(object, properties) { + for (var property in properties) { + if (owns(properties, property)) + Object.defineProperty(object, property, properties[property]); + } + return object; + }; +} +if (!Object.seal) { + Object.seal = function seal(object) { + return object; + }; +} +if (!Object.freeze) { + Object.freeze = function freeze(object) { + return object; + }; +} +try { + Object.freeze(function () {}); +} catch (exception) { + Object.freeze = (function freeze(freezeObject) { + return function freeze(object) { + if (typeof object == "function") { + return object; + } else { + return freezeObject(object); + } + }; + })(Object.freeze); +} +if (!Object.preventExtensions) { + Object.preventExtensions = function preventExtensions(object) { + return object; + }; +} +if (!Object.isSealed) { + Object.isSealed = function isSealed(object) { + return false; + }; +} +if (!Object.isFrozen) { + Object.isFrozen = function isFrozen(object) { + return false; + }; +} +if (!Object.isExtensible) { + Object.isExtensible = function isExtensible(object) { + if (Object(object) === object) { + throw new TypeError(); // TODO message + } + var name = ''; + while (owns(object, name)) { + name += '?'; + } + object[name] = true; + var returnValue = owns(object, name); + delete object[name]; + return returnValue; + }; +} +if (!Object.keys) { + var hasDontEnumBug = true, + dontEnums = [ + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "constructor" + ], + dontEnumsLength = dontEnums.length; + + for (var key in {"toString": null}) { + hasDontEnumBug = false; + } + + Object.keys = function keys(object) { + + if ( + (typeof object != "object" && typeof object != "function") || + object === null + ) { + throw new TypeError("Object.keys called on a non-object"); + } + + var keys = []; + for (var name in object) { + if (owns(object, name)) { + keys.push(name); + } + } + + if (hasDontEnumBug) { + for (var i = 0, ii = dontEnumsLength; i < ii; i++) { + var dontEnum = dontEnums[i]; + if (owns(object, dontEnum)) { + keys.push(dontEnum); + } + } + } + return keys; + }; + +} +if (!Date.now) { + Date.now = function now() { + return new Date().getTime(); + }; +} +var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + + "\u2029\uFEFF"; +if (!String.prototype.trim || ws.trim()) { + ws = "[" + ws + "]"; + var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), + trimEndRegexp = new RegExp(ws + ws + "*$"); + String.prototype.trim = function trim() { + return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); + }; +} + +function toInteger(n) { + n = +n; + if (n !== n) { // isNaN + n = 0; + } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { + n = (n > 0 || -1) * Math.floor(Math.abs(n)); + } + return n; +} + +function isPrimitive(input) { + var type = typeof input; + return ( + input === null || + type === "undefined" || + type === "boolean" || + type === "number" || + type === "string" + ); +} + +function toPrimitive(input) { + var val, valueOf, toString; + if (isPrimitive(input)) { + return input; + } + valueOf = input.valueOf; + if (typeof valueOf === "function") { + val = valueOf.call(input); + if (isPrimitive(val)) { + return val; + } + } + toString = input.toString; + if (typeof toString === "function") { + val = toString.call(input); + if (isPrimitive(val)) { + return val; + } + } + throw new TypeError(); +} +var toObject = function (o) { + if (o == null) { // this matches both null and undefined + throw new TypeError("can't convert "+o+" to object"); + } + return Object(o); +}; + +}); + +ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(acequire, exports, module) { +"use strict"; + +acequire("./regexp"); +acequire("./es5-shim"); + +}); + +ace.define("ace/lib/dom",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var XHTML_NS = "http://www.w3.org/1999/xhtml"; + +exports.getDocumentHead = function(doc) { + if (!doc) + doc = document; + return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement; +} + +exports.createElement = function(tag, ns) { + return document.createElementNS ? + document.createElementNS(ns || XHTML_NS, tag) : + document.createElement(tag); +}; + +exports.hasCssClass = function(el, name) { + var classes = (el.className + "").split(/\s+/g); + return classes.indexOf(name) !== -1; +}; +exports.addCssClass = function(el, name) { + if (!exports.hasCssClass(el, name)) { + el.className += " " + name; + } +}; +exports.removeCssClass = function(el, name) { + var classes = el.className.split(/\s+/g); + while (true) { + var index = classes.indexOf(name); + if (index == -1) { + break; + } + classes.splice(index, 1); + } + el.className = classes.join(" "); +}; + +exports.toggleCssClass = function(el, name) { + var classes = el.className.split(/\s+/g), add = true; + while (true) { + var index = classes.indexOf(name); + if (index == -1) { + break; + } + add = false; + classes.splice(index, 1); + } + if (add) + classes.push(name); + + el.className = classes.join(" "); + return add; +}; +exports.setCssClass = function(node, className, include) { + if (include) { + exports.addCssClass(node, className); + } else { + exports.removeCssClass(node, className); + } +}; + +exports.hasCssString = function(id, doc) { + var index = 0, sheets; + doc = doc || document; + + if (doc.createStyleSheet && (sheets = doc.styleSheets)) { + while (index < sheets.length) + if (sheets[index++].owningElement.id === id) return true; + } else if ((sheets = doc.getElementsByTagName("style"))) { + while (index < sheets.length) + if (sheets[index++].id === id) return true; + } + + return false; +}; + +exports.importCssString = function importCssString(cssText, id, doc) { + doc = doc || document; + if (id && exports.hasCssString(id, doc)) + return null; + + var style; + + if (id) + cssText += "\n/*# sourceURL=ace/css/" + id + " */"; + + if (doc.createStyleSheet) { + style = doc.createStyleSheet(); + style.cssText = cssText; + if (id) + style.owningElement.id = id; + } else { + style = exports.createElement("style"); + style.appendChild(doc.createTextNode(cssText)); + if (id) + style.id = id; + + exports.getDocumentHead(doc).appendChild(style); + } +}; + +exports.importCssStylsheet = function(uri, doc) { + if (doc.createStyleSheet) { + doc.createStyleSheet(uri); + } else { + var link = exports.createElement('link'); + link.rel = 'stylesheet'; + link.href = uri; + + exports.getDocumentHead(doc).appendChild(link); + } +}; + +exports.getInnerWidth = function(element) { + return ( + parseInt(exports.computedStyle(element, "paddingLeft"), 10) + + parseInt(exports.computedStyle(element, "paddingRight"), 10) + + element.clientWidth + ); +}; + +exports.getInnerHeight = function(element) { + return ( + parseInt(exports.computedStyle(element, "paddingTop"), 10) + + parseInt(exports.computedStyle(element, "paddingBottom"), 10) + + element.clientHeight + ); +}; + +exports.scrollbarWidth = function(document) { + var inner = exports.createElement("ace_inner"); + inner.style.width = "100%"; + inner.style.minWidth = "0px"; + inner.style.height = "200px"; + inner.style.display = "block"; + + var outer = exports.createElement("ace_outer"); + var style = outer.style; + + style.position = "absolute"; + style.left = "-10000px"; + style.overflow = "hidden"; + style.width = "200px"; + style.minWidth = "0px"; + style.height = "150px"; + style.display = "block"; + + outer.appendChild(inner); + + var body = document.documentElement; + body.appendChild(outer); + + var noScrollbar = inner.offsetWidth; + + style.overflow = "scroll"; + var withScrollbar = inner.offsetWidth; + + if (noScrollbar == withScrollbar) { + withScrollbar = outer.clientWidth; + } + + body.removeChild(outer); + + return noScrollbar-withScrollbar; +}; + +if (typeof document == "undefined") { + exports.importCssString = function() {}; + return; +} + +if (window.pageYOffset !== undefined) { + exports.getPageScrollTop = function() { + return window.pageYOffset; + }; + + exports.getPageScrollLeft = function() { + return window.pageXOffset; + }; +} +else { + exports.getPageScrollTop = function() { + return document.body.scrollTop; + }; + + exports.getPageScrollLeft = function() { + return document.body.scrollLeft; + }; +} + +if (window.getComputedStyle) + exports.computedStyle = function(element, style) { + if (style) + return (window.getComputedStyle(element, "") || {})[style] || ""; + return window.getComputedStyle(element, "") || {}; + }; +else + exports.computedStyle = function(element, style) { + if (style) + return element.currentStyle[style]; + return element.currentStyle; + }; +exports.setInnerHtml = function(el, innerHtml) { + var element = el.cloneNode(false);//document.createElement("div"); + element.innerHTML = innerHtml; + el.parentNode.replaceChild(element, el); + return element; +}; + +if ("textContent" in document.documentElement) { + exports.setInnerText = function(el, innerText) { + el.textContent = innerText; + }; + + exports.getInnerText = function(el) { + return el.textContent; + }; +} +else { + exports.setInnerText = function(el, innerText) { + el.innerText = innerText; + }; + + exports.getInnerText = function(el) { + return el.innerText; + }; +} + +exports.getParentWindow = function(document) { + return document.defaultView || document.parentWindow; +}; + +}); + +ace.define("ace/lib/oop",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; + +exports.mixin = function(obj, mixin) { + for (var key in mixin) { + obj[key] = mixin[key]; + } + return obj; +}; + +exports.implement = function(proto, mixin) { + exports.mixin(proto, mixin); +}; + +}); + +ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +acequire("./fixoldbrowsers"); + +var oop = acequire("./oop"); +var Keys = (function() { + var ret = { + MODIFIER_KEYS: { + 16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta' + }, + + KEY_MODS: { + "ctrl": 1, "alt": 2, "option" : 2, "shift": 4, + "super": 8, "meta": 8, "command": 8, "cmd": 8 + }, + + FUNCTION_KEYS : { + 8 : "Backspace", + 9 : "Tab", + 13 : "Return", + 19 : "Pause", + 27 : "Esc", + 32 : "Space", + 33 : "PageUp", + 34 : "PageDown", + 35 : "End", + 36 : "Home", + 37 : "Left", + 38 : "Up", + 39 : "Right", + 40 : "Down", + 44 : "Print", + 45 : "Insert", + 46 : "Delete", + 96 : "Numpad0", + 97 : "Numpad1", + 98 : "Numpad2", + 99 : "Numpad3", + 100: "Numpad4", + 101: "Numpad5", + 102: "Numpad6", + 103: "Numpad7", + 104: "Numpad8", + 105: "Numpad9", + '-13': "NumpadEnter", + 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" + }, + + PRINTABLE_KEYS: { + 32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', + 54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a', + 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', + 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o', + 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', + 87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.', + 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', + 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*' + } + }; + var name, i; + for (i in ret.FUNCTION_KEYS) { + name = ret.FUNCTION_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + for (i in ret.PRINTABLE_KEYS) { + name = ret.PRINTABLE_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + oop.mixin(ret, ret.MODIFIER_KEYS); + oop.mixin(ret, ret.PRINTABLE_KEYS); + oop.mixin(ret, ret.FUNCTION_KEYS); + ret.enter = ret["return"]; + ret.escape = ret.esc; + ret.del = ret["delete"]; + ret[173] = '-'; + + (function() { + var mods = ["cmd", "ctrl", "alt", "shift"]; + for (var i = Math.pow(2, mods.length); i--;) { + ret.KEY_MODS[i] = mods.filter(function(x) { + return i & ret.KEY_MODS[x]; + }).join("-") + "-"; + } + })(); + + ret.KEY_MODS[0] = ""; + ret.KEY_MODS[-1] = "input-"; + + return ret; +})(); +oop.mixin(exports, Keys); + +exports.keyCodeToString = function(keyCode) { + var keyString = Keys[keyCode]; + if (typeof keyString != "string") + keyString = String.fromCharCode(keyCode); + return keyString.toLowerCase(); +}; + +}); + +ace.define("ace/lib/useragent",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +exports.OS = { + LINUX: "LINUX", + MAC: "MAC", + WINDOWS: "WINDOWS" +}; +exports.getOS = function() { + if (exports.isMac) { + return exports.OS.MAC; + } else if (exports.isLinux) { + return exports.OS.LINUX; + } else { + return exports.OS.WINDOWS; + } +}; +if (typeof navigator != "object") + return; + +var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); +var ua = navigator.userAgent; +exports.isWin = (os == "win"); +exports.isMac = (os == "mac"); +exports.isLinux = (os == "linux"); +exports.isIE = + (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0) + ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]) + : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie + +exports.isOldIE = exports.isIE && exports.isIE < 9; +exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko"; +exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4; +exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; +exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined; + +exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined; + +exports.isAIR = ua.indexOf("AdobeAIR") >= 0; + +exports.isIPad = ua.indexOf("iPad") >= 0; + +exports.isTouchPad = ua.indexOf("TouchPad") >= 0; + +exports.isChromeOS = ua.indexOf(" CrOS ") >= 0; + +}); + +ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keys = acequire("./keys"); +var useragent = acequire("./useragent"); + +var pressedKeys = null; +var ts = 0; + +exports.addListener = function(elem, type, callback) { + if (elem.addEventListener) { + return elem.addEventListener(type, callback, false); + } + if (elem.attachEvent) { + var wrapper = function() { + callback.call(elem, window.event); + }; + callback._wrapper = wrapper; + elem.attachEvent("on" + type, wrapper); + } +}; + +exports.removeListener = function(elem, type, callback) { + if (elem.removeEventListener) { + return elem.removeEventListener(type, callback, false); + } + if (elem.detachEvent) { + elem.detachEvent("on" + type, callback._wrapper || callback); + } +}; +exports.stopEvent = function(e) { + exports.stopPropagation(e); + exports.preventDefault(e); + return false; +}; + +exports.stopPropagation = function(e) { + if (e.stopPropagation) + e.stopPropagation(); + else + e.cancelBubble = true; +}; + +exports.preventDefault = function(e) { + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue = false; +}; +exports.getButton = function(e) { + if (e.type == "dblclick") + return 0; + if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey))) + return 2; + if (e.preventDefault) { + return e.button; + } + else { + return {1:0, 2:2, 4:1}[e.button]; + } +}; + +exports.capture = function(el, eventHandler, releaseCaptureHandler) { + function onMouseUp(e) { + eventHandler && eventHandler(e); + releaseCaptureHandler && releaseCaptureHandler(e); + + exports.removeListener(document, "mousemove", eventHandler, true); + exports.removeListener(document, "mouseup", onMouseUp, true); + exports.removeListener(document, "dragstart", onMouseUp, true); + } + + exports.addListener(document, "mousemove", eventHandler, true); + exports.addListener(document, "mouseup", onMouseUp, true); + exports.addListener(document, "dragstart", onMouseUp, true); + + return onMouseUp; +}; + +exports.addTouchMoveListener = function (el, callback) { + if ("ontouchmove" in el) { + var startx, starty; + exports.addListener(el, "touchstart", function (e) { + var touchObj = e.changedTouches[0]; + startx = touchObj.clientX; + starty = touchObj.clientY; + }); + exports.addListener(el, "touchmove", function (e) { + var factor = 1, + touchObj = e.changedTouches[0]; + + e.wheelX = -(touchObj.clientX - startx) / factor; + e.wheelY = -(touchObj.clientY - starty) / factor; + + startx = touchObj.clientX; + starty = touchObj.clientY; + + callback(e); + }); + } +}; + +exports.addMouseWheelListener = function(el, callback) { + if ("onmousewheel" in el) { + exports.addListener(el, "mousewheel", function(e) { + var factor = 8; + if (e.wheelDeltaX !== undefined) { + e.wheelX = -e.wheelDeltaX / factor; + e.wheelY = -e.wheelDeltaY / factor; + } else { + e.wheelX = 0; + e.wheelY = -e.wheelDelta / factor; + } + callback(e); + }); + } else if ("onwheel" in el) { + exports.addListener(el, "wheel", function(e) { + var factor = 0.35; + switch (e.deltaMode) { + case e.DOM_DELTA_PIXEL: + e.wheelX = e.deltaX * factor || 0; + e.wheelY = e.deltaY * factor || 0; + break; + case e.DOM_DELTA_LINE: + case e.DOM_DELTA_PAGE: + e.wheelX = (e.deltaX || 0) * 5; + e.wheelY = (e.deltaY || 0) * 5; + break; + } + + callback(e); + }); + } else { + exports.addListener(el, "DOMMouseScroll", function(e) { + if (e.axis && e.axis == e.HORIZONTAL_AXIS) { + e.wheelX = (e.detail || 0) * 5; + e.wheelY = 0; + } else { + e.wheelX = 0; + e.wheelY = (e.detail || 0) * 5; + } + callback(e); + }); + } +}; + +exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) { + var clicks = 0; + var startX, startY, timer; + var eventNames = { + 2: "dblclick", + 3: "tripleclick", + 4: "quadclick" + }; + + function onMousedown(e) { + if (exports.getButton(e) !== 0) { + clicks = 0; + } else if (e.detail > 1) { + clicks++; + if (clicks > 4) + clicks = 1; + } else { + clicks = 1; + } + if (useragent.isIE) { + var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; + if (!timer || isNewClick) + clicks = 1; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); + + if (clicks == 1) { + startX = e.clientX; + startY = e.clientY; + } + } + + e._clicks = clicks; + + eventHandler[callbackName]("mousedown", e); + + if (clicks > 4) + clicks = 0; + else if (clicks > 1) + return eventHandler[callbackName](eventNames[clicks], e); + } + function onDblclick(e) { + clicks = 2; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); + eventHandler[callbackName]("mousedown", e); + eventHandler[callbackName](eventNames[clicks], e); + } + if (!Array.isArray(elements)) + elements = [elements]; + elements.forEach(function(el) { + exports.addListener(el, "mousedown", onMousedown); + if (useragent.isOldIE) + exports.addListener(el, "dblclick", onDblclick); + }); +}; + +var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window) + ? function(e) { + return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); + } + : function(e) { + return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); + }; + +exports.getModifierString = function(e) { + return keys.KEY_MODS[getModifierHash(e)]; +}; + +function normalizeCommandKeys(callback, e, keyCode) { + var hashId = getModifierHash(e); + + if (!useragent.isMac && pressedKeys) { + if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win"))) + hashId |= 8; + if (pressedKeys.altGr) { + if ((3 & hashId) != 3) + pressedKeys.altGr = 0; + else + return; + } + if (keyCode === 18 || keyCode === 17) { + var location = "location" in e ? e.location : e.keyLocation; + if (keyCode === 17 && location === 1) { + if (pressedKeys[keyCode] == 1) + ts = e.timeStamp; + } else if (keyCode === 18 && hashId === 3 && location === 2) { + var dt = e.timeStamp - ts; + if (dt < 50) + pressedKeys.altGr = true; + } + } + } + + if (keyCode in keys.MODIFIER_KEYS) { + keyCode = -1; + } + if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) { + keyCode = -1; + } + + if (!hashId && keyCode === 13) { + var location = "location" in e ? e.location : e.keyLocation; + if (location === 3) { + callback(e, hashId, -keyCode); + if (e.defaultPrevented) + return; + } + } + + if (useragent.isChromeOS && hashId & 8) { + callback(e, hashId, keyCode); + if (e.defaultPrevented) + return; + else + hashId &= ~8; + } + if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) { + return false; + } + + return callback(e, hashId, keyCode); +} + + +exports.addCommandKeyListener = function(el, callback) { + var addListener = exports.addListener; + if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) { + var lastKeyDownKeyCode = null; + addListener(el, "keydown", function(e) { + lastKeyDownKeyCode = e.keyCode; + }); + addListener(el, "keypress", function(e) { + return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); + }); + } else { + var lastDefaultPrevented = null; + + addListener(el, "keydown", function(e) { + pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; + var result = normalizeCommandKeys(callback, e, e.keyCode); + lastDefaultPrevented = e.defaultPrevented; + return result; + }); + + addListener(el, "keypress", function(e) { + if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { + exports.stopEvent(e); + lastDefaultPrevented = null; + } + }); + + addListener(el, "keyup", function(e) { + pressedKeys[e.keyCode] = null; + }); + + if (!pressedKeys) { + resetPressedKeys(); + addListener(window, "focus", resetPressedKeys); + } + } +}; +function resetPressedKeys() { + pressedKeys = Object.create(null); +} + +if (typeof window == "object" && window.postMessage && !useragent.isOldIE) { + var postMessageId = 1; + exports.nextTick = function(callback, win) { + win = win || window; + var messageName = "zero-timeout-message-" + postMessageId; + exports.addListener(win, "message", function listener(e) { + if (e.data == messageName) { + exports.stopPropagation(e); + exports.removeListener(win, "message", listener); + callback(); + } + }); + win.postMessage(messageName, "*"); + }; +} + + +exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame + || window.mozRequestAnimationFrame + || window.webkitRequestAnimationFrame + || window.msRequestAnimationFrame + || window.oRequestAnimationFrame); + +if (exports.nextFrame) + exports.nextFrame = exports.nextFrame.bind(window); +else + exports.nextFrame = function(callback) { + setTimeout(callback, 17); + }; +}); + +ace.define("ace/lib/lang",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.last = function(a) { + return a[a.length - 1]; +}; + +exports.stringReverse = function(string) { + return string.split("").reverse().join(""); +}; + +exports.stringRepeat = function (string, count) { + var result = ''; + while (count > 0) { + if (count & 1) + result += string; + + if (count >>= 1) + string += string; + } + return result; +}; + +var trimBeginRegexp = /^\s\s*/; +var trimEndRegexp = /\s\s*$/; + +exports.stringTrimLeft = function (string) { + return string.replace(trimBeginRegexp, ''); +}; + +exports.stringTrimRight = function (string) { + return string.replace(trimEndRegexp, ''); +}; + +exports.copyObject = function(obj) { + var copy = {}; + for (var key in obj) { + copy[key] = obj[key]; + } + return copy; +}; + +exports.copyArray = function(array){ + var copy = []; + for (var i=0, l=array.length; i= 53) { + onInput(); + } + }; + + + + var syncComposition = lang.delayedCall(onCompositionUpdate, 50); + + event.addListener(text, "compositionstart", onCompositionStart); + if (useragent.isGecko) { + event.addListener(text, "text", function(){syncComposition.schedule()}); + } else { + event.addListener(text, "keyup", function(){syncComposition.schedule()}); + event.addListener(text, "keydown", function(){syncComposition.schedule()}); + } + event.addListener(text, "compositionend", onCompositionEnd); + + this.getElement = function() { + return text; + }; + + this.setReadOnly = function(readOnly) { + text.readOnly = readOnly; + }; + + this.onContextMenu = function(e) { + afterContextMenu = true; + resetSelection(host.selection.isEmpty()); + host._emit("nativecontextmenu", {target: host, domEvent: e}); + this.moveToMouse(e, true); + }; + + this.moveToMouse = function(e, bringToFront) { + if (!bringToFront && useragent.isOldIE) + return; + if (!tempStyle) + tempStyle = text.style.cssText; + text.style.cssText = (bringToFront ? "z-index:100000;" : "") + + "height:" + text.style.height + ";" + + (useragent.isIE ? "opacity:0.1;" : ""); + + var rect = host.container.getBoundingClientRect(); + var style = dom.computedStyle(host.container); + var top = rect.top + (parseInt(style.borderTopWidth) || 0); + var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); + var maxTop = rect.bottom - top - text.clientHeight -2; + var move = function(e) { + text.style.left = e.clientX - left - 2 + "px"; + text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px"; + }; + move(e); + + if (e.type != "mousedown") + return; + + if (host.renderer.$keepTextAreaAtCursor) + host.renderer.$keepTextAreaAtCursor = null; + + clearTimeout(closeTimeout); + if (useragent.isWin && !useragent.isOldIE) + event.capture(host.container, move, onContextMenuClose); + }; + + this.onContextMenuClose = onContextMenuClose; + var closeTimeout; + function onContextMenuClose() { + clearTimeout(closeTimeout); + closeTimeout = setTimeout(function () { + if (tempStyle) { + text.style.cssText = tempStyle; + tempStyle = ''; + } + if (host.renderer.$keepTextAreaAtCursor == null) { + host.renderer.$keepTextAreaAtCursor = true; + host.renderer.$moveTextAreaToCursor(); + } + }, useragent.isOldIE ? 200 : 0); + } + + var onContextMenu = function(e) { + host.textInput.onContextMenu(e); + onContextMenuClose(); + }; + event.addListener(text, "mouseup", onContextMenu); + event.addListener(text, "mousedown", function(e) { + e.preventDefault(); + onContextMenuClose(); + }); + event.addListener(host.renderer.scroller, "contextmenu", onContextMenu); + event.addListener(text, "contextmenu", onContextMenu); +}; + +exports.TextInput = TextInput; +}); + +ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var DRAG_OFFSET = 0; // pixels + +function DefaultHandlers(mouseHandler) { + mouseHandler.$clickSelection = null; + + var editor = mouseHandler.editor; + editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler)); + editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler)); + editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler)); + editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler)); + editor.setDefaultHandler("mousewheel", this.onMouseWheel.bind(mouseHandler)); + editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler)); + + var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd", + "selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + + mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); + mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); +} + +(function() { + + this.onMouseDown = function(ev) { + var inSelection = ev.inSelection(); + var pos = ev.getDocumentPosition(); + this.mousedownEvent = ev; + var editor = this.editor; + + var button = ev.getButton(); + if (button !== 0) { + var selectionRange = editor.getSelectionRange(); + var selectionEmpty = selectionRange.isEmpty(); + editor.$blockScrolling++; + if (selectionEmpty || button == 1) + editor.selection.moveToPosition(pos); + editor.$blockScrolling--; + if (button == 2) + editor.textInput.onContextMenu(ev.domEvent); + return; // stopping event here breaks contextmenu on ff mac + } + + this.mousedownEvent.time = Date.now(); + if (inSelection && !editor.isFocused()) { + editor.focus(); + if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) { + this.setState("focusWait"); + this.captureMouse(ev); + return; + } + } + + this.captureMouse(ev); + this.startSelect(pos, ev.domEvent._clicks > 1); + return ev.preventDefault(); + }; + + this.startSelect = function(pos, waitForClickSelection) { + pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); + var editor = this.editor; + editor.$blockScrolling++; + if (this.mousedownEvent.getShiftKey()) + editor.selection.selectToPosition(pos); + else if (!waitForClickSelection) + editor.selection.moveToPosition(pos); + if (!waitForClickSelection) + this.select(); + if (editor.renderer.scroller.setCapture) { + editor.renderer.scroller.setCapture(); + } + editor.setStyle("ace_selecting"); + this.setState("select"); + editor.$blockScrolling--; + }; + + this.select = function() { + var anchor, editor = this.editor; + var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); + editor.$blockScrolling++; + if (this.$clickSelection) { + var cmp = this.$clickSelection.comparePoint(cursor); + + if (cmp == -1) { + anchor = this.$clickSelection.end; + } else if (cmp == 1) { + anchor = this.$clickSelection.start; + } else { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + editor.renderer.scrollCursorIntoView(); + }; + + this.extendSelectionBy = function(unitName) { + var anchor, editor = this.editor; + var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); + var range = editor.selection[unitName](cursor.row, cursor.column); + editor.$blockScrolling++; + if (this.$clickSelection) { + var cmpStart = this.$clickSelection.comparePoint(range.start); + var cmpEnd = this.$clickSelection.comparePoint(range.end); + + if (cmpStart == -1 && cmpEnd <= 0) { + anchor = this.$clickSelection.end; + if (range.end.row != cursor.row || range.end.column != cursor.column) + cursor = range.start; + } else if (cmpEnd == 1 && cmpStart >= 0) { + anchor = this.$clickSelection.start; + if (range.start.row != cursor.row || range.start.column != cursor.column) + cursor = range.end; + } else if (cmpStart == -1 && cmpEnd == 1) { + cursor = range.end; + anchor = range.start; + } else { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + editor.renderer.scrollCursorIntoView(); + }; + + this.selectEnd = + this.selectAllEnd = + this.selectByWordsEnd = + this.selectByLinesEnd = function() { + this.$clickSelection = null; + this.editor.unsetStyle("ace_selecting"); + if (this.editor.renderer.scroller.releaseCapture) { + this.editor.renderer.scroller.releaseCapture(); + } + }; + + this.focusWait = function() { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + var time = Date.now(); + + if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout) + this.startSelect(this.mousedownEvent.getDocumentPosition()); + }; + + this.onDoubleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + var session = editor.session; + + var range = session.getBracketRange(pos); + if (range) { + if (range.isEmpty()) { + range.start.column--; + range.end.column++; + } + this.setState("select"); + } else { + range = editor.selection.getWordRange(pos.row, pos.column); + this.setState("selectByWords"); + } + this.$clickSelection = range; + this.select(); + }; + + this.onTripleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + + this.setState("selectByLines"); + var range = editor.getSelectionRange(); + if (range.isMultiLine() && range.contains(pos.row, pos.column)) { + this.$clickSelection = editor.selection.getLineRange(range.start.row); + this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end; + } else { + this.$clickSelection = editor.selection.getLineRange(pos.row); + } + this.select(); + }; + + this.onQuadClick = function(ev) { + var editor = this.editor; + + editor.selectAll(); + this.$clickSelection = editor.getSelectionRange(); + this.setState("selectAll"); + }; + + this.onMouseWheel = function(ev) { + if (ev.getAccelKey()) + return; + if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) { + ev.wheelX = ev.wheelY; + ev.wheelY = 0; + } + + var t = ev.domEvent.timeStamp; + var dt = t - (this.$lastScrollTime||0); + + var editor = this.editor; + var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + if (isScrolable || dt < 200) { + this.$lastScrollTime = t; + editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + return ev.stop(); + } + }; + + this.onTouchMove = function (ev) { + var t = ev.domEvent.timeStamp; + var dt = t - (this.$lastScrollTime || 0); + + var editor = this.editor; + var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + if (isScrolable || dt < 200) { + this.$lastScrollTime = t; + editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + return ev.stop(); + } + }; + +}).call(DefaultHandlers.prototype); + +exports.DefaultHandlers = DefaultHandlers; + +function calcDistance(ax, ay, bx, by) { + return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); +} + +function calcRangeOrientation(range, cursor) { + if (range.start.row == range.end.row) + var cmp = 2 * cursor.column - range.start.column - range.end.column; + else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column) + var cmp = cursor.column - 4; + else + var cmp = 2 * cursor.row - range.start.row - range.end.row; + + if (cmp < 0) + return {cursor: range.start, anchor: range.end}; + else + return {cursor: range.end, anchor: range.start}; +} + +}); + +ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +function Tooltip (parentNode) { + this.isOpen = false; + this.$element = null; + this.$parentNode = parentNode; +} + +(function() { + this.$init = function() { + this.$element = dom.createElement("div"); + this.$element.className = "ace_tooltip"; + this.$element.style.display = "none"; + this.$parentNode.appendChild(this.$element); + return this.$element; + }; + this.getElement = function() { + return this.$element || this.$init(); + }; + this.setText = function(text) { + dom.setInnerText(this.getElement(), text); + }; + this.setHtml = function(html) { + this.getElement().innerHTML = html; + }; + this.setPosition = function(x, y) { + this.getElement().style.left = x + "px"; + this.getElement().style.top = y + "px"; + }; + this.setClassName = function(className) { + dom.addCssClass(this.getElement(), className); + }; + this.show = function(text, x, y) { + if (text != null) + this.setText(text); + if (x != null && y != null) + this.setPosition(x, y); + if (!this.isOpen) { + this.getElement().style.display = "block"; + this.isOpen = true; + } + }; + + this.hide = function() { + if (this.isOpen) { + this.getElement().style.display = "none"; + this.isOpen = false; + } + }; + this.getHeight = function() { + return this.getElement().offsetHeight; + }; + this.getWidth = function() { + return this.getElement().offsetWidth; + }; + +}).call(Tooltip.prototype); + +exports.Tooltip = Tooltip; +}); + +ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var event = acequire("../lib/event"); +var Tooltip = acequire("../tooltip").Tooltip; + +function GutterHandler(mouseHandler) { + var editor = mouseHandler.editor; + var gutter = editor.renderer.$gutterLayer; + var tooltip = new GutterTooltip(editor.container); + + mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { + if (!editor.isFocused() || e.getButton() != 0) + return; + var gutterRegion = gutter.getRegion(e); + + if (gutterRegion == "foldWidgets") + return; + + var row = e.getDocumentPosition().row; + var selection = editor.session.selection; + + if (e.getShiftKey()) + selection.selectTo(row, 0); + else { + if (e.domEvent.detail == 2) { + editor.selectAll(); + return e.preventDefault(); + } + mouseHandler.$clickSelection = editor.selection.getLineRange(row); + } + mouseHandler.setState("selectByLines"); + mouseHandler.captureMouse(e); + return e.preventDefault(); + }); + + + var tooltipTimeout, mouseEvent, tooltipAnnotation; + + function showTooltip() { + var row = mouseEvent.getDocumentPosition().row; + var annotation = gutter.$annotations[row]; + if (!annotation) + return hideTooltip(); + + var maxRow = editor.session.getLength(); + if (row == maxRow) { + var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row; + var pos = mouseEvent.$pos; + if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column)) + return hideTooltip(); + } + + if (tooltipAnnotation == annotation) + return; + tooltipAnnotation = annotation.text.join("
"); + + tooltip.setHtml(tooltipAnnotation); + tooltip.show(); + editor._signal("showGutterTooltip", tooltip); + editor.on("mousewheel", hideTooltip); + + if (mouseHandler.$tooltipFollowsMouse) { + moveTooltip(mouseEvent); + } else { + var gutterElement = mouseEvent.domEvent.target; + var rect = gutterElement.getBoundingClientRect(); + var style = tooltip.getElement().style; + style.left = rect.right + "px"; + style.top = rect.bottom + "px"; + } + } + + function hideTooltip() { + if (tooltipTimeout) + tooltipTimeout = clearTimeout(tooltipTimeout); + if (tooltipAnnotation) { + tooltip.hide(); + tooltipAnnotation = null; + editor._signal("hideGutterTooltip", tooltip); + editor.removeEventListener("mousewheel", hideTooltip); + } + } + + function moveTooltip(e) { + tooltip.setPosition(e.x, e.y); + } + + mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) { + var target = e.domEvent.target || e.domEvent.srcElement; + if (dom.hasCssClass(target, "ace_fold-widget")) + return hideTooltip(); + + if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse) + moveTooltip(e); + + mouseEvent = e; + if (tooltipTimeout) + return; + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + if (mouseEvent && !mouseHandler.isMousePressed) + showTooltip(); + else + hideTooltip(); + }, 50); + }); + + event.addListener(editor.renderer.$gutter, "mouseout", function(e) { + mouseEvent = null; + if (!tooltipAnnotation || tooltipTimeout) + return; + + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + hideTooltip(); + }, 50); + }); + + editor.on("changeSession", hideTooltip); +} + +function GutterTooltip(parentNode) { + Tooltip.call(this, parentNode); +} + +oop.inherits(GutterTooltip, Tooltip); + +(function(){ + this.setPosition = function(x, y) { + var windowWidth = window.innerWidth || document.documentElement.clientWidth; + var windowHeight = window.innerHeight || document.documentElement.clientHeight; + var width = this.getWidth(); + var height = this.getHeight(); + x += 15; + y += 15; + if (x + width > windowWidth) { + x -= (x + width) - windowWidth; + } + if (y + height > windowHeight) { + y -= 20 + height; + } + Tooltip.prototype.setPosition.call(this, x, y); + }; + +}).call(GutterTooltip.prototype); + + + +exports.GutterHandler = GutterHandler; + +}); + +ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +var MouseEvent = exports.MouseEvent = function(domEvent, editor) { + this.domEvent = domEvent; + this.editor = editor; + + this.x = this.clientX = domEvent.clientX; + this.y = this.clientY = domEvent.clientY; + + this.$pos = null; + this.$inSelection = null; + + this.propagationStopped = false; + this.defaultPrevented = false; +}; + +(function() { + + this.stopPropagation = function() { + event.stopPropagation(this.domEvent); + this.propagationStopped = true; + }; + + this.preventDefault = function() { + event.preventDefault(this.domEvent); + this.defaultPrevented = true; + }; + + this.stop = function() { + this.stopPropagation(); + this.preventDefault(); + }; + this.getDocumentPosition = function() { + if (this.$pos) + return this.$pos; + + this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY); + return this.$pos; + }; + this.inSelection = function() { + if (this.$inSelection !== null) + return this.$inSelection; + + var editor = this.editor; + + + var selectionRange = editor.getSelectionRange(); + if (selectionRange.isEmpty()) + this.$inSelection = false; + else { + var pos = this.getDocumentPosition(); + this.$inSelection = selectionRange.contains(pos.row, pos.column); + } + + return this.$inSelection; + }; + this.getButton = function() { + return event.getButton(this.domEvent); + }; + this.getShiftKey = function() { + return this.domEvent.shiftKey; + }; + + this.getAccelKey = useragent.isMac + ? function() { return this.domEvent.metaKey; } + : function() { return this.domEvent.ctrlKey; }; + +}).call(MouseEvent.prototype); + +}); + +ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var AUTOSCROLL_DELAY = 200; +var SCROLL_CURSOR_DELAY = 200; +var SCROLL_CURSOR_HYSTERESIS = 5; + +function DragdropHandler(mouseHandler) { + + var editor = mouseHandler.editor; + + var blankImage = dom.createElement("img"); + blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (useragent.isOpera) + blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;"; + + var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler)); + + + var mouseTarget = editor.container; + var dragSelectionMarker, x, y; + var timerId, range; + var dragCursor, counter = 0; + var dragOperation; + var isInternal; + var autoScrollStartTime; + var cursorMovedTime; + var cursorPointOnCaretMoved; + + this.onDragStart = function(e) { + if (this.cancelDrag || !mouseTarget.draggable) { + var self = this; + setTimeout(function(){ + self.startSelect(); + self.captureMouse(e); + }, 0); + return e.preventDefault(); + } + range = editor.getSelectionRange(); + + var dataTransfer = e.dataTransfer; + dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove"; + if (useragent.isOpera) { + editor.container.appendChild(blankImage); + blankImage.scrollTop = 0; + } + dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0); + if (useragent.isOpera) { + editor.container.removeChild(blankImage); + } + dataTransfer.clearData(); + dataTransfer.setData("Text", editor.session.getTextRange()); + + isInternal = true; + this.setState("drag"); + }; + + this.onDragEnd = function(e) { + mouseTarget.draggable = false; + isInternal = false; + this.setState(null); + if (!editor.getReadOnly()) { + var dropEffect = e.dataTransfer.dropEffect; + if (!dragOperation && dropEffect == "move") + editor.session.remove(editor.getSelectionRange()); + editor.renderer.$cursorLayer.setBlinking(true); + } + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + }; + + this.onDragEnter = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) + addDragMarker(); + counter++; + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragOver = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) { + addDragMarker(); + counter++; + } + if (onMouseMoveTimer !== null) + onMouseMoveTimer = null; + + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragLeave = function(e) { + counter--; + if (counter <= 0 && dragSelectionMarker) { + clearDragMarker(); + dragOperation = null; + return event.preventDefault(e); + } + }; + + this.onDrop = function(e) { + if (!dragCursor) + return; + var dataTransfer = e.dataTransfer; + if (isInternal) { + switch (dragOperation) { + case "move": + if (range.contains(dragCursor.row, dragCursor.column)) { + range = { + start: dragCursor, + end: dragCursor + }; + } else { + range = editor.moveText(range, dragCursor); + } + break; + case "copy": + range = editor.moveText(range, dragCursor, true); + break; + } + } else { + var dropData = dataTransfer.getData('Text'); + range = { + start: dragCursor, + end: editor.session.insert(dragCursor, dropData) + }; + editor.focus(); + dragOperation = null; + } + clearDragMarker(); + return event.preventDefault(e); + }; + + event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler)); + event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler)); + event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler)); + event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler)); + event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler)); + event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler)); + + function scrollCursorIntoView(cursor, prevCursor) { + var now = Date.now(); + var vMovement = !prevCursor || cursor.row != prevCursor.row; + var hMovement = !prevCursor || cursor.column != prevCursor.column; + if (!cursorMovedTime || vMovement || hMovement) { + editor.$blockScrolling += 1; + editor.moveCursorToPosition(cursor); + editor.$blockScrolling -= 1; + cursorMovedTime = now; + cursorPointOnCaretMoved = {x: x, y: y}; + } else { + var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y); + if (distance > SCROLL_CURSOR_HYSTERESIS) { + cursorMovedTime = null; + } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) { + editor.renderer.scrollCursorIntoView(); + cursorMovedTime = null; + } + } + } + + function autoScroll(cursor, prevCursor) { + var now = Date.now(); + var lineHeight = editor.renderer.layerConfig.lineHeight; + var characterWidth = editor.renderer.layerConfig.characterWidth; + var editorRect = editor.renderer.scroller.getBoundingClientRect(); + var offsets = { + x: { + left: x - editorRect.left, + right: editorRect.right - x + }, + y: { + top: y - editorRect.top, + bottom: editorRect.bottom - y + } + }; + var nearestXOffset = Math.min(offsets.x.left, offsets.x.right); + var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom); + var scrollCursor = {row: cursor.row, column: cursor.column}; + if (nearestXOffset / characterWidth <= 2) { + scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2); + } + if (nearestYOffset / lineHeight <= 1) { + scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1); + } + var vScroll = cursor.row != scrollCursor.row; + var hScroll = cursor.column != scrollCursor.column; + var vMovement = !prevCursor || cursor.row != prevCursor.row; + if (vScroll || (hScroll && !vMovement)) { + if (!autoScrollStartTime) + autoScrollStartTime = now; + else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY) + editor.renderer.scrollCursorIntoView(scrollCursor); + } else { + autoScrollStartTime = null; + } + } + + function onDragInterval() { + var prevCursor = dragCursor; + dragCursor = editor.renderer.screenToTextCoordinates(x, y); + scrollCursorIntoView(dragCursor, prevCursor); + autoScroll(dragCursor, prevCursor); + } + + function addDragMarker() { + range = editor.selection.toOrientedRange(); + dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle()); + editor.clearSelection(); + if (editor.isFocused()) + editor.renderer.$cursorLayer.setBlinking(false); + clearInterval(timerId); + onDragInterval(); + timerId = setInterval(onDragInterval, 20); + counter = 0; + event.addListener(document, "mousemove", onMouseMove); + } + + function clearDragMarker() { + clearInterval(timerId); + editor.session.removeMarker(dragSelectionMarker); + dragSelectionMarker = null; + editor.$blockScrolling += 1; + editor.selection.fromOrientedRange(range); + editor.$blockScrolling -= 1; + if (editor.isFocused() && !isInternal) + editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly()); + range = null; + dragCursor = null; + counter = 0; + autoScrollStartTime = null; + cursorMovedTime = null; + event.removeListener(document, "mousemove", onMouseMove); + } + var onMouseMoveTimer = null; + function onMouseMove() { + if (onMouseMoveTimer == null) { + onMouseMoveTimer = setTimeout(function() { + if (onMouseMoveTimer != null && dragSelectionMarker) + clearDragMarker(); + }, 20); + } + } + + function canAccept(dataTransfer) { + var types = dataTransfer.types; + return !types || Array.prototype.some.call(types, function(type) { + return type == 'text/plain' || type == 'Text'; + }); + } + + function getDropEffect(e) { + var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized']; + var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized']; + + var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey; + var effectAllowed = "uninitialized"; + try { + effectAllowed = e.dataTransfer.effectAllowed.toLowerCase(); + } catch (e) {} + var dropEffect = "none"; + + if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + else if (moveAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "move"; + else if (copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + + return dropEffect; + } +} + +(function() { + + this.dragWait = function() { + var interval = Date.now() - this.mousedownEvent.time; + if (interval > this.editor.getDragDelay()) + this.startDrag(); + }; + + this.dragWaitEnd = function() { + var target = this.editor.container; + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + this.selectEnd(); + }; + + this.dragReadyEnd = function(e) { + this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()); + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + this.dragWaitEnd(); + }; + + this.startDrag = function(){ + this.cancelDrag = false; + var editor = this.editor; + var target = editor.container; + target.draggable = true; + editor.renderer.$cursorLayer.setBlinking(false); + editor.setStyle("ace_dragging"); + var cursorStyle = useragent.isWin ? "default" : "move"; + editor.renderer.setCursorStyle(cursorStyle); + this.setState("dragReady"); + }; + + this.onMouseDrag = function(e) { + var target = this.editor.container; + if (useragent.isIE && this.state == "dragReady") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 3) + target.dragDrop(); + } + if (this.state === "dragWait") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 0) { + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + } + } + }; + + this.onMouseDown = function(e) { + if (!this.$dragEnabled) + return; + this.mousedownEvent = e; + var editor = this.editor; + + var inSelection = e.inSelection(); + var button = e.getButton(); + var clickCount = e.domEvent.detail || 1; + if (clickCount === 1 && button === 0 && inSelection) { + if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey())) + return; + this.mousedownEvent.time = Date.now(); + var eventTarget = e.domEvent.target || e.domEvent.srcElement; + if ("unselectable" in eventTarget) + eventTarget.unselectable = "on"; + if (editor.getDragDelay()) { + if (useragent.isWebKit) { + this.cancelDrag = true; + var mouseTarget = editor.container; + mouseTarget.draggable = true; + } + this.setState("dragWait"); + } else { + this.startDrag(); + } + this.captureMouse(e, this.onMouseDrag.bind(this)); + e.defaultPrevented = true; + } + }; + +}).call(DragdropHandler.prototype); + + +function calcDistance(ax, ay, bx, by) { + return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); +} + +exports.DragdropHandler = DragdropHandler; + +}); + +ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("./dom"); + +exports.get = function (url, callback) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + callback(xhr.responseText); + } + }; + xhr.send(null); +}; + +exports.loadScript = function(path, callback) { + var head = dom.getDocumentHead(); + var s = document.createElement('script'); + + s.src = path; + head.appendChild(s); + + s.onload = s.onreadystatechange = function(_, isAbort) { + if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") { + s = s.onload = s.onreadystatechange = null; + if (!isAbort) + callback(); + } + }; +}; +exports.qualifyURL = function(url) { + var a = document.createElement('a'); + a.href = url; + return a.href; +} + +}); + +ace.define("ace/lib/event_emitter",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var EventEmitter = {}; +var stopPropagation = function() { this.propagationStopped = true; }; +var preventDefault = function() { this.defaultPrevented = true; }; + +EventEmitter._emit = +EventEmitter._dispatchEvent = function(eventName, e) { + this._eventRegistry || (this._eventRegistry = {}); + this._defaultHandlers || (this._defaultHandlers = {}); + + var listeners = this._eventRegistry[eventName] || []; + var defaultHandler = this._defaultHandlers[eventName]; + if (!listeners.length && !defaultHandler) + return; + + if (typeof e != "object" || !e) + e = {}; + + if (!e.type) + e.type = eventName; + if (!e.stopPropagation) + e.stopPropagation = stopPropagation; + if (!e.preventDefault) + e.preventDefault = preventDefault; + + listeners = listeners.slice(); + for (var i=0; i 1) + base = parts[parts.length - 2]; + var path = options[component + "Path"]; + if (path == null) { + path = options.basePath; + } else if (sep == "/") { + component = sep = ""; + } + if (path && path.slice(-1) != "/") + path += "/"; + return path + component + sep + base + this.get("suffix"); +}; + +exports.setModuleUrl = function(name, subst) { + return options.$moduleUrls[name] = subst; +}; + +exports.$loading = {}; +exports.loadModule = function(moduleName, onLoad) { + var module, moduleType; + if (Array.isArray(moduleName)) { + moduleType = moduleName[0]; + moduleName = moduleName[1]; + } + + try { + module = acequire(moduleName); + } catch (e) {} + if (module && !exports.$loading[moduleName]) + return onLoad && onLoad(module); + + if (!exports.$loading[moduleName]) + exports.$loading[moduleName] = []; + + exports.$loading[moduleName].push(onLoad); + + if (exports.$loading[moduleName].length > 1) + return; + + var afterLoad = function() { + acequire([moduleName], function(module) { + exports._emit("load.module", {name: moduleName, module: module}); + var listeners = exports.$loading[moduleName]; + exports.$loading[moduleName] = null; + listeners.forEach(function(onLoad) { + onLoad && onLoad(module); + }); + }); + }; + + if (!exports.get("packaged")) + return afterLoad(); + net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad); +}; +init(true);function init(packaged) { + + if (!global || !global.document) + return; + + options.packaged = packaged || acequire.packaged || module.packaged || (global.define && define.packaged); + + var scriptOptions = {}; + var scriptUrl = ""; + var currentScript = (document.currentScript || document._currentScript ); // native or polyfill + var currentDocument = currentScript && currentScript.ownerDocument || document; + + var scripts = currentDocument.getElementsByTagName("script"); + for (var i=0; i [" + this.end.row + "/" + this.end.column + "]"); + }; + + this.contains = function(row, column) { + return this.compare(row, column) == 0; + }; + this.compareRange = function(range) { + var cmp, + end = range.end, + start = range.start; + + cmp = this.compare(end.row, end.column); + if (cmp == 1) { + cmp = this.compare(start.row, start.column); + if (cmp == 1) { + return 2; + } else if (cmp == 0) { + return 1; + } else { + return 0; + } + } else if (cmp == -1) { + return -2; + } else { + cmp = this.compare(start.row, start.column); + if (cmp == -1) { + return -1; + } else if (cmp == 1) { + return 42; + } else { + return 0; + } + } + }; + this.comparePoint = function(p) { + return this.compare(p.row, p.column); + }; + this.containsRange = function(range) { + return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; + }; + this.intersects = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + }; + this.isEnd = function(row, column) { + return this.end.row == row && this.end.column == column; + }; + this.isStart = function(row, column) { + return this.start.row == row && this.start.column == column; + }; + this.setStart = function(row, column) { + if (typeof row == "object") { + this.start.column = row.column; + this.start.row = row.row; + } else { + this.start.row = row; + this.start.column = column; + } + }; + this.setEnd = function(row, column) { + if (typeof row == "object") { + this.end.column = row.column; + this.end.row = row.row; + } else { + this.end.row = row; + this.end.column = column; + } + }; + this.inside = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isEnd(row, column) || this.isStart(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.insideStart = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isEnd(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.insideEnd = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isStart(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.compare = function(row, column) { + if (!this.isMultiLine()) { + if (row === this.start.row) { + return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); + } + } + + if (row < this.start.row) + return -1; + + if (row > this.end.row) + return 1; + + if (this.start.row === row) + return column >= this.start.column ? 0 : -1; + + if (this.end.row === row) + return column <= this.end.column ? 0 : 1; + + return 0; + }; + this.compareStart = function(row, column) { + if (this.start.row == row && this.start.column == column) { + return -1; + } else { + return this.compare(row, column); + } + }; + this.compareEnd = function(row, column) { + if (this.end.row == row && this.end.column == column) { + return 1; + } else { + return this.compare(row, column); + } + }; + this.compareInside = function(row, column) { + if (this.end.row == row && this.end.column == column) { + return 1; + } else if (this.start.row == row && this.start.column == column) { + return -1; + } else { + return this.compare(row, column); + } + }; + this.clipRows = function(firstRow, lastRow) { + if (this.end.row > lastRow) + var end = {row: lastRow + 1, column: 0}; + else if (this.end.row < firstRow) + var end = {row: firstRow, column: 0}; + + if (this.start.row > lastRow) + var start = {row: lastRow + 1, column: 0}; + else if (this.start.row < firstRow) + var start = {row: firstRow, column: 0}; + + return Range.fromPoints(start || this.start, end || this.end); + }; + this.extend = function(row, column) { + var cmp = this.compare(row, column); + + if (cmp == 0) + return this; + else if (cmp == -1) + var start = {row: row, column: column}; + else + var end = {row: row, column: column}; + + return Range.fromPoints(start || this.start, end || this.end); + }; + + this.isEmpty = function() { + return (this.start.row === this.end.row && this.start.column === this.end.column); + }; + this.isMultiLine = function() { + return (this.start.row !== this.end.row); + }; + this.clone = function() { + return Range.fromPoints(this.start, this.end); + }; + this.collapseRows = function() { + if (this.end.column == 0) + return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) + else + return new Range(this.start.row, 0, this.end.row, 0) + }; + this.toScreenRange = function(session) { + var screenPosStart = session.documentToScreenPosition(this.start); + var screenPosEnd = session.documentToScreenPosition(this.end); + + return new Range( + screenPosStart.row, screenPosStart.column, + screenPosEnd.row, screenPosEnd.column + ); + }; + this.moveBy = function(row, column) { + this.start.row += row; + this.start.column += column; + this.end.row += row; + this.end.column += column; + }; + +}).call(Range.prototype); +Range.fromPoints = function(start, end) { + return new Range(start.row, start.column, end.row, end.column); +}; +Range.comparePoints = comparePoints; + +Range.comparePoints = function(p1, p2) { + return p1.row - p2.row || p1.column - p2.column; +}; + + +exports.Range = Range; +}); + +ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +var Selection = function(session) { + this.session = session; + this.doc = session.getDocument(); + + this.clearSelection(); + this.lead = this.selectionLead = this.doc.createAnchor(0, 0); + this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0); + + var self = this; + this.lead.on("change", function(e) { + self._emit("changeCursor"); + if (!self.$isEmpty) + self._emit("changeSelection"); + if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column) + self.$desiredColumn = null; + }); + + this.selectionAnchor.on("change", function() { + if (!self.$isEmpty) + self._emit("changeSelection"); + }); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.isEmpty = function() { + return (this.$isEmpty || ( + this.anchor.row == this.lead.row && + this.anchor.column == this.lead.column + )); + }; + this.isMultiLine = function() { + if (this.isEmpty()) { + return false; + } + + return this.getRange().isMultiLine(); + }; + this.getCursor = function() { + return this.lead.getPosition(); + }; + this.setSelectionAnchor = function(row, column) { + this.anchor.setPosition(row, column); + + if (this.$isEmpty) { + this.$isEmpty = false; + this._emit("changeSelection"); + } + }; + this.getSelectionAnchor = function() { + if (this.$isEmpty) + return this.getSelectionLead(); + else + return this.anchor.getPosition(); + }; + this.getSelectionLead = function() { + return this.lead.getPosition(); + }; + this.shiftSelection = function(columns) { + if (this.$isEmpty) { + this.moveCursorTo(this.lead.row, this.lead.column + columns); + return; + } + + var anchor = this.getSelectionAnchor(); + var lead = this.getSelectionLead(); + + var isBackwards = this.isBackwards(); + + if (!isBackwards || anchor.column !== 0) + this.setSelectionAnchor(anchor.row, anchor.column + columns); + + if (isBackwards || lead.column !== 0) { + this.$moveSelection(function() { + this.moveCursorTo(lead.row, lead.column + columns); + }); + } + }; + this.isBackwards = function() { + var anchor = this.anchor; + var lead = this.lead; + return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column)); + }; + this.getRange = function() { + var anchor = this.anchor; + var lead = this.lead; + + if (this.isEmpty()) + return Range.fromPoints(lead, lead); + + if (this.isBackwards()) { + return Range.fromPoints(lead, anchor); + } + else { + return Range.fromPoints(anchor, lead); + } + }; + this.clearSelection = function() { + if (!this.$isEmpty) { + this.$isEmpty = true; + this._emit("changeSelection"); + } + }; + this.selectAll = function() { + var lastRow = this.doc.getLength() - 1; + this.setSelectionAnchor(0, 0); + this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length); + }; + this.setRange = + this.setSelectionRange = function(range, reverse) { + if (reverse) { + this.setSelectionAnchor(range.end.row, range.end.column); + this.selectTo(range.start.row, range.start.column); + } else { + this.setSelectionAnchor(range.start.row, range.start.column); + this.selectTo(range.end.row, range.end.column); + } + if (this.getRange().isEmpty()) + this.$isEmpty = true; + this.$desiredColumn = null; + }; + + this.$moveSelection = function(mover) { + var lead = this.lead; + if (this.$isEmpty) + this.setSelectionAnchor(lead.row, lead.column); + + mover.call(this); + }; + this.selectTo = function(row, column) { + this.$moveSelection(function() { + this.moveCursorTo(row, column); + }); + }; + this.selectToPosition = function(pos) { + this.$moveSelection(function() { + this.moveCursorToPosition(pos); + }); + }; + this.moveTo = function(row, column) { + this.clearSelection(); + this.moveCursorTo(row, column); + }; + this.moveToPosition = function(pos) { + this.clearSelection(); + this.moveCursorToPosition(pos); + }; + this.selectUp = function() { + this.$moveSelection(this.moveCursorUp); + }; + this.selectDown = function() { + this.$moveSelection(this.moveCursorDown); + }; + this.selectRight = function() { + this.$moveSelection(this.moveCursorRight); + }; + this.selectLeft = function() { + this.$moveSelection(this.moveCursorLeft); + }; + this.selectLineStart = function() { + this.$moveSelection(this.moveCursorLineStart); + }; + this.selectLineEnd = function() { + this.$moveSelection(this.moveCursorLineEnd); + }; + this.selectFileEnd = function() { + this.$moveSelection(this.moveCursorFileEnd); + }; + this.selectFileStart = function() { + this.$moveSelection(this.moveCursorFileStart); + }; + this.selectWordRight = function() { + this.$moveSelection(this.moveCursorWordRight); + }; + this.selectWordLeft = function() { + this.$moveSelection(this.moveCursorWordLeft); + }; + this.getWordRange = function(row, column) { + if (typeof column == "undefined") { + var cursor = row || this.lead; + row = cursor.row; + column = cursor.column; + } + return this.session.getWordRange(row, column); + }; + this.selectWord = function() { + this.setSelectionRange(this.getWordRange()); + }; + this.selectAWord = function() { + var cursor = this.getCursor(); + var range = this.session.getAWordRange(cursor.row, cursor.column); + this.setSelectionRange(range); + }; + + this.getLineRange = function(row, excludeLastChar) { + var rowStart = typeof row == "number" ? row : this.lead.row; + var rowEnd; + + var foldLine = this.session.getFoldLine(rowStart); + if (foldLine) { + rowStart = foldLine.start.row; + rowEnd = foldLine.end.row; + } else { + rowEnd = rowStart; + } + if (excludeLastChar === true) + return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length); + else + return new Range(rowStart, 0, rowEnd + 1, 0); + }; + this.selectLine = function() { + this.setSelectionRange(this.getLineRange()); + }; + this.moveCursorUp = function() { + this.moveCursorBy(-1, 0); + }; + this.moveCursorDown = function() { + this.moveCursorBy(1, 0); + }; + this.moveCursorLeft = function() { + var cursor = this.lead.getPosition(), + fold; + + if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) { + this.moveCursorTo(fold.start.row, fold.start.column); + } else if (cursor.column === 0) { + if (cursor.row > 0) { + this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length); + } + } + else { + var tabSize = this.session.getTabSize(); + if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize) + this.moveCursorBy(0, -tabSize); + else + this.moveCursorBy(0, -1); + } + }; + this.moveCursorRight = function() { + var cursor = this.lead.getPosition(), + fold; + if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) { + this.moveCursorTo(fold.end.row, fold.end.column); + } + else if (this.lead.column == this.doc.getLine(this.lead.row).length) { + if (this.lead.row < this.doc.getLength() - 1) { + this.moveCursorTo(this.lead.row + 1, 0); + } + } + else { + var tabSize = this.session.getTabSize(); + var cursor = this.lead; + if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize) + this.moveCursorBy(0, tabSize); + else + this.moveCursorBy(0, 1); + } + }; + this.moveCursorLineStart = function() { + var row = this.lead.row; + var column = this.lead.column; + var screenRow = this.session.documentToScreenRow(row, column); + var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); + var beforeCursor = this.session.getDisplayLine( + row, null, firstColumnPosition.row, + firstColumnPosition.column + ); + + var leadingSpace = beforeCursor.match(/^\s*/); + if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart) + firstColumnPosition.column += leadingSpace[0].length; + this.moveCursorToPosition(firstColumnPosition); + }; + this.moveCursorLineEnd = function() { + var lead = this.lead; + var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); + if (this.lead.column == lineEnd.column) { + var line = this.session.getLine(lineEnd.row); + if (lineEnd.column == line.length) { + var textEnd = line.search(/\s+$/); + if (textEnd > 0) + lineEnd.column = textEnd; + } + } + + this.moveCursorTo(lineEnd.row, lineEnd.column); + }; + this.moveCursorFileEnd = function() { + var row = this.doc.getLength() - 1; + var column = this.doc.getLine(row).length; + this.moveCursorTo(row, column); + }; + this.moveCursorFileStart = function() { + this.moveCursorTo(0, 0); + }; + this.moveCursorLongWordRight = function() { + var row = this.lead.row; + var column = this.lead.column; + var line = this.doc.getLine(row); + var rightOfCursor = line.substring(column); + + var match; + this.session.nonTokenRe.lastIndex = 0; + this.session.tokenRe.lastIndex = 0; + var fold = this.session.getFoldAt(row, column, 1); + if (fold) { + this.moveCursorTo(fold.end.row, fold.end.column); + return; + } + if (match = this.session.nonTokenRe.exec(rightOfCursor)) { + column += this.session.nonTokenRe.lastIndex; + this.session.nonTokenRe.lastIndex = 0; + rightOfCursor = line.substring(column); + } + if (column >= line.length) { + this.moveCursorTo(row, line.length); + this.moveCursorRight(); + if (row < this.doc.getLength() - 1) + this.moveCursorWordRight(); + return; + } + if (match = this.session.tokenRe.exec(rightOfCursor)) { + column += this.session.tokenRe.lastIndex; + this.session.tokenRe.lastIndex = 0; + } + + this.moveCursorTo(row, column); + }; + this.moveCursorLongWordLeft = function() { + var row = this.lead.row; + var column = this.lead.column; + var fold; + if (fold = this.session.getFoldAt(row, column, -1)) { + this.moveCursorTo(fold.start.row, fold.start.column); + return; + } + + var str = this.session.getFoldStringAt(row, column, -1); + if (str == null) { + str = this.doc.getLine(row).substring(0, column); + } + + var leftOfCursor = lang.stringReverse(str); + var match; + this.session.nonTokenRe.lastIndex = 0; + this.session.tokenRe.lastIndex = 0; + if (match = this.session.nonTokenRe.exec(leftOfCursor)) { + column -= this.session.nonTokenRe.lastIndex; + leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex); + this.session.nonTokenRe.lastIndex = 0; + } + if (column <= 0) { + this.moveCursorTo(row, 0); + this.moveCursorLeft(); + if (row > 0) + this.moveCursorWordLeft(); + return; + } + if (match = this.session.tokenRe.exec(leftOfCursor)) { + column -= this.session.tokenRe.lastIndex; + this.session.tokenRe.lastIndex = 0; + } + + this.moveCursorTo(row, column); + }; + + this.$shortWordEndIndex = function(rightOfCursor) { + var match, index = 0, ch; + var whitespaceRe = /\s/; + var tokenRe = this.session.tokenRe; + + tokenRe.lastIndex = 0; + if (match = this.session.tokenRe.exec(rightOfCursor)) { + index = this.session.tokenRe.lastIndex; + } else { + while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) + index ++; + + if (index < 1) { + tokenRe.lastIndex = 0; + while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) { + tokenRe.lastIndex = 0; + index ++; + if (whitespaceRe.test(ch)) { + if (index > 2) { + index--; + break; + } else { + while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) + index ++; + if (index > 2) + break; + } + } + } + } + } + tokenRe.lastIndex = 0; + + return index; + }; + + this.moveCursorShortWordRight = function() { + var row = this.lead.row; + var column = this.lead.column; + var line = this.doc.getLine(row); + var rightOfCursor = line.substring(column); + + var fold = this.session.getFoldAt(row, column, 1); + if (fold) + return this.moveCursorTo(fold.end.row, fold.end.column); + + if (column == line.length) { + var l = this.doc.getLength(); + do { + row++; + rightOfCursor = this.doc.getLine(row); + } while (row < l && /^\s*$/.test(rightOfCursor)); + + if (!/^\s+/.test(rightOfCursor)) + rightOfCursor = ""; + column = 0; + } + + var index = this.$shortWordEndIndex(rightOfCursor); + + this.moveCursorTo(row, column + index); + }; + + this.moveCursorShortWordLeft = function() { + var row = this.lead.row; + var column = this.lead.column; + + var fold; + if (fold = this.session.getFoldAt(row, column, -1)) + return this.moveCursorTo(fold.start.row, fold.start.column); + + var line = this.session.getLine(row).substring(0, column); + if (column === 0) { + do { + row--; + line = this.doc.getLine(row); + } while (row > 0 && /^\s*$/.test(line)); + + column = line.length; + if (!/\s+$/.test(line)) + line = ""; + } + + var leftOfCursor = lang.stringReverse(line); + var index = this.$shortWordEndIndex(leftOfCursor); + + return this.moveCursorTo(row, column - index); + }; + + this.moveCursorWordRight = function() { + if (this.session.$selectLongWords) + this.moveCursorLongWordRight(); + else + this.moveCursorShortWordRight(); + }; + + this.moveCursorWordLeft = function() { + if (this.session.$selectLongWords) + this.moveCursorLongWordLeft(); + else + this.moveCursorShortWordLeft(); + }; + this.moveCursorBy = function(rows, chars) { + var screenPos = this.session.documentToScreenPosition( + this.lead.row, + this.lead.column + ); + + if (chars === 0) { + if (this.$desiredColumn) + screenPos.column = this.$desiredColumn; + else + this.$desiredColumn = screenPos.column; + } + + var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column); + + if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) { + if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) { + if (docPos.row > 0 || rows > 0) + docPos.row++; + } + } + this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0); + }; + this.moveCursorToPosition = function(position) { + this.moveCursorTo(position.row, position.column); + }; + this.moveCursorTo = function(row, column, keepDesiredColumn) { + var fold = this.session.getFoldAt(row, column, 1); + if (fold) { + row = fold.start.row; + column = fold.start.column; + } + + this.$keepDesiredColumnOnChange = true; + this.lead.setPosition(row, column); + this.$keepDesiredColumnOnChange = false; + + if (!keepDesiredColumn) + this.$desiredColumn = null; + }; + this.moveCursorToScreen = function(row, column, keepDesiredColumn) { + var pos = this.session.screenToDocumentPosition(row, column); + this.moveCursorTo(pos.row, pos.column, keepDesiredColumn); + }; + this.detach = function() { + this.lead.detach(); + this.anchor.detach(); + this.session = this.doc = null; + }; + + this.fromOrientedRange = function(range) { + this.setSelectionRange(range, range.cursor == range.start); + this.$desiredColumn = range.desiredColumn || this.$desiredColumn; + }; + + this.toOrientedRange = function(range) { + var r = this.getRange(); + if (range) { + range.start.column = r.start.column; + range.start.row = r.start.row; + range.end.column = r.end.column; + range.end.row = r.end.row; + } else { + range = r; + } + + range.cursor = this.isBackwards() ? range.start : range.end; + range.desiredColumn = this.$desiredColumn; + return range; + }; + this.getRangeOfMovements = function(func) { + var start = this.getCursor(); + try { + func(this); + var end = this.getCursor(); + return Range.fromPoints(start,end); + } catch(e) { + return Range.fromPoints(start,start); + } finally { + this.moveCursorToPosition(start); + } + }; + + this.toJSON = function() { + if (this.rangeCount) { + var data = this.ranges.map(function(r) { + var r1 = r.clone(); + r1.isBackwards = r.cursor == r.start; + return r1; + }); + } else { + var data = this.getRange(); + data.isBackwards = this.isBackwards(); + } + return data; + }; + + this.fromJSON = function(data) { + if (data.start == undefined) { + if (this.rangeList) { + this.toSingleRange(data[0]); + for (var i = data.length; i--; ) { + var r = Range.fromPoints(data[i].start, data[i].end); + if (data[i].isBackwards) + r.cursor = r.start; + this.addRange(r, true); + } + return; + } else + data = data[0]; + } + if (this.rangeList) + this.toSingleRange(data); + this.setSelectionRange(data, data.isBackwards); + }; + + this.isEqual = function(data) { + if ((data.length || this.rangeCount) && data.length != this.rangeCount) + return false; + if (!data.length || !this.ranges) + return this.getRange().isEqual(data); + + for (var i = this.ranges.length; i--; ) { + if (!this.ranges[i].isEqual(data[i])) + return false; + } + return true; + }; + +}).call(Selection.prototype); + +exports.Selection = Selection; +}); + +ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(acequire, exports, module) { +"use strict"; + +var config = acequire("./config"); +var MAX_TOKEN_COUNT = 2000; +var Tokenizer = function(rules) { + this.states = rules; + + this.regExps = {}; + this.matchMappings = {}; + for (var key in this.states) { + var state = this.states[key]; + var ruleRegExps = []; + var matchTotal = 0; + var mapping = this.matchMappings[key] = {defaultToken: "text"}; + var flag = "g"; + + var splitterRurles = []; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + if (rule.defaultToken) + mapping.defaultToken = rule.defaultToken; + if (rule.caseInsensitive) + flag = "gi"; + if (rule.regex == null) + continue; + + if (rule.regex instanceof RegExp) + rule.regex = rule.regex.toString().slice(1, -1); + var adjustedregex = rule.regex; + var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2; + if (Array.isArray(rule.token)) { + if (rule.token.length == 1 || matchcount == 1) { + rule.token = rule.token[0]; + } else if (matchcount - 1 != rule.token.length) { + this.reportError("number of classes and regexp groups doesn't match", { + rule: rule, + groupCount: matchcount - 1 + }); + rule.token = rule.token[0]; + } else { + rule.tokenArray = rule.token; + rule.token = null; + rule.onMatch = this.$arrayTokens; + } + } else if (typeof rule.token == "function" && !rule.onMatch) { + if (matchcount > 1) + rule.onMatch = this.$applyToken; + else + rule.onMatch = rule.token; + } + + if (matchcount > 1) { + if (/\\\d/.test(rule.regex)) { + adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) { + return "\\" + (parseInt(digit, 10) + matchTotal + 1); + }); + } else { + matchcount = 1; + adjustedregex = this.removeCapturingGroups(rule.regex); + } + if (!rule.splitRegex && typeof rule.token != "string") + splitterRurles.push(rule); // flag will be known only at the very end + } + + mapping[matchTotal] = i; + matchTotal += matchcount; + + ruleRegExps.push(adjustedregex); + if (!rule.onMatch) + rule.onMatch = null; + } + + if (!ruleRegExps.length) { + mapping[0] = 0; + ruleRegExps.push("$"); + } + + splitterRurles.forEach(function(rule) { + rule.splitRegex = this.createSplitterRegexp(rule.regex, flag); + }, this); + + this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag); + } +}; + +(function() { + this.$setMaxTokenCount = function(m) { + MAX_TOKEN_COUNT = m | 0; + }; + + this.$applyToken = function(str) { + var values = this.splitRegex.exec(str).slice(1); + var types = this.token.apply(this, values); + if (typeof types === "string") + return [{type: types, value: str}]; + + var tokens = []; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i]) + tokens[tokens.length] = { + type: types[i], + value: values[i] + }; + } + return tokens; + }; + + this.$arrayTokens = function(str) { + if (!str) + return []; + var values = this.splitRegex.exec(str); + if (!values) + return "text"; + var tokens = []; + var types = this.tokenArray; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i + 1]) + tokens[tokens.length] = { + type: types[i], + value: values[i + 1] + }; + } + return tokens; + }; + + this.removeCapturingGroups = function(src) { + var r = src.replace( + /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g, + function(x, y) {return y ? "(?:" : x;} + ); + return r; + }; + + this.createSplitterRegexp = function(src, flag) { + if (src.indexOf("(?=") != -1) { + var stack = 0; + var inChClass = false; + var lastCapture = {}; + src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function( + m, esc, parenOpen, parenClose, square, index + ) { + if (inChClass) { + inChClass = square != "]"; + } else if (square) { + inChClass = true; + } else if (parenClose) { + if (stack == lastCapture.stack) { + lastCapture.end = index+1; + lastCapture.stack = -1; + } + stack--; + } else if (parenOpen) { + stack++; + if (parenOpen.length != 1) { + lastCapture.stack = stack + lastCapture.start = index; + } + } + return m; + }); + + if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end))) + src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end); + } + if (src.charAt(0) != "^") src = "^" + src; + if (src.charAt(src.length - 1) != "$") src += "$"; + + return new RegExp(src, (flag||"").replace("g", "")); + }; + this.getLineTokens = function(line, startState) { + if (startState && typeof startState != "string") { + var stack = startState.slice(0); + startState = stack[0]; + if (startState === "#tmp") { + stack.shift() + startState = stack.shift() + } + } else + var stack = []; + + var currentState = startState || "start"; + var state = this.states[currentState]; + if (!state) { + currentState = "start"; + state = this.states[currentState]; + } + var mapping = this.matchMappings[currentState]; + var re = this.regExps[currentState]; + re.lastIndex = 0; + + var match, tokens = []; + var lastIndex = 0; + var matchAttempts = 0; + + var token = {type: null, value: ""}; + + while (match = re.exec(line)) { + var type = mapping.defaultToken; + var rule = null; + var value = match[0]; + var index = re.lastIndex; + + if (index - value.length > lastIndex) { + var skipped = line.substring(lastIndex, index - value.length); + if (token.type == type) { + token.value += skipped; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: skipped}; + } + } + + for (var i = 0; i < match.length-2; i++) { + if (match[i + 1] === undefined) + continue; + + rule = state[mapping[i]]; + + if (rule.onMatch) + type = rule.onMatch(value, currentState, stack); + else + type = rule.token; + + if (rule.next) { + if (typeof rule.next == "string") { + currentState = rule.next; + } else { + currentState = rule.next(currentState, stack); + } + + state = this.states[currentState]; + if (!state) { + this.reportError("state doesn't exist", currentState); + currentState = "start"; + state = this.states[currentState]; + } + mapping = this.matchMappings[currentState]; + lastIndex = index; + re = this.regExps[currentState]; + re.lastIndex = index; + } + break; + } + + if (value) { + if (typeof type === "string") { + if ((!rule || rule.merge !== false) && token.type === type) { + token.value += value; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: value}; + } + } else if (type) { + if (token.type) + tokens.push(token); + token = {type: null, value: ""}; + for (var i = 0; i < type.length; i++) + tokens.push(type[i]); + } + } + + if (lastIndex == line.length) + break; + + lastIndex = index; + + if (matchAttempts++ > MAX_TOKEN_COUNT) { + if (matchAttempts > 2 * line.length) { + this.reportError("infinite loop with in ace tokenizer", { + startState: startState, + line: line + }); + } + while (lastIndex < line.length) { + if (token.type) + tokens.push(token); + token = { + value: line.substring(lastIndex, lastIndex += 2000), + type: "overflow" + }; + } + currentState = "start"; + stack = []; + break; + } + } + + if (token.type) + tokens.push(token); + + if (stack.length > 1) { + if (stack[0] !== currentState) + stack.unshift("#tmp", currentState); + } + return { + tokens : tokens, + state : stack.length ? stack : currentState + }; + }; + + this.reportError = config.reportError; + +}).call(Tokenizer.prototype); + +exports.Tokenizer = Tokenizer; +}); + +ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); + +var TextHighlightRules = function() { + + this.$rules = { + "start" : [{ + token : "empty_line", + regex : '^$' + }, { + defaultToken : "text" + }] + }; +}; + +(function() { + + this.addRules = function(rules, prefix) { + if (!prefix) { + for (var key in rules) + this.$rules[key] = rules[key]; + return; + } + for (var key in rules) { + var state = rules[key]; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + if (rule.next || rule.onMatch) { + if (typeof rule.next == "string") { + if (rule.next.indexOf(prefix) !== 0) + rule.next = prefix + rule.next; + } + if (rule.nextState && rule.nextState.indexOf(prefix) !== 0) + rule.nextState = prefix + rule.nextState; + } + } + this.$rules[prefix + key] = state; + } + }; + + this.getRules = function() { + return this.$rules; + }; + + this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) { + var embedRules = typeof HighlightRules == "function" + ? new HighlightRules().getRules() + : HighlightRules; + if (states) { + for (var i = 0; i < states.length; i++) + states[i] = prefix + states[i]; + } else { + states = []; + for (var key in embedRules) + states.push(prefix + key); + } + + this.addRules(embedRules, prefix); + + if (escapeRules) { + var addRules = Array.prototype[append ? "push" : "unshift"]; + for (var i = 0; i < states.length; i++) + addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); + } + + if (!this.$embeds) + this.$embeds = []; + this.$embeds.push(prefix); + }; + + this.getEmbeds = function() { + return this.$embeds; + }; + + var pushState = function(currentState, stack) { + if (currentState != "start" || stack.length) + stack.unshift(this.nextState, currentState); + return this.nextState; + }; + var popState = function(currentState, stack) { + stack.shift(); + return stack.shift() || "start"; + }; + + this.normalizeRules = function() { + var id = 0; + var rules = this.$rules; + function processState(key) { + var state = rules[key]; + state.processed = true; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + var toInsert = null; + if (Array.isArray(rule)) { + toInsert = rule; + rule = {}; + } + if (!rule.regex && rule.start) { + rule.regex = rule.start; + if (!rule.next) + rule.next = []; + rule.next.push({ + defaultToken: rule.token + }, { + token: rule.token + ".end", + regex: rule.end || rule.start, + next: "pop" + }); + rule.token = rule.token + ".start"; + rule.push = true; + } + var next = rule.next || rule.push; + if (next && Array.isArray(next)) { + var stateName = rule.stateName; + if (!stateName) { + stateName = rule.token; + if (typeof stateName != "string") + stateName = stateName[0] || ""; + if (rules[stateName]) + stateName += id++; + } + rules[stateName] = next; + rule.next = stateName; + processState(stateName); + } else if (next == "pop") { + rule.next = popState; + } + + if (rule.push) { + rule.nextState = rule.next || rule.push; + rule.next = pushState; + delete rule.push; + } + + if (rule.rules) { + for (var r in rule.rules) { + if (rules[r]) { + if (rules[r].push) + rules[r].push.apply(rules[r], rule.rules[r]); + } else { + rules[r] = rule.rules[r]; + } + } + } + var includeName = typeof rule == "string" + ? rule + : typeof rule.include == "string" + ? rule.include + : ""; + if (includeName) { + toInsert = rules[includeName]; + } + + if (toInsert) { + var args = [i, 1].concat(toInsert); + if (rule.noEscape) + args = args.filter(function(x) {return !x.next;}); + state.splice.apply(state, args); + i--; + } + + if (rule.keywordMap) { + rule.token = this.createKeywordMapper( + rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive + ); + delete rule.defaultToken; + } + } + } + Object.keys(rules).forEach(processState, this); + }; + + this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) { + var keywords = Object.create(null); + Object.keys(map).forEach(function(className) { + var a = map[className]; + if (ignoreCase) + a = a.toLowerCase(); + var list = a.split(splitChar || "|"); + for (var i = list.length; i--; ) + keywords[list[i]] = className; + }); + if (Object.getPrototypeOf(keywords)) { + keywords.__proto__ = null; + } + this.$keywordList = Object.keys(keywords); + map = null; + return ignoreCase + ? function(value) {return keywords[value.toLowerCase()] || defaultToken } + : function(value) {return keywords[value] || defaultToken }; + }; + + this.getKeywords = function() { + return this.$keywords; + }; + +}).call(TextHighlightRules.prototype); + +exports.TextHighlightRules = TextHighlightRules; +}); + +ace.define("ace/mode/behaviour",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var Behaviour = function() { + this.$behaviours = {}; +}; + +(function () { + + this.add = function (name, action, callback) { + switch (undefined) { + case this.$behaviours: + this.$behaviours = {}; + case this.$behaviours[name]: + this.$behaviours[name] = {}; + } + this.$behaviours[name][action] = callback; + } + + this.addBehaviours = function (behaviours) { + for (var key in behaviours) { + for (var action in behaviours[key]) { + this.add(key, action, behaviours[key][action]); + } + } + } + + this.remove = function (name) { + if (this.$behaviours && this.$behaviours[name]) { + delete this.$behaviours[name]; + } + } + + this.inherit = function (mode, filter) { + if (typeof mode === "function") { + var behaviours = new mode().getBehaviours(filter); + } else { + var behaviours = mode.getBehaviours(filter); + } + this.addBehaviours(behaviours); + } + + this.getBehaviours = function (filter) { + if (!filter) { + return this.$behaviours; + } else { + var ret = {} + for (var i = 0; i < filter.length; i++) { + if (this.$behaviours[filter[i]]) { + ret[filter[i]] = this.$behaviours[filter[i]]; + } + } + return ret; + } + } + +}).call(Behaviour.prototype); + +exports.Behaviour = Behaviour; +}); + +ace.define("ace/token_iterator",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +var TokenIterator = function(session, initialRow, initialColumn) { + this.$session = session; + this.$row = initialRow; + this.$rowTokens = session.getTokens(initialRow); + + var token = session.getTokenAt(initialRow, initialColumn); + this.$tokenIndex = token ? token.index : -1; +}; + +(function() { + this.stepBackward = function() { + this.$tokenIndex -= 1; + + while (this.$tokenIndex < 0) { + this.$row -= 1; + if (this.$row < 0) { + this.$row = 0; + return null; + } + + this.$rowTokens = this.$session.getTokens(this.$row); + this.$tokenIndex = this.$rowTokens.length - 1; + } + + return this.$rowTokens[this.$tokenIndex]; + }; + this.stepForward = function() { + this.$tokenIndex += 1; + var rowCount; + while (this.$tokenIndex >= this.$rowTokens.length) { + this.$row += 1; + if (!rowCount) + rowCount = this.$session.getLength(); + if (this.$row >= rowCount) { + this.$row = rowCount - 1; + return null; + } + + this.$rowTokens = this.$session.getTokens(this.$row); + this.$tokenIndex = 0; + } + + return this.$rowTokens[this.$tokenIndex]; + }; + this.getCurrentToken = function () { + return this.$rowTokens[this.$tokenIndex]; + }; + this.getCurrentTokenRow = function () { + return this.$row; + }; + this.getCurrentTokenColumn = function() { + var rowTokens = this.$rowTokens; + var tokenIndex = this.$tokenIndex; + var column = rowTokens[tokenIndex].start; + if (column !== undefined) + return column; + + column = 0; + while (tokenIndex > 0) { + tokenIndex -= 1; + column += rowTokens[tokenIndex].value.length; + } + + return column; + }; + this.getCurrentTokenPosition = function() { + return {row: this.$row, column: this.getCurrentTokenColumn()}; + }; + +}).call(TokenIterator.prototype); + +exports.TokenIterator = TokenIterator; +}); + +ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +var SAFE_INSERT_IN_TOKENS = + ["text", "paren.rparen", "punctuation.operator"]; +var SAFE_INSERT_BEFORE_TOKENS = + ["text", "paren.rparen", "punctuation.operator", "comment"]; + +var context; +var contextCache = {}; +var initContext = function(editor) { + var id = -1; + if (editor.multiSelect) { + id = editor.selection.index; + if (contextCache.rangeCount != editor.multiSelect.rangeCount) + contextCache = {rangeCount: editor.multiSelect.rangeCount}; + } + if (contextCache[id]) + return context = contextCache[id]; + context = contextCache[id] = { + autoInsertedBrackets: 0, + autoInsertedRow: -1, + autoInsertedLineEnd: "", + maybeInsertedBrackets: 0, + maybeInsertedRow: -1, + maybeInsertedLineStart: "", + maybeInsertedLineEnd: "" + }; +}; + +var getWrapped = function(selection, selected, opening, closing) { + var rowDiff = selection.end.row - selection.start.row; + return { + text: opening + selected + closing, + selection: [ + 0, + selection.start.column + 1, + rowDiff, + selection.end.column + (rowDiff ? 0 : 1) + ] + }; +}; + +var CstyleBehaviour = function() { + this.add("braces", "insertion", function(state, action, editor, session, text) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (text == '{') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '{', '}'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { + CstyleBehaviour.recordAutoInsert(editor, session, "}"); + return { + text: '{}', + selection: [1, 1] + }; + } else { + CstyleBehaviour.recordMaybeInsert(editor, session, "{"); + return { + text: '{', + selection: [1, 1] + }; + } + } + } else if (text == '}') { + initContext(editor); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == '}') { + var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } else if (text == "\n" || text == "\r\n") { + initContext(editor); + var closing = ""; + if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { + closing = lang.stringRepeat("}", context.maybeInsertedBrackets); + CstyleBehaviour.clearMaybeInsertedClosing(); + } + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === '}') { + var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); + if (!openBracePos) + return null; + var next_indent = this.$getIndent(session.getLine(openBracePos.row)); + } else if (closing) { + var next_indent = this.$getIndent(line); + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + return; + } + var indent = next_indent + session.getTabString(); + + return { + text: '\n' + indent + '\n' + next_indent + closing, + selection: [1, indent.length, 1, indent.length] + }; + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + } + }); + + this.add("braces", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '{') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.end.column, range.end.column + 1); + if (rightChar == '}') { + range.end.column++; + return range; + } else { + context.maybeInsertedBrackets--; + } + } + }); + + this.add("parens", "insertion", function(state, action, editor, session, text) { + if (text == '(') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '(', ')'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, ")"); + return { + text: '()', + selection: [1, 1] + }; + } + } else if (text == ')') { + initContext(editor); + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == ')') { + var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("parens", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '(') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == ')') { + range.end.column++; + return range; + } + } + }); + + this.add("brackets", "insertion", function(state, action, editor, session, text) { + if (text == '[') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '[', ']'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, "]"); + return { + text: '[]', + selection: [1, 1] + }; + } + } else if (text == ']') { + initContext(editor); + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar == ']') { + var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); + if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("brackets", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '[') { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == ']') { + range.end.column++; + return range; + } + } + }); + + this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { + if (text == '"' || text == "'") { + if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1) + return; + initContext(editor); + var quote = text; + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, quote, quote); + } else if (!selected) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var leftChar = line.substring(cursor.column-1, cursor.column); + var rightChar = line.substring(cursor.column, cursor.column + 1); + + var token = session.getTokenAt(cursor.row, cursor.column); + var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); + if (leftChar == "\\" && token && /escape/.test(token.type)) + return null; + + var stringBefore = token && /string|escape/.test(token.type); + var stringAfter = !rightToken || /string|escape/.test(rightToken.type); + + var pair; + if (rightChar == quote) { + pair = stringBefore !== stringAfter; + if (pair && /string\.end/.test(rightToken.type)) + pair = false; + } else { + if (stringBefore && !stringAfter) + return null; // wrap string with different quote + if (stringBefore && stringAfter) + return null; // do not pair quotes inside strings + var wordRe = session.$mode.tokenRe; + wordRe.lastIndex = 0; + var isWordBefore = wordRe.test(leftChar); + wordRe.lastIndex = 0; + var isWordAfter = wordRe.test(leftChar); + if (isWordBefore || isWordAfter) + return null; // before or after alphanumeric + if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) + return null; // there is rightChar and it isn't closing + pair = true; + } + return { + text: pair ? quote + quote : "", + selection: [1,1] + }; + } + } + }); + + this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + +}; + + +CstyleBehaviour.isSaneInsertion = function(editor, session) { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { + var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); + if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) + return false; + } + iterator.stepForward(); + return iterator.getCurrentTokenRow() !== cursor.row || + this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); +}; + +CstyleBehaviour.$matchTokenType = function(token, types) { + return types.indexOf(token.type || token) > -1; +}; + +CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) + context.autoInsertedBrackets = 0; + context.autoInsertedRow = cursor.row; + context.autoInsertedLineEnd = bracket + line.substr(cursor.column); + context.autoInsertedBrackets++; +}; + +CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isMaybeInsertedClosing(cursor, line)) + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = cursor.row; + context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; + context.maybeInsertedLineEnd = line.substr(cursor.column); + context.maybeInsertedBrackets++; +}; + +CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { + return context.autoInsertedBrackets > 0 && + cursor.row === context.autoInsertedRow && + bracket === context.autoInsertedLineEnd[0] && + line.substr(cursor.column) === context.autoInsertedLineEnd; +}; + +CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { + return context.maybeInsertedBrackets > 0 && + cursor.row === context.maybeInsertedRow && + line.substr(cursor.column) === context.maybeInsertedLineEnd && + line.substr(0, cursor.column) == context.maybeInsertedLineStart; +}; + +CstyleBehaviour.popAutoInsertedClosing = function() { + context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); + context.autoInsertedBrackets--; +}; + +CstyleBehaviour.clearMaybeInsertedClosing = function() { + if (context) { + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = -1; + } +}; + + + +oop.inherits(CstyleBehaviour, Behaviour); + +exports.CstyleBehaviour = CstyleBehaviour; +}); + +ace.define("ace/unicode",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +exports.packages = {}; + +addUnicodePackage({ + L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", + Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A", + Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A", + Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC", + Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F", + Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", + M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26", + Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26", + Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC", + Me: "0488048906DE20DD-20E020E2-20E4A670-A672", + N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", + Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", + Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF", + No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835", + P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65", + Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D", + Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62", + Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63", + Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20", + Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21", + Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F", + Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65", + S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD", + Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC", + Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6", + Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3", + So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD", + Z: "002000A01680180E2000-200A20282029202F205F3000", + Zs: "002000A01680180E2000-200A202F205F3000", + Zl: "2028", + Zp: "2029", + C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF", + Cc: "0000-001F007F-009F", + Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB", + Co: "E000-F8FF", + Cs: "D800-DFFF", + Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF" +}); + +function addUnicodePackage (pack) { + var codePoint = /\w{4}/g; + for (var name in pack) + exports.packages[name] = pack[name].replace(codePoint, "\\u$&"); +} + +}); + +ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Tokenizer = acequire("../tokenizer").Tokenizer; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var unicode = acequire("../unicode"); +var lang = acequire("../lib/lang"); +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + +var Mode = function() { + this.HighlightRules = TextHighlightRules; +}; + +(function() { + this.$defaultBehaviour = new CstyleBehaviour(); + + this.tokenRe = new RegExp("^[" + + unicode.packages.L + + unicode.packages.Mn + unicode.packages.Mc + + unicode.packages.Nd + + unicode.packages.Pc + "\\$_]+", "g" + ); + + this.nonTokenRe = new RegExp("^(?:[^" + + unicode.packages.L + + unicode.packages.Mn + unicode.packages.Mc + + unicode.packages.Nd + + unicode.packages.Pc + "\\$_]|\\s])+", "g" + ); + + this.getTokenizer = function() { + if (!this.$tokenizer) { + this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig); + this.$tokenizer = new Tokenizer(this.$highlightRules.getRules()); + } + return this.$tokenizer; + }; + + this.lineCommentStart = ""; + this.blockComment = ""; + + this.toggleCommentLines = function(state, session, startRow, endRow) { + var doc = session.doc; + + var ignoreBlankLines = true; + var shouldRemove = true; + var minIndent = Infinity; + var tabSize = session.getTabSize(); + var insertAtTabStop = false; + + if (!this.lineCommentStart) { + if (!this.blockComment) + return false; + var lineCommentStart = this.blockComment.start; + var lineCommentEnd = this.blockComment.end; + var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")"); + var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$"); + + var comment = function(line, i) { + if (testRemove(line, i)) + return; + if (!ignoreBlankLines || /\S/.test(line)) { + doc.insertInLine({row: i, column: line.length}, lineCommentEnd); + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + + var uncomment = function(line, i) { + var m; + if (m = line.match(regexpEnd)) + doc.removeInLine(i, line.length - m[0].length, line.length); + if (m = line.match(regexpStart)) + doc.removeInLine(i, m[1].length, m[0].length); + }; + + var testRemove = function(line, row) { + if (regexpStart.test(line)) + return true; + var tokens = session.getTokens(row); + for (var i = 0; i < tokens.length; i++) { + if (tokens[i].type === "comment") + return true; + } + }; + } else { + if (Array.isArray(this.lineCommentStart)) { + var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); + var lineCommentStart = this.lineCommentStart[0]; + } else { + var regexpStart = lang.escapeRegExp(this.lineCommentStart); + var lineCommentStart = this.lineCommentStart; + } + regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?"); + + insertAtTabStop = session.getUseSoftTabs(); + + var uncomment = function(line, i) { + var m = line.match(regexpStart); + if (!m) return; + var start = m[1].length, end = m[0].length; + if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ") + end--; + doc.removeInLine(i, start, end); + }; + var commentWithSpace = lineCommentStart + " "; + var comment = function(line, i) { + if (!ignoreBlankLines || /\S/.test(line)) { + if (shouldInsertSpace(line, minIndent, minIndent)) + doc.insertInLine({row: i, column: minIndent}, commentWithSpace); + else + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + var testRemove = function(line, i) { + return regexpStart.test(line); + }; + + var shouldInsertSpace = function(line, before, after) { + var spaces = 0; + while (before-- && line.charAt(before) == " ") + spaces++; + if (spaces % tabSize != 0) + return false; + var spaces = 0; + while (line.charAt(after++) == " ") + spaces++; + if (tabSize > 2) + return spaces % tabSize != tabSize - 1; + else + return spaces % tabSize == 0; + return true; + }; + } + + function iter(fun) { + for (var i = startRow; i <= endRow; i++) + fun(doc.getLine(i), i); + } + + + var minEmptyLength = Infinity; + iter(function(line, i) { + var indent = line.search(/\S/); + if (indent !== -1) { + if (indent < minIndent) + minIndent = indent; + if (shouldRemove && !testRemove(line, i)) + shouldRemove = false; + } else if (minEmptyLength > line.length) { + minEmptyLength = line.length; + } + }); + + if (minIndent == Infinity) { + minIndent = minEmptyLength; + ignoreBlankLines = false; + shouldRemove = false; + } + + if (insertAtTabStop && minIndent % tabSize != 0) + minIndent = Math.floor(minIndent / tabSize) * tabSize; + + iter(shouldRemove ? uncomment : comment); + }; + + this.toggleBlockComment = function(state, session, range, cursor) { + var comment = this.blockComment; + if (!comment) + return; + if (!comment.start && comment[0]) + comment = comment[0]; + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + var sel = session.selection; + var initialRange = session.selection.toOrientedRange(); + var startRow, colDiff; + + if (token && /comment/.test(token.type)) { + var startRange, endRange; + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.start); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + startRange = new Range(row, column, row, column + comment.start.length); + break; + } + token = iterator.stepBackward(); + } + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.end); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + endRange = new Range(row, column, row, column + comment.end.length); + break; + } + token = iterator.stepForward(); + } + if (endRange) + session.remove(endRange); + if (startRange) { + session.remove(startRange); + startRow = startRange.start.row; + colDiff = -comment.start.length; + } + } else { + colDiff = comment.start.length; + startRow = range.start.row; + session.insert(range.end, comment.end); + session.insert(range.start, comment.start); + } + if (initialRange.start.row == startRow) + initialRange.start.column += colDiff; + if (initialRange.end.row == startRow) + initialRange.end.column += colDiff; + session.selection.fromOrientedRange(initialRange); + }; + + this.getNextLineIndent = function(state, line, tab) { + return this.$getIndent(line); + }; + + this.checkOutdent = function(state, line, input) { + return false; + }; + + this.autoOutdent = function(state, doc, row) { + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + + this.createWorker = function(session) { + return null; + }; + + this.createModeDelegates = function (mapping) { + this.$embeds = []; + this.$modes = {}; + for (var i in mapping) { + if (mapping[i]) { + this.$embeds.push(i); + this.$modes[i] = new mapping[i](); + } + } + + var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent", + "checkOutdent", "autoOutdent", "transformAction", "getCompletions"]; + + for (var i = 0; i < delegations.length; i++) { + (function(scope) { + var functionName = delegations[i]; + var defaultHandler = scope[functionName]; + scope[delegations[i]] = function() { + return this.$delegator(functionName, arguments, defaultHandler); + }; + }(this)); + } + }; + + this.$delegator = function(method, args, defaultHandler) { + var state = args[0]; + if (typeof state != "string") + state = state[0]; + for (var i = 0; i < this.$embeds.length; i++) { + if (!this.$modes[this.$embeds[i]]) continue; + + var split = state.split(this.$embeds[i]); + if (!split[0] && split[1]) { + args[0] = split[1]; + var mode = this.$modes[this.$embeds[i]]; + return mode[method].apply(mode, args); + } + } + var ret = defaultHandler.apply(this, args); + return defaultHandler ? ret : undefined; + }; + + this.transformAction = function(state, action, editor, session, param) { + if (this.$behaviour) { + var behaviours = this.$behaviour.getBehaviours(); + for (var key in behaviours) { + if (behaviours[key][action]) { + var ret = behaviours[key][action].apply(this, arguments); + if (ret) { + return ret; + } + } + } + } + }; + + this.getKeywords = function(append) { + if (!this.completionKeywords) { + var rules = this.$tokenizer.rules; + var completionKeywords = []; + for (var rule in rules) { + var ruleItr = rules[rule]; + for (var r = 0, l = ruleItr.length; r < l; r++) { + if (typeof ruleItr[r].token === "string") { + if (/keyword|support|storage/.test(ruleItr[r].token)) + completionKeywords.push(ruleItr[r].regex); + } + else if (typeof ruleItr[r].token === "object") { + for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) { + if (/keyword|support|storage/.test(ruleItr[r].token[a])) { + var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a]; + completionKeywords.push(rule.substr(1, rule.length - 2)); + } + } + } + } + } + this.completionKeywords = completionKeywords; + } + if (!append) + return this.$keywordList; + return completionKeywords.concat(this.$keywordList || []); + }; + + this.$createKeywordList = function() { + if (!this.$highlightRules) + this.getTokenizer(); + return this.$keywordList = this.$highlightRules.$keywordList || []; + }; + + this.getCompletions = function(state, session, pos, prefix) { + var keywords = this.$keywordList || this.$createKeywordList(); + return keywords.map(function(word) { + return { + name: word, + value: word, + score: 0, + meta: "keyword" + }; + }); + }; + + this.$id = "ace/mode/text"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/apply_delta",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +function throwDeltaError(delta, errorText){ + console.log("Invalid Delta:", delta); + throw "Invalid Delta: " + errorText; +} + +function positionInDocument(docLines, position) { + return position.row >= 0 && position.row < docLines.length && + position.column >= 0 && position.column <= docLines[position.row].length; +} + +function validateDelta(docLines, delta) { + if (delta.action != "insert" && delta.action != "remove") + throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); + if (!(delta.lines instanceof Array)) + throwDeltaError(delta, "delta.lines must be an Array"); + if (!delta.start || !delta.end) + throwDeltaError(delta, "delta.start/end must be an present"); + var start = delta.start; + if (!positionInDocument(docLines, delta.start)) + throwDeltaError(delta, "delta.start must be contained in document"); + var end = delta.end; + if (delta.action == "remove" && !positionInDocument(docLines, end)) + throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); + var numRangeRows = end.row - start.row; + var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); + if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) + throwDeltaError(delta, "delta.range must match delta lines"); +} + +exports.applyDelta = function(docLines, delta, doNotValidate) { + + var row = delta.start.row; + var startColumn = delta.start.column; + var line = docLines[row] || ""; + switch (delta.action) { + case "insert": + var lines = delta.lines; + if (lines.length === 1) { + docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); + } else { + var args = [row, 1].concat(delta.lines); + docLines.splice.apply(docLines, args); + docLines[row] = line.substring(0, startColumn) + docLines[row]; + docLines[row + delta.lines.length - 1] += line.substring(startColumn); + } + break; + case "remove": + var endColumn = delta.end.column; + var endRow = delta.end.row; + if (row === endRow) { + docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); + } else { + docLines.splice( + row, endRow - row + 1, + line.substring(0, startColumn) + docLines[endRow].substring(endColumn) + ); + } + break; + } +} +}); + +ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +var Anchor = exports.Anchor = function(doc, row, column) { + this.$onChange = this.onChange.bind(this); + this.attach(doc); + + if (typeof column == "undefined") + this.setPosition(row.row, row.column); + else + this.setPosition(row, column); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.getPosition = function() { + return this.$clipPositionToDocument(this.row, this.column); + }; + this.getDocument = function() { + return this.document; + }; + this.$insertRight = false; + this.onChange = function(delta) { + if (delta.start.row == delta.end.row && delta.start.row != this.row) + return; + + if (delta.start.row > this.row) + return; + + var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); + this.setPosition(point.row, point.column, true); + }; + + function $pointsInOrder(point1, point2, equalPointsInOrder) { + var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; + return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); + } + + function $getTransformedPoint(delta, point, moveIfEqual) { + var deltaIsInsert = delta.action == "insert"; + var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); + var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); + var deltaStart = delta.start; + var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. + if ($pointsInOrder(point, deltaStart, moveIfEqual)) { + return { + row: point.row, + column: point.column + }; + } + if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { + return { + row: point.row + deltaRowShift, + column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) + }; + } + + return { + row: deltaStart.row, + column: deltaStart.column + }; + } + this.setPosition = function(row, column, noClip) { + var pos; + if (noClip) { + pos = { + row: row, + column: column + }; + } else { + pos = this.$clipPositionToDocument(row, column); + } + + if (this.row == pos.row && this.column == pos.column) + return; + + var old = { + row: this.row, + column: this.column + }; + + this.row = pos.row; + this.column = pos.column; + this._signal("change", { + old: old, + value: pos + }); + }; + this.detach = function() { + this.document.removeEventListener("change", this.$onChange); + }; + this.attach = function(doc) { + this.document = doc || this.document; + this.document.on("change", this.$onChange); + }; + this.$clipPositionToDocument = function(row, column) { + var pos = {}; + + if (row >= this.document.getLength()) { + pos.row = Math.max(0, this.document.getLength() - 1); + pos.column = this.document.getLine(pos.row).length; + } + else if (row < 0) { + pos.row = 0; + pos.column = 0; + } + else { + pos.row = row; + pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); + } + + if (column < 0) + pos.column = 0; + + return pos; + }; + +}).call(Anchor.prototype); + +}); + +ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var applyDelta = acequire("./apply_delta").applyDelta; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +var Anchor = acequire("./anchor").Anchor; + +var Document = function(textOrLines) { + this.$lines = [""]; + if (textOrLines.length === 0) { + this.$lines = [""]; + } else if (Array.isArray(textOrLines)) { + this.insertMergedLines({row: 0, column: 0}, textOrLines); + } else { + this.insert({row: 0, column:0}, textOrLines); + } +}; + +(function() { + + oop.implement(this, EventEmitter); + this.setValue = function(text) { + var len = this.getLength() - 1; + this.remove(new Range(0, 0, len, this.getLine(len).length)); + this.insert({row: 0, column: 0}, text); + }; + this.getValue = function() { + return this.getAllLines().join(this.getNewLineCharacter()); + }; + this.createAnchor = function(row, column) { + return new Anchor(this, row, column); + }; + if ("aaa".split(/a/).length === 0) { + this.$split = function(text) { + return text.replace(/\r\n|\r/g, "\n").split("\n"); + }; + } else { + this.$split = function(text) { + return text.split(/\r\n|\r|\n/); + }; + } + + + this.$detectNewLine = function(text) { + var match = text.match(/^.*?(\r\n|\r|\n)/m); + this.$autoNewLine = match ? match[1] : "\n"; + this._signal("changeNewLineMode"); + }; + this.getNewLineCharacter = function() { + switch (this.$newLineMode) { + case "windows": + return "\r\n"; + case "unix": + return "\n"; + default: + return this.$autoNewLine || "\n"; + } + }; + + this.$autoNewLine = ""; + this.$newLineMode = "auto"; + this.setNewLineMode = function(newLineMode) { + if (this.$newLineMode === newLineMode) + return; + + this.$newLineMode = newLineMode; + this._signal("changeNewLineMode"); + }; + this.getNewLineMode = function() { + return this.$newLineMode; + }; + this.isNewLine = function(text) { + return (text == "\r\n" || text == "\r" || text == "\n"); + }; + this.getLine = function(row) { + return this.$lines[row] || ""; + }; + this.getLines = function(firstRow, lastRow) { + return this.$lines.slice(firstRow, lastRow + 1); + }; + this.getAllLines = function() { + return this.getLines(0, this.getLength()); + }; + this.getLength = function() { + return this.$lines.length; + }; + this.getTextRange = function(range) { + return this.getLinesForRange(range).join(this.getNewLineCharacter()); + }; + this.getLinesForRange = function(range) { + var lines; + if (range.start.row === range.end.row) { + lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; + } else { + lines = this.getLines(range.start.row, range.end.row); + lines[0] = (lines[0] || "").substring(range.start.column); + var l = lines.length - 1; + if (range.end.row - range.start.row == l) + lines[l] = lines[l].substring(0, range.end.column); + } + return lines; + }; + this.insertLines = function(row, lines) { + console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); + return this.insertFullLines(row, lines); + }; + this.removeLines = function(firstRow, lastRow) { + console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); + return this.removeFullLines(firstRow, lastRow); + }; + this.insertNewLine = function(position) { + console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); + return this.insertMergedLines(position, ["", ""]); + }; + this.insert = function(position, text) { + if (this.getLength() <= 1) + this.$detectNewLine(text); + + return this.insertMergedLines(position, this.$split(text)); + }; + this.insertInLine = function(position, text) { + var start = this.clippedPos(position.row, position.column); + var end = this.pos(position.row, position.column + text.length); + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: [text] + }, true); + + return this.clonePos(end); + }; + + this.clippedPos = function(row, column) { + var length = this.getLength(); + if (row === undefined) { + row = length; + } else if (row < 0) { + row = 0; + } else if (row >= length) { + row = length - 1; + column = undefined; + } + var line = this.getLine(row); + if (column == undefined) + column = line.length; + column = Math.min(Math.max(column, 0), line.length); + return {row: row, column: column}; + }; + + this.clonePos = function(pos) { + return {row: pos.row, column: pos.column}; + }; + + this.pos = function(row, column) { + return {row: row, column: column}; + }; + + this.$clipPosition = function(position) { + var length = this.getLength(); + if (position.row >= length) { + position.row = Math.max(0, length - 1); + position.column = this.getLine(length - 1).length; + } else { + position.row = Math.max(0, position.row); + position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); + } + return position; + }; + this.insertFullLines = function(row, lines) { + row = Math.min(Math.max(row, 0), this.getLength()); + var column = 0; + if (row < this.getLength()) { + lines = lines.concat([""]); + column = 0; + } else { + lines = [""].concat(lines); + row--; + column = this.$lines[row].length; + } + this.insertMergedLines({row: row, column: column}, lines); + }; + this.insertMergedLines = function(position, lines) { + var start = this.clippedPos(position.row, position.column); + var end = { + row: start.row + lines.length - 1, + column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length + }; + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: lines + }); + + return this.clonePos(end); + }; + this.remove = function(range) { + var start = this.clippedPos(range.start.row, range.start.column); + var end = this.clippedPos(range.end.row, range.end.column); + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }); + return this.clonePos(start); + }; + this.removeInLine = function(row, startColumn, endColumn) { + var start = this.clippedPos(row, startColumn); + var end = this.clippedPos(row, endColumn); + + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }, true); + + return this.clonePos(start); + }; + this.removeFullLines = function(firstRow, lastRow) { + firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); + lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); + var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; + var deleteLastNewLine = lastRow < this.getLength() - 1; + var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); + var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); + var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); + var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); + var range = new Range(startRow, startCol, endRow, endCol); + var deletedLines = this.$lines.slice(firstRow, lastRow + 1); + + this.applyDelta({ + start: range.start, + end: range.end, + action: "remove", + lines: this.getLinesForRange(range) + }); + return deletedLines; + }; + this.removeNewLine = function(row) { + if (row < this.getLength() - 1 && row >= 0) { + this.applyDelta({ + start: this.pos(row, this.getLine(row).length), + end: this.pos(row + 1, 0), + action: "remove", + lines: ["", ""] + }); + } + }; + this.replace = function(range, text) { + if (!(range instanceof Range)) + range = Range.fromPoints(range.start, range.end); + if (text.length === 0 && range.isEmpty()) + return range.start; + if (text == this.getTextRange(range)) + return range.end; + + this.remove(range); + var end; + if (text) { + end = this.insert(range.start, text); + } + else { + end = range.start; + } + + return end; + }; + this.applyDeltas = function(deltas) { + for (var i=0; i=0; i--) { + this.revertDelta(deltas[i]); + } + }; + this.applyDelta = function(delta, doNotValidate) { + var isInsert = delta.action == "insert"; + if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] + : !Range.comparePoints(delta.start, delta.end)) { + return; + } + + if (isInsert && delta.lines.length > 20000) + this.$splitAndapplyLargeDelta(delta, 20000); + applyDelta(this.$lines, delta, doNotValidate); + this._signal("change", delta); + }; + + this.$splitAndapplyLargeDelta = function(delta, MAX) { + var lines = delta.lines; + var l = lines.length; + var row = delta.start.row; + var column = delta.start.column; + var from = 0, to = 0; + do { + from = to; + to += MAX - 1; + var chunk = lines.slice(from, to); + if (to > l) { + delta.lines = chunk; + delta.start.row = row + from; + delta.start.column = column; + break; + } + chunk.push(""); + this.applyDelta({ + start: this.pos(row + from, column), + end: this.pos(row + to, column = 0), + action: delta.action, + lines: chunk + }, true); + } while(true); + }; + this.revertDelta = function(delta) { + this.applyDelta({ + start: this.clonePos(delta.start), + end: this.clonePos(delta.end), + action: (delta.action == "insert" ? "remove" : "insert"), + lines: delta.lines.slice() + }); + }; + this.indexToPosition = function(index, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + for (var i = startRow || 0, l = lines.length; i < l; i++) { + index -= lines[i].length + newlineLength; + if (index < 0) + return {row: i, column: index + lines[i].length + newlineLength}; + } + return {row: l-1, column: lines[l-1].length}; + }; + this.positionToIndex = function(pos, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + var index = 0; + var row = Math.min(pos.row, lines.length); + for (var i = startRow || 0; i < row; ++i) + index += lines[i].length + newlineLength; + + return index + pos.column; + }; + +}).call(Document.prototype); + +exports.Document = Document; +}); + +ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +var BackgroundTokenizer = function(tokenizer, editor) { + this.running = false; + this.lines = []; + this.states = []; + this.currentLine = 0; + this.tokenizer = tokenizer; + + var self = this; + + this.$worker = function() { + if (!self.running) { return; } + + var workerStart = new Date(); + var currentLine = self.currentLine; + var endLine = -1; + var doc = self.doc; + + var startLine = currentLine; + while (self.lines[currentLine]) + currentLine++; + + var len = doc.getLength(); + var processedLines = 0; + self.running = false; + while (currentLine < len) { + self.$tokenizeRow(currentLine); + endLine = currentLine; + do { + currentLine++; + } while (self.lines[currentLine]); + processedLines ++; + if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) { + self.running = setTimeout(self.$worker, 20); + break; + } + } + self.currentLine = currentLine; + + if (startLine <= endLine) + self.fireUpdateEvent(startLine, endLine); + }; +}; + +(function(){ + + oop.implement(this, EventEmitter); + this.setTokenizer = function(tokenizer) { + this.tokenizer = tokenizer; + this.lines = []; + this.states = []; + + this.start(0); + }; + this.setDocument = function(doc) { + this.doc = doc; + this.lines = []; + this.states = []; + + this.stop(); + }; + this.fireUpdateEvent = function(firstRow, lastRow) { + var data = { + first: firstRow, + last: lastRow + }; + this._signal("update", {data: data}); + }; + this.start = function(startRow) { + this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); + this.lines.splice(this.currentLine, this.lines.length); + this.states.splice(this.currentLine, this.states.length); + + this.stop(); + this.running = setTimeout(this.$worker, 700); + }; + + this.scheduleStart = function() { + if (!this.running) + this.running = setTimeout(this.$worker, 700); + } + + this.$updateOnChange = function(delta) { + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + this.lines[startRow] = null; + } else if (delta.action == "remove") { + this.lines.splice(startRow, len + 1, null); + this.states.splice(startRow, len + 1, null); + } else { + var args = Array(len + 1); + args.unshift(startRow, 1); + this.lines.splice.apply(this.lines, args); + this.states.splice.apply(this.states, args); + } + + this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength()); + + this.stop(); + }; + this.stop = function() { + if (this.running) + clearTimeout(this.running); + this.running = false; + }; + this.getTokens = function(row) { + return this.lines[row] || this.$tokenizeRow(row); + }; + this.getState = function(row) { + if (this.currentLine == row) + this.$tokenizeRow(row); + return this.states[row] || "start"; + }; + + this.$tokenizeRow = function(row) { + var line = this.doc.getLine(row); + var state = this.states[row - 1]; + + var data = this.tokenizer.getLineTokens(line, state, row); + + if (this.states[row] + "" !== data.state + "") { + this.states[row] = data.state; + this.lines[row + 1] = null; + if (this.currentLine > row + 1) + this.currentLine = row + 1; + } else if (this.currentLine == row) { + this.currentLine = row + 1; + } + + return this.lines[row] = data.tokens; + }; + +}).call(BackgroundTokenizer.prototype); + +exports.BackgroundTokenizer = BackgroundTokenizer; +}); + +ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var SearchHighlight = function(regExp, clazz, type) { + this.setRegexp(regExp); + this.clazz = clazz; + this.type = type || "text"; +}; + +(function() { + this.MAX_RANGES = 500; + + this.setRegexp = function(regExp) { + if (this.regExp+"" == regExp+"") + return; + this.regExp = regExp; + this.cache = []; + }; + + this.update = function(html, markerLayer, session, config) { + if (!this.regExp) + return; + var start = config.firstRow, end = config.lastRow; + + for (var i = start; i <= end; i++) { + var ranges = this.cache[i]; + if (ranges == null) { + ranges = lang.getMatchOffsets(session.getLine(i), this.regExp); + if (ranges.length > this.MAX_RANGES) + ranges = ranges.slice(0, this.MAX_RANGES); + ranges = ranges.map(function(match) { + return new Range(i, match.offset, i, match.offset + match.length); + }); + this.cache[i] = ranges.length ? ranges : ""; + } + + for (var j = ranges.length; j --; ) { + markerLayer.drawSingleLineMarker( + html, ranges[j].toScreenRange(session), this.clazz, config); + } + } + }; + +}).call(SearchHighlight.prototype); + +exports.SearchHighlight = SearchHighlight; +}); + +ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +function FoldLine(foldData, folds) { + this.foldData = foldData; + if (Array.isArray(folds)) { + this.folds = folds; + } else { + folds = this.folds = [ folds ]; + } + + var last = folds[folds.length - 1]; + this.range = new Range(folds[0].start.row, folds[0].start.column, + last.end.row, last.end.column); + this.start = this.range.start; + this.end = this.range.end; + + this.folds.forEach(function(fold) { + fold.setFoldLine(this); + }, this); +} + +(function() { + this.shiftRow = function(shift) { + this.start.row += shift; + this.end.row += shift; + this.folds.forEach(function(fold) { + fold.start.row += shift; + fold.end.row += shift; + }); + }; + + this.addFold = function(fold) { + if (fold.sameRow) { + if (fold.start.row < this.startRow || fold.endRow > this.endRow) { + throw new Error("Can't add a fold to this FoldLine as it has no connection"); + } + this.folds.push(fold); + this.folds.sort(function(a, b) { + return -a.range.compareEnd(b.start.row, b.start.column); + }); + if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) { + this.end.row = fold.end.row; + this.end.column = fold.end.column; + } else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) { + this.start.row = fold.start.row; + this.start.column = fold.start.column; + } + } else if (fold.start.row == this.end.row) { + this.folds.push(fold); + this.end.row = fold.end.row; + this.end.column = fold.end.column; + } else if (fold.end.row == this.start.row) { + this.folds.unshift(fold); + this.start.row = fold.start.row; + this.start.column = fold.start.column; + } else { + throw new Error("Trying to add fold to FoldRow that doesn't have a matching row"); + } + fold.foldLine = this; + }; + + this.containsRow = function(row) { + return row >= this.start.row && row <= this.end.row; + }; + + this.walk = function(callback, endRow, endColumn) { + var lastEnd = 0, + folds = this.folds, + fold, + cmp, stop, isNewRow = true; + + if (endRow == null) { + endRow = this.end.row; + endColumn = this.end.column; + } + + for (var i = 0; i < folds.length; i++) { + fold = folds[i]; + + cmp = fold.range.compareStart(endRow, endColumn); + if (cmp == -1) { + callback(null, endRow, endColumn, lastEnd, isNewRow); + return; + } + + stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow); + stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd); + if (stop || cmp === 0) { + return; + } + isNewRow = !fold.sameRow; + lastEnd = fold.end.column; + } + callback(null, endRow, endColumn, lastEnd, isNewRow); + }; + + this.getNextFoldTo = function(row, column) { + var fold, cmp; + for (var i = 0; i < this.folds.length; i++) { + fold = this.folds[i]; + cmp = fold.range.compareEnd(row, column); + if (cmp == -1) { + return { + fold: fold, + kind: "after" + }; + } else if (cmp === 0) { + return { + fold: fold, + kind: "inside" + }; + } + } + return null; + }; + + this.addRemoveChars = function(row, column, len) { + var ret = this.getNextFoldTo(row, column), + fold, folds; + if (ret) { + fold = ret.fold; + if (ret.kind == "inside" + && fold.start.column != column + && fold.start.row != row) + { + window.console && window.console.log(row, column, fold); + } else if (fold.start.row == row) { + folds = this.folds; + var i = folds.indexOf(fold); + if (i === 0) { + this.start.column += len; + } + for (i; i < folds.length; i++) { + fold = folds[i]; + fold.start.column += len; + if (!fold.sameRow) { + return; + } + fold.end.column += len; + } + this.end.column += len; + } + } + }; + + this.split = function(row, column) { + var pos = this.getNextFoldTo(row, column); + + if (!pos || pos.kind == "inside") + return null; + + var fold = pos.fold; + var folds = this.folds; + var foldData = this.foldData; + + var i = folds.indexOf(fold); + var foldBefore = folds[i - 1]; + this.end.row = foldBefore.end.row; + this.end.column = foldBefore.end.column; + folds = folds.splice(i, folds.length - i); + + var newFoldLine = new FoldLine(foldData, folds); + foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine); + return newFoldLine; + }; + + this.merge = function(foldLineNext) { + var folds = foldLineNext.folds; + for (var i = 0; i < folds.length; i++) { + this.addFold(folds[i]); + } + var foldData = this.foldData; + foldData.splice(foldData.indexOf(foldLineNext), 1); + }; + + this.toString = function() { + var ret = [this.range.toString() + ": [" ]; + + this.folds.forEach(function(fold) { + ret.push(" " + fold.toString()); + }); + ret.push("]"); + return ret.join("\n"); + }; + + this.idxToPosition = function(idx) { + var lastFoldEndColumn = 0; + + for (var i = 0; i < this.folds.length; i++) { + var fold = this.folds[i]; + + idx -= fold.start.column - lastFoldEndColumn; + if (idx < 0) { + return { + row: fold.start.row, + column: fold.start.column + idx + }; + } + + idx -= fold.placeholder.length; + if (idx < 0) { + return fold.start; + } + + lastFoldEndColumn = fold.end.column; + } + + return { + row: this.end.row, + column: this.end.column + idx + }; + }; +}).call(FoldLine.prototype); + +exports.FoldLine = FoldLine; +}); + +ace.define("ace/range_list",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; +var Range = acequire("./range").Range; +var comparePoints = Range.comparePoints; + +var RangeList = function() { + this.ranges = []; +}; + +(function() { + this.comparePoints = comparePoints; + + this.pointIndex = function(pos, excludeEdges, startIndex) { + var list = this.ranges; + + for (var i = startIndex || 0; i < list.length; i++) { + var range = list[i]; + var cmpEnd = comparePoints(pos, range.end); + if (cmpEnd > 0) + continue; + var cmpStart = comparePoints(pos, range.start); + if (cmpEnd === 0) + return excludeEdges && cmpStart !== 0 ? -i-2 : i; + if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges)) + return i; + + return -i-1; + } + return -i - 1; + }; + + this.add = function(range) { + var excludeEdges = !range.isEmpty(); + var startIndex = this.pointIndex(range.start, excludeEdges); + if (startIndex < 0) + startIndex = -startIndex - 1; + + var endIndex = this.pointIndex(range.end, excludeEdges, startIndex); + + if (endIndex < 0) + endIndex = -endIndex - 1; + else + endIndex++; + return this.ranges.splice(startIndex, endIndex - startIndex, range); + }; + + this.addList = function(list) { + var removed = []; + for (var i = list.length; i--; ) { + removed.push.apply(removed, this.add(list[i])); + } + return removed; + }; + + this.substractPoint = function(pos) { + var i = this.pointIndex(pos); + + if (i >= 0) + return this.ranges.splice(i, 1); + }; + this.merge = function() { + var removed = []; + var list = this.ranges; + + list = list.sort(function(a, b) { + return comparePoints(a.start, b.start); + }); + + var next = list[0], range; + for (var i = 1; i < list.length; i++) { + range = next; + next = list[i]; + var cmp = comparePoints(range.end, next.start); + if (cmp < 0) + continue; + + if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) + continue; + + if (comparePoints(range.end, next.end) < 0) { + range.end.row = next.end.row; + range.end.column = next.end.column; + } + + list.splice(i, 1); + removed.push(next); + next = range; + i--; + } + + this.ranges = list; + + return removed; + }; + + this.contains = function(row, column) { + return this.pointIndex({row: row, column: column}) >= 0; + }; + + this.containsPoint = function(pos) { + return this.pointIndex(pos) >= 0; + }; + + this.rangeAtPoint = function(pos) { + var i = this.pointIndex(pos); + if (i >= 0) + return this.ranges[i]; + }; + + + this.clipRows = function(startRow, endRow) { + var list = this.ranges; + if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow) + return []; + + var startIndex = this.pointIndex({row: startRow, column: 0}); + if (startIndex < 0) + startIndex = -startIndex - 1; + var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex); + if (endIndex < 0) + endIndex = -endIndex - 1; + + var clipped = []; + for (var i = startIndex; i < endIndex; i++) { + clipped.push(list[i]); + } + return clipped; + }; + + this.removeAll = function() { + return this.ranges.splice(0, this.ranges.length); + }; + + this.attach = function(session) { + if (this.session) + this.detach(); + + this.session = session; + this.onChange = this.$onChange.bind(this); + + this.session.on('change', this.onChange); + }; + + this.detach = function() { + if (!this.session) + return; + this.session.removeListener('change', this.onChange); + this.session = null; + }; + + this.$onChange = function(delta) { + if (delta.action == "insert"){ + var start = delta.start; + var end = delta.end; + } else { + var end = delta.start; + var start = delta.end; + } + var startRow = start.row; + var endRow = end.row; + var lineDif = endRow - startRow; + + var colDiff = -start.column + end.column; + var ranges = this.ranges; + + for (var i = 0, n = ranges.length; i < n; i++) { + var r = ranges[i]; + if (r.end.row < startRow) + continue; + if (r.start.row > startRow) + break; + + if (r.start.row == startRow && r.start.column >= start.column ) { + if (r.start.column == start.column && this.$insertRight) { + } else { + r.start.column += colDiff; + r.start.row += lineDif; + } + } + if (r.end.row == startRow && r.end.column >= start.column) { + if (r.end.column == start.column && this.$insertRight) { + continue; + } + if (r.end.column == start.column && colDiff > 0 && i < n - 1) { + if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column) + r.end.column -= colDiff; + } + r.end.column += colDiff; + r.end.row += lineDif; + } + } + + if (lineDif != 0 && i < n) { + for (; i < n; i++) { + var r = ranges[i]; + r.start.row += lineDif; + r.end.row += lineDif; + } + } + }; + +}).call(RangeList.prototype); + +exports.RangeList = RangeList; +}); + +ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var RangeList = acequire("../range_list").RangeList; +var oop = acequire("../lib/oop") +var Fold = exports.Fold = function(range, placeholder) { + this.foldLine = null; + this.placeholder = placeholder; + this.range = range; + this.start = range.start; + this.end = range.end; + + this.sameRow = range.start.row == range.end.row; + this.subFolds = this.ranges = []; +}; + +oop.inherits(Fold, RangeList); + +(function() { + + this.toString = function() { + return '"' + this.placeholder + '" ' + this.range.toString(); + }; + + this.setFoldLine = function(foldLine) { + this.foldLine = foldLine; + this.subFolds.forEach(function(fold) { + fold.setFoldLine(foldLine); + }); + }; + + this.clone = function() { + var range = this.range.clone(); + var fold = new Fold(range, this.placeholder); + this.subFolds.forEach(function(subFold) { + fold.subFolds.push(subFold.clone()); + }); + fold.collapseChildren = this.collapseChildren; + return fold; + }; + + this.addSubFold = function(fold) { + if (this.range.isEqual(fold)) + return; + + if (!this.range.containsRange(fold)) + throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); + consumeRange(fold, this.start); + + var row = fold.start.row, column = fold.start.column; + for (var i = 0, cmp = -1; i < this.subFolds.length; i++) { + cmp = this.subFolds[i].range.compare(row, column); + if (cmp != 1) + break; + } + var afterStart = this.subFolds[i]; + + if (cmp == 0) + return afterStart.addSubFold(fold); + var row = fold.range.end.row, column = fold.range.end.column; + for (var j = i, cmp = -1; j < this.subFolds.length; j++) { + cmp = this.subFolds[j].range.compare(row, column); + if (cmp != 1) + break; + } + var afterEnd = this.subFolds[j]; + + if (cmp == 0) + throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); + + var consumedFolds = this.subFolds.splice(i, j - i, fold); + fold.setFoldLine(this.foldLine); + + return fold; + }; + + this.restoreRange = function(range) { + return restoreRange(range, this.start); + }; + +}).call(Fold.prototype); + +function consumePoint(point, anchor) { + point.row -= anchor.row; + if (point.row == 0) + point.column -= anchor.column; +} +function consumeRange(range, anchor) { + consumePoint(range.start, anchor); + consumePoint(range.end, anchor); +} +function restorePoint(point, anchor) { + if (point.row == 0) + point.column += anchor.column; + point.row += anchor.row; +} +function restoreRange(range, anchor) { + restorePoint(range.start, anchor); + restorePoint(range.end, anchor); +} + +}); + +ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var FoldLine = acequire("./fold_line").FoldLine; +var Fold = acequire("./fold").Fold; +var TokenIterator = acequire("../token_iterator").TokenIterator; + +function Folding() { + this.getFoldAt = function(row, column, side) { + var foldLine = this.getFoldLine(row); + if (!foldLine) + return null; + + var folds = foldLine.folds; + for (var i = 0; i < folds.length; i++) { + var fold = folds[i]; + if (fold.range.contains(row, column)) { + if (side == 1 && fold.range.isEnd(row, column)) { + continue; + } else if (side == -1 && fold.range.isStart(row, column)) { + continue; + } + return fold; + } + } + }; + this.getFoldsInRange = function(range) { + var start = range.start; + var end = range.end; + var foldLines = this.$foldData; + var foundFolds = []; + + start.column += 1; + end.column -= 1; + + for (var i = 0; i < foldLines.length; i++) { + var cmp = foldLines[i].range.compareRange(range); + if (cmp == 2) { + continue; + } + else if (cmp == -2) { + break; + } + + var folds = foldLines[i].folds; + for (var j = 0; j < folds.length; j++) { + var fold = folds[j]; + cmp = fold.range.compareRange(range); + if (cmp == -2) { + break; + } else if (cmp == 2) { + continue; + } else + if (cmp == 42) { + break; + } + foundFolds.push(fold); + } + } + start.column -= 1; + end.column += 1; + + return foundFolds; + }; + + this.getFoldsInRangeList = function(ranges) { + if (Array.isArray(ranges)) { + var folds = []; + ranges.forEach(function(range) { + folds = folds.concat(this.getFoldsInRange(range)); + }, this); + } else { + var folds = this.getFoldsInRange(ranges); + } + return folds; + }; + this.getAllFolds = function() { + var folds = []; + var foldLines = this.$foldData; + + for (var i = 0; i < foldLines.length; i++) + for (var j = 0; j < foldLines[i].folds.length; j++) + folds.push(foldLines[i].folds[j]); + + return folds; + }; + this.getFoldStringAt = function(row, column, trim, foldLine) { + foldLine = foldLine || this.getFoldLine(row); + if (!foldLine) + return null; + + var lastFold = { + end: { column: 0 } + }; + var str, fold; + for (var i = 0; i < foldLine.folds.length; i++) { + fold = foldLine.folds[i]; + var cmp = fold.range.compareEnd(row, column); + if (cmp == -1) { + str = this + .getLine(fold.start.row) + .substring(lastFold.end.column, fold.start.column); + break; + } + else if (cmp === 0) { + return null; + } + lastFold = fold; + } + if (!str) + str = this.getLine(fold.start.row).substring(lastFold.end.column); + + if (trim == -1) + return str.substring(0, column - lastFold.end.column); + else if (trim == 1) + return str.substring(column - lastFold.end.column); + else + return str; + }; + + this.getFoldLine = function(docRow, startFoldLine) { + var foldData = this.$foldData; + var i = 0; + if (startFoldLine) + i = foldData.indexOf(startFoldLine); + if (i == -1) + i = 0; + for (i; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) { + return foldLine; + } else if (foldLine.end.row > docRow) { + return null; + } + } + return null; + }; + this.getNextFoldLine = function(docRow, startFoldLine) { + var foldData = this.$foldData; + var i = 0; + if (startFoldLine) + i = foldData.indexOf(startFoldLine); + if (i == -1) + i = 0; + for (i; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (foldLine.end.row >= docRow) { + return foldLine; + } + } + return null; + }; + + this.getFoldedRowCount = function(first, last) { + var foldData = this.$foldData, rowCount = last-first+1; + for (var i = 0; i < foldData.length; i++) { + var foldLine = foldData[i], + end = foldLine.end.row, + start = foldLine.start.row; + if (end >= last) { + if (start < last) { + if (start >= first) + rowCount -= last-start; + else + rowCount = 0; // in one fold + } + break; + } else if (end >= first){ + if (start >= first) // fold inside range + rowCount -= end-start; + else + rowCount -= end-first+1; + } + } + return rowCount; + }; + + this.$addFoldLine = function(foldLine) { + this.$foldData.push(foldLine); + this.$foldData.sort(function(a, b) { + return a.start.row - b.start.row; + }); + return foldLine; + }; + this.addFold = function(placeholder, range) { + var foldData = this.$foldData; + var added = false; + var fold; + + if (placeholder instanceof Fold) + fold = placeholder; + else { + fold = new Fold(range, placeholder); + fold.collapseChildren = range.collapseChildren; + } + this.$clipRangeToDocument(fold.range); + + var startRow = fold.start.row; + var startColumn = fold.start.column; + var endRow = fold.end.row; + var endColumn = fold.end.column; + if (!(startRow < endRow || + startRow == endRow && startColumn <= endColumn - 2)) + throw new Error("The range has to be at least 2 characters width"); + + var startFold = this.getFoldAt(startRow, startColumn, 1); + var endFold = this.getFoldAt(endRow, endColumn, -1); + if (startFold && endFold == startFold) + return startFold.addSubFold(fold); + + if (startFold && !startFold.range.isStart(startRow, startColumn)) + this.removeFold(startFold); + + if (endFold && !endFold.range.isEnd(endRow, endColumn)) + this.removeFold(endFold); + var folds = this.getFoldsInRange(fold.range); + if (folds.length > 0) { + this.removeFolds(folds); + folds.forEach(function(subFold) { + fold.addSubFold(subFold); + }); + } + + for (var i = 0; i < foldData.length; i++) { + var foldLine = foldData[i]; + if (endRow == foldLine.start.row) { + foldLine.addFold(fold); + added = true; + break; + } else if (startRow == foldLine.end.row) { + foldLine.addFold(fold); + added = true; + if (!fold.sameRow) { + var foldLineNext = foldData[i + 1]; + if (foldLineNext && foldLineNext.start.row == endRow) { + foldLine.merge(foldLineNext); + break; + } + } + break; + } else if (endRow <= foldLine.start.row) { + break; + } + } + + if (!added) + foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold)); + + if (this.$useWrapMode) + this.$updateWrapData(foldLine.start.row, foldLine.start.row); + else + this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row); + this.$modified = true; + this._signal("changeFold", { data: fold, action: "add" }); + + return fold; + }; + + this.addFolds = function(folds) { + folds.forEach(function(fold) { + this.addFold(fold); + }, this); + }; + + this.removeFold = function(fold) { + var foldLine = fold.foldLine; + var startRow = foldLine.start.row; + var endRow = foldLine.end.row; + + var foldLines = this.$foldData; + var folds = foldLine.folds; + if (folds.length == 1) { + foldLines.splice(foldLines.indexOf(foldLine), 1); + } else + if (foldLine.range.isEnd(fold.end.row, fold.end.column)) { + folds.pop(); + foldLine.end.row = folds[folds.length - 1].end.row; + foldLine.end.column = folds[folds.length - 1].end.column; + } else + if (foldLine.range.isStart(fold.start.row, fold.start.column)) { + folds.shift(); + foldLine.start.row = folds[0].start.row; + foldLine.start.column = folds[0].start.column; + } else + if (fold.sameRow) { + folds.splice(folds.indexOf(fold), 1); + } else + { + var newFoldLine = foldLine.split(fold.start.row, fold.start.column); + folds = newFoldLine.folds; + folds.shift(); + newFoldLine.start.row = folds[0].start.row; + newFoldLine.start.column = folds[0].start.column; + } + + if (!this.$updating) { + if (this.$useWrapMode) + this.$updateWrapData(startRow, endRow); + else + this.$updateRowLengthCache(startRow, endRow); + } + this.$modified = true; + this._signal("changeFold", { data: fold, action: "remove" }); + }; + + this.removeFolds = function(folds) { + var cloneFolds = []; + for (var i = 0; i < folds.length; i++) { + cloneFolds.push(folds[i]); + } + + cloneFolds.forEach(function(fold) { + this.removeFold(fold); + }, this); + this.$modified = true; + }; + + this.expandFold = function(fold) { + this.removeFold(fold); + fold.subFolds.forEach(function(subFold) { + fold.restoreRange(subFold); + this.addFold(subFold); + }, this); + if (fold.collapseChildren > 0) { + this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1); + } + fold.subFolds = []; + }; + + this.expandFolds = function(folds) { + folds.forEach(function(fold) { + this.expandFold(fold); + }, this); + }; + + this.unfold = function(location, expandInner) { + var range, folds; + if (location == null) { + range = new Range(0, 0, this.getLength(), 0); + expandInner = true; + } else if (typeof location == "number") + range = new Range(location, 0, location, this.getLine(location).length); + else if ("row" in location) + range = Range.fromPoints(location, location); + else + range = location; + + folds = this.getFoldsInRangeList(range); + if (expandInner) { + this.removeFolds(folds); + } else { + var subFolds = folds; + while (subFolds.length) { + this.expandFolds(subFolds); + subFolds = this.getFoldsInRangeList(range); + } + } + if (folds.length) + return folds; + }; + this.isRowFolded = function(docRow, startFoldRow) { + return !!this.getFoldLine(docRow, startFoldRow); + }; + + this.getRowFoldEnd = function(docRow, startFoldRow) { + var foldLine = this.getFoldLine(docRow, startFoldRow); + return foldLine ? foldLine.end.row : docRow; + }; + + this.getRowFoldStart = function(docRow, startFoldRow) { + var foldLine = this.getFoldLine(docRow, startFoldRow); + return foldLine ? foldLine.start.row : docRow; + }; + + this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { + if (startRow == null) + startRow = foldLine.start.row; + if (startColumn == null) + startColumn = 0; + if (endRow == null) + endRow = foldLine.end.row; + if (endColumn == null) + endColumn = this.getLine(endRow).length; + var doc = this.doc; + var textLine = ""; + + foldLine.walk(function(placeholder, row, column, lastColumn) { + if (row < startRow) + return; + if (row == startRow) { + if (column < startColumn) + return; + lastColumn = Math.max(startColumn, lastColumn); + } + + if (placeholder != null) { + textLine += placeholder; + } else { + textLine += doc.getLine(row).substring(lastColumn, column); + } + }, endRow, endColumn); + return textLine; + }; + + this.getDisplayLine = function(row, endColumn, startRow, startColumn) { + var foldLine = this.getFoldLine(row); + + if (!foldLine) { + var line; + line = this.doc.getLine(row); + return line.substring(startColumn || 0, endColumn || line.length); + } else { + return this.getFoldDisplayLine( + foldLine, row, endColumn, startRow, startColumn); + } + }; + + this.$cloneFoldData = function() { + var fd = []; + fd = this.$foldData.map(function(foldLine) { + var folds = foldLine.folds.map(function(fold) { + return fold.clone(); + }); + return new FoldLine(fd, folds); + }); + + return fd; + }; + + this.toggleFold = function(tryToUnfold) { + var selection = this.selection; + var range = selection.getRange(); + var fold; + var bracketPos; + + if (range.isEmpty()) { + var cursor = range.start; + fold = this.getFoldAt(cursor.row, cursor.column); + + if (fold) { + this.expandFold(fold); + return; + } else if (bracketPos = this.findMatchingBracket(cursor)) { + if (range.comparePoint(bracketPos) == 1) { + range.end = bracketPos; + } else { + range.start = bracketPos; + range.start.column++; + range.end.column--; + } + } else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) { + if (range.comparePoint(bracketPos) == 1) + range.end = bracketPos; + else + range.start = bracketPos; + + range.start.column++; + } else { + range = this.getCommentFoldRange(cursor.row, cursor.column) || range; + } + } else { + var folds = this.getFoldsInRange(range); + if (tryToUnfold && folds.length) { + this.expandFolds(folds); + return; + } else if (folds.length == 1 ) { + fold = folds[0]; + } + } + + if (!fold) + fold = this.getFoldAt(range.start.row, range.start.column); + + if (fold && fold.range.toString() == range.toString()) { + this.expandFold(fold); + return; + } + + var placeholder = "..."; + if (!range.isMultiLine()) { + placeholder = this.getTextRange(range); + if (placeholder.length < 4) + return; + placeholder = placeholder.trim().substring(0, 2) + ".."; + } + + this.addFold(placeholder, range); + }; + + this.getCommentFoldRange = function(row, column, dir) { + var iterator = new TokenIterator(this, row, column); + var token = iterator.getCurrentToken(); + if (token && /^comment|string/.test(token.type)) { + var range = new Range(); + var re = new RegExp(token.type.replace(/\..*/, "\\.")); + if (dir != 1) { + do { + token = iterator.stepBackward(); + } while (token && re.test(token.type)); + iterator.stepForward(); + } + + range.start.row = iterator.getCurrentTokenRow(); + range.start.column = iterator.getCurrentTokenColumn() + 2; + + iterator = new TokenIterator(this, row, column); + + if (dir != -1) { + do { + token = iterator.stepForward(); + } while (token && re.test(token.type)); + token = iterator.stepBackward(); + } else + token = iterator.getCurrentToken(); + + range.end.row = iterator.getCurrentTokenRow(); + range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2; + return range; + } + }; + + this.foldAll = function(startRow, endRow, depth) { + if (depth == undefined) + depth = 100000; // JSON.stringify doesn't hanle Infinity + var foldWidgets = this.foldWidgets; + if (!foldWidgets) + return; // mode doesn't support folding + endRow = endRow || this.getLength(); + startRow = startRow || 0; + for (var row = startRow; row < endRow; row++) { + if (foldWidgets[row] == null) + foldWidgets[row] = this.getFoldWidget(row); + if (foldWidgets[row] != "start") + continue; + + var range = this.getFoldWidgetRange(row); + if (range && range.isMultiLine() + && range.end.row <= endRow + && range.start.row >= startRow + ) { + row = range.end.row; + try { + var fold = this.addFold("...", range); + if (fold) + fold.collapseChildren = depth; + } catch(e) {} + } + } + }; + this.$foldStyles = { + "manual": 1, + "markbegin": 1, + "markbeginend": 1 + }; + this.$foldStyle = "markbegin"; + this.setFoldStyle = function(style) { + if (!this.$foldStyles[style]) + throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]"); + + if (this.$foldStyle == style) + return; + + this.$foldStyle = style; + + if (style == "manual") + this.unfold(); + var mode = this.$foldMode; + this.$setFolding(null); + this.$setFolding(mode); + }; + + this.$setFolding = function(foldMode) { + if (this.$foldMode == foldMode) + return; + + this.$foldMode = foldMode; + + this.off('change', this.$updateFoldWidgets); + this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + this._signal("changeAnnotation"); + + if (!foldMode || this.$foldStyle == "manual") { + this.foldWidgets = null; + return; + } + + this.foldWidgets = []; + this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle); + this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle); + + this.$updateFoldWidgets = this.updateFoldWidgets.bind(this); + this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this); + this.on('change', this.$updateFoldWidgets); + this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + }; + + this.getParentFoldRangeData = function (row, ignoreCurrent) { + var fw = this.foldWidgets; + if (!fw || (ignoreCurrent && fw[row])) + return {}; + + var i = row - 1, firstRange; + while (i >= 0) { + var c = fw[i]; + if (c == null) + c = fw[i] = this.getFoldWidget(i); + + if (c == "start") { + var range = this.getFoldWidgetRange(i); + if (!firstRange) + firstRange = range; + if (range && range.end.row >= row) + break; + } + i--; + } + + return { + range: i !== -1 && range, + firstRange: firstRange + }; + }; + + this.onFoldWidgetClick = function(row, e) { + e = e.domEvent; + var options = { + children: e.shiftKey, + all: e.ctrlKey || e.metaKey, + siblings: e.altKey + }; + + var range = this.$toggleFoldWidget(row, options); + if (!range) { + var el = (e.target || e.srcElement); + if (el && /ace_fold-widget/.test(el.className)) + el.className += " ace_invalid"; + } + }; + + this.$toggleFoldWidget = function(row, options) { + if (!this.getFoldWidget) + return; + var type = this.getFoldWidget(row); + var line = this.getLine(row); + + var dir = type === "end" ? -1 : 1; + var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir); + + if (fold) { + if (options.children || options.all) + this.removeFold(fold); + else + this.expandFold(fold); + return fold; + } + + var range = this.getFoldWidgetRange(row, true); + if (range && !range.isMultiLine()) { + fold = this.getFoldAt(range.start.row, range.start.column, 1); + if (fold && range.isEqual(fold.range)) { + this.removeFold(fold); + return fold; + } + } + + if (options.siblings) { + var data = this.getParentFoldRangeData(row); + if (data.range) { + var startRow = data.range.start.row + 1; + var endRow = data.range.end.row; + } + this.foldAll(startRow, endRow, options.all ? 10000 : 0); + } else if (options.children) { + endRow = range ? range.end.row : this.getLength(); + this.foldAll(row + 1, endRow, options.all ? 10000 : 0); + } else if (range) { + if (options.all) + range.collapseChildren = 10000; + this.addFold("...", range); + } + + return range; + }; + + + + this.toggleFoldWidget = function(toggleParent) { + var row = this.selection.getCursor().row; + row = this.getRowFoldStart(row); + var range = this.$toggleFoldWidget(row, {}); + + if (range) + return; + var data = this.getParentFoldRangeData(row, true); + range = data.range || data.firstRange; + + if (range) { + row = range.start.row; + var fold = this.getFoldAt(row, this.getLine(row).length, 1); + + if (fold) { + this.removeFold(fold); + } else { + this.addFold("...", range); + } + } + }; + + this.updateFoldWidgets = function(delta) { + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + + if (len === 0) { + this.foldWidgets[firstRow] = null; + } else if (delta.action == 'remove') { + this.foldWidgets.splice(firstRow, len + 1, null); + } else { + var args = Array(len + 1); + args.unshift(firstRow, 1); + this.foldWidgets.splice.apply(this.foldWidgets, args); + } + }; + this.tokenizerUpdateFoldWidgets = function(e) { + var rows = e.data; + if (rows.first != rows.last) { + if (this.foldWidgets.length > rows.first) + this.foldWidgets.splice(rows.first, this.foldWidgets.length); + } + }; +} + +exports.Folding = Folding; + +}); + +ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + + +function BracketMatch() { + + this.findMatchingBracket = function(position, chr) { + if (position.column == 0) return null; + + var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1); + if (charBeforeCursor == "") return null; + + var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/); + if (!match) + return null; + + if (match[1]) + return this.$findClosingBracket(match[1], position); + else + return this.$findOpeningBracket(match[2], position); + }; + + this.getBracketRange = function(pos) { + var line = this.getLine(pos.row); + var before = true, range; + + var chr = line.charAt(pos.column-1); + var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + if (!match) { + chr = line.charAt(pos.column); + pos = {row: pos.row, column: pos.column + 1}; + match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + before = false; + } + if (!match) + return null; + + if (match[1]) { + var bracketPos = this.$findClosingBracket(match[1], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(pos, bracketPos); + if (!before) { + range.end.column++; + range.start.column--; + } + range.cursor = range.end; + } else { + var bracketPos = this.$findOpeningBracket(match[2], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(bracketPos, pos); + if (!before) { + range.start.column++; + range.end.column--; + } + range.cursor = range.start; + } + + return range; + }; + + this.$brackets = { + ")": "(", + "(": ")", + "]": "[", + "[": "]", + "{": "}", + "}": "{" + }; + + this.$findOpeningBracket = function(bracket, position, typeRe) { + var openBracket = this.$brackets[bracket]; + var depth = 1; + + var iterator = new TokenIterator(this, position.row, position.column); + var token = iterator.getCurrentToken(); + if (!token) + token = iterator.stepForward(); + if (!token) + return; + + if (!typeRe){ + typeRe = new RegExp( + "(\\.?" + + token.type.replace(".", "\\.").replace("rparen", ".paren") + .replace(/\b(?:end)\b/, "(?:start|begin|end)") + + ")+" + ); + } + var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2; + var value = token.value; + + while (true) { + + while (valueIndex >= 0) { + var chr = value.charAt(valueIndex); + if (chr == openBracket) { + depth -= 1; + if (depth == 0) { + return {row: iterator.getCurrentTokenRow(), + column: valueIndex + iterator.getCurrentTokenColumn()}; + } + } + else if (chr == bracket) { + depth += 1; + } + valueIndex -= 1; + } + do { + token = iterator.stepBackward(); + } while (token && !typeRe.test(token.type)); + + if (token == null) + break; + + value = token.value; + valueIndex = value.length - 1; + } + + return null; + }; + + this.$findClosingBracket = function(bracket, position, typeRe) { + var closingBracket = this.$brackets[bracket]; + var depth = 1; + + var iterator = new TokenIterator(this, position.row, position.column); + var token = iterator.getCurrentToken(); + if (!token) + token = iterator.stepForward(); + if (!token) + return; + + if (!typeRe){ + typeRe = new RegExp( + "(\\.?" + + token.type.replace(".", "\\.").replace("lparen", ".paren") + .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)") + + ")+" + ); + } + var valueIndex = position.column - iterator.getCurrentTokenColumn(); + + while (true) { + + var value = token.value; + var valueLength = value.length; + while (valueIndex < valueLength) { + var chr = value.charAt(valueIndex); + if (chr == closingBracket) { + depth -= 1; + if (depth == 0) { + return {row: iterator.getCurrentTokenRow(), + column: valueIndex + iterator.getCurrentTokenColumn()}; + } + } + else if (chr == bracket) { + depth += 1; + } + valueIndex += 1; + } + do { + token = iterator.stepForward(); + } while (token && !typeRe.test(token.type)); + + if (token == null) + break; + + valueIndex = 0; + } + + return null; + }; +} +exports.BracketMatch = BracketMatch; + +}); + +ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var config = acequire("./config"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Selection = acequire("./selection").Selection; +var TextMode = acequire("./mode/text").Mode; +var Range = acequire("./range").Range; +var Document = acequire("./document").Document; +var BackgroundTokenizer = acequire("./background_tokenizer").BackgroundTokenizer; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; + +var EditSession = function(text, mode) { + this.$breakpoints = []; + this.$decorations = []; + this.$frontMarkers = {}; + this.$backMarkers = {}; + this.$markerId = 1; + this.$undoSelect = true; + + this.$foldData = []; + this.id = "session" + (++EditSession.$uid); + this.$foldData.toString = function() { + return this.join("\n"); + }; + this.on("changeFold", this.onChangeFold.bind(this)); + this.$onChange = this.onChange.bind(this); + + if (typeof text != "object" || !text.getLine) + text = new Document(text); + + this.setDocument(text); + this.selection = new Selection(this); + + config.resetOptions(this); + this.setMode(mode); + config._signal("session", this); +}; + + +(function() { + + oop.implement(this, EventEmitter); + this.setDocument = function(doc) { + if (this.doc) + this.doc.removeListener("change", this.$onChange); + + this.doc = doc; + doc.on("change", this.$onChange); + + if (this.bgTokenizer) + this.bgTokenizer.setDocument(this.getDocument()); + + this.resetCaches(); + }; + this.getDocument = function() { + return this.doc; + }; + this.$resetRowCache = function(docRow) { + if (!docRow) { + this.$docRowCache = []; + this.$screenRowCache = []; + return; + } + var l = this.$docRowCache.length; + var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1; + if (l > i) { + this.$docRowCache.splice(i, l); + this.$screenRowCache.splice(i, l); + } + }; + + this.$getRowCacheIndex = function(cacheArray, val) { + var low = 0; + var hi = cacheArray.length - 1; + + while (low <= hi) { + var mid = (low + hi) >> 1; + var c = cacheArray[mid]; + + if (val > c) + low = mid + 1; + else if (val < c) + hi = mid - 1; + else + return mid; + } + + return low -1; + }; + + this.resetCaches = function() { + this.$modified = true; + this.$wrapData = []; + this.$rowLengthCache = []; + this.$resetRowCache(0); + if (this.bgTokenizer) + this.bgTokenizer.start(0); + }; + + this.onChangeFold = function(e) { + var fold = e.data; + this.$resetRowCache(fold.start.row); + }; + + this.onChange = function(delta) { + this.$modified = true; + + this.$resetRowCache(delta.start.row); + + var removedFolds = this.$updateInternalDataOnChange(delta); + if (!this.$fromUndo && this.$undoManager && !delta.ignore) { + this.$deltasDoc.push(delta); + if (removedFolds && removedFolds.length != 0) { + this.$deltasFold.push({ + action: "removeFolds", + folds: removedFolds + }); + } + + this.$informUndoManager.schedule(); + } + + this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta); + this._signal("change", delta); + }; + this.setValue = function(text) { + this.doc.setValue(text); + this.selection.moveTo(0, 0); + + this.$resetRowCache(0); + this.$deltas = []; + this.$deltasDoc = []; + this.$deltasFold = []; + this.setUndoManager(this.$undoManager); + this.getUndoManager().reset(); + }; + this.getValue = + this.toString = function() { + return this.doc.getValue(); + }; + this.getSelection = function() { + return this.selection; + }; + this.getState = function(row) { + return this.bgTokenizer.getState(row); + }; + this.getTokens = function(row) { + return this.bgTokenizer.getTokens(row); + }; + this.getTokenAt = function(row, column) { + var tokens = this.bgTokenizer.getTokens(row); + var token, c = 0; + if (column == null) { + i = tokens.length - 1; + c = this.getLine(row).length; + } else { + for (var i = 0; i < tokens.length; i++) { + c += tokens[i].value.length; + if (c >= column) + break; + } + } + token = tokens[i]; + if (!token) + return null; + token.index = i; + token.start = c - token.value.length; + return token; + }; + this.setUndoManager = function(undoManager) { + this.$undoManager = undoManager; + this.$deltas = []; + this.$deltasDoc = []; + this.$deltasFold = []; + + if (this.$informUndoManager) + this.$informUndoManager.cancel(); + + if (undoManager) { + var self = this; + + this.$syncInformUndoManager = function() { + self.$informUndoManager.cancel(); + + if (self.$deltasFold.length) { + self.$deltas.push({ + group: "fold", + deltas: self.$deltasFold + }); + self.$deltasFold = []; + } + + if (self.$deltasDoc.length) { + self.$deltas.push({ + group: "doc", + deltas: self.$deltasDoc + }); + self.$deltasDoc = []; + } + + if (self.$deltas.length > 0) { + undoManager.execute({ + action: "aceupdate", + args: [self.$deltas, self], + merge: self.mergeUndoDeltas + }); + } + self.mergeUndoDeltas = false; + self.$deltas = []; + }; + this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager); + } + }; + this.markUndoGroup = function() { + if (this.$syncInformUndoManager) + this.$syncInformUndoManager(); + }; + + this.$defaultUndoManager = { + undo: function() {}, + redo: function() {}, + reset: function() {} + }; + this.getUndoManager = function() { + return this.$undoManager || this.$defaultUndoManager; + }; + this.getTabString = function() { + if (this.getUseSoftTabs()) { + return lang.stringRepeat(" ", this.getTabSize()); + } else { + return "\t"; + } + }; + this.setUseSoftTabs = function(val) { + this.setOption("useSoftTabs", val); + }; + this.getUseSoftTabs = function() { + return this.$useSoftTabs && !this.$mode.$indentWithTabs; + }; + this.setTabSize = function(tabSize) { + this.setOption("tabSize", tabSize); + }; + this.getTabSize = function() { + return this.$tabSize; + }; + this.isTabStop = function(position) { + return this.$useSoftTabs && (position.column % this.$tabSize === 0); + }; + + this.$overwrite = false; + this.setOverwrite = function(overwrite) { + this.setOption("overwrite", overwrite); + }; + this.getOverwrite = function() { + return this.$overwrite; + }; + this.toggleOverwrite = function() { + this.setOverwrite(!this.$overwrite); + }; + this.addGutterDecoration = function(row, className) { + if (!this.$decorations[row]) + this.$decorations[row] = ""; + this.$decorations[row] += " " + className; + this._signal("changeBreakpoint", {}); + }; + this.removeGutterDecoration = function(row, className) { + this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); + this._signal("changeBreakpoint", {}); + }; + this.getBreakpoints = function() { + return this.$breakpoints; + }; + this.setBreakpoints = function(rows) { + this.$breakpoints = []; + for (var i=0; i 0) + inToken = !!line.charAt(column - 1).match(this.tokenRe); + + if (!inToken) + inToken = !!line.charAt(column).match(this.tokenRe); + + if (inToken) + var re = this.tokenRe; + else if (/^\s+$/.test(line.slice(column-1, column+1))) + var re = /\s/; + else + var re = this.nonTokenRe; + + var start = column; + if (start > 0) { + do { + start--; + } + while (start >= 0 && line.charAt(start).match(re)); + start++; + } + + var end = column; + while (end < line.length && line.charAt(end).match(re)) { + end++; + } + + return new Range(row, start, row, end); + }; + this.getAWordRange = function(row, column) { + var wordRange = this.getWordRange(row, column); + var line = this.getLine(wordRange.end.row); + + while (line.charAt(wordRange.end.column).match(/[ \t]/)) { + wordRange.end.column += 1; + } + return wordRange; + }; + this.setNewLineMode = function(newLineMode) { + this.doc.setNewLineMode(newLineMode); + }; + this.getNewLineMode = function() { + return this.doc.getNewLineMode(); + }; + this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); }; + this.getUseWorker = function() { return this.$useWorker; }; + this.onReloadTokenizer = function(e) { + var rows = e.data; + this.bgTokenizer.start(rows.first); + this._signal("tokenizerUpdate", e); + }; + + this.$modes = {}; + this.$mode = null; + this.$modeId = null; + this.setMode = function(mode, cb) { + if (mode && typeof mode === "object") { + if (mode.getTokenizer) + return this.$onChangeMode(mode); + var options = mode; + var path = options.path; + } else { + path = mode || "ace/mode/text"; + } + if (!this.$modes["ace/mode/text"]) + this.$modes["ace/mode/text"] = new TextMode(); + + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + cb && cb(); + return; + } + this.$modeId = path; + config.loadModule(["mode", path], function(m) { + if (this.$modeId !== path) + return cb && cb(); + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + } else if (m && m.Mode) { + m = new m.Mode(options); + if (!options) { + this.$modes[path] = m; + m.$id = path; + } + this.$onChangeMode(m); + } + cb && cb(); + }.bind(this)); + if (!this.$mode) + this.$onChangeMode(this.$modes["ace/mode/text"], true); + }; + + this.$onChangeMode = function(mode, $isPlaceholder) { + if (!$isPlaceholder) + this.$modeId = mode.$id; + if (this.$mode === mode) + return; + + this.$mode = mode; + + this.$stopWorker(); + + if (this.$useWorker) + this.$startWorker(); + + var tokenizer = mode.getTokenizer(); + + if(tokenizer.addEventListener !== undefined) { + var onReloadTokenizer = this.onReloadTokenizer.bind(this); + tokenizer.addEventListener("update", onReloadTokenizer); + } + + if (!this.bgTokenizer) { + this.bgTokenizer = new BackgroundTokenizer(tokenizer); + var _self = this; + this.bgTokenizer.addEventListener("update", function(e) { + _self._signal("tokenizerUpdate", e); + }); + } else { + this.bgTokenizer.setTokenizer(tokenizer); + } + + this.bgTokenizer.setDocument(this.getDocument()); + + this.tokenRe = mode.tokenRe; + this.nonTokenRe = mode.nonTokenRe; + + + if (!$isPlaceholder) { + if (mode.attachToSession) + mode.attachToSession(this); + this.$options.wrapMethod.set.call(this, this.$wrapMethod); + this.$setFolding(mode.foldingRules); + this.bgTokenizer.start(0); + this._emit("changeMode"); + } + }; + + this.$stopWorker = function() { + if (this.$worker) { + this.$worker.terminate(); + this.$worker = null; + } + }; + + this.$startWorker = function() { + try { + this.$worker = this.$mode.createWorker(this); + } catch (e) { + config.warn("Could not load worker", e); + this.$worker = null; + } + }; + this.getMode = function() { + return this.$mode; + }; + + this.$scrollTop = 0; + this.setScrollTop = function(scrollTop) { + if (this.$scrollTop === scrollTop || isNaN(scrollTop)) + return; + + this.$scrollTop = scrollTop; + this._signal("changeScrollTop", scrollTop); + }; + this.getScrollTop = function() { + return this.$scrollTop; + }; + + this.$scrollLeft = 0; + this.setScrollLeft = function(scrollLeft) { + if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft)) + return; + + this.$scrollLeft = scrollLeft; + this._signal("changeScrollLeft", scrollLeft); + }; + this.getScrollLeft = function() { + return this.$scrollLeft; + }; + this.getScreenWidth = function() { + this.$computeWidth(); + if (this.lineWidgets) + return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth); + return this.screenWidth; + }; + + this.getLineWidgetMaxWidth = function() { + if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth; + var width = 0; + this.lineWidgets.forEach(function(w) { + if (w && w.screenWidth > width) + width = w.screenWidth; + }); + return this.lineWidgetWidth = width; + }; + + this.$computeWidth = function(force) { + if (this.$modified || force) { + this.$modified = false; + + if (this.$useWrapMode) + return this.screenWidth = this.$wrapLimit; + + var lines = this.doc.getAllLines(); + var cache = this.$rowLengthCache; + var longestScreenLine = 0; + var foldIndex = 0; + var foldLine = this.$foldData[foldIndex]; + var foldStart = foldLine ? foldLine.start.row : Infinity; + var len = lines.length; + + for (var i = 0; i < len; i++) { + if (i > foldStart) { + i = foldLine.end.row + 1; + if (i >= len) + break; + foldLine = this.$foldData[foldIndex++]; + foldStart = foldLine ? foldLine.start.row : Infinity; + } + + if (cache[i] == null) + cache[i] = this.$getStringScreenWidth(lines[i])[0]; + + if (cache[i] > longestScreenLine) + longestScreenLine = cache[i]; + } + this.screenWidth = longestScreenLine; + } + }; + this.getLine = function(row) { + return this.doc.getLine(row); + }; + this.getLines = function(firstRow, lastRow) { + return this.doc.getLines(firstRow, lastRow); + }; + this.getLength = function() { + return this.doc.getLength(); + }; + this.getTextRange = function(range) { + return this.doc.getTextRange(range || this.selection.getRange()); + }; + this.insert = function(position, text) { + return this.doc.insert(position, text); + }; + this.remove = function(range) { + return this.doc.remove(range); + }; + this.removeFullLines = function(firstRow, lastRow){ + return this.doc.removeFullLines(firstRow, lastRow); + }; + this.undoChanges = function(deltas, dontSelect) { + if (!deltas.length) + return; + + this.$fromUndo = true; + var lastUndoRange = null; + for (var i = deltas.length - 1; i != -1; i--) { + var delta = deltas[i]; + if (delta.group == "doc") { + this.doc.revertDeltas(delta.deltas); + lastUndoRange = + this.$getUndoSelection(delta.deltas, true, lastUndoRange); + } else { + delta.deltas.forEach(function(foldDelta) { + this.addFolds(foldDelta.folds); + }, this); + } + } + this.$fromUndo = false; + lastUndoRange && + this.$undoSelect && + !dontSelect && + this.selection.setSelectionRange(lastUndoRange); + return lastUndoRange; + }; + this.redoChanges = function(deltas, dontSelect) { + if (!deltas.length) + return; + + this.$fromUndo = true; + var lastUndoRange = null; + for (var i = 0; i < deltas.length; i++) { + var delta = deltas[i]; + if (delta.group == "doc") { + this.doc.applyDeltas(delta.deltas); + lastUndoRange = + this.$getUndoSelection(delta.deltas, false, lastUndoRange); + } + } + this.$fromUndo = false; + lastUndoRange && + this.$undoSelect && + !dontSelect && + this.selection.setSelectionRange(lastUndoRange); + return lastUndoRange; + }; + this.setUndoSelect = function(enable) { + this.$undoSelect = enable; + }; + + this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) { + function isInsert(delta) { + return isUndo ? delta.action !== "insert" : delta.action === "insert"; + } + + var delta = deltas[0]; + var range, point; + var lastDeltaIsInsert = false; + if (isInsert(delta)) { + range = Range.fromPoints(delta.start, delta.end); + lastDeltaIsInsert = true; + } else { + range = Range.fromPoints(delta.start, delta.start); + lastDeltaIsInsert = false; + } + + for (var i = 1; i < deltas.length; i++) { + delta = deltas[i]; + if (isInsert(delta)) { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range.setStart(point); + } + point = delta.end; + if (range.compare(point.row, point.column) == 1) { + range.setEnd(point); + } + lastDeltaIsInsert = true; + } else { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range = Range.fromPoints(delta.start, delta.start); + } + lastDeltaIsInsert = false; + } + } + if (lastUndoRange != null) { + if (Range.comparePoints(lastUndoRange.start, range.start) === 0) { + lastUndoRange.start.column += range.end.column - range.start.column; + lastUndoRange.end.column += range.end.column - range.start.column; + } + + var cmp = lastUndoRange.compareRange(range); + if (cmp == 1) { + range.setStart(lastUndoRange.start); + } else if (cmp == -1) { + range.setEnd(lastUndoRange.end); + } + } + + return range; + }; + this.replace = function(range, text) { + return this.doc.replace(range, text); + }; + this.moveText = function(fromRange, toPosition, copy) { + var text = this.getTextRange(fromRange); + var folds = this.getFoldsInRange(fromRange); + + var toRange = Range.fromPoints(toPosition, toPosition); + if (!copy) { + this.remove(fromRange); + var rowDiff = fromRange.start.row - fromRange.end.row; + var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column; + if (collDiff) { + if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column) + toRange.start.column += collDiff; + if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column) + toRange.end.column += collDiff; + } + if (rowDiff && toRange.start.row >= fromRange.end.row) { + toRange.start.row += rowDiff; + toRange.end.row += rowDiff; + } + } + + toRange.end = this.insert(toRange.start, text); + if (folds.length) { + var oldStart = fromRange.start; + var newStart = toRange.start; + var rowDiff = newStart.row - oldStart.row; + var collDiff = newStart.column - oldStart.column; + this.addFolds(folds.map(function(x) { + x = x.clone(); + if (x.start.row == oldStart.row) + x.start.column += collDiff; + if (x.end.row == oldStart.row) + x.end.column += collDiff; + x.start.row += rowDiff; + x.end.row += rowDiff; + return x; + })); + } + + return toRange; + }; + this.indentRows = function(startRow, endRow, indentString) { + indentString = indentString.replace(/\t/g, this.getTabString()); + for (var row=startRow; row<=endRow; row++) + this.doc.insertInLine({row: row, column: 0}, indentString); + }; + this.outdentRows = function (range) { + var rowRange = range.collapseRows(); + var deleteRange = new Range(0, 0, 0, 0); + var size = this.getTabSize(); + + for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) { + var line = this.getLine(i); + + deleteRange.start.row = i; + deleteRange.end.row = i; + for (var j = 0; j < size; ++j) + if (line.charAt(j) != ' ') + break; + if (j < size && line.charAt(j) == '\t') { + deleteRange.start.column = j; + deleteRange.end.column = j + 1; + } else { + deleteRange.start.column = 0; + deleteRange.end.column = j; + } + this.remove(deleteRange); + } + }; + + this.$moveLines = function(firstRow, lastRow, dir) { + firstRow = this.getRowFoldStart(firstRow); + lastRow = this.getRowFoldEnd(lastRow); + if (dir < 0) { + var row = this.getRowFoldStart(firstRow + dir); + if (row < 0) return 0; + var diff = row-firstRow; + } else if (dir > 0) { + var row = this.getRowFoldEnd(lastRow + dir); + if (row > this.doc.getLength()-1) return 0; + var diff = row-lastRow; + } else { + firstRow = this.$clipRowToDocument(firstRow); + lastRow = this.$clipRowToDocument(lastRow); + var diff = lastRow - firstRow + 1; + } + + var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE); + var folds = this.getFoldsInRange(range).map(function(x){ + x = x.clone(); + x.start.row += diff; + x.end.row += diff; + return x; + }); + + var lines = dir == 0 + ? this.doc.getLines(firstRow, lastRow) + : this.doc.removeFullLines(firstRow, lastRow); + this.doc.insertFullLines(firstRow+diff, lines); + folds.length && this.addFolds(folds); + return diff; + }; + this.moveLinesUp = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, -1); + }; + this.moveLinesDown = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 1); + }; + this.duplicateLines = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 0); + }; + + + this.$clipRowToDocument = function(row) { + return Math.max(0, Math.min(row, this.doc.getLength()-1)); + }; + + this.$clipColumnToRow = function(row, column) { + if (column < 0) + return 0; + return Math.min(this.doc.getLine(row).length, column); + }; + + + this.$clipPositionToDocument = function(row, column) { + column = Math.max(0, column); + + if (row < 0) { + row = 0; + column = 0; + } else { + var len = this.doc.getLength(); + if (row >= len) { + row = len - 1; + column = this.doc.getLine(len-1).length; + } else { + column = Math.min(this.doc.getLine(row).length, column); + } + } + + return { + row: row, + column: column + }; + }; + + this.$clipRangeToDocument = function(range) { + if (range.start.row < 0) { + range.start.row = 0; + range.start.column = 0; + } else { + range.start.column = this.$clipColumnToRow( + range.start.row, + range.start.column + ); + } + + var len = this.doc.getLength() - 1; + if (range.end.row > len) { + range.end.row = len; + range.end.column = this.doc.getLine(len).length; + } else { + range.end.column = this.$clipColumnToRow( + range.end.row, + range.end.column + ); + } + return range; + }; + this.$wrapLimit = 80; + this.$useWrapMode = false; + this.$wrapLimitRange = { + min : null, + max : null + }; + this.setUseWrapMode = function(useWrapMode) { + if (useWrapMode != this.$useWrapMode) { + this.$useWrapMode = useWrapMode; + this.$modified = true; + this.$resetRowCache(0); + if (useWrapMode) { + var len = this.getLength(); + this.$wrapData = Array(len); + this.$updateWrapData(0, len - 1); + } + + this._signal("changeWrapMode"); + } + }; + this.getUseWrapMode = function() { + return this.$useWrapMode; + }; + this.setWrapLimitRange = function(min, max) { + if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { + this.$wrapLimitRange = { min: min, max: max }; + this.$modified = true; + if (this.$useWrapMode) + this._signal("changeWrapMode"); + } + }; + this.adjustWrapLimit = function(desiredLimit, $printMargin) { + var limits = this.$wrapLimitRange; + if (limits.max < 0) + limits = {min: $printMargin, max: $printMargin}; + var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max); + if (wrapLimit != this.$wrapLimit && wrapLimit > 1) { + this.$wrapLimit = wrapLimit; + this.$modified = true; + if (this.$useWrapMode) { + this.$updateWrapData(0, this.getLength() - 1); + this.$resetRowCache(0); + this._signal("changeWrapLimit"); + } + return true; + } + return false; + }; + + this.$constrainWrapLimit = function(wrapLimit, min, max) { + if (min) + wrapLimit = Math.max(min, wrapLimit); + + if (max) + wrapLimit = Math.min(max, wrapLimit); + + return wrapLimit; + }; + this.getWrapLimit = function() { + return this.$wrapLimit; + }; + this.setWrapLimit = function (limit) { + this.setWrapLimitRange(limit, limit); + }; + this.getWrapLimitRange = function() { + return { + min : this.$wrapLimitRange.min, + max : this.$wrapLimitRange.max + }; + }; + + this.$updateInternalDataOnChange = function(delta) { + var useWrapMode = this.$useWrapMode; + var action = delta.action; + var start = delta.start; + var end = delta.end; + var firstRow = start.row; + var lastRow = end.row; + var len = lastRow - firstRow; + var removedFolds = null; + + this.$updating = true; + if (len != 0) { + if (action === "remove") { + this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); + + var foldLines = this.$foldData; + removedFolds = this.getFoldsInRange(delta); + this.removeFolds(removedFolds); + + var foldLine = this.getFoldLine(end.row); + var idx = 0; + if (foldLine) { + foldLine.addRemoveChars(end.row, end.column, start.column - end.column); + foldLine.shiftRow(-len); + + var foldLineBefore = this.getFoldLine(firstRow); + if (foldLineBefore && foldLineBefore !== foldLine) { + foldLineBefore.merge(foldLine); + foldLine = foldLineBefore; + } + idx = foldLines.indexOf(foldLine) + 1; + } + + for (idx; idx < foldLines.length; idx++) { + var foldLine = foldLines[idx]; + if (foldLine.start.row >= end.row) { + foldLine.shiftRow(-len); + } + } + + lastRow = firstRow; + } else { + var args = Array(len); + args.unshift(firstRow, 0); + var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache + arr.splice.apply(arr, args); + var foldLines = this.$foldData; + var foldLine = this.getFoldLine(firstRow); + var idx = 0; + if (foldLine) { + var cmp = foldLine.range.compareInside(start.row, start.column); + if (cmp == 0) { + foldLine = foldLine.split(start.row, start.column); + if (foldLine) { + foldLine.shiftRow(len); + foldLine.addRemoveChars(lastRow, 0, end.column - start.column); + } + } else + if (cmp == -1) { + foldLine.addRemoveChars(firstRow, 0, end.column - start.column); + foldLine.shiftRow(len); + } + idx = foldLines.indexOf(foldLine) + 1; + } + + for (idx; idx < foldLines.length; idx++) { + var foldLine = foldLines[idx]; + if (foldLine.start.row >= firstRow) { + foldLine.shiftRow(len); + } + } + } + } else { + len = Math.abs(delta.start.column - delta.end.column); + if (action === "remove") { + removedFolds = this.getFoldsInRange(delta); + this.removeFolds(removedFolds); + + len = -len; + } + var foldLine = this.getFoldLine(firstRow); + if (foldLine) { + foldLine.addRemoveChars(firstRow, start.column, len); + } + } + + if (useWrapMode && this.$wrapData.length != this.doc.getLength()) { + console.error("doc.getLength() and $wrapData.length have to be the same!"); + } + this.$updating = false; + + if (useWrapMode) + this.$updateWrapData(firstRow, lastRow); + else + this.$updateRowLengthCache(firstRow, lastRow); + + return removedFolds; + }; + + this.$updateRowLengthCache = function(firstRow, lastRow, b) { + this.$rowLengthCache[firstRow] = null; + this.$rowLengthCache[lastRow] = null; + }; + + this.$updateWrapData = function(firstRow, lastRow) { + var lines = this.doc.getAllLines(); + var tabSize = this.getTabSize(); + var wrapData = this.$wrapData; + var wrapLimit = this.$wrapLimit; + var tokens; + var foldLine; + + var row = firstRow; + lastRow = Math.min(lastRow, lines.length - 1); + while (row <= lastRow) { + foldLine = this.getFoldLine(row, foldLine); + if (!foldLine) { + tokens = this.$getDisplayTokens(lines[row]); + wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row ++; + } else { + tokens = []; + foldLine.walk(function(placeholder, row, column, lastColumn) { + var walkTokens; + if (placeholder != null) { + walkTokens = this.$getDisplayTokens( + placeholder, tokens.length); + walkTokens[0] = PLACEHOLDER_START; + for (var i = 1; i < walkTokens.length; i++) { + walkTokens[i] = PLACEHOLDER_BODY; + } + } else { + walkTokens = this.$getDisplayTokens( + lines[row].substring(lastColumn, column), + tokens.length); + } + tokens = tokens.concat(walkTokens); + }.bind(this), + foldLine.end.row, + lines[foldLine.end.row].length + 1 + ); + + wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row = foldLine.end.row + 1; + } + } + }; + var CHAR = 1, + CHAR_EXT = 2, + PLACEHOLDER_START = 3, + PLACEHOLDER_BODY = 4, + PUNCTUATION = 9, + SPACE = 10, + TAB = 11, + TAB_SPACE = 12; + + + this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) { + if (tokens.length == 0) { + return []; + } + + var splits = []; + var displayLength = tokens.length; + var lastSplit = 0, lastDocSplit = 0; + + var isCode = this.$wrapAsCode; + + var indentedSoftWrap = this.$indentedSoftWrap; + var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8) + || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2); + + function getWrapIndent() { + var indentation = 0; + if (maxIndent === 0) + return indentation; + if (indentedSoftWrap) { + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (token == SPACE) + indentation += 1; + else if (token == TAB) + indentation += tabSize; + else if (token == TAB_SPACE) + continue; + else + break; + } + } + if (isCode && indentedSoftWrap !== false) + indentation += tabSize; + return Math.min(indentation, maxIndent); + } + function addSplit(screenPos) { + var displayed = tokens.slice(lastSplit, screenPos); + var len = displayed.length; + displayed.join("") + .replace(/12/g, function() { + len -= 1; + }) + .replace(/2/g, function() { + len -= 1; + }); + + if (!splits.length) { + indent = getWrapIndent(); + splits.indent = indent; + } + lastDocSplit += len; + splits.push(lastDocSplit); + lastSplit = screenPos; + } + var indent = 0; + while (displayLength - lastSplit > wrapLimit - indent) { + var split = lastSplit + wrapLimit - indent; + if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) { + addSplit(split); + continue; + } + if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { + for (split; split != lastSplit - 1; split--) { + if (tokens[split] == PLACEHOLDER_START) { + break; + } + } + if (split > lastSplit) { + addSplit(split); + continue; + } + split = lastSplit + wrapLimit; + for (split; split < tokens.length; split++) { + if (tokens[split] != PLACEHOLDER_BODY) { + break; + } + } + if (split == tokens.length) { + break; // Breaks the while-loop. + } + addSplit(split); + continue; + } + var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1); + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + if (isCode) { + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + while (split > minSplit && tokens[split] == PUNCTUATION) { + split --; + } + } else { + while (split > minSplit && tokens[split] < SPACE) { + split --; + } + } + if (split > minSplit) { + addSplit(++split); + continue; + } + split = lastSplit + wrapLimit; + if (tokens[split] == CHAR_EXT) + split--; + addSplit(split - indent); + } + return splits; + }; + this.$getDisplayTokens = function(str, offset) { + var arr = []; + var tabSize; + offset = offset || 0; + + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (c == 9) { + tabSize = this.getScreenTabSize(arr.length + offset); + arr.push(TAB); + for (var n = 1; n < tabSize; n++) { + arr.push(TAB_SPACE); + } + } + else if (c == 32) { + arr.push(SPACE); + } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { + arr.push(PUNCTUATION); + } + else if (c >= 0x1100 && isFullWidth(c)) { + arr.push(CHAR, CHAR_EXT); + } else { + arr.push(CHAR); + } + } + return arr; + }; + this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { + if (maxScreenColumn == 0) + return [0, 0]; + if (maxScreenColumn == null) + maxScreenColumn = Infinity; + screenColumn = screenColumn || 0; + + var c, column; + for (column = 0; column < str.length; column++) { + c = str.charCodeAt(column); + if (c == 9) { + screenColumn += this.getScreenTabSize(screenColumn); + } + else if (c >= 0x1100 && isFullWidth(c)) { + screenColumn += 2; + } else { + screenColumn += 1; + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + + this.lineWidgets = null; + this.getRowLength = function(row) { + if (this.lineWidgets) + var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0 + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + this.getRowLineCount = function(row) { + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1; + } else { + return this.$wrapData[row].length + 1; + } + }; + + this.getRowWrapIndent = function(screenRow) { + if (this.$useWrapMode) { + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); + var splits = this.$wrapData[pos.row]; + return splits.length && splits[0] < pos.column ? splits.indent : 0; + } else { + return 0; + } + } + this.getScreenLastRowColumn = function(screenRow) { + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); + return this.documentToScreenColumn(pos.row, pos.column); + }; + this.getDocumentLastRowColumn = function(docRow, docColumn) { + var screenRow = this.documentToScreenRow(docRow, docColumn); + return this.getScreenLastRowColumn(screenRow); + }; + this.getDocumentLastRowColumnPosition = function(docRow, docColumn) { + var screenRow = this.documentToScreenRow(docRow, docColumn); + return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10); + }; + this.getRowSplitData = function(row) { + if (!this.$useWrapMode) { + return undefined; + } else { + return this.$wrapData[row]; + } + }; + this.getScreenTabSize = function(screenColumn) { + return this.$tabSize - screenColumn % this.$tabSize; + }; + + + this.screenToDocumentRow = function(screenRow, screenColumn) { + return this.screenToDocumentPosition(screenRow, screenColumn).row; + }; + + + this.screenToDocumentColumn = function(screenRow, screenColumn) { + return this.screenToDocumentPosition(screenRow, screenColumn).column; + }; + this.screenToDocumentPosition = function(screenRow, screenColumn) { + if (screenRow < 0) + return {row: 0, column: 0}; + + var line; + var docRow = 0; + var docColumn = 0; + var column; + var row = 0; + var rowLength = 0; + + var rowCache = this.$screenRowCache; + var i = this.$getRowCacheIndex(rowCache, screenRow); + var l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var docRow = this.$docRowCache[i]; + var doCache = screenRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + var maxRow = this.getLength() - 1; + var foldLine = this.getNextFoldLine(docRow); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (row <= screenRow) { + rowLength = this.getRowLength(docRow); + if (row + rowLength > screenRow || docRow >= maxRow) { + break; + } else { + row += rowLength; + docRow++; + if (docRow > foldStart) { + docRow = foldLine.end.row+1; + foldLine = this.getNextFoldLine(docRow, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; + } + } + + if (doCache) { + this.$docRowCache.push(docRow); + this.$screenRowCache.push(row); + } + } + + if (foldLine && foldLine.start.row <= docRow) { + line = this.getFoldDisplayLine(foldLine); + docRow = foldLine.start.row; + } else if (row + rowLength <= screenRow || docRow > maxRow) { + return { + row: maxRow, + column: this.getLine(maxRow).length + }; + } else { + line = this.getLine(docRow); + foldLine = null; + } + var wrapIndent = 0; + if (this.$useWrapMode) { + var splits = this.$wrapData[docRow]; + if (splits) { + var splitIndex = Math.floor(screenRow - row); + column = splits[splitIndex]; + if(splitIndex > 0 && splits.length) { + wrapIndent = splits.indent; + docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; + line = line.substring(docColumn); + } + } + } + + docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1]; + if (this.$useWrapMode && docColumn >= column) + docColumn = column - 1; + + if (foldLine) + return foldLine.idxToPosition(docColumn); + + return {row: docRow, column: docColumn}; + }; + this.documentToScreenPosition = function(docRow, docColumn) { + if (typeof docColumn === "undefined") + var pos = this.$clipPositionToDocument(docRow.row, docRow.column); + else + pos = this.$clipPositionToDocument(docRow, docColumn); + + docRow = pos.row; + docColumn = pos.column; + + var screenRow = 0; + var foldStartRow = null; + var fold = null; + fold = this.getFoldAt(docRow, docColumn, 1); + if (fold) { + docRow = fold.start.row; + docColumn = fold.start.column; + } + + var rowEnd, row = 0; + + + var rowCache = this.$docRowCache; + var i = this.$getRowCacheIndex(rowCache, docRow); + var l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var screenRow = this.$screenRowCache[i]; + var doCache = docRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + var foldLine = this.getNextFoldLine(row); + var foldStart = foldLine ?foldLine.start.row :Infinity; + + while (row < docRow) { + if (row >= foldStart) { + rowEnd = foldLine.end.row + 1; + if (rowEnd > docRow) + break; + foldLine = this.getNextFoldLine(rowEnd, foldLine); + foldStart = foldLine ?foldLine.start.row :Infinity; + } + else { + rowEnd = row + 1; + } + + screenRow += this.getRowLength(row); + row = rowEnd; + + if (doCache) { + this.$docRowCache.push(row); + this.$screenRowCache.push(screenRow); + } + } + var textLine = ""; + if (foldLine && row >= foldStart) { + textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); + foldStartRow = foldLine.start.row; + } else { + textLine = this.getLine(docRow).substring(0, docColumn); + foldStartRow = docRow; + } + var wrapIndent = 0; + if (this.$useWrapMode) { + var wrapRow = this.$wrapData[foldStartRow]; + if (wrapRow) { + var screenRowOffset = 0; + while (textLine.length >= wrapRow[screenRowOffset]) { + screenRow ++; + screenRowOffset++; + } + textLine = textLine.substring( + wrapRow[screenRowOffset - 1] || 0, textLine.length + ); + wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0; + } + } + + return { + row: screenRow, + column: wrapIndent + this.$getStringScreenWidth(textLine)[0] + }; + }; + this.documentToScreenColumn = function(row, docColumn) { + return this.documentToScreenPosition(row, docColumn).column; + }; + this.documentToScreenRow = function(docRow, docColumn) { + return this.documentToScreenPosition(docRow, docColumn).row; + }; + this.getScreenLength = function() { + var screenRows = 0; + var fold = null; + if (!this.$useWrapMode) { + screenRows = this.getLength(); + var foldData = this.$foldData; + for (var i = 0; i < foldData.length; i++) { + fold = foldData[i]; + screenRows -= fold.end.row - fold.start.row; + } + } else { + var lastRow = this.$wrapData.length; + var row = 0, i = 0; + var fold = this.$foldData[i++]; + var foldStart = fold ? fold.start.row :Infinity; + + while (row < lastRow) { + var splits = this.$wrapData[row]; + screenRows += splits ? splits.length + 1 : 1; + row ++; + if (row > foldStart) { + row = fold.end.row+1; + fold = this.$foldData[i++]; + foldStart = fold ?fold.start.row :Infinity; + } + } + } + if (this.lineWidgets) + screenRows += this.$getWidgetScreenLength(); + + return screenRows; + }; + this.$setFontMetrics = function(fm) { + if (!this.$enableVarChar) return; + this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { + if (maxScreenColumn === 0) + return [0, 0]; + if (!maxScreenColumn) + maxScreenColumn = Infinity; + screenColumn = screenColumn || 0; + + var c, column; + for (column = 0; column < str.length; column++) { + c = str.charAt(column); + if (c === "\t") { + screenColumn += this.getScreenTabSize(screenColumn); + } else { + screenColumn += fm.getCharacterWidth(c); + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + }; + + this.destroy = function() { + if (this.bgTokenizer) { + this.bgTokenizer.setDocument(null); + this.bgTokenizer = null; + } + this.$stopWorker(); + }; + function isFullWidth(c) { + if (c < 0x1100) + return false; + return c >= 0x1100 && c <= 0x115F || + c >= 0x11A3 && c <= 0x11A7 || + c >= 0x11FA && c <= 0x11FF || + c >= 0x2329 && c <= 0x232A || + c >= 0x2E80 && c <= 0x2E99 || + c >= 0x2E9B && c <= 0x2EF3 || + c >= 0x2F00 && c <= 0x2FD5 || + c >= 0x2FF0 && c <= 0x2FFB || + c >= 0x3000 && c <= 0x303E || + c >= 0x3041 && c <= 0x3096 || + c >= 0x3099 && c <= 0x30FF || + c >= 0x3105 && c <= 0x312D || + c >= 0x3131 && c <= 0x318E || + c >= 0x3190 && c <= 0x31BA || + c >= 0x31C0 && c <= 0x31E3 || + c >= 0x31F0 && c <= 0x321E || + c >= 0x3220 && c <= 0x3247 || + c >= 0x3250 && c <= 0x32FE || + c >= 0x3300 && c <= 0x4DBF || + c >= 0x4E00 && c <= 0xA48C || + c >= 0xA490 && c <= 0xA4C6 || + c >= 0xA960 && c <= 0xA97C || + c >= 0xAC00 && c <= 0xD7A3 || + c >= 0xD7B0 && c <= 0xD7C6 || + c >= 0xD7CB && c <= 0xD7FB || + c >= 0xF900 && c <= 0xFAFF || + c >= 0xFE10 && c <= 0xFE19 || + c >= 0xFE30 && c <= 0xFE52 || + c >= 0xFE54 && c <= 0xFE66 || + c >= 0xFE68 && c <= 0xFE6B || + c >= 0xFF01 && c <= 0xFF60 || + c >= 0xFFE0 && c <= 0xFFE6; + } + +}).call(EditSession.prototype); + +acequire("./edit_session/folding").Folding.call(EditSession.prototype); +acequire("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); + + +config.defineOptions(EditSession.prototype, "session", { + wrap: { + set: function(value) { + if (!value || value == "off") + value = false; + else if (value == "free") + value = true; + else if (value == "printMargin") + value = -1; + else if (typeof value == "string") + value = parseInt(value, 10) || false; + + if (this.$wrap == value) + return; + this.$wrap = value; + if (!value) { + this.setUseWrapMode(false); + } else { + var col = typeof value == "number" ? value : null; + this.setWrapLimitRange(col, col); + this.setUseWrapMode(true); + } + }, + get: function() { + if (this.getUseWrapMode()) { + if (this.$wrap == -1) + return "printMargin"; + if (!this.getWrapLimitRange().min) + return "free"; + return this.$wrap; + } + return "off"; + }, + handlesSet: true + }, + wrapMethod: { + set: function(val) { + val = val == "auto" + ? this.$mode.type != "text" + : val != "text"; + if (val != this.$wrapAsCode) { + this.$wrapAsCode = val; + if (this.$useWrapMode) { + this.$modified = true; + this.$resetRowCache(0); + this.$updateWrapData(0, this.getLength() - 1); + } + } + }, + initialValue: "auto" + }, + indentedSoftWrap: { initialValue: true }, + firstLineNumber: { + set: function() {this._signal("changeBreakpoint");}, + initialValue: 1 + }, + useWorker: { + set: function(useWorker) { + this.$useWorker = useWorker; + + this.$stopWorker(); + if (useWorker) + this.$startWorker(); + }, + initialValue: true + }, + useSoftTabs: {initialValue: true}, + tabSize: { + set: function(tabSize) { + if (isNaN(tabSize) || this.$tabSize === tabSize) return; + + this.$modified = true; + this.$rowLengthCache = []; + this.$tabSize = tabSize; + this._signal("changeTabSize"); + }, + initialValue: 4, + handlesSet: true + }, + overwrite: { + set: function(val) {this._signal("changeOverwrite");}, + initialValue: false + }, + newLineMode: { + set: function(val) {this.doc.setNewLineMode(val)}, + get: function() {return this.doc.getNewLineMode()}, + handlesSet: true + }, + mode: { + set: function(val) { this.setMode(val) }, + get: function() { return this.$modeId } + } +}); + +exports.EditSession = EditSession; +}); + +ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var Search = function() { + this.$options = {}; +}; + +(function() { + this.set = function(options) { + oop.mixin(this.$options, options); + return this; + }; + this.getOptions = function() { + return lang.copyObject(this.$options); + }; + this.setOptions = function(options) { + this.$options = options; + }; + this.find = function(session) { + var options = this.$options; + var iterator = this.$matchIterator(session, options); + if (!iterator) + return false; + + var firstRange = null; + iterator.forEach(function(range, row, offset) { + if (!range.start) { + var column = range.offset + (offset || 0); + firstRange = new Range(row, column, row, column + range.length); + if (!range.length && options.start && options.start.start + && options.skipCurrent != false && firstRange.isEqual(options.start) + ) { + firstRange = null; + return false; + } + } else + firstRange = range; + return true; + }); + + return firstRange; + }; + this.findAll = function(session) { + var options = this.$options; + if (!options.needle) + return []; + this.$assembleRegExp(options); + + var range = options.range; + var lines = range + ? session.getLines(range.start.row, range.end.row) + : session.doc.getAllLines(); + + var ranges = []; + var re = options.re; + if (options.$isMultiLine) { + var len = re.length; + var maxRow = lines.length - len; + var prevRange; + outer: for (var row = re.offset || 0; row <= maxRow; row++) { + for (var j = 0; j < len; j++) + if (lines[row + j].search(re[j]) == -1) + continue outer; + + var startLine = lines[row]; + var line = lines[row + len - 1]; + var startIndex = startLine.length - startLine.match(re[0])[0].length; + var endIndex = line.match(re[len - 1])[0].length; + + if (prevRange && prevRange.end.row === row && + prevRange.end.column > startIndex + ) { + continue; + } + ranges.push(prevRange = new Range( + row, startIndex, row + len - 1, endIndex + )); + if (len > 2) + row = row + len - 2; + } + } else { + for (var i = 0; i < lines.length; i++) { + var matches = lang.getMatchOffsets(lines[i], re); + for (var j = 0; j < matches.length; j++) { + var match = matches[j]; + ranges.push(new Range(i, match.offset, i, match.offset + match.length)); + } + } + } + + if (range) { + var startColumn = range.start.column; + var endColumn = range.start.column; + var i = 0, j = ranges.length - 1; + while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row) + i++; + + while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row) + j--; + + ranges = ranges.slice(i, j + 1); + for (i = 0, j = ranges.length; i < j; i++) { + ranges[i].start.row += range.start.row; + ranges[i].end.row += range.start.row; + } + } + + return ranges; + }; + this.replace = function(input, replacement) { + var options = this.$options; + + var re = this.$assembleRegExp(options); + if (options.$isMultiLine) + return replacement; + + if (!re) + return; + + var match = re.exec(input); + if (!match || match[0].length != input.length) + return null; + + replacement = input.replace(re, replacement); + if (options.preserveCase) { + replacement = replacement.split(""); + for (var i = Math.min(input.length, input.length); i--; ) { + var ch = input[i]; + if (ch && ch.toLowerCase() != ch) + replacement[i] = replacement[i].toUpperCase(); + else + replacement[i] = replacement[i].toLowerCase(); + } + replacement = replacement.join(""); + } + + return replacement; + }; + + this.$matchIterator = function(session, options) { + var re = this.$assembleRegExp(options); + if (!re) + return false; + + var callback; + if (options.$isMultiLine) { + var len = re.length; + var matchIterator = function(line, row, offset) { + var startIndex = line.search(re[0]); + if (startIndex == -1) + return; + for (var i = 1; i < len; i++) { + line = session.getLine(row + i); + if (line.search(re[i]) == -1) + return; + } + + var endIndex = line.match(re[len - 1])[0].length; + + var range = new Range(row, startIndex, row + len - 1, endIndex); + if (re.offset == 1) { + range.start.row--; + range.start.column = Number.MAX_VALUE; + } else if (offset) + range.start.column += offset; + + if (callback(range)) + return true; + }; + } else if (options.backwards) { + var matchIterator = function(line, row, startIndex) { + var matches = lang.getMatchOffsets(line, re); + for (var i = matches.length-1; i >= 0; i--) + if (callback(matches[i], row, startIndex)) + return true; + }; + } else { + var matchIterator = function(line, row, startIndex) { + var matches = lang.getMatchOffsets(line, re); + for (var i = 0; i < matches.length; i++) + if (callback(matches[i], row, startIndex)) + return true; + }; + } + + var lineIterator = this.$lineIterator(session, options); + + return { + forEach: function(_callback) { + callback = _callback; + lineIterator.forEach(matchIterator); + } + }; + }; + + this.$assembleRegExp = function(options, $disableFakeMultiline) { + if (options.needle instanceof RegExp) + return options.re = options.needle; + + var needle = options.needle; + + if (!options.needle) + return options.re = false; + + if (!options.regExp) + needle = lang.escapeRegExp(needle); + + if (options.wholeWord) + needle = addWordBoundary(needle, options); + + var modifier = options.caseSensitive ? "gm" : "gmi"; + + options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle); + if (options.$isMultiLine) + return options.re = this.$assembleMultilineRegExp(needle, modifier); + + try { + var re = new RegExp(needle, modifier); + } catch(e) { + re = false; + } + return options.re = re; + }; + + this.$assembleMultilineRegExp = function(needle, modifier) { + var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n"); + var re = []; + for (var i = 0; i < parts.length; i++) try { + re.push(new RegExp(parts[i], modifier)); + } catch(e) { + return false; + } + if (parts[0] == "") { + re.shift(); + re.offset = 1; + } else { + re.offset = 0; + } + return re; + }; + + this.$lineIterator = function(session, options) { + var backwards = options.backwards == true; + var skipCurrent = options.skipCurrent != false; + + var range = options.range; + var start = options.start; + if (!start) + start = range ? range[backwards ? "end" : "start"] : session.selection.getRange(); + + if (start.start) + start = start[skipCurrent != backwards ? "end" : "start"]; + + var firstRow = range ? range.start.row : 0; + var lastRow = range ? range.end.row : session.getLength() - 1; + + var forEach = backwards ? function(callback) { + var row = start.row; + + var line = session.getLine(row).substring(0, start.column); + if (callback(line, row)) + return; + + for (row--; row >= firstRow; row--) + if (callback(session.getLine(row), row)) + return; + + if (options.wrap == false) + return; + + for (row = lastRow, firstRow = start.row; row >= firstRow; row--) + if (callback(session.getLine(row), row)) + return; + } : function(callback) { + var row = start.row; + + var line = session.getLine(row).substr(start.column); + if (callback(line, row, start.column)) + return; + + for (row = row+1; row <= lastRow; row++) + if (callback(session.getLine(row), row)) + return; + + if (options.wrap == false) + return; + + for (row = firstRow, lastRow = start.row; row <= lastRow; row++) + if (callback(session.getLine(row), row)) + return; + }; + + return {forEach: forEach}; + }; + +}).call(Search.prototype); + +function addWordBoundary(needle, options) { + function wordBoundary(c) { + if (/\w/.test(c) || options.regExp) return "\\b"; + return ""; + } + return wordBoundary(needle[0]) + needle + + wordBoundary(needle[needle.length - 1]); +} + +exports.Search = Search; +}); + +ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keyUtil = acequire("../lib/keys"); +var useragent = acequire("../lib/useragent"); +var KEY_MODS = keyUtil.KEY_MODS; + +function HashHandler(config, platform) { + this.platform = platform || (useragent.isMac ? "mac" : "win"); + this.commands = {}; + this.commandKeyBinding = {}; + this.addCommands(config); + this.$singleCommand = true; +} + +function MultiHashHandler(config, platform) { + HashHandler.call(this, config, platform); + this.$singleCommand = false; +} + +MultiHashHandler.prototype = HashHandler.prototype; + +(function() { + + + this.addCommand = function(command) { + if (this.commands[command.name]) + this.removeCommand(command); + + this.commands[command.name] = command; + + if (command.bindKey) + this._buildKeyHash(command); + }; + + this.removeCommand = function(command, keepCommand) { + var name = command && (typeof command === 'string' ? command : command.name); + command = this.commands[name]; + if (!keepCommand) + delete this.commands[name]; + var ckb = this.commandKeyBinding; + for (var keyId in ckb) { + var cmdGroup = ckb[keyId]; + if (cmdGroup == command) { + delete ckb[keyId]; + } else if (Array.isArray(cmdGroup)) { + var i = cmdGroup.indexOf(command); + if (i != -1) { + cmdGroup.splice(i, 1); + if (cmdGroup.length == 1) + ckb[keyId] = cmdGroup[0]; + } + } + } + }; + + this.bindKey = function(key, command, position) { + if (typeof key == "object" && key) { + if (position == undefined) + position = key.position; + key = key[this.platform]; + } + if (!key) + return; + if (typeof command == "function") + return this.addCommand({exec: command, bindKey: key, name: command.name || key}); + + key.split("|").forEach(function(keyPart) { + var chain = ""; + if (keyPart.indexOf(" ") != -1) { + var parts = keyPart.split(/\s+/); + keyPart = parts.pop(); + parts.forEach(function(keyPart) { + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + chain += (chain ? " " : "") + id; + this._addCommandToBinding(chain, "chainKeys"); + }, this); + chain += " "; + } + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + this._addCommandToBinding(chain + id, command, position); + }, this); + }; + + function getPosition(command) { + return typeof command == "object" && command.bindKey + && command.bindKey.position || 0; + } + this._addCommandToBinding = function(keyId, command, position) { + var ckb = this.commandKeyBinding, i; + if (!command) { + delete ckb[keyId]; + } else if (!ckb[keyId] || this.$singleCommand) { + ckb[keyId] = command; + } else { + if (!Array.isArray(ckb[keyId])) { + ckb[keyId] = [ckb[keyId]]; + } else if ((i = ckb[keyId].indexOf(command)) != -1) { + ckb[keyId].splice(i, 1); + } + + if (typeof position != "number") { + if (position || command.isDefault) + position = -100; + else + position = getPosition(command); + } + var commands = ckb[keyId]; + for (i = 0; i < commands.length; i++) { + var other = commands[i]; + var otherPos = getPosition(other); + if (otherPos > position) + break; + } + commands.splice(i, 0, command); + } + }; + + this.addCommands = function(commands) { + commands && Object.keys(commands).forEach(function(name) { + var command = commands[name]; + if (!command) + return; + + if (typeof command === "string") + return this.bindKey(command, name); + + if (typeof command === "function") + command = { exec: command }; + + if (typeof command !== "object") + return; + + if (!command.name) + command.name = name; + + this.addCommand(command); + }, this); + }; + + this.removeCommands = function(commands) { + Object.keys(commands).forEach(function(name) { + this.removeCommand(commands[name]); + }, this); + }; + + this.bindKeys = function(keyList) { + Object.keys(keyList).forEach(function(key) { + this.bindKey(key, keyList[key]); + }, this); + }; + + this._buildKeyHash = function(command) { + this.bindKey(command.bindKey, command); + }; + this.parseKeys = function(keys) { + var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x}); + var key = parts.pop(); + + var keyCode = keyUtil[key]; + if (keyUtil.FUNCTION_KEYS[keyCode]) + key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase(); + else if (!parts.length) + return {key: key, hashId: -1}; + else if (parts.length == 1 && parts[0] == "shift") + return {key: key.toUpperCase(), hashId: -1}; + + var hashId = 0; + for (var i = parts.length; i--;) { + var modifier = keyUtil.KEY_MODS[parts[i]]; + if (modifier == null) { + if (typeof console != "undefined") + console.error("invalid modifier " + parts[i] + " in " + keys); + return false; + } + hashId |= modifier; + } + return {key: key, hashId: hashId}; + }; + + this.findKeyCommand = function findKeyCommand(hashId, keyString) { + var key = KEY_MODS[hashId] + keyString; + return this.commandKeyBinding[key]; + }; + + this.handleKeyboard = function(data, hashId, keyString, keyCode) { + if (keyCode < 0) return; + var key = KEY_MODS[hashId] + keyString; + var command = this.commandKeyBinding[key]; + if (data.$keyChain) { + data.$keyChain += " " + key; + command = this.commandKeyBinding[data.$keyChain] || command; + } + + if (command) { + if (command == "chainKeys" || command[command.length - 1] == "chainKeys") { + data.$keyChain = data.$keyChain || key; + return {command: "null"}; + } + } + + if (data.$keyChain) { + if ((!hashId || hashId == 4) && keyString.length == 1) + data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input + else if (hashId == -1 || keyCode > 0) + data.$keyChain = ""; // reset keyChain + } + return {command: command}; + }; + + this.getStatusText = function(editor, data) { + return data.$keyChain || ""; + }; + +}).call(HashHandler.prototype); + +exports.HashHandler = HashHandler; +exports.MultiHashHandler = MultiHashHandler; +}); + +ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var MultiHashHandler = acequire("../keyboard/hash_handler").MultiHashHandler; +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CommandManager = function(platform, commands) { + MultiHashHandler.call(this, commands, platform); + this.byName = this.commands; + this.setDefaultHandler("exec", function(e) { + return e.command.exec(e.editor, e.args || {}); + }); +}; + +oop.inherits(CommandManager, MultiHashHandler); + +(function() { + + oop.implement(this, EventEmitter); + + this.exec = function(command, editor, args) { + if (Array.isArray(command)) { + for (var i = command.length; i--; ) { + if (this.exec(command[i], editor, args)) return true; + } + return false; + } + + if (typeof command === "string") + command = this.commands[command]; + + if (!command) + return false; + + if (editor && editor.$readOnly && !command.readOnly) + return false; + + var e = {editor: editor, command: command, args: args}; + e.returnValue = this._emit("exec", e); + this._signal("afterExec", e); + + return e.returnValue === false ? false : true; + }; + + this.toggleRecording = function(editor) { + if (this.$inReplay) + return; + + editor && editor._emit("changeStatus"); + if (this.recording) { + this.macro.pop(); + this.removeEventListener("exec", this.$addCommandToMacro); + + if (!this.macro.length) + this.macro = this.oldMacro; + + return this.recording = false; + } + if (!this.$addCommandToMacro) { + this.$addCommandToMacro = function(e) { + this.macro.push([e.command, e.args]); + }.bind(this); + } + + this.oldMacro = this.macro; + this.macro = []; + this.on("exec", this.$addCommandToMacro); + return this.recording = true; + }; + + this.replay = function(editor) { + if (this.$inReplay || !this.macro) + return; + + if (this.recording) + return this.toggleRecording(editor); + + try { + this.$inReplay = true; + this.macro.forEach(function(x) { + if (typeof x == "string") + this.exec(x, editor); + else + this.exec(x[0], editor, x[1]); + }, this); + } finally { + this.$inReplay = false; + } + }; + + this.trimMacro = function(m) { + return m.map(function(x){ + if (typeof x[0] != "string") + x[0] = x[0].name; + if (!x[1]) + x = x[0]; + return x; + }); + }; + +}).call(CommandManager.prototype); + +exports.CommandManager = CommandManager; + +}); + +ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); +var config = acequire("../config"); +var Range = acequire("../range").Range; + +function bindKey(win, mac) { + return {win: win, mac: mac}; +} +exports.commands = [{ + name: "showSettingsMenu", + bindKey: bindKey("Ctrl-,", "Command-,"), + exec: function(editor) { + config.loadModule("ace/ext/settings_menu", function(module) { + module.init(editor); + editor.showSettingsMenu(); + }); + }, + readOnly: true +}, { + name: "goToNextError", + bindKey: bindKey("Alt-E", "F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, 1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + name: "goToPreviousError", + bindKey: bindKey("Alt-Shift-E", "Shift-F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, -1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + name: "selectall", + bindKey: bindKey("Ctrl-A", "Command-A"), + exec: function(editor) { editor.selectAll(); }, + readOnly: true +}, { + name: "centerselection", + bindKey: bindKey(null, "Ctrl-L"), + exec: function(editor) { editor.centerSelection(); }, + readOnly: true +}, { + name: "gotoline", + bindKey: bindKey("Ctrl-L", "Command-L"), + exec: function(editor) { + var line = parseInt(prompt("Enter line number:"), 10); + if (!isNaN(line)) { + editor.gotoLine(line); + } + }, + readOnly: true +}, { + name: "fold", + bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"), + exec: function(editor) { editor.session.toggleFold(false); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "unfold", + bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), + exec: function(editor) { editor.session.toggleFold(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleFoldWidget", + bindKey: bindKey("F2", "F2"), + exec: function(editor) { editor.session.toggleFoldWidget(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleParentFoldWidget", + bindKey: bindKey("Alt-F2", "Alt-F2"), + exec: function(editor) { editor.session.toggleFoldWidget(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "foldall", + bindKey: bindKey(null, "Ctrl-Command-Option-0"), + exec: function(editor) { editor.session.foldAll(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "foldOther", + bindKey: bindKey("Alt-0", "Command-Option-0"), + exec: function(editor) { + editor.session.foldAll(); + editor.session.unfold(editor.selection.getAllRanges()); + }, + scrollIntoView: "center", + readOnly: true +}, { + name: "unfoldall", + bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"), + exec: function(editor) { editor.session.unfold(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "findnext", + bindKey: bindKey("Ctrl-K", "Command-G"), + exec: function(editor) { editor.findNext(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "findprevious", + bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), + exec: function(editor) { editor.findPrevious(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "selectOrFindNext", + bindKey: bindKey("Alt-K", "Ctrl-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findNext(); + }, + readOnly: true +}, { + name: "selectOrFindPrevious", + bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findPrevious(); + }, + readOnly: true +}, { + name: "find", + bindKey: bindKey("Ctrl-F", "Command-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor)}); + }, + readOnly: true +}, { + name: "overwrite", + bindKey: "Insert", + exec: function(editor) { editor.toggleOverwrite(); }, + readOnly: true +}, { + name: "selecttostart", + bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"), + exec: function(editor) { editor.getSelection().selectFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotostart", + bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"), + exec: function(editor) { editor.navigateFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectup", + bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"), + exec: function(editor) { editor.getSelection().selectUp(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golineup", + bindKey: bindKey("Up", "Up|Ctrl-P"), + exec: function(editor, args) { editor.navigateUp(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttoend", + bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"), + exec: function(editor) { editor.getSelection().selectFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotoend", + bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"), + exec: function(editor) { editor.navigateFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectdown", + bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"), + exec: function(editor) { editor.getSelection().selectDown(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golinedown", + bindKey: bindKey("Down", "Down|Ctrl-N"), + exec: function(editor, args) { editor.navigateDown(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordleft", + bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), + exec: function(editor) { editor.getSelection().selectWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordleft", + bindKey: bindKey("Ctrl-Left", "Option-Left"), + exec: function(editor) { editor.navigateWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolinestart", + bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"), + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolinestart", + bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), + exec: function(editor) { editor.navigateLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectleft", + bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"), + exec: function(editor) { editor.getSelection().selectLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoleft", + bindKey: bindKey("Left", "Left|Ctrl-B"), + exec: function(editor, args) { editor.navigateLeft(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordright", + bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), + exec: function(editor) { editor.getSelection().selectWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordright", + bindKey: bindKey("Ctrl-Right", "Option-Right"), + exec: function(editor) { editor.navigateWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolineend", + bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"), + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolineend", + bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), + exec: function(editor) { editor.navigateLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectright", + bindKey: bindKey("Shift-Right", "Shift-Right"), + exec: function(editor) { editor.getSelection().selectRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoright", + bindKey: bindKey("Right", "Right|Ctrl-F"), + exec: function(editor, args) { editor.navigateRight(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectpagedown", + bindKey: "Shift-PageDown", + exec: function(editor) { editor.selectPageDown(); }, + readOnly: true +}, { + name: "pagedown", + bindKey: bindKey(null, "Option-PageDown"), + exec: function(editor) { editor.scrollPageDown(); }, + readOnly: true +}, { + name: "gotopagedown", + bindKey: bindKey("PageDown", "PageDown|Ctrl-V"), + exec: function(editor) { editor.gotoPageDown(); }, + readOnly: true +}, { + name: "selectpageup", + bindKey: "Shift-PageUp", + exec: function(editor) { editor.selectPageUp(); }, + readOnly: true +}, { + name: "pageup", + bindKey: bindKey(null, "Option-PageUp"), + exec: function(editor) { editor.scrollPageUp(); }, + readOnly: true +}, { + name: "gotopageup", + bindKey: "PageUp", + exec: function(editor) { editor.gotoPageUp(); }, + readOnly: true +}, { + name: "scrollup", + bindKey: bindKey("Ctrl-Up", null), + exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "scrolldown", + bindKey: bindKey("Ctrl-Down", null), + exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "selectlinestart", + bindKey: "Shift-Home", + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectlineend", + bindKey: "Shift-End", + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "togglerecording", + bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), + exec: function(editor) { editor.commands.toggleRecording(editor); }, + readOnly: true +}, { + name: "replaymacro", + bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"), + exec: function(editor) { editor.commands.replay(editor); }, + readOnly: true +}, { + name: "jumptomatching", + bindKey: bindKey("Ctrl-P", "Ctrl-P"), + exec: function(editor) { editor.jumpToMatching(); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "selecttomatching", + bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), + exec: function(editor) { editor.jumpToMatching(true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "expandToMatching", + bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"), + exec: function(editor) { editor.jumpToMatching(true, true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "passKeysToBrowser", + bindKey: bindKey(null, null), + exec: function() {}, + passEvent: true, + readOnly: true +}, { + name: "copy", + exec: function(editor) { + }, + readOnly: true +}, +{ + name: "cut", + exec: function(editor) { + var range = editor.getSelectionRange(); + editor._emit("cut", range); + + if (!editor.selection.isEmpty()) { + editor.session.remove(range); + editor.clearSelection(); + } + }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "paste", + exec: function(editor, args) { + editor.$handlePaste(args); + }, + scrollIntoView: "cursor" +}, { + name: "removeline", + bindKey: bindKey("Ctrl-D", "Command-D"), + exec: function(editor) { editor.removeLines(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEachLine" +}, { + name: "duplicateSelection", + bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"), + exec: function(editor) { editor.duplicateSelection(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "sortlines", + bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"), + exec: function(editor) { editor.sortLines(); }, + scrollIntoView: "selection", + multiSelectAction: "forEachLine" +}, { + name: "togglecomment", + bindKey: bindKey("Ctrl-/", "Command-/"), + exec: function(editor) { editor.toggleCommentLines(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "toggleBlockComment", + bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"), + exec: function(editor) { editor.toggleBlockComment(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "modifyNumberUp", + bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), + exec: function(editor) { editor.modifyNumber(1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "modifyNumberDown", + bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"), + exec: function(editor) { editor.modifyNumber(-1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "replace", + bindKey: bindKey("Ctrl-H", "Command-Option-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true)}); + } +}, { + name: "undo", + bindKey: bindKey("Ctrl-Z", "Command-Z"), + exec: function(editor) { editor.undo(); } +}, { + name: "redo", + bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"), + exec: function(editor) { editor.redo(); } +}, { + name: "copylinesup", + bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"), + exec: function(editor) { editor.copyLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesup", + bindKey: bindKey("Alt-Up", "Option-Up"), + exec: function(editor) { editor.moveLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "copylinesdown", + bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"), + exec: function(editor) { editor.copyLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesdown", + bindKey: bindKey("Alt-Down", "Option-Down"), + exec: function(editor) { editor.moveLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "del", + bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"), + exec: function(editor) { editor.remove("right"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "backspace", + bindKey: bindKey( + "Shift-Backspace|Backspace", + "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H" + ), + exec: function(editor) { editor.remove("left"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "cut_or_delete", + bindKey: bindKey("Shift-Delete", null), + exec: function(editor) { + if (editor.selection.isEmpty()) { + editor.remove("left"); + } else { + return false; + } + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolinestart", + bindKey: bindKey("Alt-Backspace", "Command-Backspace"), + exec: function(editor) { editor.removeToLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolineend", + bindKey: bindKey("Alt-Delete", "Ctrl-K"), + exec: function(editor) { editor.removeToLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordleft", + bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), + exec: function(editor) { editor.removeWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordright", + bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), + exec: function(editor) { editor.removeWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "outdent", + bindKey: bindKey("Shift-Tab", "Shift-Tab"), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "indent", + bindKey: bindKey("Tab", "Tab"), + exec: function(editor) { editor.indent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "blockoutdent", + bindKey: bindKey("Ctrl-[", "Ctrl-["), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "blockindent", + bindKey: bindKey("Ctrl-]", "Ctrl-]"), + exec: function(editor) { editor.blockIndent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "insertstring", + exec: function(editor, str) { editor.insert(str); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "inserttext", + exec: function(editor, args) { + editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "splitline", + bindKey: bindKey(null, "Ctrl-O"), + exec: function(editor) { editor.splitLine(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "transposeletters", + bindKey: bindKey("Ctrl-T", "Ctrl-T"), + exec: function(editor) { editor.transposeLetters(); }, + multiSelectAction: function(editor) {editor.transposeSelections(1); }, + scrollIntoView: "cursor" +}, { + name: "touppercase", + bindKey: bindKey("Ctrl-U", "Ctrl-U"), + exec: function(editor) { editor.toUpperCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "tolowercase", + bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), + exec: function(editor) { editor.toLowerCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "expandtoline", + bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"), + exec: function(editor) { + var range = editor.selection.getRange(); + + range.start.column = range.end.column = 0; + range.end.row++; + editor.selection.setRange(range, false); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "joinlines", + bindKey: bindKey(null, null), + exec: function(editor) { + var isBackwards = editor.selection.isBackwards(); + var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor(); + var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead(); + var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length; + var selectedText = editor.session.doc.getTextRange(editor.selection.getRange()); + var selectedCount = selectedText.replace(/\n\s*/, " ").length; + var insertLine = editor.session.doc.getLine(selectionStart.row); + + for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) { + var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i))); + if (curLine.length !== 0) { + curLine = " " + curLine; + } + insertLine += curLine; + } + + if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) { + insertLine += editor.session.doc.getNewLineCharacter(); + } + + editor.clearSelection(); + editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine); + + if (selectedCount > 0) { + editor.selection.moveCursorTo(selectionStart.row, selectionStart.column); + editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount); + } else { + firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol; + editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol); + } + }, + multiSelectAction: "forEach", + readOnly: true +}, { + name: "invertSelection", + bindKey: bindKey(null, null), + exec: function(editor) { + var endRow = editor.session.doc.getLength() - 1; + var endCol = editor.session.doc.getLine(endRow).length; + var ranges = editor.selection.rangeList.ranges; + var newRanges = []; + if (ranges.length < 1) { + ranges = [editor.selection.getRange()]; + } + + for (var i = 0; i < ranges.length; i++) { + if (i == (ranges.length - 1)) { + if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) { + newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol)); + } + } + + if (i === 0) { + if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) { + newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column)); + } + } else { + newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column)); + } + } + + editor.exitMultiSelectMode(); + editor.clearSelection(); + + for(var i = 0; i < newRanges.length; i++) { + editor.selection.addRange(newRanges[i], false); + } + }, + readOnly: true, + scrollIntoView: "none" +}]; + +}); + +ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var lang = acequire("./lib/lang"); +var useragent = acequire("./lib/useragent"); +var TextInput = acequire("./keyboard/textinput").TextInput; +var MouseHandler = acequire("./mouse/mouse_handler").MouseHandler; +var FoldHandler = acequire("./mouse/fold_handler").FoldHandler; +var KeyBinding = acequire("./keyboard/keybinding").KeyBinding; +var EditSession = acequire("./edit_session").EditSession; +var Search = acequire("./search").Search; +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var CommandManager = acequire("./commands/command_manager").CommandManager; +var defaultCommands = acequire("./commands/default_commands").commands; +var config = acequire("./config"); +var TokenIterator = acequire("./token_iterator").TokenIterator; +var Editor = function(renderer, session) { + var container = renderer.getContainerElement(); + this.container = container; + this.renderer = renderer; + + this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); + this.textInput = new TextInput(renderer.getTextAreaContainer(), this); + this.renderer.textarea = this.textInput.getElement(); + this.keyBinding = new KeyBinding(this); + this.$mouseHandler = new MouseHandler(this); + new FoldHandler(this); + + this.$blockScrolling = 0; + this.$search = new Search().set({ + wrap: true + }); + + this.$historyTracker = this.$historyTracker.bind(this); + this.commands.on("exec", this.$historyTracker); + + this.$initOperationListeners(); + + this._$emitInputEvent = lang.delayedCall(function() { + this._signal("input", {}); + if (this.session && this.session.bgTokenizer) + this.session.bgTokenizer.scheduleStart(); + }.bind(this)); + + this.on("change", function(_, _self) { + _self._$emitInputEvent.schedule(31); + }); + + this.setSession(session || new EditSession("")); + config.resetOptions(this); + config._signal("editor", this); +}; + +(function(){ + + oop.implement(this, EventEmitter); + + this.$initOperationListeners = function() { + function last(a) {return a[a.length - 1]} + + this.selections = []; + this.commands.on("exec", this.startOperation.bind(this), true); + this.commands.on("afterExec", this.endOperation.bind(this), true); + + this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this)); + + this.on("change", function() { + this.curOp || this.startOperation(); + this.curOp.docChanged = true; + }.bind(this), true); + + this.on("changeSelection", function() { + this.curOp || this.startOperation(); + this.curOp.selectionChanged = true; + }.bind(this), true); + }; + + this.curOp = null; + this.prevOp = {}; + this.startOperation = function(commadEvent) { + if (this.curOp) { + if (!commadEvent || this.curOp.command) + return; + this.prevOp = this.curOp; + } + if (!commadEvent) { + this.previousCommand = null; + commadEvent = {}; + } + + this.$opResetTimer.schedule(); + this.curOp = { + command: commadEvent.command || {}, + args: commadEvent.args, + scrollTop: this.renderer.scrollTop + }; + if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined) + this.$blockScrolling++; + }; + + this.endOperation = function(e) { + if (this.curOp) { + if (e && e.returnValue === false) + return this.curOp = null; + this._signal("beforeEndOperation"); + var command = this.curOp.command; + if (command.name && this.$blockScrolling > 0) + this.$blockScrolling--; + var scrollIntoView = command && command.scrollIntoView; + if (scrollIntoView) { + switch (scrollIntoView) { + case "center-animate": + scrollIntoView = "animate"; + case "center": + this.renderer.scrollCursorIntoView(null, 0.5); + break; + case "animate": + case "cursor": + this.renderer.scrollCursorIntoView(); + break; + case "selectionPart": + var range = this.selection.getRange(); + var config = this.renderer.layerConfig; + if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) { + this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); + } + break; + default: + break; + } + if (scrollIntoView == "animate") + this.renderer.animateScrolling(this.curOp.scrollTop); + } + + this.prevOp = this.curOp; + this.curOp = null; + } + }; + this.$mergeableCommands = ["backspace", "del", "insertstring"]; + this.$historyTracker = function(e) { + if (!this.$mergeUndoDeltas) + return; + + var prev = this.prevOp; + var mergeableCommands = this.$mergeableCommands; + var shouldMerge = prev.command && (e.command.name == prev.command.name); + if (e.command.name == "insertstring") { + var text = e.args; + if (this.mergeNextCommand === undefined) + this.mergeNextCommand = true; + + shouldMerge = shouldMerge + && this.mergeNextCommand // previous command allows to coalesce with + && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type + + this.mergeNextCommand = true; + } else { + shouldMerge = shouldMerge + && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable + } + + if ( + this.$mergeUndoDeltas != "always" + && Date.now() - this.sequenceStartTime > 2000 + ) { + shouldMerge = false; // the sequence is too long + } + + if (shouldMerge) + this.session.mergeUndoDeltas = true; + else if (mergeableCommands.indexOf(e.command.name) !== -1) + this.sequenceStartTime = Date.now(); + }; + this.setKeyboardHandler = function(keyboardHandler, cb) { + if (keyboardHandler && typeof keyboardHandler === "string") { + this.$keybindingId = keyboardHandler; + var _self = this; + config.loadModule(["keybinding", keyboardHandler], function(module) { + if (_self.$keybindingId == keyboardHandler) + _self.keyBinding.setKeyboardHandler(module && module.handler); + cb && cb(); + }); + } else { + this.$keybindingId = null; + this.keyBinding.setKeyboardHandler(keyboardHandler); + cb && cb(); + } + }; + this.getKeyboardHandler = function() { + return this.keyBinding.getKeyboardHandler(); + }; + this.setSession = function(session) { + if (this.session == session) + return; + if (this.curOp) this.endOperation(); + this.curOp = {}; + + var oldSession = this.session; + if (oldSession) { + this.session.off("change", this.$onDocumentChange); + this.session.off("changeMode", this.$onChangeMode); + this.session.off("tokenizerUpdate", this.$onTokenizerUpdate); + this.session.off("changeTabSize", this.$onChangeTabSize); + this.session.off("changeWrapLimit", this.$onChangeWrapLimit); + this.session.off("changeWrapMode", this.$onChangeWrapMode); + this.session.off("changeFold", this.$onChangeFold); + this.session.off("changeFrontMarker", this.$onChangeFrontMarker); + this.session.off("changeBackMarker", this.$onChangeBackMarker); + this.session.off("changeBreakpoint", this.$onChangeBreakpoint); + this.session.off("changeAnnotation", this.$onChangeAnnotation); + this.session.off("changeOverwrite", this.$onCursorChange); + this.session.off("changeScrollTop", this.$onScrollTopChange); + this.session.off("changeScrollLeft", this.$onScrollLeftChange); + + var selection = this.session.getSelection(); + selection.off("changeCursor", this.$onCursorChange); + selection.off("changeSelection", this.$onSelectionChange); + } + + this.session = session; + if (session) { + this.$onDocumentChange = this.onDocumentChange.bind(this); + session.on("change", this.$onDocumentChange); + this.renderer.setSession(session); + + this.$onChangeMode = this.onChangeMode.bind(this); + session.on("changeMode", this.$onChangeMode); + + this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); + session.on("tokenizerUpdate", this.$onTokenizerUpdate); + + this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer); + session.on("changeTabSize", this.$onChangeTabSize); + + this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); + session.on("changeWrapLimit", this.$onChangeWrapLimit); + + this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); + session.on("changeWrapMode", this.$onChangeWrapMode); + + this.$onChangeFold = this.onChangeFold.bind(this); + session.on("changeFold", this.$onChangeFold); + + this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); + this.session.on("changeFrontMarker", this.$onChangeFrontMarker); + + this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); + this.session.on("changeBackMarker", this.$onChangeBackMarker); + + this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); + this.session.on("changeBreakpoint", this.$onChangeBreakpoint); + + this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); + this.session.on("changeAnnotation", this.$onChangeAnnotation); + + this.$onCursorChange = this.onCursorChange.bind(this); + this.session.on("changeOverwrite", this.$onCursorChange); + + this.$onScrollTopChange = this.onScrollTopChange.bind(this); + this.session.on("changeScrollTop", this.$onScrollTopChange); + + this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); + this.session.on("changeScrollLeft", this.$onScrollLeftChange); + + this.selection = session.getSelection(); + this.selection.on("changeCursor", this.$onCursorChange); + + this.$onSelectionChange = this.onSelectionChange.bind(this); + this.selection.on("changeSelection", this.$onSelectionChange); + + this.onChangeMode(); + + this.$blockScrolling += 1; + this.onCursorChange(); + this.$blockScrolling -= 1; + + this.onScrollTopChange(); + this.onScrollLeftChange(); + this.onSelectionChange(); + this.onChangeFrontMarker(); + this.onChangeBackMarker(); + this.onChangeBreakpoint(); + this.onChangeAnnotation(); + this.session.getUseWrapMode() && this.renderer.adjustWrapLimit(); + this.renderer.updateFull(); + } else { + this.selection = null; + this.renderer.setSession(session); + } + + this._signal("changeSession", { + session: session, + oldSession: oldSession + }); + + this.curOp = null; + + oldSession && oldSession._signal("changeEditor", {oldEditor: this}); + session && session._signal("changeEditor", {editor: this}); + }; + this.getSession = function() { + return this.session; + }; + this.setValue = function(val, cursorPos) { + this.session.doc.setValue(val); + + if (!cursorPos) + this.selectAll(); + else if (cursorPos == 1) + this.navigateFileEnd(); + else if (cursorPos == -1) + this.navigateFileStart(); + + return val; + }; + this.getValue = function() { + return this.session.getValue(); + }; + this.getSelection = function() { + return this.selection; + }; + this.resize = function(force) { + this.renderer.onResize(force); + }; + this.setTheme = function(theme, cb) { + this.renderer.setTheme(theme, cb); + }; + this.getTheme = function() { + return this.renderer.getTheme(); + }; + this.setStyle = function(style) { + this.renderer.setStyle(style); + }; + this.unsetStyle = function(style) { + this.renderer.unsetStyle(style); + }; + this.getFontSize = function () { + return this.getOption("fontSize") || + dom.computedStyle(this.container, "fontSize"); + }; + this.setFontSize = function(size) { + this.setOption("fontSize", size); + }; + + this.$highlightBrackets = function() { + if (this.session.$bracketHighlight) { + this.session.removeMarker(this.session.$bracketHighlight); + this.session.$bracketHighlight = null; + } + + if (this.$highlightPending) { + return; + } + var self = this; + this.$highlightPending = true; + setTimeout(function() { + self.$highlightPending = false; + var session = self.session; + if (!session || !session.bgTokenizer) return; + var pos = session.findMatchingBracket(self.getCursorPosition()); + if (pos) { + var range = new Range(pos.row, pos.column, pos.row, pos.column + 1); + } else if (session.$mode.getMatching) { + var range = session.$mode.getMatching(self.session); + } + if (range) + session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text"); + }, 50); + }; + this.$highlightTags = function() { + if (this.$highlightTagPending) + return; + var self = this; + this.$highlightTagPending = true; + setTimeout(function() { + self.$highlightTagPending = false; + + var session = self.session; + if (!session || !session.bgTokenizer) return; + + var pos = self.getCursorPosition(); + var iterator = new TokenIterator(self.session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + + if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) { + session.removeMarker(session.$tagHighlight); + session.$tagHighlight = null; + return; + } + + if (token.type.indexOf("tag-open") != -1) { + token = iterator.stepForward(); + if (!token) + return; + } + + var tag = token.value; + var depth = 0; + var prevToken = iterator.stepBackward(); + + if (prevToken.value == '<'){ + do { + prevToken = token; + token = iterator.stepForward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<'){ + depth++; + } else if (prevToken.value === '= 0); + } else { + do { + token = prevToken; + prevToken = iterator.stepBackward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<') { + depth++; + } else if (prevToken.value === ' 1)) + highlight = false; + } + + if (session.$highlightLineMarker && !highlight) { + session.removeMarker(session.$highlightLineMarker.id); + session.$highlightLineMarker = null; + } else if (!session.$highlightLineMarker && highlight) { + var range = new Range(highlight.row, highlight.column, highlight.row, Infinity); + range.id = session.addMarker(range, "ace_active-line", "screenLine"); + session.$highlightLineMarker = range; + } else if (highlight) { + session.$highlightLineMarker.start.row = highlight.row; + session.$highlightLineMarker.end.row = highlight.row; + session.$highlightLineMarker.start.column = highlight.column; + session._signal("changeBackMarker"); + } + }; + + this.onSelectionChange = function(e) { + var session = this.session; + + if (session.$selectionMarker) { + session.removeMarker(session.$selectionMarker); + } + session.$selectionMarker = null; + + if (!this.selection.isEmpty()) { + var range = this.selection.getRange(); + var style = this.getSelectionStyle(); + session.$selectionMarker = session.addMarker(range, "ace_selection", style); + } else { + this.$updateHighlightActiveLine(); + } + + var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp(); + this.session.highlight(re); + + this._signal("changeSelection"); + }; + + this.$getSelectionHighLightRegexp = function() { + var session = this.session; + + var selection = this.getSelectionRange(); + if (selection.isEmpty() || selection.isMultiLine()) + return; + + var startOuter = selection.start.column - 1; + var endOuter = selection.end.column + 1; + var line = session.getLine(selection.start.row); + var lineCols = line.length; + var needle = line.substring(Math.max(startOuter, 0), + Math.min(endOuter, lineCols)); + if ((startOuter >= 0 && /^[\w\d]/.test(needle)) || + (endOuter <= lineCols && /[\w\d]$/.test(needle))) + return; + + needle = line.substring(selection.start.column, selection.end.column); + if (!/^[\w\d]+$/.test(needle)) + return; + + var re = this.$search.$assembleRegExp({ + wholeWord: true, + caseSensitive: true, + needle: needle + }); + + return re; + }; + + + this.onChangeFrontMarker = function() { + this.renderer.updateFrontMarkers(); + }; + + this.onChangeBackMarker = function() { + this.renderer.updateBackMarkers(); + }; + + + this.onChangeBreakpoint = function() { + this.renderer.updateBreakpoints(); + }; + + this.onChangeAnnotation = function() { + this.renderer.setAnnotations(this.session.getAnnotations()); + }; + + + this.onChangeMode = function(e) { + this.renderer.updateText(); + this._emit("changeMode", e); + }; + + + this.onChangeWrapLimit = function() { + this.renderer.updateFull(); + }; + + this.onChangeWrapMode = function() { + this.renderer.onResize(true); + }; + + + this.onChangeFold = function() { + this.$updateHighlightActiveLine(); + this.renderer.updateFull(); + }; + this.getSelectedText = function() { + return this.session.getTextRange(this.getSelectionRange()); + }; + this.getCopyText = function() { + var text = this.getSelectedText(); + this._signal("copy", text); + return text; + }; + this.onCopy = function() { + this.commands.exec("copy", this); + }; + this.onCut = function() { + this.commands.exec("cut", this); + }; + this.onPaste = function(text, event) { + var e = {text: text, event: event}; + this.commands.exec("paste", this, e); + }; + + this.$handlePaste = function(e) { + if (typeof e == "string") + e = {text: e}; + this._signal("paste", e); + var text = e.text; + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) { + this.insert(text); + } else { + var lines = text.split(/\r\n|\r|\n/); + var ranges = this.selection.rangeList.ranges; + + if (lines.length > ranges.length || lines.length < 2 || !lines[1]) + return this.commands.exec("insertstring", this, text); + + for (var i = ranges.length; i--;) { + var range = ranges[i]; + if (!range.isEmpty()) + this.session.remove(range); + + this.session.insert(range.start, lines[i]); + } + } + }; + + this.execCommand = function(command, args) { + return this.commands.exec(command, this, args); + }; + this.insert = function(text, pasted) { + var session = this.session; + var mode = session.getMode(); + var cursor = this.getCursorPosition(); + + if (this.getBehavioursEnabled() && !pasted) { + var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); + if (transform) { + if (text !== transform.text) { + this.session.mergeUndoDeltas = false; + this.$mergeNextCommand = false; + } + text = transform.text; + + } + } + + if (text == "\t") + text = this.session.getTabString(); + if (!this.selection.isEmpty()) { + var range = this.getSelectionRange(); + cursor = this.session.remove(range); + this.clearSelection(); + } + else if (this.session.getOverwrite()) { + var range = new Range.fromPoints(cursor, cursor); + range.end.column += text.length; + this.session.remove(range); + } + + if (text == "\n" || text == "\r\n") { + var line = session.getLine(cursor.row); + if (cursor.column > line.search(/\S|$/)) { + var d = line.substr(cursor.column).search(/\S|$/); + session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d); + } + } + this.clearSelection(); + + var start = cursor.column; + var lineState = session.getState(cursor.row); + var line = session.getLine(cursor.row); + var shouldOutdent = mode.checkOutdent(lineState, line, text); + var end = session.insert(cursor, text); + + if (transform && transform.selection) { + if (transform.selection.length == 2) { // Transform relative to the current column + this.selection.setSelectionRange( + new Range(cursor.row, start + transform.selection[0], + cursor.row, start + transform.selection[1])); + } else { // Transform relative to the current row. + this.selection.setSelectionRange( + new Range(cursor.row + transform.selection[0], + transform.selection[1], + cursor.row + transform.selection[2], + transform.selection[3])); + } + } + + if (session.getDocument().isNewLine(text)) { + var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); + + session.insert({row: cursor.row+1, column: 0}, lineIndent); + } + if (shouldOutdent) + mode.autoOutdent(lineState, session, cursor.row); + }; + + this.onTextInput = function(text) { + this.keyBinding.onTextInput(text); + }; + + this.onCommandKey = function(e, hashId, keyCode) { + this.keyBinding.onCommandKey(e, hashId, keyCode); + }; + this.setOverwrite = function(overwrite) { + this.session.setOverwrite(overwrite); + }; + this.getOverwrite = function() { + return this.session.getOverwrite(); + }; + this.toggleOverwrite = function() { + this.session.toggleOverwrite(); + }; + this.setScrollSpeed = function(speed) { + this.setOption("scrollSpeed", speed); + }; + this.getScrollSpeed = function() { + return this.getOption("scrollSpeed"); + }; + this.setDragDelay = function(dragDelay) { + this.setOption("dragDelay", dragDelay); + }; + this.getDragDelay = function() { + return this.getOption("dragDelay"); + }; + this.setSelectionStyle = function(val) { + this.setOption("selectionStyle", val); + }; + this.getSelectionStyle = function() { + return this.getOption("selectionStyle"); + }; + this.setHighlightActiveLine = function(shouldHighlight) { + this.setOption("highlightActiveLine", shouldHighlight); + }; + this.getHighlightActiveLine = function() { + return this.getOption("highlightActiveLine"); + }; + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + this.setHighlightSelectedWord = function(shouldHighlight) { + this.setOption("highlightSelectedWord", shouldHighlight); + }; + this.getHighlightSelectedWord = function() { + return this.$highlightSelectedWord; + }; + + this.setAnimatedScroll = function(shouldAnimate){ + this.renderer.setAnimatedScroll(shouldAnimate); + }; + + this.getAnimatedScroll = function(){ + return this.renderer.getAnimatedScroll(); + }; + this.setShowInvisibles = function(showInvisibles) { + this.renderer.setShowInvisibles(showInvisibles); + }; + this.getShowInvisibles = function() { + return this.renderer.getShowInvisibles(); + }; + + this.setDisplayIndentGuides = function(display) { + this.renderer.setDisplayIndentGuides(display); + }; + + this.getDisplayIndentGuides = function() { + return this.renderer.getDisplayIndentGuides(); + }; + this.setShowPrintMargin = function(showPrintMargin) { + this.renderer.setShowPrintMargin(showPrintMargin); + }; + this.getShowPrintMargin = function() { + return this.renderer.getShowPrintMargin(); + }; + this.setPrintMarginColumn = function(showPrintMargin) { + this.renderer.setPrintMarginColumn(showPrintMargin); + }; + this.getPrintMarginColumn = function() { + return this.renderer.getPrintMarginColumn(); + }; + this.setReadOnly = function(readOnly) { + this.setOption("readOnly", readOnly); + }; + this.getReadOnly = function() { + return this.getOption("readOnly"); + }; + this.setBehavioursEnabled = function (enabled) { + this.setOption("behavioursEnabled", enabled); + }; + this.getBehavioursEnabled = function () { + return this.getOption("behavioursEnabled"); + }; + this.setWrapBehavioursEnabled = function (enabled) { + this.setOption("wrapBehavioursEnabled", enabled); + }; + this.getWrapBehavioursEnabled = function () { + return this.getOption("wrapBehavioursEnabled"); + }; + this.setShowFoldWidgets = function(show) { + this.setOption("showFoldWidgets", show); + + }; + this.getShowFoldWidgets = function() { + return this.getOption("showFoldWidgets"); + }; + + this.setFadeFoldWidgets = function(fade) { + this.setOption("fadeFoldWidgets", fade); + }; + + this.getFadeFoldWidgets = function() { + return this.getOption("fadeFoldWidgets"); + }; + this.remove = function(dir) { + if (this.selection.isEmpty()){ + if (dir == "left") + this.selection.selectLeft(); + else + this.selection.selectRight(); + } + + var range = this.getSelectionRange(); + if (this.getBehavioursEnabled()) { + var session = this.session; + var state = session.getState(range.start.row); + var new_range = session.getMode().transformAction(state, 'deletion', this, session, range); + + if (range.end.column === 0) { + var text = session.getTextRange(range); + if (text[text.length - 1] == "\n") { + var line = session.getLine(range.end.row); + if (/^\s+$/.test(line)) { + range.end.column = line.length; + } + } + } + if (new_range) + range = new_range; + } + + this.session.remove(range); + this.clearSelection(); + }; + this.removeWordRight = function() { + if (this.selection.isEmpty()) + this.selection.selectWordRight(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeWordLeft = function() { + if (this.selection.isEmpty()) + this.selection.selectWordLeft(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeToLineStart = function() { + if (this.selection.isEmpty()) + this.selection.selectLineStart(); + + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + }; + this.removeToLineEnd = function() { + if (this.selection.isEmpty()) + this.selection.selectLineEnd(); + + var range = this.getSelectionRange(); + if (range.start.column == range.end.column && range.start.row == range.end.row) { + range.end.column = 0; + range.end.row++; + } + + this.session.remove(range); + this.clearSelection(); + }; + this.splitLine = function() { + if (!this.selection.isEmpty()) { + this.session.remove(this.getSelectionRange()); + this.clearSelection(); + } + + var cursor = this.getCursorPosition(); + this.insert("\n"); + this.moveCursorToPosition(cursor); + }; + this.transposeLetters = function() { + if (!this.selection.isEmpty()) { + return; + } + + var cursor = this.getCursorPosition(); + var column = cursor.column; + if (column === 0) + return; + + var line = this.session.getLine(cursor.row); + var swap, range; + if (column < line.length) { + swap = line.charAt(column) + line.charAt(column-1); + range = new Range(cursor.row, column-1, cursor.row, column+1); + } + else { + swap = line.charAt(column-1) + line.charAt(column-2); + range = new Range(cursor.row, column-2, cursor.row, column); + } + this.session.replace(range, swap); + }; + this.toLowerCase = function() { + var originalRange = this.getSelectionRange(); + if (this.selection.isEmpty()) { + this.selection.selectWord(); + } + + var range = this.getSelectionRange(); + var text = this.session.getTextRange(range); + this.session.replace(range, text.toLowerCase()); + this.selection.setSelectionRange(originalRange); + }; + this.toUpperCase = function() { + var originalRange = this.getSelectionRange(); + if (this.selection.isEmpty()) { + this.selection.selectWord(); + } + + var range = this.getSelectionRange(); + var text = this.session.getTextRange(range); + this.session.replace(range, text.toUpperCase()); + this.selection.setSelectionRange(originalRange); + }; + this.indent = function() { + var session = this.session; + var range = this.getSelectionRange(); + + if (range.start.row < range.end.row) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } else if (range.start.column < range.end.column) { + var text = session.getTextRange(range); + if (!/^\s+$/.test(text)) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } + } + + var line = session.getLine(range.start.row); + var position = range.start; + var size = session.getTabSize(); + var column = session.documentToScreenColumn(position.row, position.column); + + if (this.session.getUseSoftTabs()) { + var count = (size - column % size); + var indentString = lang.stringRepeat(" ", count); + } else { + var count = column % size; + while (line[range.start.column - 1] == " " && count) { + range.start.column--; + count--; + } + this.selection.setSelectionRange(range); + indentString = "\t"; + } + return this.insert(indentString); + }; + this.blockIndent = function() { + var rows = this.$getSelectedRows(); + this.session.indentRows(rows.first, rows.last, "\t"); + }; + this.blockOutdent = function() { + var selection = this.session.getSelection(); + this.session.outdentRows(selection.getRange()); + }; + this.sortLines = function() { + var rows = this.$getSelectedRows(); + var session = this.session; + + var lines = []; + for (i = rows.first; i <= rows.last; i++) + lines.push(session.getLine(i)); + + lines.sort(function(a, b) { + if (a.toLowerCase() < b.toLowerCase()) return -1; + if (a.toLowerCase() > b.toLowerCase()) return 1; + return 0; + }); + + var deleteRange = new Range(0, 0, 0, 0); + for (var i = rows.first; i <= rows.last; i++) { + var line = session.getLine(i); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = line.length; + session.replace(deleteRange, lines[i-rows.first]); + } + }; + this.toggleCommentLines = function() { + var state = this.session.getState(this.getCursorPosition().row); + var rows = this.$getSelectedRows(); + this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last); + }; + + this.toggleBlockComment = function() { + var cursor = this.getCursorPosition(); + var state = this.session.getState(cursor.row); + var range = this.getSelectionRange(); + this.session.getMode().toggleBlockComment(state, this.session, range, cursor); + }; + this.getNumberAt = function(row, column) { + var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g; + _numberRx.lastIndex = 0; + + var s = this.session.getLine(row); + while (_numberRx.lastIndex < column) { + var m = _numberRx.exec(s); + if(m.index <= column && m.index+m[0].length >= column){ + var number = { + value: m[0], + start: m.index, + end: m.index+m[0].length + }; + return number; + } + } + return null; + }; + this.modifyNumber = function(amount) { + var row = this.selection.getCursor().row; + var column = this.selection.getCursor().column; + var charRange = new Range(row, column-1, row, column); + + var c = this.session.getTextRange(charRange); + if (!isNaN(parseFloat(c)) && isFinite(c)) { + var nr = this.getNumberAt(row, column); + if (nr) { + var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end; + var decimals = nr.start + nr.value.length - fp; + + var t = parseFloat(nr.value); + t *= Math.pow(10, decimals); + + + if(fp !== nr.end && column < fp){ + amount *= Math.pow(10, nr.end - column - 1); + } else { + amount *= Math.pow(10, nr.end - column); + } + + t += amount; + t /= Math.pow(10, decimals); + var nnr = t.toFixed(decimals); + var replaceRange = new Range(row, nr.start, row, nr.end); + this.session.replace(replaceRange, nnr); + this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length)); + + } + } + }; + this.removeLines = function() { + var rows = this.$getSelectedRows(); + this.session.removeFullLines(rows.first, rows.last); + this.clearSelection(); + }; + + this.duplicateSelection = function() { + var sel = this.selection; + var doc = this.session; + var range = sel.getRange(); + var reverse = sel.isBackwards(); + if (range.isEmpty()) { + var row = range.start.row; + doc.duplicateLines(row, row); + } else { + var point = reverse ? range.start : range.end; + var endPoint = doc.insert(point, doc.getTextRange(range), false); + range.start = point; + range.end = endPoint; + + sel.setSelectionRange(range, reverse); + } + }; + this.moveLinesDown = function() { + this.$moveLines(1, false); + }; + this.moveLinesUp = function() { + this.$moveLines(-1, false); + }; + this.moveText = function(range, toPosition, copy) { + return this.session.moveText(range, toPosition, copy); + }; + this.copyLinesUp = function() { + this.$moveLines(-1, true); + }; + this.copyLinesDown = function() { + this.$moveLines(1, true); + }; + this.$moveLines = function(dir, copy) { + var rows, moved; + var selection = this.selection; + if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) { + var range = selection.toOrientedRange(); + rows = this.$getSelectedRows(range); + moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir); + if (copy && dir == -1) moved = 0; + range.moveBy(moved, 0); + selection.fromOrientedRange(range); + } else { + var ranges = selection.rangeList.ranges; + selection.rangeList.detach(this.session); + this.inVirtualSelectionMode = true; + + var diff = 0; + var totalDiff = 0; + var l = ranges.length; + for (var i = 0; i < l; i++) { + var rangeIndex = i; + ranges[i].moveBy(diff, 0); + rows = this.$getSelectedRows(ranges[i]); + var first = rows.first; + var last = rows.last; + while (++i < l) { + if (totalDiff) ranges[i].moveBy(totalDiff, 0); + var subRows = this.$getSelectedRows(ranges[i]); + if (copy && subRows.first != last) + break; + else if (!copy && subRows.first > last + 1) + break; + last = subRows.last; + } + i--; + diff = this.session.$moveLines(first, last, copy ? 0 : dir); + if (copy && dir == -1) rangeIndex = i + 1; + while (rangeIndex <= i) { + ranges[rangeIndex].moveBy(diff, 0); + rangeIndex++; + } + if (!copy) diff = 0; + totalDiff += diff; + } + + selection.fromOrientedRange(selection.ranges[0]); + selection.rangeList.attach(this.session); + this.inVirtualSelectionMode = false; + } + }; + this.$getSelectedRows = function(range) { + range = (range || this.getSelectionRange()).collapseRows(); + + return { + first: this.session.getRowFoldStart(range.start.row), + last: this.session.getRowFoldEnd(range.end.row) + }; + }; + + this.onCompositionStart = function(text) { + this.renderer.showComposition(this.getCursorPosition()); + }; + + this.onCompositionUpdate = function(text) { + this.renderer.setCompositionText(text); + }; + + this.onCompositionEnd = function() { + this.renderer.hideComposition(); + }; + this.getFirstVisibleRow = function() { + return this.renderer.getFirstVisibleRow(); + }; + this.getLastVisibleRow = function() { + return this.renderer.getLastVisibleRow(); + }; + this.isRowVisible = function(row) { + return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow()); + }; + this.isRowFullyVisible = function(row) { + return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow()); + }; + this.$getVisibleRowCount = function() { + return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1; + }; + + this.$moveByPage = function(dir, select) { + var renderer = this.renderer; + var config = this.renderer.layerConfig; + var rows = dir * Math.floor(config.height / config.lineHeight); + + this.$blockScrolling++; + if (select === true) { + this.selection.$moveSelection(function(){ + this.moveCursorBy(rows, 0); + }); + } else if (select === false) { + this.selection.moveCursorBy(rows, 0); + this.selection.clearSelection(); + } + this.$blockScrolling--; + + var scrollTop = renderer.scrollTop; + + renderer.scrollBy(0, rows * config.lineHeight); + if (select != null) + renderer.scrollCursorIntoView(null, 0.5); + + renderer.animateScrolling(scrollTop); + }; + this.selectPageDown = function() { + this.$moveByPage(1, true); + }; + this.selectPageUp = function() { + this.$moveByPage(-1, true); + }; + this.gotoPageDown = function() { + this.$moveByPage(1, false); + }; + this.gotoPageUp = function() { + this.$moveByPage(-1, false); + }; + this.scrollPageDown = function() { + this.$moveByPage(1); + }; + this.scrollPageUp = function() { + this.$moveByPage(-1); + }; + this.scrollToRow = function(row) { + this.renderer.scrollToRow(row); + }; + this.scrollToLine = function(line, center, animate, callback) { + this.renderer.scrollToLine(line, center, animate, callback); + }; + this.centerSelection = function() { + var range = this.getSelectionRange(); + var pos = { + row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2), + column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2) + }; + this.renderer.alignCursor(pos, 0.5); + }; + this.getCursorPosition = function() { + return this.selection.getCursor(); + }; + this.getCursorPositionScreen = function() { + return this.session.documentToScreenPosition(this.getCursorPosition()); + }; + this.getSelectionRange = function() { + return this.selection.getRange(); + }; + this.selectAll = function() { + this.$blockScrolling += 1; + this.selection.selectAll(); + this.$blockScrolling -= 1; + }; + this.clearSelection = function() { + this.selection.clearSelection(); + }; + this.moveCursorTo = function(row, column) { + this.selection.moveCursorTo(row, column); + }; + this.moveCursorToPosition = function(pos) { + this.selection.moveCursorToPosition(pos); + }; + this.jumpToMatching = function(select, expand) { + var cursor = this.getCursorPosition(); + var iterator = new TokenIterator(this.session, cursor.row, cursor.column); + var prevToken = iterator.getCurrentToken(); + var token = prevToken || iterator.stepForward(); + + if (!token) return; + var matchType; + var found = false; + var depth = {}; + var i = cursor.column - token.start; + var bracketType; + var brackets = { + ")": "(", + "(": "(", + "]": "[", + "[": "[", + "{": "{", + "}": "{" + }; + + do { + if (token.value.match(/[{}()\[\]]/g)) { + for (; i < token.value.length && !found; i++) { + if (!brackets[token.value[i]]) { + continue; + } + + bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen"); + + if (isNaN(depth[bracketType])) { + depth[bracketType] = 0; + } + + switch (token.value[i]) { + case '(': + case '[': + case '{': + depth[bracketType]++; + break; + case ')': + case ']': + case '}': + depth[bracketType]--; + + if (depth[bracketType] === -1) { + matchType = 'bracket'; + found = true; + } + break; + } + } + } + else if (token && token.type.indexOf('tag-name') !== -1) { + if (isNaN(depth[token.value])) { + depth[token.value] = 0; + } + + if (prevToken.value === '<') { + depth[token.value]++; + } + else if (prevToken.value === '= 0; --i) { + if(this.$tryReplace(ranges[i], replacement)) { + replaced++; + } + } + + this.selection.setSelectionRange(selection); + this.$blockScrolling -= 1; + + return replaced; + }; + + this.$tryReplace = function(range, replacement) { + var input = this.session.getTextRange(range); + replacement = this.$search.replace(input, replacement); + if (replacement !== null) { + range.end = this.session.replace(range, replacement); + return range; + } else { + return null; + } + }; + this.getLastSearchOptions = function() { + return this.$search.getOptions(); + }; + this.find = function(needle, options, animate) { + if (!options) + options = {}; + + if (typeof needle == "string" || needle instanceof RegExp) + options.needle = needle; + else if (typeof needle == "object") + oop.mixin(options, needle); + + var range = this.selection.getRange(); + if (options.needle == null) { + needle = this.session.getTextRange(range) + || this.$search.$options.needle; + if (!needle) { + range = this.session.getWordRange(range.start.row, range.start.column); + needle = this.session.getTextRange(range); + } + this.$search.set({needle: needle}); + } + + this.$search.set(options); + if (!options.start) + this.$search.set({start: range}); + + var newRange = this.$search.find(this.session); + if (options.preventScroll) + return newRange; + if (newRange) { + this.revealRange(newRange, animate); + return newRange; + } + if (options.backwards) + range.start = range.end; + else + range.end = range.start; + this.selection.setRange(range); + }; + this.findNext = function(options, animate) { + this.find({skipCurrent: true, backwards: false}, options, animate); + }; + this.findPrevious = function(options, animate) { + this.find(options, {skipCurrent: true, backwards: true}, animate); + }; + + this.revealRange = function(range, animate) { + this.$blockScrolling += 1; + this.session.unfold(range); + this.selection.setSelectionRange(range); + this.$blockScrolling -= 1; + + var scrollTop = this.renderer.scrollTop; + this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5); + if (animate !== false) + this.renderer.animateScrolling(scrollTop); + }; + this.undo = function() { + this.$blockScrolling++; + this.session.getUndoManager().undo(); + this.$blockScrolling--; + this.renderer.scrollCursorIntoView(null, 0.5); + }; + this.redo = function() { + this.$blockScrolling++; + this.session.getUndoManager().redo(); + this.$blockScrolling--; + this.renderer.scrollCursorIntoView(null, 0.5); + }; + this.destroy = function() { + this.renderer.destroy(); + this._signal("destroy", this); + if (this.session) { + this.session.destroy(); + } + }; + this.setAutoScrollEditorIntoView = function(enable) { + if (!enable) + return; + var rect; + var self = this; + var shouldScroll = false; + if (!this.$scrollAnchor) + this.$scrollAnchor = document.createElement("div"); + var scrollAnchor = this.$scrollAnchor; + scrollAnchor.style.cssText = "position:absolute"; + this.container.insertBefore(scrollAnchor, this.container.firstChild); + var onChangeSelection = this.on("changeSelection", function() { + shouldScroll = true; + }); + var onBeforeRender = this.renderer.on("beforeRender", function() { + if (shouldScroll) + rect = self.renderer.container.getBoundingClientRect(); + }); + var onAfterRender = this.renderer.on("afterRender", function() { + if (shouldScroll && rect && (self.isFocused() + || self.searchBox && self.searchBox.isFocused()) + ) { + var renderer = self.renderer; + var pos = renderer.$cursorLayer.$pixelPos; + var config = renderer.layerConfig; + var top = pos.top - config.offset; + if (pos.top >= 0 && top + rect.top < 0) { + shouldScroll = true; + } else if (pos.top < config.height && + pos.top + rect.top + config.lineHeight > window.innerHeight) { + shouldScroll = false; + } else { + shouldScroll = null; + } + if (shouldScroll != null) { + scrollAnchor.style.top = top + "px"; + scrollAnchor.style.left = pos.left + "px"; + scrollAnchor.style.height = config.lineHeight + "px"; + scrollAnchor.scrollIntoView(shouldScroll); + } + shouldScroll = rect = null; + } + }); + this.setAutoScrollEditorIntoView = function(enable) { + if (enable) + return; + delete this.setAutoScrollEditorIntoView; + this.off("changeSelection", onChangeSelection); + this.renderer.off("afterRender", onAfterRender); + this.renderer.off("beforeRender", onBeforeRender); + }; + }; + + + this.$resetCursorStyle = function() { + var style = this.$cursorStyle || "ace"; + var cursorLayer = this.renderer.$cursorLayer; + if (!cursorLayer) + return; + cursorLayer.setSmoothBlinking(/smooth/.test(style)); + cursorLayer.isBlinking = !this.$readOnly && style != "wide"; + dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style)); + }; + +}).call(Editor.prototype); + + + +config.defineOptions(Editor.prototype, "editor", { + selectionStyle: { + set: function(style) { + this.onSelectionChange(); + this._signal("changeSelectionStyle", {data: style}); + }, + initialValue: "line" + }, + highlightActiveLine: { + set: function() {this.$updateHighlightActiveLine();}, + initialValue: true + }, + highlightSelectedWord: { + set: function(shouldHighlight) {this.$onSelectionChange();}, + initialValue: true + }, + readOnly: { + set: function(readOnly) { + this.$resetCursorStyle(); + }, + initialValue: false + }, + cursorStyle: { + set: function(val) { this.$resetCursorStyle(); }, + values: ["ace", "slim", "smooth", "wide"], + initialValue: "ace" + }, + mergeUndoDeltas: { + values: [false, true, "always"], + initialValue: true + }, + behavioursEnabled: {initialValue: true}, + wrapBehavioursEnabled: {initialValue: true}, + autoScrollEditorIntoView: { + set: function(val) {this.setAutoScrollEditorIntoView(val)} + }, + keyboardHandler: { + set: function(val) { this.setKeyboardHandler(val); }, + get: function() { return this.keybindingId; }, + handlesSet: true + }, + + hScrollBarAlwaysVisible: "renderer", + vScrollBarAlwaysVisible: "renderer", + highlightGutterLine: "renderer", + animatedScroll: "renderer", + showInvisibles: "renderer", + showPrintMargin: "renderer", + printMarginColumn: "renderer", + printMargin: "renderer", + fadeFoldWidgets: "renderer", + showFoldWidgets: "renderer", + showLineNumbers: "renderer", + showGutter: "renderer", + displayIndentGuides: "renderer", + fontSize: "renderer", + fontFamily: "renderer", + maxLines: "renderer", + minLines: "renderer", + scrollPastEnd: "renderer", + fixedWidthGutter: "renderer", + theme: "renderer", + + scrollSpeed: "$mouseHandler", + dragDelay: "$mouseHandler", + dragEnabled: "$mouseHandler", + focusTimout: "$mouseHandler", + tooltipFollowsMouse: "$mouseHandler", + + firstLineNumber: "session", + overwrite: "session", + newLineMode: "session", + useWorker: "session", + useSoftTabs: "session", + tabSize: "session", + wrap: "session", + indentedSoftWrap: "session", + foldStyle: "session", + mode: "session" +}); + +exports.Editor = Editor; +}); + +ace.define("ace/undomanager",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +var UndoManager = function() { + this.reset(); +}; + +(function() { + this.execute = function(options) { + var deltaSets = options.args[0]; + this.$doc = options.args[1]; + if (options.merge && this.hasUndo()){ + this.dirtyCounter--; + deltaSets = this.$undoStack.pop().concat(deltaSets); + } + this.$undoStack.push(deltaSets); + this.$redoStack = []; + if (this.dirtyCounter < 0) { + this.dirtyCounter = NaN; + } + this.dirtyCounter++; + }; + this.undo = function(dontSelect) { + var deltaSets = this.$undoStack.pop(); + var undoSelectionRange = null; + if (deltaSets) { + undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect); + this.$redoStack.push(deltaSets); + this.dirtyCounter--; + } + + return undoSelectionRange; + }; + this.redo = function(dontSelect) { + var deltaSets = this.$redoStack.pop(); + var redoSelectionRange = null; + if (deltaSets) { + redoSelectionRange = + this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect); + this.$undoStack.push(deltaSets); + this.dirtyCounter++; + } + return redoSelectionRange; + }; + this.reset = function() { + this.$undoStack = []; + this.$redoStack = []; + this.dirtyCounter = 0; + }; + this.hasUndo = function() { + return this.$undoStack.length > 0; + }; + this.hasRedo = function() { + return this.$redoStack.length > 0; + }; + this.markClean = function() { + this.dirtyCounter = 0; + }; + this.isClean = function() { + return this.dirtyCounter === 0; + }; + this.$serializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $serializeDelta); + }; + this.$deserializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $deserializeDelta); + }; + + function $serializeDelta(delta){ + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines.length == 1 ? null : delta.lines, + text: delta.lines.length == 1 ? delta.lines[0] : null + }; + } + + function $deserializeDelta(delta) { + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines || [delta.text] + }; + } + + function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) { + var deltaSets_new = new Array(deltaSets_old.length); + for (var i = 0; i < deltaSets_old.length; i++) { + var deltaSet_old = deltaSets_old[i]; + var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)}; + + for (var j = 0; j < deltaSet_old.deltas.length; j++) { + var delta_old = deltaSet_old.deltas[j]; + deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old); + } + + deltaSets_new[i] = deltaSet_new; + } + return deltaSets_new; + } + +}).call(UndoManager.prototype); + +exports.UndoManager = UndoManager; +}); + +ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var Gutter = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_gutter-layer"; + parentEl.appendChild(this.element); + this.setShowFoldWidgets(this.$showFoldWidgets); + + this.gutterWidth = 0; + + this.$annotations = []; + this.$updateAnnotations = this.$updateAnnotations.bind(this); + + this.$cells = []; +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.setSession = function(session) { + if (this.session) + this.session.removeEventListener("change", this.$updateAnnotations); + this.session = session; + if (session) + session.on("change", this.$updateAnnotations); + }; + + this.addGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.addGutterDecoration"); + this.session.addGutterDecoration(row, className); + }; + + this.removeGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.removeGutterDecoration"); + this.session.removeGutterDecoration(row, className); + }; + + this.setAnnotations = function(annotations) { + this.$annotations = []; + for (var i = 0; i < annotations.length; i++) { + var annotation = annotations[i]; + var row = annotation.row; + var rowInfo = this.$annotations[row]; + if (!rowInfo) + rowInfo = this.$annotations[row] = {text: []}; + + var annoText = annotation.text; + annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || ""; + + if (rowInfo.text.indexOf(annoText) === -1) + rowInfo.text.push(annoText); + + var type = annotation.type; + if (type == "error") + rowInfo.className = " ace_error"; + else if (type == "warning" && rowInfo.className != " ace_error") + rowInfo.className = " ace_warning"; + else if (type == "info" && (!rowInfo.className)) + rowInfo.className = " ace_info"; + } + }; + + this.$updateAnnotations = function (delta) { + if (!this.$annotations.length) + return; + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + if (len === 0) { + } else if (delta.action == 'remove') { + this.$annotations.splice(firstRow, len + 1, null); + } else { + var args = new Array(len + 1); + args.unshift(firstRow, 1); + this.$annotations.splice.apply(this.$annotations, args); + } + }; + + this.update = function(config) { + var session = this.session; + var firstRow = config.firstRow; + var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar + session.getLength() - 1); + var fold = session.getNextFoldLine(firstRow); + var foldStart = fold ? fold.start.row : Infinity; + var foldWidgets = this.$showFoldWidgets && session.foldWidgets; + var breakpoints = session.$breakpoints; + var decorations = session.$decorations; + var firstLineNumber = session.$firstLineNumber; + var lastLineNumber = 0; + + var gutterRenderer = session.gutterRenderer || this.$renderer; + + var cell = null; + var index = -1; + var row = firstRow; + while (true) { + if (row > foldStart) { + row = fold.end.row + 1; + fold = session.getNextFoldLine(row, fold); + foldStart = fold ? fold.start.row : Infinity; + } + if (row > lastRow) { + while (this.$cells.length > index + 1) { + cell = this.$cells.pop(); + this.element.removeChild(cell.element); + } + break; + } + + cell = this.$cells[++index]; + if (!cell) { + cell = {element: null, textNode: null, foldWidget: null}; + cell.element = dom.createElement("div"); + cell.textNode = document.createTextNode(''); + cell.element.appendChild(cell.textNode); + this.element.appendChild(cell.element); + this.$cells[index] = cell; + } + + var className = "ace_gutter-cell "; + if (breakpoints[row]) + className += breakpoints[row]; + if (decorations[row]) + className += decorations[row]; + if (this.$annotations[row]) + className += this.$annotations[row].className; + if (cell.element.className != className) + cell.element.className = className; + + var height = session.getRowLength(row) * config.lineHeight + "px"; + if (height != cell.element.style.height) + cell.element.style.height = height; + + if (foldWidgets) { + var c = foldWidgets[row]; + if (c == null) + c = foldWidgets[row] = session.getFoldWidget(row); + } + + if (c) { + if (!cell.foldWidget) { + cell.foldWidget = dom.createElement("span"); + cell.element.appendChild(cell.foldWidget); + } + var className = "ace_fold-widget ace_" + c; + if (c == "start" && row == foldStart && row < fold.end.row) + className += " ace_closed"; + else + className += " ace_open"; + if (cell.foldWidget.className != className) + cell.foldWidget.className = className; + + var height = config.lineHeight + "px"; + if (cell.foldWidget.style.height != height) + cell.foldWidget.style.height = height; + } else { + if (cell.foldWidget) { + cell.element.removeChild(cell.foldWidget); + cell.foldWidget = null; + } + } + + var text = lastLineNumber = gutterRenderer + ? gutterRenderer.getText(session, row) + : row + firstLineNumber; + if (text != cell.textNode.data) + cell.textNode.data = text; + + row++; + } + + this.element.style.height = config.minHeight + "px"; + + if (this.$fixedWidth || session.$useWrapMode) + lastLineNumber = session.getLength() + firstLineNumber; + + var gutterWidth = gutterRenderer + ? gutterRenderer.getWidth(session, lastLineNumber, config) + : lastLineNumber.toString().length * config.characterWidth; + + var padding = this.$padding || this.$computePadding(); + gutterWidth += padding.left + padding.right; + if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) { + this.gutterWidth = gutterWidth; + this.element.style.width = Math.ceil(this.gutterWidth) + "px"; + this._emit("changeGutterWidth", gutterWidth); + } + }; + + this.$fixedWidth = false; + + this.$showLineNumbers = true; + this.$renderer = ""; + this.setShowLineNumbers = function(show) { + this.$renderer = !show && { + getWidth: function() {return ""}, + getText: function() {return ""} + }; + }; + + this.getShowLineNumbers = function() { + return this.$showLineNumbers; + }; + + this.$showFoldWidgets = true; + this.setShowFoldWidgets = function(show) { + if (show) + dom.addCssClass(this.element, "ace_folding-enabled"); + else + dom.removeCssClass(this.element, "ace_folding-enabled"); + + this.$showFoldWidgets = show; + this.$padding = null; + }; + + this.getShowFoldWidgets = function() { + return this.$showFoldWidgets; + }; + + this.$computePadding = function() { + if (!this.element.firstChild) + return {left: 0, right: 0}; + var style = dom.computedStyle(this.element.firstChild); + this.$padding = {}; + this.$padding.left = parseInt(style.paddingLeft) + 1 || 0; + this.$padding.right = parseInt(style.paddingRight) || 0; + return this.$padding; + }; + + this.getRegion = function(point) { + var padding = this.$padding || this.$computePadding(); + var rect = this.element.getBoundingClientRect(); + if (point.x < padding.left + rect.left) + return "markers"; + if (this.$showFoldWidgets && point.x > rect.right - padding.right) + return "foldWidgets"; + }; + +}).call(Gutter.prototype); + +exports.Gutter = Gutter; + +}); + +ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var dom = acequire("../lib/dom"); + +var Marker = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_marker-layer"; + parentEl.appendChild(this.element); +}; + +(function() { + + this.$padding = 0; + + this.setPadding = function(padding) { + this.$padding = padding; + }; + this.setSession = function(session) { + this.session = session; + }; + + this.setMarkers = function(markers) { + this.markers = markers; + }; + + this.update = function(config) { + var config = config || this.config; + if (!config) + return; + + this.config = config; + + + var html = []; + for (var key in this.markers) { + var marker = this.markers[key]; + + if (!marker.range) { + marker.update(html, this, this.session, config); + continue; + } + + var range = marker.range.clipRows(config.firstRow, config.lastRow); + if (range.isEmpty()) continue; + + range = range.toScreenRange(this.session); + if (marker.renderer) { + var top = this.$getTop(range.start.row, config); + var left = this.$padding + range.start.column * config.characterWidth; + marker.renderer(html, range, left, top, config); + } else if (marker.type == "fullLine") { + this.drawFullLineMarker(html, range, marker.clazz, config); + } else if (marker.type == "screenLine") { + this.drawScreenLineMarker(html, range, marker.clazz, config); + } else if (range.isMultiLine()) { + if (marker.type == "text") + this.drawTextMarker(html, range, marker.clazz, config); + else + this.drawMultiLineMarker(html, range, marker.clazz, config); + } else { + this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); + } + } + this.element.innerHTML = html.join(""); + }; + + this.$getTop = function(row, layerConfig) { + return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; + }; + + function getBorderClass(tl, tr, br, bl) { + return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0); + } + this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) { + var session = this.session; + var start = range.start.row; + var end = range.end.row; + var row = start; + var prev = 0; + var curr = 0; + var next = session.getScreenLastRowColumn(row); + var lineRange = new Range(row, range.start.column, row, curr); + for (; row <= end; row++) { + lineRange.start.row = lineRange.end.row = row; + lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row); + lineRange.end.column = next; + prev = curr; + curr = next; + next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column; + this.drawSingleLineMarker(stringBuilder, lineRange, + clazz + (row == start ? " ace_start" : "") + " ace_br" + + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end), + layerConfig, row == end ? 0 : 1, extraStyle); + } + }; + this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var padding = this.$padding; + var height = config.lineHeight; + var top = this.$getTop(range.start.row, config); + var left = padding + range.start.column * config.characterWidth; + extraStyle = extraStyle || ""; + + stringBuilder.push( + "
" + ); + top = this.$getTop(range.end.row, config); + var width = range.end.column * config.characterWidth; + + stringBuilder.push( + "
" + ); + height = (range.end.row - range.start.row - 1) * config.lineHeight; + if (height <= 0) + return; + top = this.$getTop(range.start.row + 1, config); + + var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8); + + stringBuilder.push( + "
" + ); + }; + this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { + var height = config.lineHeight; + var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth; + + var top = this.$getTop(range.start.row, config); + var left = this.$padding + range.start.column * config.characterWidth; + + stringBuilder.push( + "
" + ); + }; + + this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + if (range.start.row != range.end.row) + height += this.$getTop(range.end.row, config) - top; + + stringBuilder.push( + "
" + ); + }; + + this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + + stringBuilder.push( + "
" + ); + }; + +}).call(Marker.prototype); + +exports.Marker = Marker; + +}); + +ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var Text = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_text-layer"; + parentEl.appendChild(this.element); + this.$updateEolChar = this.$updateEolChar.bind(this); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.EOF_CHAR = "\xB6"; + this.EOL_CHAR_LF = "\xAC"; + this.EOL_CHAR_CRLF = "\xa4"; + this.EOL_CHAR = this.EOL_CHAR_LF; + this.TAB_CHAR = "\u2014"; //"\u21E5"; + this.SPACE_CHAR = "\xB7"; + this.$padding = 0; + + this.$updateEolChar = function() { + var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n" + ? this.EOL_CHAR_LF + : this.EOL_CHAR_CRLF; + if (this.EOL_CHAR != EOL_CHAR) { + this.EOL_CHAR = EOL_CHAR; + return true; + } + } + + this.setPadding = function(padding) { + this.$padding = padding; + this.element.style.padding = "0 " + padding + "px"; + }; + + this.getLineHeight = function() { + return this.$fontMetrics.$characterSize.height || 0; + }; + + this.getCharacterWidth = function() { + return this.$fontMetrics.$characterSize.width || 0; + }; + + this.$setFontMetrics = function(measure) { + this.$fontMetrics = measure; + this.$fontMetrics.on("changeCharacterSize", function(e) { + this._signal("changeCharacterSize", e); + }.bind(this)); + this.$pollSizeChanges(); + } + + this.checkForSizeChanges = function() { + this.$fontMetrics.checkForSizeChanges(); + }; + this.$pollSizeChanges = function() { + return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges(); + }; + this.setSession = function(session) { + this.session = session; + if (session) + this.$computeTabString(); + }; + + this.showInvisibles = false; + this.setShowInvisibles = function(showInvisibles) { + if (this.showInvisibles == showInvisibles) + return false; + + this.showInvisibles = showInvisibles; + this.$computeTabString(); + return true; + }; + + this.displayIndentGuides = true; + this.setDisplayIndentGuides = function(display) { + if (this.displayIndentGuides == display) + return false; + + this.displayIndentGuides = display; + this.$computeTabString(); + return true; + }; + + this.$tabStrings = []; + this.onChangeTabSize = + this.$computeTabString = function() { + var tabSize = this.session.getTabSize(); + this.tabSize = tabSize; + var tabStr = this.$tabStrings = [0]; + for (var i = 1; i < tabSize + 1; i++) { + if (this.showInvisibles) { + tabStr.push("" + + lang.stringRepeat(this.TAB_CHAR, i) + + ""); + } else { + tabStr.push(lang.stringRepeat(" ", i)); + } + } + if (this.displayIndentGuides) { + this.$indentGuideRe = /\s\S| \t|\t |\s$/; + var className = "ace_indent-guide"; + var spaceClass = ""; + var tabClass = ""; + if (this.showInvisibles) { + className += " ace_invisible"; + spaceClass = " ace_invisible_space"; + tabClass = " ace_invisible_tab"; + var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize); + var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize); + } else{ + var spaceContent = lang.stringRepeat(" ", this.tabSize); + var tabContent = spaceContent; + } + + this.$tabStrings[" "] = "" + spaceContent + ""; + this.$tabStrings["\t"] = "" + tabContent + ""; + } + }; + + this.updateLines = function(config, firstRow, lastRow) { + if (this.config.lastRow != config.lastRow || + this.config.firstRow != config.firstRow) { + this.scrollLines(config); + } + this.config = config; + + var first = Math.max(firstRow, config.firstRow); + var last = Math.min(lastRow, config.lastRow); + + var lineElements = this.element.childNodes; + var lineElementsIdx = 0; + + for (var row = config.firstRow; row < first; row++) { + var foldLine = this.session.getFoldLine(row); + if (foldLine) { + if (foldLine.containsRow(first)) { + first = foldLine.start.row; + break; + } else { + row = foldLine.end.row; + } + } + lineElementsIdx ++; + } + + var row = first; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > last) + break; + + var lineElement = lineElements[lineElementsIdx++]; + if (lineElement) { + var html = []; + this.$renderLine( + html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false + ); + lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + lineElement.innerHTML = html.join(""); + } + row++; + } + }; + + this.scrollLines = function(config) { + var oldConfig = this.config; + this.config = config; + + if (!oldConfig || oldConfig.lastRow < config.firstRow) + return this.update(config); + + if (config.lastRow < oldConfig.firstRow) + return this.update(config); + + var el = this.element; + if (oldConfig.firstRow < config.firstRow) + for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) + el.removeChild(el.firstChild); + + if (oldConfig.lastRow > config.lastRow) + for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--) + el.removeChild(el.lastChild); + + if (config.firstRow < oldConfig.firstRow) { + var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1); + if (el.firstChild) + el.insertBefore(fragment, el.firstChild); + else + el.appendChild(fragment); + } + + if (config.lastRow > oldConfig.lastRow) { + var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow); + el.appendChild(fragment); + } + }; + + this.$renderLinesFragment = function(config, firstRow, lastRow) { + var fragment = this.element.ownerDocument.createDocumentFragment(); + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; + } + if (row > lastRow) + break; + + var container = dom.createElement("div"); + + var html = []; + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + container.innerHTML = html.join(""); + if (this.$useLineGroups()) { + container.className = 'ace_line_group'; + fragment.appendChild(container); + container.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + + } else { + while(container.firstChild) + fragment.appendChild(container.firstChild); + } + + row++; + } + return fragment; + }; + + this.update = function(config) { + this.config = config; + + var html = []; + var firstRow = config.firstRow, lastRow = config.lastRow; + + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > lastRow) + break; + + if (this.$useLineGroups()) + html.push("
") + + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + + if (this.$useLineGroups()) + html.push("
"); // end the line group + + row++; + } + this.element.innerHTML = html.join(""); + }; + + this.$textToken = { + "text": true, + "rparen": true, + "lparen": true + }; + + this.$renderToken = function(stringBuilder, screenColumn, token, value) { + var self = this; + var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g; + var replaceFunc = function(c, a, b, tabIdx, idx4) { + if (a) { + return self.showInvisibles + ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "" + : c; + } else if (c == "&") { + return "&"; + } else if (c == "<") { + return "<"; + } else if (c == ">") { + return ">"; + } else if (c == "\t") { + var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); + screenColumn += tabSize - 1; + return self.$tabStrings[tabSize]; + } else if (c == "\u3000") { + var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk"; + var space = self.showInvisibles ? self.SPACE_CHAR : ""; + screenColumn += 1; + return "" + space + ""; + } else if (b) { + return "" + self.SPACE_CHAR + ""; + } else { + screenColumn += 1; + return "" + c + ""; + } + }; + + var output = value.replace(replaceReg, replaceFunc); + + if (!this.$textToken[token.type]) { + var classes = "ace_" + token.type.replace(/\./g, " ace_"); + var style = ""; + if (token.type == "fold") + style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' "; + stringBuilder.push("", output, ""); + } + else { + stringBuilder.push(output); + } + return screenColumn + value.length; + }; + + this.renderIndentGuide = function(stringBuilder, value, max) { + var cols = value.search(this.$indentGuideRe); + if (cols <= 0 || cols >= max) + return value; + if (value[0] == " ") { + cols -= cols % this.tabSize; + stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize)); + return value.substr(cols); + } else if (value[0] == "\t") { + stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols)); + return value.substr(cols); + } + return value; + }; + + this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) { + var chars = 0; + var split = 0; + var splitChars = splits[0]; + var screenColumn = 0; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + var value = token.value; + if (i == 0 && this.displayIndentGuides) { + chars = value.length; + value = this.renderIndentGuide(stringBuilder, value, splitChars); + if (!value) + continue; + chars -= value.length; + } + + if (chars + value.length < splitChars) { + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + chars += value.length; + } else { + while (chars + value.length >= splitChars) { + screenColumn = this.$renderToken( + stringBuilder, screenColumn, + token, value.substring(0, splitChars - chars) + ); + value = value.substring(splitChars - chars); + chars = splitChars; + + if (!onlyContents) { + stringBuilder.push("
", + "
" + ); + } + + stringBuilder.push(lang.stringRepeat("\xa0", splits.indent)); + + split ++; + screenColumn = 0; + splitChars = splits[split] || Number.MAX_VALUE; + } + if (value.length != 0) { + chars += value.length; + screenColumn = this.$renderToken( + stringBuilder, screenColumn, token, value + ); + } + } + } + }; + + this.$renderSimpleLine = function(stringBuilder, tokens) { + var screenColumn = 0; + var token = tokens[0]; + var value = token.value; + if (this.displayIndentGuides) + value = this.renderIndentGuide(stringBuilder, value); + if (value) + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + for (var i = 1; i < tokens.length; i++) { + token = tokens[i]; + value = token.value; + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + } + }; + this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) { + if (!foldLine && foldLine != false) + foldLine = this.session.getFoldLine(row); + + if (foldLine) + var tokens = this.$getFoldLineTokens(row, foldLine); + else + var tokens = this.session.getTokens(row); + + + if (!onlyContents) { + stringBuilder.push( + "
" + ); + } + + if (tokens.length) { + var splits = this.session.getRowSplitData(row); + if (splits && splits.length) + this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents); + else + this.$renderSimpleLine(stringBuilder, tokens); + } + + if (this.showInvisibles) { + if (foldLine) + row = foldLine.end.row + + stringBuilder.push( + "", + row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR, + "" + ); + } + if (!onlyContents) + stringBuilder.push("
"); + }; + + this.$getFoldLineTokens = function(row, foldLine) { + var session = this.session; + var renderTokens = []; + + function addTokens(tokens, from, to) { + var idx = 0, col = 0; + while ((col + tokens[idx].value.length) < from) { + col += tokens[idx].value.length; + idx++; + + if (idx == tokens.length) + return; + } + if (col != from) { + var value = tokens[idx].value.substring(from - col); + if (value.length > (to - from)) + value = value.substring(0, to - from); + + renderTokens.push({ + type: tokens[idx].type, + value: value + }); + + col = from + value.length; + idx += 1; + } + + while (col < to && idx < tokens.length) { + var value = tokens[idx].value; + if (value.length + col > to) { + renderTokens.push({ + type: tokens[idx].type, + value: value.substring(0, to - col) + }); + } else + renderTokens.push(tokens[idx]); + col += value.length; + idx += 1; + } + } + + var tokens = session.getTokens(row); + foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { + if (placeholder != null) { + renderTokens.push({ + type: "fold", + value: placeholder + }); + } else { + if (isNewRow) + tokens = session.getTokens(row); + + if (tokens.length) + addTokens(tokens, lastColumn, column); + } + }, foldLine.end.row, this.session.getLine(foldLine.end.row).length); + + return renderTokens; + }; + + this.$useLineGroups = function() { + return this.session.getUseWrapMode(); + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.$measureNode) + this.$measureNode.parentNode.removeChild(this.$measureNode); + delete this.$measureNode; + }; + +}).call(Text.prototype); + +exports.Text = Text; + +}); + +ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var isIE8; + +var Cursor = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_cursor-layer"; + parentEl.appendChild(this.element); + + if (isIE8 === undefined) + isIE8 = !("opacity" in this.element.style); + + this.isVisible = false; + this.isBlinking = true; + this.blinkInterval = 1000; + this.smoothBlinking = false; + + this.cursors = []; + this.cursor = this.addCursor(); + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.$updateCursors = (isIE8 + ? this.$updateVisibility + : this.$updateOpacity).bind(this); +}; + +(function() { + + this.$updateVisibility = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.visibility = val ? "" : "hidden"; + }; + this.$updateOpacity = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.opacity = val ? "" : "0"; + }; + + + this.$padding = 0; + this.setPadding = function(padding) { + this.$padding = padding; + }; + + this.setSession = function(session) { + this.session = session; + }; + + this.setBlinking = function(blinking) { + if (blinking != this.isBlinking){ + this.isBlinking = blinking; + this.restartTimer(); + } + }; + + this.setBlinkInterval = function(blinkInterval) { + if (blinkInterval != this.blinkInterval){ + this.blinkInterval = blinkInterval; + this.restartTimer(); + } + }; + + this.setSmoothBlinking = function(smoothBlinking) { + if (smoothBlinking != this.smoothBlinking && !isIE8) { + this.smoothBlinking = smoothBlinking; + dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking); + this.$updateCursors(true); + this.$updateCursors = (this.$updateOpacity).bind(this); + this.restartTimer(); + } + }; + + this.addCursor = function() { + var el = dom.createElement("div"); + el.className = "ace_cursor"; + this.element.appendChild(el); + this.cursors.push(el); + return el; + }; + + this.removeCursor = function() { + if (this.cursors.length > 1) { + var el = this.cursors.pop(); + el.parentNode.removeChild(el); + return el; + } + }; + + this.hideCursor = function() { + this.isVisible = false; + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.showCursor = function() { + this.isVisible = true; + dom.removeCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.restartTimer = function() { + var update = this.$updateCursors; + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + if (this.smoothBlinking) { + dom.removeCssClass(this.element, "ace_smooth-blinking"); + } + + update(true); + + if (!this.isBlinking || !this.blinkInterval || !this.isVisible) + return; + + if (this.smoothBlinking) { + setTimeout(function(){ + dom.addCssClass(this.element, "ace_smooth-blinking"); + }.bind(this)); + } + + var blink = function(){ + this.timeoutId = setTimeout(function() { + update(false); + }, 0.6 * this.blinkInterval); + }.bind(this); + + this.intervalId = setInterval(function() { + update(true); + blink(); + }, this.blinkInterval); + + blink(); + }; + + this.getPixelPosition = function(position, onScreen) { + if (!this.config || !this.session) + return {left : 0, top : 0}; + + if (!position) + position = this.session.selection.getCursor(); + var pos = this.session.documentToScreenPosition(position); + var cursorLeft = this.$padding + pos.column * this.config.characterWidth; + var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) * + this.config.lineHeight; + + return {left : cursorLeft, top : cursorTop}; + }; + + this.update = function(config) { + this.config = config; + + var selections = this.session.$selectionMarkers; + var i = 0, cursorIndex = 0; + + if (selections === undefined || selections.length === 0){ + selections = [{cursor: null}]; + } + + for (var i = 0, n = selections.length; i < n; i++) { + var pixelPos = this.getPixelPosition(selections[i].cursor, true); + if ((pixelPos.top > config.height + config.offset || + pixelPos.top < 0) && i > 1) { + continue; + } + + var style = (this.cursors[cursorIndex++] || this.addCursor()).style; + + if (!this.drawCursor) { + style.left = pixelPos.left + "px"; + style.top = pixelPos.top + "px"; + style.width = config.characterWidth + "px"; + style.height = config.lineHeight + "px"; + } else { + this.drawCursor(style, pixelPos, config, selections[i], this.session); + } + } + while (this.cursors.length > cursorIndex) + this.removeCursor(); + + var overwrite = this.session.getOverwrite(); + this.$setOverwrite(overwrite); + this.$pixelPos = pixelPos; + this.restartTimer(); + }; + + this.drawCursor = null; + + this.$setOverwrite = function(overwrite) { + if (overwrite != this.overwrite) { + this.overwrite = overwrite; + if (overwrite) + dom.addCssClass(this.element, "ace_overwrite-cursors"); + else + dom.removeCssClass(this.element, "ace_overwrite-cursors"); + } + }; + + this.destroy = function() { + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + }; + +}).call(Cursor.prototype); + +exports.Cursor = Cursor; + +}); + +ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var MAX_SCROLL_H = 0x8000; +var ScrollBar = function(parent) { + this.element = dom.createElement("div"); + this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix; + + this.inner = dom.createElement("div"); + this.inner.className = "ace_scrollbar-inner"; + this.element.appendChild(this.inner); + + parent.appendChild(this.element); + + this.setVisible(false); + this.skipEvent = false; + + event.addListener(this.element, "scroll", this.onScroll.bind(this)); + event.addListener(this.element, "mousedown", event.preventDefault); +}; + +(function() { + oop.implement(this, EventEmitter); + + this.setVisible = function(isVisible) { + this.element.style.display = isVisible ? "" : "none"; + this.isVisible = isVisible; + this.coeff = 1; + }; +}).call(ScrollBar.prototype); +var VScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollTop = 0; + this.scrollHeight = 0; + renderer.$scrollbarWidth = + this.width = dom.scrollbarWidth(parent.ownerDocument); + this.inner.style.width = + this.element.style.width = (this.width || 15) + 5 + "px"; +}; + +oop.inherits(VScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-v'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollTop = this.element.scrollTop; + if (this.coeff != 1) { + var h = this.element.clientHeight / this.scrollHeight; + this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h); + } + this._emit("scroll", {data: this.scrollTop}); + } + this.skipEvent = false; + }; + this.getWidth = function() { + return this.isVisible ? this.width : 0; + }; + this.setHeight = function(height) { + this.element.style.height = height + "px"; + }; + this.setInnerHeight = + this.setScrollHeight = function(height) { + this.scrollHeight = height; + if (height > MAX_SCROLL_H) { + this.coeff = MAX_SCROLL_H / height; + height = MAX_SCROLL_H; + } else if (this.coeff != 1) { + this.coeff = 1 + } + this.inner.style.height = height + "px"; + }; + this.setScrollTop = function(scrollTop) { + if (this.scrollTop != scrollTop) { + this.skipEvent = true; + this.scrollTop = scrollTop; + this.element.scrollTop = scrollTop * this.coeff; + } + }; + +}).call(VScrollBar.prototype); +var HScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollLeft = 0; + this.height = renderer.$scrollbarWidth; + this.inner.style.height = + this.element.style.height = (this.height || 15) + 5 + "px"; +}; + +oop.inherits(HScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-h'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollLeft = this.element.scrollLeft; + this._emit("scroll", {data: this.scrollLeft}); + } + this.skipEvent = false; + }; + this.getHeight = function() { + return this.isVisible ? this.height : 0; + }; + this.setWidth = function(width) { + this.element.style.width = width + "px"; + }; + this.setInnerWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollLeft = function(scrollLeft) { + if (this.scrollLeft != scrollLeft) { + this.skipEvent = true; + this.scrollLeft = this.element.scrollLeft = scrollLeft; + } + }; + +}).call(HScrollBar.prototype); + + +exports.ScrollBar = VScrollBar; // backward compatibility +exports.ScrollBarV = VScrollBar; // backward compatibility +exports.ScrollBarH = HScrollBar; // backward compatibility + +exports.VScrollBar = VScrollBar; +exports.HScrollBar = HScrollBar; +}); + +ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("./lib/event"); + + +var RenderLoop = function(onRender, win) { + this.onRender = onRender; + this.pending = false; + this.changes = 0; + this.window = win || window; +}; + +(function() { + + + this.schedule = function(change) { + this.changes = this.changes | change; + if (!this.pending && this.changes) { + this.pending = true; + var _self = this; + event.nextFrame(function() { + _self.pending = false; + var changes; + while (changes = _self.changes) { + _self.changes = 0; + _self.onRender(changes); + } + }, this.window); + } + }; + +}).call(RenderLoop.prototype); + +exports.RenderLoop = RenderLoop; +}); + +ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CHAR_COUNT = 0; + +var FontMetrics = exports.FontMetrics = function(parentEl) { + this.el = dom.createElement("div"); + this.$setMeasureNodeStyles(this.el.style, true); + + this.$main = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$main.style); + + this.$measureNode = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$measureNode.style); + + + this.el.appendChild(this.$main); + this.el.appendChild(this.$measureNode); + parentEl.appendChild(this.el); + + if (!CHAR_COUNT) + this.$testFractionalRect(); + this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT); + + this.$characterSize = {width: 0, height: 0}; + this.checkForSizeChanges(); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.$characterSize = {width: 0, height: 0}; + + this.$testFractionalRect = function() { + var el = dom.createElement("div"); + this.$setMeasureNodeStyles(el.style); + el.style.width = "0.2px"; + document.documentElement.appendChild(el); + var w = el.getBoundingClientRect().width; + if (w > 0 && w < 1) + CHAR_COUNT = 50; + else + CHAR_COUNT = 100; + el.parentNode.removeChild(el); + }; + + this.$setMeasureNodeStyles = function(style, isRoot) { + style.width = style.height = "auto"; + style.left = style.top = "0px"; + style.visibility = "hidden"; + style.position = "absolute"; + style.whiteSpace = "pre"; + + if (useragent.isIE < 8) { + style["font-family"] = "inherit"; + } else { + style.font = "inherit"; + } + style.overflow = isRoot ? "hidden" : "visible"; + }; + + this.checkForSizeChanges = function() { + var size = this.$measureSizes(); + if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { + this.$measureNode.style.fontWeight = "bold"; + var boldSize = this.$measureSizes(); + this.$measureNode.style.fontWeight = ""; + this.$characterSize = size; + this.charSizes = Object.create(null); + this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height; + this._emit("changeCharacterSize", {data: size}); + } + }; + + this.$pollSizeChanges = function() { + if (this.$pollSizeChangesTimer) + return this.$pollSizeChangesTimer; + var self = this; + return this.$pollSizeChangesTimer = setInterval(function() { + self.checkForSizeChanges(); + }, 500); + }; + + this.setPolling = function(val) { + if (val) { + this.$pollSizeChanges(); + } else if (this.$pollSizeChangesTimer) { + clearInterval(this.$pollSizeChangesTimer); + this.$pollSizeChangesTimer = 0; + } + }; + + this.$measureSizes = function() { + if (CHAR_COUNT === 50) { + var rect = null; + try { + rect = this.$measureNode.getBoundingClientRect(); + } catch(e) { + rect = {width: 0, height:0 }; + } + var size = { + height: rect.height, + width: rect.width / CHAR_COUNT + }; + } else { + var size = { + height: this.$measureNode.clientHeight, + width: this.$measureNode.clientWidth / CHAR_COUNT + }; + } + if (size.width === 0 || size.height === 0) + return null; + return size; + }; + + this.$measureCharWidth = function(ch) { + this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT); + var rect = this.$main.getBoundingClientRect(); + return rect.width / CHAR_COUNT; + }; + + this.getCharacterWidth = function(ch) { + var w = this.charSizes[ch]; + if (w === undefined) { + w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width; + } + return w; + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.el && this.el.parentNode) + this.el.parentNode.removeChild(this.el); + }; + +}).call(FontMetrics.prototype); + +}); + +ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var config = acequire("./config"); +var useragent = acequire("./lib/useragent"); +var GutterLayer = acequire("./layer/gutter").Gutter; +var MarkerLayer = acequire("./layer/marker").Marker; +var TextLayer = acequire("./layer/text").Text; +var CursorLayer = acequire("./layer/cursor").Cursor; +var HScrollBar = acequire("./scrollbar").HScrollBar; +var VScrollBar = acequire("./scrollbar").VScrollBar; +var RenderLoop = acequire("./renderloop").RenderLoop; +var FontMetrics = acequire("./layer/font_metrics").FontMetrics; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var editorCss = ".ace_editor {\ +position: relative;\ +overflow: hidden;\ +font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\ +direction: ltr;\ +text-align: left;\ +}\ +.ace_scroller {\ +position: absolute;\ +overflow: hidden;\ +top: 0;\ +bottom: 0;\ +background-color: inherit;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +cursor: text;\ +}\ +.ace_content {\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +min-width: 100%;\ +}\ +.ace_dragging .ace_scroller:before{\ +position: absolute;\ +top: 0;\ +left: 0;\ +right: 0;\ +bottom: 0;\ +content: '';\ +background: rgba(250, 250, 250, 0.01);\ +z-index: 1000;\ +}\ +.ace_dragging.ace_dark .ace_scroller:before{\ +background: rgba(0, 0, 0, 0.01);\ +}\ +.ace_selecting, .ace_selecting * {\ +cursor: text !important;\ +}\ +.ace_gutter {\ +position: absolute;\ +overflow : hidden;\ +width: auto;\ +top: 0;\ +bottom: 0;\ +left: 0;\ +cursor: default;\ +z-index: 4;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +}\ +.ace_gutter-active-line {\ +position: absolute;\ +left: 0;\ +right: 0;\ +}\ +.ace_scroller.ace_scroll-left {\ +box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\ +}\ +.ace_gutter-cell {\ +padding-left: 19px;\ +padding-right: 6px;\ +background-repeat: no-repeat;\ +}\ +.ace_gutter-cell.ace_error {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_warning {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\ +background-position: 2px center;\ +}\ +.ace_dark .ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\ +}\ +.ace_scrollbar {\ +position: absolute;\ +right: 0;\ +bottom: 0;\ +z-index: 6;\ +}\ +.ace_scrollbar-inner {\ +position: absolute;\ +cursor: text;\ +left: 0;\ +top: 0;\ +}\ +.ace_scrollbar-v{\ +overflow-x: hidden;\ +overflow-y: scroll;\ +top: 0;\ +}\ +.ace_scrollbar-h {\ +overflow-x: scroll;\ +overflow-y: hidden;\ +left: 0;\ +}\ +.ace_print-margin {\ +position: absolute;\ +height: 100%;\ +}\ +.ace_text-input {\ +position: absolute;\ +z-index: 0;\ +width: 0.5em;\ +height: 1em;\ +opacity: 0;\ +background: transparent;\ +-moz-appearance: none;\ +appearance: none;\ +border: none;\ +resize: none;\ +outline: none;\ +overflow: hidden;\ +font: inherit;\ +padding: 0 1px;\ +margin: 0 -1px;\ +text-indent: -1em;\ +-ms-user-select: text;\ +-moz-user-select: text;\ +-webkit-user-select: text;\ +user-select: text;\ +white-space: pre!important;\ +}\ +.ace_text-input.ace_composition {\ +background: inherit;\ +color: inherit;\ +z-index: 1000;\ +opacity: 1;\ +text-indent: 0;\ +}\ +.ace_layer {\ +z-index: 1;\ +position: absolute;\ +overflow: hidden;\ +word-wrap: normal;\ +white-space: pre;\ +height: 100%;\ +width: 100%;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +pointer-events: none;\ +}\ +.ace_gutter-layer {\ +position: relative;\ +width: auto;\ +text-align: right;\ +pointer-events: auto;\ +}\ +.ace_text-layer {\ +font: inherit !important;\ +}\ +.ace_cjk {\ +display: inline-block;\ +text-align: center;\ +}\ +.ace_cursor-layer {\ +z-index: 4;\ +}\ +.ace_cursor {\ +z-index: 4;\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +border-left: 2px solid;\ +transform: translatez(0);\ +}\ +.ace_slim-cursors .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_overwrite-cursors .ace_cursor {\ +border-left-width: 0;\ +border-bottom: 1px solid;\ +}\ +.ace_hidden-cursors .ace_cursor {\ +opacity: 0.2;\ +}\ +.ace_smooth-blinking .ace_cursor {\ +-webkit-transition: opacity 0.18s;\ +transition: opacity 0.18s;\ +}\ +.ace_editor.ace_multiselect .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\ +position: absolute;\ +z-index: 3;\ +}\ +.ace_marker-layer .ace_selection {\ +position: absolute;\ +z-index: 5;\ +}\ +.ace_marker-layer .ace_bracket {\ +position: absolute;\ +z-index: 6;\ +}\ +.ace_marker-layer .ace_active-line {\ +position: absolute;\ +z-index: 2;\ +}\ +.ace_marker-layer .ace_selected-word {\ +position: absolute;\ +z-index: 4;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +}\ +.ace_line .ace_fold {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +display: inline-block;\ +height: 11px;\ +margin-top: -2px;\ +vertical-align: middle;\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\ +background-repeat: no-repeat, repeat-x;\ +background-position: center center, top left;\ +color: transparent;\ +border: 1px solid black;\ +border-radius: 2px;\ +cursor: pointer;\ +pointer-events: auto;\ +}\ +.ace_dark .ace_fold {\ +}\ +.ace_fold:hover{\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\ +}\ +.ace_tooltip {\ +background-color: #FFF;\ +background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\ +background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\ +border: 1px solid gray;\ +border-radius: 1px;\ +box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\ +color: black;\ +max-width: 100%;\ +padding: 3px 4px;\ +position: fixed;\ +z-index: 999999;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +cursor: default;\ +white-space: pre;\ +word-wrap: break-word;\ +line-height: normal;\ +font-style: normal;\ +font-weight: normal;\ +letter-spacing: normal;\ +pointer-events: none;\ +}\ +.ace_folding-enabled > .ace_gutter-cell {\ +padding-right: 13px;\ +}\ +.ace_fold-widget {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +margin: 0 -12px 0 1px;\ +display: none;\ +width: 11px;\ +vertical-align: top;\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: center;\ +border-radius: 3px;\ +border: 1px solid transparent;\ +cursor: pointer;\ +}\ +.ace_folding-enabled .ace_fold-widget {\ +display: inline-block; \ +}\ +.ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\ +}\ +.ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\ +}\ +.ace_fold-widget:hover {\ +border: 1px solid rgba(0, 0, 0, 0.3);\ +background-color: rgba(255, 255, 255, 0.2);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\ +}\ +.ace_fold-widget:active {\ +border: 1px solid rgba(0, 0, 0, 0.4);\ +background-color: rgba(0, 0, 0, 0.05);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\ +}\ +.ace_dark .ace_fold-widget {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\ +}\ +.ace_dark .ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget:hover {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +background-color: rgba(255, 255, 255, 0.1);\ +}\ +.ace_dark .ace_fold-widget:active {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +}\ +.ace_fold-widget.ace_invalid {\ +background-color: #FFB4B4;\ +border-color: #DE5555;\ +}\ +.ace_fade-fold-widgets .ace_fold-widget {\ +-webkit-transition: opacity 0.4s ease 0.05s;\ +transition: opacity 0.4s ease 0.05s;\ +opacity: 0;\ +}\ +.ace_fade-fold-widgets:hover .ace_fold-widget {\ +-webkit-transition: opacity 0.05s ease 0.05s;\ +transition: opacity 0.05s ease 0.05s;\ +opacity:1;\ +}\ +.ace_underline {\ +text-decoration: underline;\ +}\ +.ace_bold {\ +font-weight: bold;\ +}\ +.ace_nobold .ace_bold {\ +font-weight: normal;\ +}\ +.ace_italic {\ +font-style: italic;\ +}\ +.ace_error-marker {\ +background-color: rgba(255, 0, 0,0.2);\ +position: absolute;\ +z-index: 9;\ +}\ +.ace_highlight-marker {\ +background-color: rgba(255, 255, 0,0.2);\ +position: absolute;\ +z-index: 8;\ +}\ +.ace_br1 {border-top-left-radius : 3px;}\ +.ace_br2 {border-top-right-radius : 3px;}\ +.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\ +.ace_br4 {border-bottom-right-radius: 3px;}\ +.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\ +.ace_br8 {border-bottom-left-radius : 3px;}\ +.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +"; + +dom.importCssString(editorCss, "ace_editor.css"); + +var VirtualRenderer = function(container, theme) { + var _self = this; + + this.container = container || dom.createElement("div"); + this.$keepTextAreaAtCursor = !useragent.isOldIE; + + dom.addCssClass(this.container, "ace_editor"); + + this.setTheme(theme); + + this.$gutter = dom.createElement("div"); + this.$gutter.className = "ace_gutter"; + this.container.appendChild(this.$gutter); + + this.scroller = dom.createElement("div"); + this.scroller.className = "ace_scroller"; + this.container.appendChild(this.scroller); + + this.content = dom.createElement("div"); + this.content.className = "ace_content"; + this.scroller.appendChild(this.content); + + this.$gutterLayer = new GutterLayer(this.$gutter); + this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this)); + + this.$markerBack = new MarkerLayer(this.content); + + var textLayer = this.$textLayer = new TextLayer(this.content); + this.canvas = textLayer.element; + + this.$markerFront = new MarkerLayer(this.content); + + this.$cursorLayer = new CursorLayer(this.content); + this.$horizScroll = false; + this.$vScroll = false; + + this.scrollBar = + this.scrollBarV = new VScrollBar(this.container, this); + this.scrollBarH = new HScrollBar(this.container, this); + this.scrollBarV.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollTop(e.data - _self.scrollMargin.top); + }); + this.scrollBarH.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollLeft(e.data - _self.scrollMargin.left); + }); + + this.scrollTop = 0; + this.scrollLeft = 0; + + this.cursorPos = { + row : 0, + column : 0 + }; + + this.$fontMetrics = new FontMetrics(this.container); + this.$textLayer.$setFontMetrics(this.$fontMetrics); + this.$textLayer.addEventListener("changeCharacterSize", function(e) { + _self.updateCharacterSize(); + _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height); + _self._signal("changeCharacterSize", e); + }); + + this.$size = { + width: 0, + height: 0, + scrollerHeight: 0, + scrollerWidth: 0, + $dirty: true + }; + + this.layerConfig = { + width : 1, + padding : 0, + firstRow : 0, + firstRowScreen: 0, + lastRow : 0, + lineHeight : 0, + characterWidth : 0, + minHeight : 1, + maxHeight : 1, + offset : 0, + height : 1, + gutterOffset: 1 + }; + + this.scrollMargin = { + left: 0, + right: 0, + top: 0, + bottom: 0, + v: 0, + h: 0 + }; + + this.$loop = new RenderLoop( + this.$renderChanges.bind(this), + this.container.ownerDocument.defaultView + ); + this.$loop.schedule(this.CHANGE_FULL); + + this.updateCharacterSize(); + this.setPadding(4); + config.resetOptions(this); + config._emit("renderer", this); +}; + +(function() { + + this.CHANGE_CURSOR = 1; + this.CHANGE_MARKER = 2; + this.CHANGE_GUTTER = 4; + this.CHANGE_SCROLL = 8; + this.CHANGE_LINES = 16; + this.CHANGE_TEXT = 32; + this.CHANGE_SIZE = 64; + this.CHANGE_MARKER_BACK = 128; + this.CHANGE_MARKER_FRONT = 256; + this.CHANGE_FULL = 512; + this.CHANGE_H_SCROLL = 1024; + + oop.implement(this, EventEmitter); + + this.updateCharacterSize = function() { + if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) { + this.$allowBoldFonts = this.$textLayer.allowBoldFonts; + this.setStyle("ace_nobold", !this.$allowBoldFonts); + } + + this.layerConfig.characterWidth = + this.characterWidth = this.$textLayer.getCharacterWidth(); + this.layerConfig.lineHeight = + this.lineHeight = this.$textLayer.getLineHeight(); + this.$updatePrintMargin(); + }; + this.setSession = function(session) { + if (this.session) + this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode); + + this.session = session; + if (session && this.scrollMargin.top && session.getScrollTop() <= 0) + session.setScrollTop(-this.scrollMargin.top); + + this.$cursorLayer.setSession(session); + this.$markerBack.setSession(session); + this.$markerFront.setSession(session); + this.$gutterLayer.setSession(session); + this.$textLayer.setSession(session); + if (!session) + return; + + this.$loop.schedule(this.CHANGE_FULL); + this.session.$setFontMetrics(this.$fontMetrics); + this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; + + this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this); + this.onChangeNewLineMode() + this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode); + }; + this.updateLines = function(firstRow, lastRow, force) { + if (lastRow === undefined) + lastRow = Infinity; + + if (!this.$changedLines) { + this.$changedLines = { + firstRow: firstRow, + lastRow: lastRow + }; + } + else { + if (this.$changedLines.firstRow > firstRow) + this.$changedLines.firstRow = firstRow; + + if (this.$changedLines.lastRow < lastRow) + this.$changedLines.lastRow = lastRow; + } + if (this.$changedLines.lastRow < this.layerConfig.firstRow) { + if (force) + this.$changedLines.lastRow = this.layerConfig.lastRow; + else + return; + } + if (this.$changedLines.firstRow > this.layerConfig.lastRow) + return; + this.$loop.schedule(this.CHANGE_LINES); + }; + + this.onChangeNewLineMode = function() { + this.$loop.schedule(this.CHANGE_TEXT); + this.$textLayer.$updateEolChar(); + }; + + this.onChangeTabSize = function() { + this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER); + this.$textLayer.onChangeTabSize(); + }; + this.updateText = function() { + this.$loop.schedule(this.CHANGE_TEXT); + }; + this.updateFull = function(force) { + if (force) + this.$renderChanges(this.CHANGE_FULL, true); + else + this.$loop.schedule(this.CHANGE_FULL); + }; + this.updateFontSize = function() { + this.$textLayer.checkForSizeChanges(); + }; + + this.$changes = 0; + this.$updateSizeAsync = function() { + if (this.$loop.pending) + this.$size.$dirty = true; + else + this.onResize(); + }; + this.onResize = function(force, gutterWidth, width, height) { + if (this.resizing > 2) + return; + else if (this.resizing > 0) + this.resizing++; + else + this.resizing = force ? 1 : 0; + var el = this.container; + if (!height) + height = el.clientHeight || el.scrollHeight; + if (!width) + width = el.clientWidth || el.scrollWidth; + var changes = this.$updateCachedSize(force, gutterWidth, width, height); + + + if (!this.$size.scrollerHeight || (!width && !height)) + return this.resizing = 0; + + if (force) + this.$gutterLayer.$padding = null; + + if (force) + this.$renderChanges(changes | this.$changes, true); + else + this.$loop.schedule(changes | this.$changes); + + if (this.resizing) + this.resizing = 0; + this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; + }; + + this.$updateCachedSize = function(force, gutterWidth, width, height) { + height -= (this.$extraHeight || 0); + var changes = 0; + var size = this.$size; + var oldSize = { + width: size.width, + height: size.height, + scrollerHeight: size.scrollerHeight, + scrollerWidth: size.scrollerWidth + }; + if (height && (force || size.height != height)) { + size.height = height; + changes |= this.CHANGE_SIZE; + + size.scrollerHeight = size.height; + if (this.$horizScroll) + size.scrollerHeight -= this.scrollBarH.getHeight(); + this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px"; + + changes = changes | this.CHANGE_SCROLL; + } + + if (width && (force || size.width != width)) { + changes |= this.CHANGE_SIZE; + size.width = width; + + if (gutterWidth == null) + gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + + this.gutterWidth = gutterWidth; + + this.scrollBarH.element.style.left = + this.scroller.style.left = gutterWidth + "px"; + size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth()); + + this.scrollBarH.element.style.right = + this.scroller.style.right = this.scrollBarV.getWidth() + "px"; + this.scroller.style.bottom = this.scrollBarH.getHeight() + "px"; + + if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force) + changes |= this.CHANGE_FULL; + } + + size.$dirty = !width || !height; + + if (changes) + this._signal("resize", oldSize); + + return changes; + }; + + this.onGutterResize = function() { + var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + if (gutterWidth != this.gutterWidth) + this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height); + + if (this.session.getUseWrapMode() && this.adjustWrapLimit()) { + this.$loop.schedule(this.CHANGE_FULL); + } else if (this.$size.$dirty) { + this.$loop.schedule(this.CHANGE_FULL); + } else { + this.$computeLayerConfig(); + this.$loop.schedule(this.CHANGE_MARKER); + } + }; + this.adjustWrapLimit = function() { + var availableWidth = this.$size.scrollerWidth - this.$padding * 2; + var limit = Math.floor(availableWidth / this.characterWidth); + return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn); + }; + this.setAnimatedScroll = function(shouldAnimate){ + this.setOption("animatedScroll", shouldAnimate); + }; + this.getAnimatedScroll = function() { + return this.$animatedScroll; + }; + this.setShowInvisibles = function(showInvisibles) { + this.setOption("showInvisibles", showInvisibles); + }; + this.getShowInvisibles = function() { + return this.getOption("showInvisibles"); + }; + this.getDisplayIndentGuides = function() { + return this.getOption("displayIndentGuides"); + }; + + this.setDisplayIndentGuides = function(display) { + this.setOption("displayIndentGuides", display); + }; + this.setShowPrintMargin = function(showPrintMargin) { + this.setOption("showPrintMargin", showPrintMargin); + }; + this.getShowPrintMargin = function() { + return this.getOption("showPrintMargin"); + }; + this.setPrintMarginColumn = function(showPrintMargin) { + this.setOption("printMarginColumn", showPrintMargin); + }; + this.getPrintMarginColumn = function() { + return this.getOption("printMarginColumn"); + }; + this.getShowGutter = function(){ + return this.getOption("showGutter"); + }; + this.setShowGutter = function(show){ + return this.setOption("showGutter", show); + }; + + this.getFadeFoldWidgets = function(){ + return this.getOption("fadeFoldWidgets") + }; + + this.setFadeFoldWidgets = function(show) { + this.setOption("fadeFoldWidgets", show); + }; + + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + + this.$updateGutterLineHighlight = function() { + var pos = this.$cursorLayer.$pixelPos; + var height = this.layerConfig.lineHeight; + if (this.session.getUseWrapMode()) { + var cursor = this.session.selection.getCursor(); + cursor.column = 0; + pos = this.$cursorLayer.getPixelPosition(cursor, true); + height *= this.session.getRowLength(cursor.row); + } + this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px"; + this.$gutterLineHighlight.style.height = height + "px"; + }; + + this.$updatePrintMargin = function() { + if (!this.$showPrintMargin && !this.$printMarginEl) + return; + + if (!this.$printMarginEl) { + var containerEl = dom.createElement("div"); + containerEl.className = "ace_layer ace_print-margin-layer"; + this.$printMarginEl = dom.createElement("div"); + this.$printMarginEl.className = "ace_print-margin"; + containerEl.appendChild(this.$printMarginEl); + this.content.insertBefore(containerEl, this.content.firstChild); + } + + var style = this.$printMarginEl.style; + style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; + style.visibility = this.$showPrintMargin ? "visible" : "hidden"; + + if (this.session && this.session.$wrap == -1) + this.adjustWrapLimit(); + }; + this.getContainerElement = function() { + return this.container; + }; + this.getMouseEventTarget = function() { + return this.scroller; + }; + this.getTextAreaContainer = function() { + return this.container; + }; + this.$moveTextAreaToCursor = function() { + if (!this.$keepTextAreaAtCursor) + return; + var config = this.layerConfig; + var posTop = this.$cursorLayer.$pixelPos.top; + var posLeft = this.$cursorLayer.$pixelPos.left; + posTop -= config.offset; + + var style = this.textarea.style; + var h = this.lineHeight; + if (posTop < 0 || posTop > config.height - h) { + style.top = style.left = "0"; + return; + } + + var w = this.characterWidth; + if (this.$composition) { + var val = this.textarea.value.replace(/^\x01+/, ""); + w *= (this.session.$getStringScreenWidth(val)[0]+2); + h += 2; + } + posLeft -= this.scrollLeft; + if (posLeft > this.$size.scrollerWidth - w) + posLeft = this.$size.scrollerWidth - w; + + posLeft += this.gutterWidth; + style.height = h + "px"; + style.width = w + "px"; + style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px"; + style.top = Math.min(posTop, this.$size.height - h) + "px"; + }; + this.getFirstVisibleRow = function() { + return this.layerConfig.firstRow; + }; + this.getFirstFullyVisibleRow = function() { + return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1); + }; + this.getLastFullyVisibleRow = function() { + var config = this.layerConfig; + var lastRow = config.lastRow + var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight; + if (top - this.session.getScrollTop() > config.height - config.lineHeight) + return lastRow - 1; + return lastRow; + }; + this.getLastVisibleRow = function() { + return this.layerConfig.lastRow; + }; + + this.$padding = null; + this.setPadding = function(padding) { + this.$padding = padding; + this.$textLayer.setPadding(padding); + this.$cursorLayer.setPadding(padding); + this.$markerFront.setPadding(padding); + this.$markerBack.setPadding(padding); + this.$loop.schedule(this.CHANGE_FULL); + this.$updatePrintMargin(); + }; + + this.setScrollMargin = function(top, bottom, left, right) { + var sm = this.scrollMargin; + sm.top = top|0; + sm.bottom = bottom|0; + sm.right = right|0; + sm.left = left|0; + sm.v = sm.top + sm.bottom; + sm.h = sm.left + sm.right; + if (sm.top && this.scrollTop <= 0 && this.session) + this.session.setScrollTop(-sm.top); + this.updateFull(); + }; + this.getHScrollBarAlwaysVisible = function() { + return this.$hScrollBarAlwaysVisible; + }; + this.setHScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("hScrollBarAlwaysVisible", alwaysVisible); + }; + this.getVScrollBarAlwaysVisible = function() { + return this.$vScrollBarAlwaysVisible; + }; + this.setVScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("vScrollBarAlwaysVisible", alwaysVisible); + }; + + this.$updateScrollBarV = function() { + var scrollHeight = this.layerConfig.maxHeight; + var scrollerHeight = this.$size.scrollerHeight; + if (!this.$maxLines && this.$scrollPastEnd) { + scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd; + if (this.scrollTop > scrollHeight - scrollerHeight) { + scrollHeight = this.scrollTop + scrollerHeight; + this.scrollBarV.scrollTop = null; + } + } + this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v); + this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top); + }; + this.$updateScrollBarH = function() { + this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h); + this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left); + }; + + this.$frozen = false; + this.freeze = function() { + this.$frozen = true; + }; + + this.unfreeze = function() { + this.$frozen = false; + }; + + this.$renderChanges = function(changes, force) { + if (this.$changes) { + changes |= this.$changes; + this.$changes = 0; + } + if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) { + this.$changes |= changes; + return; + } + if (this.$size.$dirty) { + this.$changes |= changes; + return this.onResize(true); + } + if (!this.lineHeight) { + this.$textLayer.checkForSizeChanges(); + } + + this._signal("beforeRender"); + var config = this.layerConfig; + if (changes & this.CHANGE_FULL || + changes & this.CHANGE_SIZE || + changes & this.CHANGE_TEXT || + changes & this.CHANGE_LINES || + changes & this.CHANGE_SCROLL || + changes & this.CHANGE_H_SCROLL + ) { + changes |= this.$computeLayerConfig(); + if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) { + var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight; + if (st > 0) { + this.scrollTop = st; + changes = changes | this.CHANGE_SCROLL; + changes |= this.$computeLayerConfig(); + } + } + config = this.layerConfig; + this.$updateScrollBarV(); + if (changes & this.CHANGE_H_SCROLL) + this.$updateScrollBarH(); + this.$gutterLayer.element.style.marginTop = (-config.offset) + "px"; + this.content.style.marginTop = (-config.offset) + "px"; + this.content.style.width = config.width + 2 * this.$padding + "px"; + this.content.style.height = config.minHeight + "px"; + } + if (changes & this.CHANGE_H_SCROLL) { + this.content.style.marginLeft = -this.scrollLeft + "px"; + this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left"; + } + if (changes & this.CHANGE_FULL) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this._signal("afterRender"); + return; + } + if (changes & this.CHANGE_SCROLL) { + if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) + this.$textLayer.update(config); + else + this.$textLayer.scrollLines(config); + + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this.$moveTextAreaToCursor(); + this._signal("afterRender"); + return; + } + + if (changes & this.CHANGE_TEXT) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_LINES) { + if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) { + if (this.$showGutter) + this.$gutterLayer.update(config); + } + + if (changes & this.CHANGE_CURSOR) { + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { + this.$markerFront.update(config); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { + this.$markerBack.update(config); + } + + this._signal("afterRender"); + }; + + + this.$autosize = function() { + var height = this.session.getScreenLength() * this.lineHeight; + var maxHeight = this.$maxLines * this.lineHeight; + var desiredHeight = Math.min(maxHeight, + Math.max((this.$minLines || 1) * this.lineHeight, height) + ) + this.scrollMargin.v + (this.$extraHeight || 0); + if (this.$horizScroll) + desiredHeight += this.scrollBarH.getHeight(); + if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight) + desiredHeight = this.$maxPixelHeight; + var vScroll = height > maxHeight; + + if (desiredHeight != this.desiredHeight || + this.$size.height != this.desiredHeight || vScroll != this.$vScroll) { + if (vScroll != this.$vScroll) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var w = this.container.clientWidth; + this.container.style.height = desiredHeight + "px"; + this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight); + this.desiredHeight = desiredHeight; + + this._signal("autosize"); + } + }; + + this.$computeLayerConfig = function() { + var session = this.session; + var size = this.$size; + + var hideScrollbars = size.height <= 2 * this.lineHeight; + var screenLines = this.session.getScreenLength(); + var maxHeight = screenLines * this.lineHeight; + + var longestLine = this.$getLongestLine(); + + var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible || + size.scrollerWidth - longestLine - 2 * this.$padding < 0); + + var hScrollChanged = this.$horizScroll !== horizScroll; + if (hScrollChanged) { + this.$horizScroll = horizScroll; + this.scrollBarH.setVisible(horizScroll); + } + var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine + if (this.$maxLines && this.lineHeight > 1) + this.$autosize(); + + var offset = this.scrollTop % this.lineHeight; + var minHeight = size.scrollerHeight + this.lineHeight; + + var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd + ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd + : 0; + maxHeight += scrollPastEnd; + + var sm = this.scrollMargin; + this.session.setScrollTop(Math.max(-sm.top, + Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom))); + + this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft, + longestLine + 2 * this.$padding - size.scrollerWidth + sm.right))); + + var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible || + size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top); + var vScrollChanged = vScrollBefore !== vScroll; + if (vScrollChanged) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; + var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); + var lastRow = firstRow + lineCount; + var firstRowScreen, firstRowHeight; + var lineHeight = this.lineHeight; + firstRow = session.screenToDocumentRow(firstRow, 0); + var foldLine = session.getFoldLine(firstRow); + if (foldLine) { + firstRow = foldLine.start.row; + } + + firstRowScreen = session.documentToScreenRow(firstRow, 0); + firstRowHeight = session.getRowLength(firstRow) * lineHeight; + + lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); + minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight + + firstRowHeight; + + offset = this.scrollTop - firstRowScreen * lineHeight; + + var changes = 0; + if (this.layerConfig.width != longestLine) + changes = this.CHANGE_H_SCROLL; + if (hScrollChanged || vScrollChanged) { + changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height); + this._signal("scrollbarVisibilityChanged"); + if (vScrollChanged) + longestLine = this.$getLongestLine(); + } + + this.layerConfig = { + width : longestLine, + padding : this.$padding, + firstRow : firstRow, + firstRowScreen: firstRowScreen, + lastRow : lastRow, + lineHeight : lineHeight, + characterWidth : this.characterWidth, + minHeight : minHeight, + maxHeight : maxHeight, + offset : offset, + gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0, + height : this.$size.scrollerHeight + }; + + return changes; + }; + + this.$updateLines = function() { + var firstRow = this.$changedLines.firstRow; + var lastRow = this.$changedLines.lastRow; + this.$changedLines = null; + + var layerConfig = this.layerConfig; + + if (firstRow > layerConfig.lastRow + 1) { return; } + if (lastRow < layerConfig.firstRow) { return; } + if (lastRow === Infinity) { + if (this.$showGutter) + this.$gutterLayer.update(layerConfig); + this.$textLayer.update(layerConfig); + return; + } + this.$textLayer.updateLines(layerConfig, firstRow, lastRow); + return true; + }; + + this.$getLongestLine = function() { + var charCount = this.session.getScreenWidth(); + if (this.showInvisibles && !this.session.$useWrapMode) + charCount += 1; + + return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth)); + }; + this.updateFrontMarkers = function() { + this.$markerFront.setMarkers(this.session.getMarkers(true)); + this.$loop.schedule(this.CHANGE_MARKER_FRONT); + }; + this.updateBackMarkers = function() { + this.$markerBack.setMarkers(this.session.getMarkers()); + this.$loop.schedule(this.CHANGE_MARKER_BACK); + }; + this.addGutterDecoration = function(row, className){ + this.$gutterLayer.addGutterDecoration(row, className); + }; + this.removeGutterDecoration = function(row, className){ + this.$gutterLayer.removeGutterDecoration(row, className); + }; + this.updateBreakpoints = function(rows) { + this.$loop.schedule(this.CHANGE_GUTTER); + }; + this.setAnnotations = function(annotations) { + this.$gutterLayer.setAnnotations(annotations); + this.$loop.schedule(this.CHANGE_GUTTER); + }; + this.updateCursor = function() { + this.$loop.schedule(this.CHANGE_CURSOR); + }; + this.hideCursor = function() { + this.$cursorLayer.hideCursor(); + }; + this.showCursor = function() { + this.$cursorLayer.showCursor(); + }; + + this.scrollSelectionIntoView = function(anchor, lead, offset) { + this.scrollCursorIntoView(anchor, offset); + this.scrollCursorIntoView(lead, offset); + }; + this.scrollCursorIntoView = function(cursor, offset, $viewMargin) { + if (this.$size.scrollerHeight === 0) + return; + + var pos = this.$cursorLayer.getPixelPosition(cursor); + + var left = pos.left; + var top = pos.top; + + var topMargin = $viewMargin && $viewMargin.top || 0; + var bottomMargin = $viewMargin && $viewMargin.bottom || 0; + + var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop; + + if (scrollTop + topMargin > top) { + if (offset && scrollTop + topMargin > top + this.lineHeight) + top -= offset * this.$size.scrollerHeight; + if (top === 0) + top = -this.scrollMargin.top; + this.session.setScrollTop(top); + } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) { + if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight) + top += offset * this.$size.scrollerHeight; + this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight); + } + + var scrollLeft = this.scrollLeft; + + if (scrollLeft > left) { + if (left < this.$padding + 2 * this.layerConfig.characterWidth) + left = -this.scrollMargin.left; + this.session.setScrollLeft(left); + } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { + this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); + } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) { + this.session.setScrollLeft(0); + } + }; + this.getScrollTop = function() { + return this.session.getScrollTop(); + }; + this.getScrollLeft = function() { + return this.session.getScrollLeft(); + }; + this.getScrollTopRow = function() { + return this.scrollTop / this.lineHeight; + }; + this.getScrollBottomRow = function() { + return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1); + }; + this.scrollToRow = function(row) { + this.session.setScrollTop(row * this.lineHeight); + }; + + this.alignCursor = function(cursor, alignment) { + if (typeof cursor == "number") + cursor = {row: cursor, column: 0}; + + var pos = this.$cursorLayer.getPixelPosition(cursor); + var h = this.$size.scrollerHeight - this.lineHeight; + var offset = pos.top - h * (alignment || 0); + + this.session.setScrollTop(offset); + return offset; + }; + + this.STEPS = 8; + this.$calcSteps = function(fromValue, toValue){ + var i = 0; + var l = this.STEPS; + var steps = []; + + var func = function(t, x_min, dx) { + return dx * (Math.pow(t - 1, 3) + 1) + x_min; + }; + + for (i = 0; i < l; ++i) + steps.push(func(i / this.STEPS, fromValue, toValue - fromValue)); + + return steps; + }; + this.scrollToLine = function(line, center, animate, callback) { + var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0}); + var offset = pos.top; + if (center) + offset -= this.$size.scrollerHeight / 2; + + var initialScroll = this.scrollTop; + this.session.setScrollTop(offset); + if (animate !== false) + this.animateScrolling(initialScroll, callback); + }; + + this.animateScrolling = function(fromValue, callback) { + var toValue = this.scrollTop; + if (!this.$animatedScroll) + return; + var _self = this; + + if (fromValue == toValue) + return; + + if (this.$scrollAnimation) { + var oldSteps = this.$scrollAnimation.steps; + if (oldSteps.length) { + fromValue = oldSteps[0]; + if (fromValue == toValue) + return; + } + } + + var steps = _self.$calcSteps(fromValue, toValue); + this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps}; + + clearInterval(this.$timer); + + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + this.$timer = setInterval(function() { + if (steps.length) { + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + } else if (toValue != null) { + _self.session.$scrollTop = -1; + _self.session.setScrollTop(toValue); + toValue = null; + } else { + _self.$timer = clearInterval(_self.$timer); + _self.$scrollAnimation = null; + callback && callback(); + } + }, 10); + }; + this.scrollToY = function(scrollTop) { + if (this.scrollTop !== scrollTop) { + this.$loop.schedule(this.CHANGE_SCROLL); + this.scrollTop = scrollTop; + } + }; + this.scrollToX = function(scrollLeft) { + if (this.scrollLeft !== scrollLeft) + this.scrollLeft = scrollLeft; + this.$loop.schedule(this.CHANGE_H_SCROLL); + }; + this.scrollTo = function(x, y) { + this.session.setScrollTop(y); + this.session.setScrollLeft(y); + }; + this.scrollBy = function(deltaX, deltaY) { + deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY); + deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX); + }; + this.isScrollableBy = function(deltaX, deltaY) { + if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top) + return true; + if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight + - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom) + return true; + if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left) + return true; + if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth + - this.layerConfig.width < -1 + this.scrollMargin.right) + return true; + }; + + this.pixelToScreenCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var offset = (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth; + var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight); + var col = Math.round(offset); + + return {row: row, column: col, side: offset - col > 0 ? 1 : -1}; + }; + + this.screenToTextCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var col = Math.round( + (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth + ); + + var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight; + + return this.session.screenToDocumentPosition(row, Math.max(col, 0)); + }; + this.textToScreenCoordinates = function(row, column) { + var canvasPos = this.scroller.getBoundingClientRect(); + var pos = this.session.documentToScreenPosition(row, column); + + var x = this.$padding + Math.round(pos.column * this.characterWidth); + var y = pos.row * this.lineHeight; + + return { + pageX: canvasPos.left + x - this.scrollLeft, + pageY: canvasPos.top + y - this.scrollTop + }; + }; + this.visualizeFocus = function() { + dom.addCssClass(this.container, "ace_focus"); + }; + this.visualizeBlur = function() { + dom.removeCssClass(this.container, "ace_focus"); + }; + this.showComposition = function(position) { + if (!this.$composition) + this.$composition = { + keepTextAreaAtCursor: this.$keepTextAreaAtCursor, + cssText: this.textarea.style.cssText + }; + + this.$keepTextAreaAtCursor = true; + dom.addCssClass(this.textarea, "ace_composition"); + this.textarea.style.cssText = ""; + this.$moveTextAreaToCursor(); + }; + this.setCompositionText = function(text) { + this.$moveTextAreaToCursor(); + }; + this.hideComposition = function() { + if (!this.$composition) + return; + + dom.removeCssClass(this.textarea, "ace_composition"); + this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor; + this.textarea.style.cssText = this.$composition.cssText; + this.$composition = null; + }; + this.setTheme = function(theme, cb) { + var _self = this; + this.$themeId = theme; + _self._dispatchEvent('themeChange',{theme:theme}); + + if (!theme || typeof theme == "string") { + var moduleName = theme || this.$options.theme.initialValue; + config.loadModule(["theme", moduleName], afterLoad); + } else { + afterLoad(theme); + } + + function afterLoad(module) { + if (_self.$themeId != theme) + return cb && cb(); + if (!module || !module.cssClass) + throw new Error("couldn't load module " + theme + " or it didn't call define"); + dom.importCssString( + module.cssText, + module.cssClass, + _self.container.ownerDocument + ); + + if (_self.theme) + dom.removeCssClass(_self.container, _self.theme.cssClass); + + var padding = "padding" in module ? module.padding + : "padding" in (_self.theme || {}) ? 4 : _self.$padding; + if (_self.$padding && padding != _self.$padding) + _self.setPadding(padding); + _self.$theme = module.cssClass; + + _self.theme = module; + dom.addCssClass(_self.container, module.cssClass); + dom.setCssClass(_self.container, "ace_dark", module.isDark); + if (_self.$size) { + _self.$size.width = 0; + _self.$updateSizeAsync(); + } + + _self._dispatchEvent('themeLoaded', {theme:module}); + cb && cb(); + } + }; + this.getTheme = function() { + return this.$themeId; + }; + this.setStyle = function(style, include) { + dom.setCssClass(this.container, style, include !== false); + }; + this.unsetStyle = function(style) { + dom.removeCssClass(this.container, style); + }; + + this.setCursorStyle = function(style) { + if (this.scroller.style.cursor != style) + this.scroller.style.cursor = style; + }; + this.setMouseCursor = function(cursorStyle) { + this.scroller.style.cursor = cursorStyle; + }; + this.destroy = function() { + this.$textLayer.destroy(); + this.$cursorLayer.destroy(); + }; + +}).call(VirtualRenderer.prototype); + + +config.defineOptions(VirtualRenderer.prototype, "renderer", { + animatedScroll: {initialValue: false}, + showInvisibles: { + set: function(value) { + if (this.$textLayer.setShowInvisibles(value)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: false + }, + showPrintMargin: { + set: function() { this.$updatePrintMargin(); }, + initialValue: true + }, + printMarginColumn: { + set: function() { this.$updatePrintMargin(); }, + initialValue: 80 + }, + printMargin: { + set: function(val) { + if (typeof val == "number") + this.$printMarginColumn = val; + this.$showPrintMargin = !!val; + this.$updatePrintMargin(); + }, + get: function() { + return this.$showPrintMargin && this.$printMarginColumn; + } + }, + showGutter: { + set: function(show){ + this.$gutter.style.display = show ? "block" : "none"; + this.$loop.schedule(this.CHANGE_FULL); + this.onGutterResize(); + }, + initialValue: true + }, + fadeFoldWidgets: { + set: function(show) { + dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show); + }, + initialValue: false + }, + showFoldWidgets: { + set: function(show) {this.$gutterLayer.setShowFoldWidgets(show)}, + initialValue: true + }, + showLineNumbers: { + set: function(show) { + this.$gutterLayer.setShowLineNumbers(show); + this.$loop.schedule(this.CHANGE_GUTTER); + }, + initialValue: true + }, + displayIndentGuides: { + set: function(show) { + if (this.$textLayer.setDisplayIndentGuides(show)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: true + }, + highlightGutterLine: { + set: function(shouldHighlight) { + if (!this.$gutterLineHighlight) { + this.$gutterLineHighlight = dom.createElement("div"); + this.$gutterLineHighlight.className = "ace_gutter-active-line"; + this.$gutter.appendChild(this.$gutterLineHighlight); + return; + } + + this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none"; + if (this.$cursorLayer.$pixelPos) + this.$updateGutterLineHighlight(); + }, + initialValue: false, + value: true + }, + hScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + vScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$vScrollBarAlwaysVisible || !this.$vScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + fontSize: { + set: function(size) { + if (typeof size == "number") + size = size + "px"; + this.container.style.fontSize = size; + this.updateFontSize(); + }, + initialValue: 12 + }, + fontFamily: { + set: function(name) { + this.container.style.fontFamily = name; + this.updateFontSize(); + } + }, + maxLines: { + set: function(val) { + this.updateFull(); + } + }, + minLines: { + set: function(val) { + this.updateFull(); + } + }, + maxPixelHeight: { + set: function(val) { + this.updateFull(); + }, + initialValue: 0 + }, + scrollPastEnd: { + set: function(val) { + val = +val || 0; + if (this.$scrollPastEnd == val) + return; + this.$scrollPastEnd = val; + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: 0, + handlesSet: true + }, + fixedWidthGutter: { + set: function(val) { + this.$gutterLayer.$fixedWidth = !!val; + this.$loop.schedule(this.CHANGE_GUTTER); + } + }, + theme: { + set: function(val) { this.setTheme(val) }, + get: function() { return this.$themeId || this.theme; }, + initialValue: "./theme/textmate", + handlesSet: true + } +}); + +exports.VirtualRenderer = VirtualRenderer; +}); + +ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var net = acequire("../lib/net"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; +var config = acequire("../config"); + +var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.onMessage = this.onMessage.bind(this); + if (acequire.nameToUrl && !acequire.toUrl) + acequire.toUrl = acequire.nameToUrl; + + if (config.get("packaged") || !acequire.toUrl) { + workerUrl = workerUrl || config.moduleUrl(mod.id, "worker") + } else { + var normalizePath = this.$normalizePath; + workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_")); + + var tlns = {}; + topLevelNamespaces.forEach(function(ns) { + tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, "")); + }); + } + + try { + var workerSrc = mod.src; + var Blob = require('w3c-blob'); + var blob = new Blob([ workerSrc ], { type: 'application/javascript' }); + var blobUrl = (window.URL || window.webkitURL).createObjectURL(blob); + + this.$worker = new Worker(blobUrl); + + } catch(e) { + if (e instanceof window.DOMException) { + var blob = this.$workerBlob(workerUrl); + var URL = window.URL || window.webkitURL; + var blobURL = URL.createObjectURL(blob); + + this.$worker = new Worker(blobURL); + URL.revokeObjectURL(blobURL); + } else { + throw e; + } + } + this.$worker.postMessage({ + init : true, + tlns : tlns, + module : mod.id, + classname : classname + }); + + this.callbackId = 1; + this.callbacks = {}; + + this.$worker.onmessage = this.onMessage; +}; + +(function(){ + + oop.implement(this, EventEmitter); + + this.onMessage = function(e) { + var msg = e.data; + switch(msg.type) { + case "event": + this._signal(msg.name, {data: msg.data}); + break; + case "call": + var callback = this.callbacks[msg.id]; + if (callback) { + callback(msg.data); + delete this.callbacks[msg.id]; + } + break; + case "error": + this.reportError(msg.data); + break; + case "log": + window.console && console.log && console.log.apply(console, msg.data); + break; + } + }; + + this.reportError = function(err) { + window.console && console.error && console.error(err); + }; + + this.$normalizePath = function(path) { + return net.qualifyURL(path); + }; + + this.terminate = function() { + this._signal("terminate", {}); + this.deltaQueue = null; + this.$worker.terminate(); + this.$worker = null; + if (this.$doc) + this.$doc.off("change", this.changeListener); + this.$doc = null; + }; + + this.send = function(cmd, args) { + this.$worker.postMessage({command: cmd, args: args}); + }; + + this.call = function(cmd, args, callback) { + if (callback) { + var id = this.callbackId++; + this.callbacks[id] = callback; + args.push(id); + } + this.send(cmd, args); + }; + + this.emit = function(event, data) { + try { + this.$worker.postMessage({event: event, data: {data: data.data}}); + } + catch(ex) { + console.error(ex.stack); + } + }; + + this.attachToDocument = function(doc) { + if(this.$doc) + this.terminate(); + + this.$doc = doc; + this.call("setValue", [doc.getValue()]); + doc.on("change", this.changeListener); + }; + + this.changeListener = function(delta) { + if (!this.deltaQueue) { + this.deltaQueue = []; + setTimeout(this.$sendDeltaQueue, 0); + } + if (delta.action == "insert") + this.deltaQueue.push(delta.start, delta.lines); + else + this.deltaQueue.push(delta.start, delta.end); + }; + + this.$sendDeltaQueue = function() { + var q = this.deltaQueue; + if (!q) return; + this.deltaQueue = null; + if (q.length > 50 && q.length > this.$doc.getLength() >> 1) { + this.call("setValue", [this.$doc.getValue()]); + } else + this.emit("change", {data: q}); + }; + + this.$workerBlob = function(workerUrl) { + var script = "importScripts('" + net.qualifyURL(workerUrl) + "');"; + try { + return new Blob([script], {"type": "application/javascript"}); + } catch (e) { // Backwards-compatibility + var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; + var blobBuilder = new BlobBuilder(); + blobBuilder.append(script); + return blobBuilder.getBlob("application/javascript"); + } + }; + +}).call(WorkerClient.prototype); + + +var UIWorkerClient = function(topLevelNamespaces, mod, classname) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.callbackId = 1; + this.callbacks = {}; + this.messageBuffer = []; + + var main = null; + var emitSync = false; + var sender = Object.create(EventEmitter); + var _self = this; + + this.$worker = {}; + this.$worker.terminate = function() {}; + this.$worker.postMessage = function(e) { + _self.messageBuffer.push(e); + if (main) { + if (emitSync) + setTimeout(processNext); + else + processNext(); + } + }; + this.setEmitSync = function(val) { emitSync = val }; + + var processNext = function() { + var msg = _self.messageBuffer.shift(); + if (msg.command) + main[msg.command].apply(main, msg.args); + else if (msg.event) + sender._signal(msg.event, msg.data); + }; + + sender.postMessage = function(msg) { + _self.onMessage({data: msg}); + }; + sender.callback = function(data, callbackId) { + this.postMessage({type: "call", id: callbackId, data: data}); + }; + sender.emit = function(name, data) { + this.postMessage({type: "event", name: name, data: data}); + }; + + config.loadModule(["worker", mod], function(Main) { + main = new Main[classname](sender); + while (_self.messageBuffer.length) + processNext(); + }); +}; + +UIWorkerClient.prototype = WorkerClient.prototype; + +exports.UIWorkerClient = UIWorkerClient; +exports.WorkerClient = WorkerClient; + +}); + +ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var oop = acequire("./lib/oop"); + +var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) { + var _self = this; + this.length = length; + this.session = session; + this.doc = session.getDocument(); + this.mainClass = mainClass; + this.othersClass = othersClass; + this.$onUpdate = this.onUpdate.bind(this); + this.doc.on("change", this.$onUpdate); + this.$others = others; + + this.$onCursorChange = function() { + setTimeout(function() { + _self.onCursorChange(); + }); + }; + + this.$pos = pos; + var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1}; + this.$undoStackDepth = undoStack.length; + this.setup(); + + session.selection.on("changeCursor", this.$onCursorChange); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.setup = function() { + var _self = this; + var doc = this.doc; + var session = this.session; + + this.selectionBefore = session.selection.toJSON(); + if (session.selection.inMultiSelectMode) + session.selection.toSingleRange(); + + this.pos = doc.createAnchor(this.$pos.row, this.$pos.column); + var pos = this.pos; + pos.$insertRight = true; + pos.detach(); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); + this.others = []; + this.$others.forEach(function(other) { + var anchor = doc.createAnchor(other.row, other.column); + anchor.$insertRight = true; + anchor.detach(); + _self.others.push(anchor); + }); + session.setUndoSelect(false); + }; + this.showOtherMarkers = function() { + if (this.othersActive) return; + var session = this.session; + var _self = this; + this.othersActive = true; + this.others.forEach(function(anchor) { + anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false); + }); + }; + this.hideOtherMarkers = function() { + if (!this.othersActive) return; + this.othersActive = false; + for (var i = 0; i < this.others.length; i++) { + this.session.removeMarker(this.others[i].markerId); + } + }; + this.onUpdate = function(delta) { + if (this.$updating) + return this.updateAnchors(delta); + + var range = delta; + if (range.start.row !== range.end.row) return; + if (range.start.row !== this.pos.row) return; + this.$updating = true; + var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column; + var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1; + var distanceFromStart = range.start.column - this.pos.column; + + this.updateAnchors(delta); + + if (inMainRange) + this.length += lengthDiff; + + if (inMainRange && !this.session.$fromUndo) { + if (delta.action === 'insert') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.insertMergedLines(newPos, delta.lines); + } + } else if (delta.action === 'remove') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); + } + } + } + + this.$updating = false; + this.updateMarkers(); + }; + + this.updateAnchors = function(delta) { + this.pos.onChange(delta); + for (var i = this.others.length; i--;) + this.others[i].onChange(delta); + this.updateMarkers(); + }; + + this.updateMarkers = function() { + if (this.$updating) + return; + var _self = this; + var session = this.session; + var updateMarker = function(pos, className) { + session.removeMarker(pos.markerId); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false); + }; + updateMarker(this.pos, this.mainClass); + for (var i = this.others.length; i--;) + updateMarker(this.others[i], this.othersClass); + }; + + this.onCursorChange = function(event) { + if (this.$updating || !this.session) return; + var pos = this.session.selection.getCursor(); + if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { + this.showOtherMarkers(); + this._emit("cursorEnter", event); + } else { + this.hideOtherMarkers(); + this._emit("cursorLeave", event); + } + }; + this.detach = function() { + this.session.removeMarker(this.pos && this.pos.markerId); + this.hideOtherMarkers(); + this.doc.removeEventListener("change", this.$onUpdate); + this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); + this.session.setUndoSelect(true); + this.session = null; + }; + this.cancel = function() { + if (this.$undoStackDepth === -1) + return; + var undoManager = this.session.getUndoManager(); + var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; + for (var i = 0; i < undosRequired; i++) { + undoManager.undo(true); + } + if (this.selectionBefore) + this.session.selection.fromJSON(this.selectionBefore); + }; +}).call(PlaceHolder.prototype); + + +exports.PlaceHolder = PlaceHolder; +}); + +ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} + +function onMouseDown(e) { + var ev = e.domEvent; + var alt = ev.altKey; + var shift = ev.shiftKey; + var ctrl = ev.ctrlKey; + var accel = e.getAccelKey(); + var button = e.getButton(); + + if (ctrl && useragent.isMac) + button = ev.button; + + if (e.editor.inMultiSelectMode && button == 2) { + e.editor.textInput.onContextMenu(e.domEvent); + return; + } + + if (!ctrl && !alt && !accel) { + if (button === 0 && e.editor.inMultiSelectMode) + e.editor.exitMultiSelectMode(); + return; + } + + if (button !== 0) + return; + + var editor = e.editor; + var selection = editor.selection; + var isMultiSelect = editor.inMultiSelectMode; + var pos = e.getDocumentPosition(); + var cursor = selection.getCursor(); + var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor)); + + var mouseX = e.x, mouseY = e.y; + var onMouseSelection = function(e) { + mouseX = e.clientX; + mouseY = e.clientY; + }; + + var session = editor.session; + var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var screenCursor = screenAnchor; + + var selectionMode; + if (editor.$mouseHandler.$enableJumpToDef) { + if (ctrl && alt || accel && alt) + selectionMode = shift ? "block" : "add"; + else if (alt && editor.$blockSelectEnabled) + selectionMode = "block"; + } else { + if (accel && !alt) { + selectionMode = "add"; + if (!isMultiSelect && shift) + return; + } else if (alt && editor.$blockSelectEnabled) { + selectionMode = "block"; + } + } + + if (selectionMode && useragent.isMac && ev.ctrlKey) { + editor.$mouseHandler.cancelContextMenu(); + } + + if (selectionMode == "add") { + if (!isMultiSelect && inSelection) + return; // dragging + + if (!isMultiSelect) { + var range = selection.toOrientedRange(); + editor.addSelectionMarker(range); + } + + var oldRange = selection.rangeList.rangeAtPoint(pos); + + + editor.$blockScrolling++; + editor.inVirtualSelectionMode = true; + + if (shift) { + oldRange = null; + range = selection.ranges[0] || range; + editor.removeSelectionMarker(range); + } + editor.once("mouseup", function() { + var tmpSel = selection.toOrientedRange(); + + if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) + selection.substractPoint(tmpSel.cursor); + else { + if (shift) { + selection.substractPoint(range.cursor); + } else if (range) { + editor.removeSelectionMarker(range); + selection.addRange(range); + } + selection.addRange(tmpSel); + } + editor.$blockScrolling--; + editor.inVirtualSelectionMode = false; + }); + + } else if (selectionMode == "block") { + e.stop(); + editor.inVirtualSelectionMode = true; + var initialRange; + var rectSel = []; + var blockSelect = function() { + var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column); + + if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead)) + return; + screenCursor = newCursor; + + editor.$blockScrolling++; + editor.selection.moveToPosition(cursor); + editor.renderer.scrollCursorIntoView(); + + editor.removeSelectionMarkers(rectSel); + rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); + if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty()) + rectSel[0] = editor.$mouseHandler.$clickSelection.clone(); + rectSel.forEach(editor.addSelectionMarker, editor); + editor.updateSelectionMarkers(); + editor.$blockScrolling--; + }; + editor.$blockScrolling++; + if (isMultiSelect && !accel) { + selection.toSingleRange(); + } else if (!isMultiSelect && accel) { + initialRange = selection.toOrientedRange(); + editor.addSelectionMarker(initialRange); + } + + if (shift) + screenAnchor = session.documentToScreenPosition(selection.lead); + else + selection.moveToPosition(pos); + editor.$blockScrolling--; + + screenCursor = {row: -1, column: -1}; + + var onMouseSelectionEnd = function(e) { + clearInterval(timerId); + editor.removeSelectionMarkers(rectSel); + if (!rectSel.length) + rectSel = [selection.toOrientedRange()]; + editor.$blockScrolling++; + if (initialRange) { + editor.removeSelectionMarker(initialRange); + selection.toSingleRange(initialRange); + } + for (var i = 0; i < rectSel.length; i++) + selection.addRange(rectSel[i]); + editor.inVirtualSelectionMode = false; + editor.$mouseHandler.$clickSelection = null; + editor.$blockScrolling--; + }; + + var onSelectionInterval = blockSelect; + + event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); + var timerId = setInterval(function() {onSelectionInterval();}, 20); + + return e.preventDefault(); + } +} + + +exports.onMouseDown = onMouseDown; + +}); + +ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) { +exports.defaultCommands = [{ + name: "addCursorAbove", + exec: function(editor) { editor.selectMoreLines(-1); }, + bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelow", + exec: function(editor) { editor.selectMoreLines(1); }, + bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorAboveSkipCurrent", + exec: function(editor) { editor.selectMoreLines(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelowSkipCurrent", + exec: function(editor) { editor.selectMoreLines(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreBefore", + exec: function(editor) { editor.selectMore(-1); }, + bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreAfter", + exec: function(editor) { editor.selectMore(1); }, + bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextBefore", + exec: function(editor) { editor.selectMore(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextAfter", + exec: function(editor) { editor.selectMore(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "splitIntoLines", + exec: function(editor) { editor.multiSelect.splitIntoLines(); }, + bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"}, + readOnly: true +}, { + name: "alignCursors", + exec: function(editor) { editor.alignCursors(); }, + bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"}, + scrollIntoView: "cursor" +}, { + name: "findAll", + exec: function(editor) { editor.findAll(); }, + bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"}, + scrollIntoView: "cursor", + readOnly: true +}]; +exports.multiSelectCommands = [{ + name: "singleSelection", + bindKey: "esc", + exec: function(editor) { editor.exitMultiSelectMode(); }, + scrollIntoView: "cursor", + readOnly: true, + isAvailable: function(editor) {return editor && editor.inMultiSelectMode} +}]; + +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); + +}); + +ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) { + +var RangeList = acequire("./range_list").RangeList; +var Range = acequire("./range").Range; +var Selection = acequire("./selection").Selection; +var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown; +var event = acequire("./lib/event"); +var lang = acequire("./lib/lang"); +var commands = acequire("./commands/multi_select_commands"); +exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); +var Search = acequire("./search").Search; +var search = new Search(); + +function find(session, needle, dir) { + search.$options.wrap = true; + search.$options.needle = needle; + search.$options.backwards = dir == -1; + return search.find(session); +} +var EditSession = acequire("./edit_session").EditSession; +(function() { + this.getSelectionMarkers = function() { + return this.$selectionMarkers; + }; +}).call(EditSession.prototype); +(function() { + this.ranges = null; + this.rangeList = null; + this.addRange = function(range, $blockChangeEvents) { + if (!range) + return; + + if (!this.inMultiSelectMode && this.rangeCount === 0) { + var oldRange = this.toOrientedRange(); + this.rangeList.add(oldRange); + this.rangeList.add(range); + if (this.rangeList.ranges.length != 2) { + this.rangeList.removeAll(); + return $blockChangeEvents || this.fromOrientedRange(range); + } + this.rangeList.removeAll(); + this.rangeList.add(oldRange); + this.$onAddRange(oldRange); + } + + if (!range.cursor) + range.cursor = range.end; + + var removed = this.rangeList.add(range); + + this.$onAddRange(range); + + if (removed.length) + this.$onRemoveRange(removed); + + if (this.rangeCount > 1 && !this.inMultiSelectMode) { + this._signal("multiSelect"); + this.inMultiSelectMode = true; + this.session.$undoSelect = false; + this.rangeList.attach(this.session); + } + + return $blockChangeEvents || this.fromOrientedRange(range); + }; + + this.toSingleRange = function(range) { + range = range || this.ranges[0]; + var removed = this.rangeList.removeAll(); + if (removed.length) + this.$onRemoveRange(removed); + + range && this.fromOrientedRange(range); + }; + this.substractPoint = function(pos) { + var removed = this.rangeList.substractPoint(pos); + if (removed) { + this.$onRemoveRange(removed); + return removed[0]; + } + }; + this.mergeOverlappingRanges = function() { + var removed = this.rangeList.merge(); + if (removed.length) + this.$onRemoveRange(removed); + else if(this.ranges[0]) + this.fromOrientedRange(this.ranges[0]); + }; + + this.$onAddRange = function(range) { + this.rangeCount = this.rangeList.ranges.length; + this.ranges.unshift(range); + this._signal("addRange", {range: range}); + }; + + this.$onRemoveRange = function(removed) { + this.rangeCount = this.rangeList.ranges.length; + if (this.rangeCount == 1 && this.inMultiSelectMode) { + var lastRange = this.rangeList.ranges.pop(); + removed.push(lastRange); + this.rangeCount = 0; + } + + for (var i = removed.length; i--; ) { + var index = this.ranges.indexOf(removed[i]); + this.ranges.splice(index, 1); + } + + this._signal("removeRange", {ranges: removed}); + + if (this.rangeCount === 0 && this.inMultiSelectMode) { + this.inMultiSelectMode = false; + this._signal("singleSelect"); + this.session.$undoSelect = true; + this.rangeList.detach(this.session); + } + + lastRange = lastRange || this.ranges[0]; + if (lastRange && !lastRange.isEqual(this.getRange())) + this.fromOrientedRange(lastRange); + }; + this.$initRangeList = function() { + if (this.rangeList) + return; + + this.rangeList = new RangeList(); + this.ranges = []; + this.rangeCount = 0; + }; + this.getAllRanges = function() { + return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()]; + }; + + this.splitIntoLines = function () { + if (this.rangeCount > 1) { + var ranges = this.rangeList.ranges; + var lastRange = ranges[ranges.length - 1]; + var range = Range.fromPoints(ranges[0].start, lastRange.end); + + this.toSingleRange(); + this.setSelectionRange(range, lastRange.cursor == lastRange.start); + } else { + var range = this.getRange(); + var isBackwards = this.isBackwards(); + var startRow = range.start.row; + var endRow = range.end.row; + if (startRow == endRow) { + if (isBackwards) + var start = range.end, end = range.start; + else + var start = range.start, end = range.end; + + this.addRange(Range.fromPoints(end, end)); + this.addRange(Range.fromPoints(start, start)); + return; + } + + var rectSel = []; + var r = this.getLineRange(startRow, true); + r.start.column = range.start.column; + rectSel.push(r); + + for (var i = startRow + 1; i < endRow; i++) + rectSel.push(this.getLineRange(i, true)); + + r = this.getLineRange(endRow, true); + r.end.column = range.end.column; + rectSel.push(r); + + rectSel.forEach(this.addRange, this); + } + }; + this.toggleBlockSelection = function () { + if (this.rangeCount > 1) { + var ranges = this.rangeList.ranges; + var lastRange = ranges[ranges.length - 1]; + var range = Range.fromPoints(ranges[0].start, lastRange.end); + + this.toSingleRange(); + this.setSelectionRange(range, lastRange.cursor == lastRange.start); + } else { + var cursor = this.session.documentToScreenPosition(this.selectionLead); + var anchor = this.session.documentToScreenPosition(this.selectionAnchor); + + var rectSel = this.rectangularRangeBlock(cursor, anchor); + rectSel.forEach(this.addRange, this); + } + }; + this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) { + var rectSel = []; + + var xBackwards = screenCursor.column < screenAnchor.column; + if (xBackwards) { + var startColumn = screenCursor.column; + var endColumn = screenAnchor.column; + } else { + var startColumn = screenAnchor.column; + var endColumn = screenCursor.column; + } + + var yBackwards = screenCursor.row < screenAnchor.row; + if (yBackwards) { + var startRow = screenCursor.row; + var endRow = screenAnchor.row; + } else { + var startRow = screenAnchor.row; + var endRow = screenCursor.row; + } + + if (startColumn < 0) + startColumn = 0; + if (startRow < 0) + startRow = 0; + + if (startRow == endRow) + includeEmptyLines = true; + + for (var row = startRow; row <= endRow; row++) { + var range = Range.fromPoints( + this.session.screenToDocumentPosition(row, startColumn), + this.session.screenToDocumentPosition(row, endColumn) + ); + if (range.isEmpty()) { + if (docEnd && isSamePoint(range.end, docEnd)) + break; + var docEnd = range.end; + } + range.cursor = xBackwards ? range.start : range.end; + rectSel.push(range); + } + + if (yBackwards) + rectSel.reverse(); + + if (!includeEmptyLines) { + var end = rectSel.length - 1; + while (rectSel[end].isEmpty() && end > 0) + end--; + if (end > 0) { + var start = 0; + while (rectSel[start].isEmpty()) + start++; + } + for (var i = end; i >= start; i--) { + if (rectSel[i].isEmpty()) + rectSel.splice(i, 1); + } + } + + return rectSel; + }; +}).call(Selection.prototype); +var Editor = acequire("./editor").Editor; +(function() { + this.updateSelectionMarkers = function() { + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + this.addSelectionMarker = function(orientedRange) { + if (!orientedRange.cursor) + orientedRange.cursor = orientedRange.end; + + var style = this.getSelectionStyle(); + orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style); + + this.session.$selectionMarkers.push(orientedRange); + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + return orientedRange; + }; + this.removeSelectionMarker = function(range) { + if (!range.marker) + return; + this.session.removeMarker(range.marker); + var index = this.session.$selectionMarkers.indexOf(range); + if (index != -1) + this.session.$selectionMarkers.splice(index, 1); + this.session.selectionMarkerCount = this.session.$selectionMarkers.length; + }; + + this.removeSelectionMarkers = function(ranges) { + var markerList = this.session.$selectionMarkers; + for (var i = ranges.length; i--; ) { + var range = ranges[i]; + if (!range.marker) + continue; + this.session.removeMarker(range.marker); + var index = markerList.indexOf(range); + if (index != -1) + markerList.splice(index, 1); + } + this.session.selectionMarkerCount = markerList.length; + }; + + this.$onAddRange = function(e) { + this.addSelectionMarker(e.range); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onRemoveRange = function(e) { + this.removeSelectionMarkers(e.ranges); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onMultiSelect = function(e) { + if (this.inMultiSelectMode) + return; + this.inMultiSelectMode = true; + + this.setStyle("ace_multiselect"); + this.keyBinding.addKeyboardHandler(commands.keyboardHandler); + this.commands.setDefaultHandler("exec", this.$onMultiSelectExec); + + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onSingleSelect = function(e) { + if (this.session.multiSelect.inVirtualMode) + return; + this.inMultiSelectMode = false; + + this.unsetStyle("ace_multiselect"); + this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); + + this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + this._emit("changeSelection"); + }; + + this.$onMultiSelectExec = function(e) { + var command = e.command; + var editor = e.editor; + if (!editor.multiSelect) + return; + if (!command.multiSelectAction) { + var result = command.exec(editor, e.args || {}); + editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); + editor.multiSelect.mergeOverlappingRanges(); + } else if (command.multiSelectAction == "forEach") { + result = editor.forEachSelection(command, e.args); + } else if (command.multiSelectAction == "forEachLine") { + result = editor.forEachSelection(command, e.args, true); + } else if (command.multiSelectAction == "single") { + editor.exitMultiSelectMode(); + result = command.exec(editor, e.args || {}); + } else { + result = command.multiSelectAction(editor, e.args || {}); + } + return result; + }; + this.forEachSelection = function(cmd, args, options) { + if (this.inVirtualSelectionMode) + return; + var keepOrder = options && options.keepOrder; + var $byLines = options == true || options && options.$byLines + var session = this.session; + var selection = this.selection; + var rangeList = selection.rangeList; + var ranges = (keepOrder ? selection : rangeList).ranges; + var result; + + if (!ranges.length) + return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + + var reg = selection._eventRegistry; + selection._eventRegistry = {}; + + var tmpSel = new Selection(session); + this.inVirtualSelectionMode = true; + for (var i = ranges.length; i--;) { + if ($byLines) { + while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row) + i--; + } + tmpSel.fromOrientedRange(ranges[i]); + tmpSel.index = i; + this.selection = session.selection = tmpSel; + var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + if (!result && cmdResult !== undefined) + result = cmdResult; + tmpSel.toOrientedRange(ranges[i]); + } + tmpSel.detach(); + + this.selection = session.selection = selection; + this.inVirtualSelectionMode = false; + selection._eventRegistry = reg; + selection.mergeOverlappingRanges(); + + var anim = this.renderer.$scrollAnimation; + this.onCursorChange(); + this.onSelectionChange(); + if (anim && anim.from == anim.to) + this.renderer.animateScrolling(anim.from); + + return result; + }; + this.exitMultiSelectMode = function() { + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) + return; + this.multiSelect.toSingleRange(); + }; + + this.getSelectedText = function() { + var text = ""; + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var ranges = this.multiSelect.rangeList.ranges; + var buf = []; + for (var i = 0; i < ranges.length; i++) { + buf.push(this.session.getTextRange(ranges[i])); + } + var nl = this.session.getDocument().getNewLineCharacter(); + text = buf.join(nl); + if (text.length == (buf.length - 1) * nl.length) + text = ""; + } else if (!this.selection.isEmpty()) { + text = this.session.getTextRange(this.getSelectionRange()); + } + return text; + }; + + this.$checkMultiselectChange = function(e, anchor) { + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var range = this.multiSelect.ranges[0]; + if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor) + return; + var pos = anchor == this.multiSelect.anchor + ? range.cursor == range.start ? range.end : range.start + : range.cursor; + if (pos.row != anchor.row + || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column) + this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange()); + } + }; + this.findAll = function(needle, options, additive) { + options = options || {}; + options.needle = needle || options.needle; + if (options.needle == undefined) { + var range = this.selection.isEmpty() + ? this.selection.getWordRange() + : this.selection.getRange(); + options.needle = this.session.getTextRange(range); + } + this.$search.set(options); + + var ranges = this.$search.findAll(this.session); + if (!ranges.length) + return 0; + + this.$blockScrolling += 1; + var selection = this.multiSelect; + + if (!additive) + selection.toSingleRange(ranges[0]); + + for (var i = ranges.length; i--; ) + selection.addRange(ranges[i], true); + if (range && selection.rangeList.rangeAtPoint(range.start)) + selection.addRange(range, true); + + this.$blockScrolling -= 1; + + return ranges.length; + }; + this.selectMoreLines = function(dir, skip) { + var range = this.selection.toOrientedRange(); + var isBackwards = range.cursor == range.end; + + var screenLead = this.session.documentToScreenPosition(range.cursor); + if (this.selection.$desiredColumn) + screenLead.column = this.selection.$desiredColumn; + + var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column); + + if (!range.isEmpty()) { + var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start); + var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column); + } else { + var anchor = lead; + } + + if (isBackwards) { + var newRange = Range.fromPoints(lead, anchor); + newRange.cursor = newRange.start; + } else { + var newRange = Range.fromPoints(anchor, lead); + newRange.cursor = newRange.end; + } + + newRange.desiredColumn = screenLead.column; + if (!this.selection.inMultiSelectMode) { + this.selection.addRange(range); + } else { + if (skip) + var toRemove = range.cursor; + } + + this.selection.addRange(newRange); + if (toRemove) + this.selection.substractPoint(toRemove); + }; + this.transposeSelections = function(dir) { + var session = this.session; + var sel = session.multiSelect; + var all = sel.ranges; + + for (var i = all.length; i--; ) { + var range = all[i]; + if (range.isEmpty()) { + var tmp = session.getWordRange(range.start.row, range.start.column); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + range.end.row = tmp.end.row; + range.end.column = tmp.end.column; + } + } + sel.mergeOverlappingRanges(); + + var words = []; + for (var i = all.length; i--; ) { + var range = all[i]; + words.unshift(session.getTextRange(range)); + } + + if (dir < 0) + words.unshift(words.pop()); + else + words.push(words.shift()); + + for (var i = all.length; i--; ) { + var range = all[i]; + var tmp = range.clone(); + session.replace(range, words[i]); + range.start.row = tmp.start.row; + range.start.column = tmp.start.column; + } + }; + this.selectMore = function(dir, skip, stopAtFirst) { + var session = this.session; + var sel = session.multiSelect; + + var range = sel.toOrientedRange(); + if (range.isEmpty()) { + range = session.getWordRange(range.start.row, range.start.column); + range.cursor = dir == -1 ? range.start : range.end; + this.multiSelect.addRange(range); + if (stopAtFirst) + return; + } + var needle = session.getTextRange(range); + + var newRange = find(session, needle, dir); + if (newRange) { + newRange.cursor = dir == -1 ? newRange.start : newRange.end; + this.$blockScrolling += 1; + this.session.unfold(newRange); + this.multiSelect.addRange(newRange); + this.$blockScrolling -= 1; + this.renderer.scrollCursorIntoView(null, 0.5); + } + if (skip) + this.multiSelect.substractPoint(range.cursor); + }; + this.alignCursors = function() { + var session = this.session; + var sel = session.multiSelect; + var ranges = sel.ranges; + var row = -1; + var sameRowRanges = ranges.filter(function(r) { + if (r.cursor.row == row) + return true; + row = r.cursor.row; + }); + + if (!ranges.length || sameRowRanges.length == ranges.length - 1) { + var range = this.selection.getRange(); + var fr = range.start.row, lr = range.end.row; + var guessRange = fr == lr; + if (guessRange) { + var max = this.session.getLength(); + var line; + do { + line = this.session.getLine(lr); + } while (/[=:]/.test(line) && ++lr < max); + do { + line = this.session.getLine(fr); + } while (/[=:]/.test(line) && --fr > 0); + + if (fr < 0) fr = 0; + if (lr >= max) lr = max - 1; + } + var lines = this.session.removeFullLines(fr, lr); + lines = this.$reAlignText(lines, guessRange); + this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n"); + if (!guessRange) { + range.start.column = 0; + range.end.column = lines[lines.length - 1].length; + } + this.selection.setRange(range); + } else { + sameRowRanges.forEach(function(r) { + sel.substractPoint(r.cursor); + }); + + var maxCol = 0; + var minSpace = Infinity; + var spaceOffsets = ranges.map(function(r) { + var p = r.cursor; + var line = session.getLine(p.row); + var spaceOffset = line.substr(p.column).search(/\S/g); + if (spaceOffset == -1) + spaceOffset = 0; + + if (p.column > maxCol) + maxCol = p.column; + if (spaceOffset < minSpace) + minSpace = spaceOffset; + return spaceOffset; + }); + ranges.forEach(function(r, i) { + var p = r.cursor; + var l = maxCol - p.column; + var d = spaceOffsets[i] - minSpace; + if (l > d) + session.insert(p, lang.stringRepeat(" ", l - d)); + else + session.remove(new Range(p.row, p.column, p.row, p.column - l + d)); + + r.start.column = r.end.column = maxCol; + r.start.row = r.end.row = p.row; + r.cursor = r.end; + }); + sel.fromOrientedRange(ranges[0]); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + } + }; + + this.$reAlignText = function(lines, forceLeft) { + var isLeftAligned = true, isRightAligned = true; + var startW, textW, endW; + + return lines.map(function(line) { + var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/); + if (!m) + return [line]; + + if (startW == null) { + startW = m[1].length; + textW = m[2].length; + endW = m[3].length; + return m; + } + + if (startW + textW + endW != m[1].length + m[2].length + m[3].length) + isRightAligned = false; + if (startW != m[1].length) + isLeftAligned = false; + + if (startW > m[1].length) + startW = m[1].length; + if (textW < m[2].length) + textW = m[2].length; + if (endW > m[3].length) + endW = m[3].length; + + return m; + }).map(forceLeft ? alignLeft : + isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign); + + function spaces(n) { + return lang.stringRepeat(" ", n); + } + + function alignLeft(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(textW - m[2].length + endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function alignRight(m) { + return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2] + + spaces(endW, " ") + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function unAlign(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + }; +}).call(Editor.prototype); + + +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} +exports.onSessionChange = function(e) { + var session = e.session; + if (session && !session.multiSelect) { + session.$selectionMarkers = []; + session.selection.$initRangeList(); + session.multiSelect = session.selection; + } + this.multiSelect = session && session.multiSelect; + + var oldSession = e.oldSession; + if (oldSession) { + oldSession.multiSelect.off("addRange", this.$onAddRange); + oldSession.multiSelect.off("removeRange", this.$onRemoveRange); + oldSession.multiSelect.off("multiSelect", this.$onMultiSelect); + oldSession.multiSelect.off("singleSelect", this.$onSingleSelect); + oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange); + oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange); + } + + if (session) { + session.multiSelect.on("addRange", this.$onAddRange); + session.multiSelect.on("removeRange", this.$onRemoveRange); + session.multiSelect.on("multiSelect", this.$onMultiSelect); + session.multiSelect.on("singleSelect", this.$onSingleSelect); + session.multiSelect.lead.on("change", this.$checkMultiselectChange); + session.multiSelect.anchor.on("change", this.$checkMultiselectChange); + } + + if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) { + if (session.selection.inMultiSelectMode) + this.$onMultiSelect(); + else + this.$onSingleSelect(); + } +}; +function MultiSelect(editor) { + if (editor.$multiselectOnSessionChange) + return; + editor.$onAddRange = editor.$onAddRange.bind(editor); + editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); + editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); + editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); + editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor); + editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor); + + editor.$multiselectOnSessionChange(editor); + editor.on("changeSession", editor.$multiselectOnSessionChange); + + editor.on("mousedown", onMouseDown); + editor.commands.addCommands(commands.defaultCommands); + + addAltCursorListeners(editor); +} + +function addAltCursorListeners(editor){ + var el = editor.textInput.getElement(); + var altCursor = false; + event.addListener(el, "keydown", function(e) { + var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey); + if (editor.$blockSelectEnabled && altDown) { + if (!altCursor) { + editor.renderer.setMouseCursor("crosshair"); + altCursor = true; + } + } else if (altCursor) { + reset(); + } + }); + + event.addListener(el, "keyup", reset); + event.addListener(el, "blur", reset); + function reset(e) { + if (altCursor) { + editor.renderer.setMouseCursor(""); + altCursor = false; + } + } +} + +exports.MultiSelect = MultiSelect; + + +acequire("./config").defineOptions(Editor.prototype, "editor", { + enableMultiselect: { + set: function(val) { + MultiSelect(this); + if (val) { + this.on("changeSession", this.$multiselectOnSessionChange); + this.on("mousedown", onMouseDown); + } else { + this.off("changeSession", this.$multiselectOnSessionChange); + this.off("mousedown", onMouseDown); + } + }, + value: true + }, + enableBlockSelect: { + set: function(val) { + this.$blockSelectEnabled = val; + }, + value: true + } +}); + + + +}); + +ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; + +(function() { + + this.foldingStartMarker = null; + this.foldingStopMarker = null; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + if (this.foldingStartMarker.test(line)) + return "start"; + if (foldStyle == "markbeginend" + && this.foldingStopMarker + && this.foldingStopMarker.test(line)) + return "end"; + return ""; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + return null; + }; + + this.indentationBlock = function(session, row, column) { + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1) + return; + + var startColumn = column || line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + var level = session.getLine(row).search(re); + + if (level == -1) + continue; + + if (level <= startLevel) + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + + this.openingBracketBlock = function(session, bracket, row, column, typeRe) { + var start = {row: row, column: column + 1}; + var end = session.$findClosingBracket(bracket, start, typeRe); + if (!end) + return; + + var fw = session.foldWidgets[end.row]; + if (fw == null) + fw = session.getFoldWidget(end.row); + + if (fw == "start" && end.row > start.row) { + end.row --; + end.column = session.getLine(end.row).length; + } + return Range.fromPoints(start, end); + }; + + this.closingBracketBlock = function(session, bracket, row, column, typeRe) { + var end = {row: row, column: column}; + var start = session.$findOpeningBracket(bracket, end); + + if (!start) + return; + + start.column++; + end.column--; + + return Range.fromPoints(start, end); + }; +}).call(FoldMode.prototype); + +}); + +ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +exports.isDark = false; +exports.cssClass = "ace-tm"; +exports.cssText = ".ace-tm .ace_gutter {\ +background: #f0f0f0;\ +color: #333;\ +}\ +.ace-tm .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-tm .ace_fold {\ +background-color: #6B72E6;\ +}\ +.ace-tm {\ +background-color: #FFFFFF;\ +color: black;\ +}\ +.ace-tm .ace_cursor {\ +color: black;\ +}\ +.ace-tm .ace_invisible {\ +color: rgb(191, 191, 191);\ +}\ +.ace-tm .ace_storage,\ +.ace-tm .ace_keyword {\ +color: blue;\ +}\ +.ace-tm .ace_constant {\ +color: rgb(197, 6, 11);\ +}\ +.ace-tm .ace_constant.ace_buildin {\ +color: rgb(88, 72, 246);\ +}\ +.ace-tm .ace_constant.ace_language {\ +color: rgb(88, 92, 246);\ +}\ +.ace-tm .ace_constant.ace_library {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_invalid {\ +background-color: rgba(255, 0, 0, 0.1);\ +color: red;\ +}\ +.ace-tm .ace_support.ace_function {\ +color: rgb(60, 76, 114);\ +}\ +.ace-tm .ace_support.ace_constant {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_support.ace_type,\ +.ace-tm .ace_support.ace_class {\ +color: rgb(109, 121, 222);\ +}\ +.ace-tm .ace_keyword.ace_operator {\ +color: rgb(104, 118, 135);\ +}\ +.ace-tm .ace_string {\ +color: rgb(3, 106, 7);\ +}\ +.ace-tm .ace_comment {\ +color: rgb(76, 136, 107);\ +}\ +.ace-tm .ace_comment.ace_doc {\ +color: rgb(0, 102, 255);\ +}\ +.ace-tm .ace_comment.ace_doc.ace_tag {\ +color: rgb(128, 159, 191);\ +}\ +.ace-tm .ace_constant.ace_numeric {\ +color: rgb(0, 0, 205);\ +}\ +.ace-tm .ace_variable {\ +color: rgb(49, 132, 149);\ +}\ +.ace-tm .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-tm .ace_entity.ace_name.ace_function {\ +color: #0000A2;\ +}\ +.ace-tm .ace_heading {\ +color: rgb(12, 7, 255);\ +}\ +.ace-tm .ace_list {\ +color:rgb(185, 6, 144);\ +}\ +.ace-tm .ace_meta.ace_tag {\ +color:rgb(0, 22, 142);\ +}\ +.ace-tm .ace_string.ace_regex {\ +color: rgb(255, 0, 0)\ +}\ +.ace-tm .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-tm.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px white;\ +}\ +.ace-tm .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-tm .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-tm .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-tm .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.07);\ +}\ +.ace-tm .ace_gutter-active-line {\ +background-color : #dcdcdc;\ +}\ +.ace-tm .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-tm .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var Range = acequire("./range").Range; + + +function LineWidgets(session) { + this.session = session; + this.session.widgetManager = this; + this.session.getRowLength = this.getRowLength; + this.session.$getWidgetScreenLength = this.$getWidgetScreenLength; + this.updateOnChange = this.updateOnChange.bind(this); + this.renderWidgets = this.renderWidgets.bind(this); + this.measureWidgets = this.measureWidgets.bind(this); + this.session._changedWidgets = []; + this.$onChangeEditor = this.$onChangeEditor.bind(this); + + this.session.on("change", this.updateOnChange); + this.session.on("changeFold", this.updateOnFold); + this.session.on("changeEditor", this.$onChangeEditor); +} + +(function() { + this.getRowLength = function(row) { + var h; + if (this.lineWidgets) + h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0; + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + + this.$getWidgetScreenLength = function() { + var screenRows = 0; + this.lineWidgets.forEach(function(w){ + if (w && w.rowCount && !w.hidden) + screenRows += w.rowCount; + }); + return screenRows; + }; + + this.$onChangeEditor = function(e) { + this.attach(e.editor); + }; + + this.attach = function(editor) { + if (editor && editor.widgetManager && editor.widgetManager != this) + editor.widgetManager.detach(); + + if (this.editor == editor) + return; + + this.detach(); + this.editor = editor; + + if (editor) { + editor.widgetManager = this; + editor.renderer.on("beforeRender", this.measureWidgets); + editor.renderer.on("afterRender", this.renderWidgets); + } + }; + this.detach = function(e) { + var editor = this.editor; + if (!editor) + return; + + this.editor = null; + editor.widgetManager = null; + + editor.renderer.off("beforeRender", this.measureWidgets); + editor.renderer.off("afterRender", this.renderWidgets); + var lineWidgets = this.session.lineWidgets; + lineWidgets && lineWidgets.forEach(function(w) { + if (w && w.el && w.el.parentNode) { + w._inDocument = false; + w.el.parentNode.removeChild(w.el); + } + }); + }; + + this.updateOnFold = function(e, session) { + var lineWidgets = session.lineWidgets; + if (!lineWidgets || !e.action) + return; + var fold = e.data; + var start = fold.start.row; + var end = fold.end.row; + var hide = e.action == "add"; + for (var i = start + 1; i < end; i++) { + if (lineWidgets[i]) + lineWidgets[i].hidden = hide; + } + if (lineWidgets[end]) { + if (hide) { + if (!lineWidgets[start]) + lineWidgets[start] = lineWidgets[end]; + else + lineWidgets[end].hidden = hide; + } else { + if (lineWidgets[start] == lineWidgets[end]) + lineWidgets[start] = undefined; + lineWidgets[end].hidden = hide; + } + } + }; + + this.updateOnChange = function(delta) { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + } else if (delta.action == 'remove') { + var removed = lineWidgets.splice(startRow + 1, len); + removed.forEach(function(w) { + w && this.removeLineWidget(w); + }, this); + this.$updateRows(); + } else { + var args = new Array(len); + args.unshift(startRow, 0); + lineWidgets.splice.apply(lineWidgets, args); + this.$updateRows(); + } + }; + + this.$updateRows = function() { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + var noWidgets = true; + lineWidgets.forEach(function(w, i) { + if (w) { + noWidgets = false; + w.row = i; + while (w.$oldWidget) { + w.$oldWidget.row = i; + w = w.$oldWidget; + } + } + }); + if (noWidgets) + this.session.lineWidgets = null; + }; + + this.addLineWidget = function(w) { + if (!this.session.lineWidgets) + this.session.lineWidgets = new Array(this.session.getLength()); + + var old = this.session.lineWidgets[w.row]; + if (old) { + w.$oldWidget = old; + if (old.el && old.el.parentNode) { + old.el.parentNode.removeChild(old.el); + old._inDocument = false; + } + } + + this.session.lineWidgets[w.row] = w; + + w.session = this.session; + + var renderer = this.editor.renderer; + if (w.html && !w.el) { + w.el = dom.createElement("div"); + w.el.innerHTML = w.html; + } + if (w.el) { + dom.addCssClass(w.el, "ace_lineWidgetContainer"); + w.el.style.position = "absolute"; + w.el.style.zIndex = 5; + renderer.container.appendChild(w.el); + w._inDocument = true; + } + + if (!w.coverGutter) { + w.el.style.zIndex = 3; + } + if (w.pixelHeight == null) { + w.pixelHeight = w.el.offsetHeight; + } + if (w.rowCount == null) { + w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight; + } + + var fold = this.session.getFoldAt(w.row, 0); + w.$fold = fold; + if (fold) { + var lineWidgets = this.session.lineWidgets; + if (w.row == fold.end.row && !lineWidgets[fold.start.row]) + lineWidgets[fold.start.row] = w; + else + w.hidden = true; + } + + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + + this.$updateRows(); + this.renderWidgets(null, renderer); + this.onWidgetChanged(w); + return w; + }; + + this.removeLineWidget = function(w) { + w._inDocument = false; + w.session = null; + if (w.el && w.el.parentNode) + w.el.parentNode.removeChild(w.el); + if (w.editor && w.editor.destroy) try { + w.editor.destroy(); + } catch(e){} + if (this.session.lineWidgets) { + var w1 = this.session.lineWidgets[w.row] + if (w1 == w) { + this.session.lineWidgets[w.row] = w.$oldWidget; + if (w.$oldWidget) + this.onWidgetChanged(w.$oldWidget); + } else { + while (w1) { + if (w1.$oldWidget == w) { + w1.$oldWidget = w.$oldWidget; + break; + } + w1 = w1.$oldWidget; + } + } + } + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + this.$updateRows(); + }; + + this.getWidgetsAtRow = function(row) { + var lineWidgets = this.session.lineWidgets; + var w = lineWidgets && lineWidgets[row]; + var list = []; + while (w) { + list.push(w); + w = w.$oldWidget; + } + return list; + }; + + this.onWidgetChanged = function(w) { + this.session._changedWidgets.push(w); + this.editor && this.editor.renderer.updateFull(); + }; + + this.measureWidgets = function(e, renderer) { + var changedWidgets = this.session._changedWidgets; + var config = renderer.layerConfig; + + if (!changedWidgets || !changedWidgets.length) return; + var min = Infinity; + for (var i = 0; i < changedWidgets.length; i++) { + var w = changedWidgets[i]; + if (!w || !w.el) continue; + if (w.session != this.session) continue; + if (!w._inDocument) { + if (this.session.lineWidgets[w.row] != w) + continue; + w._inDocument = true; + renderer.container.appendChild(w.el); + } + + w.h = w.el.offsetHeight; + + if (!w.fixedWidth) { + w.w = w.el.offsetWidth; + w.screenWidth = Math.ceil(w.w / config.characterWidth); + } + + var rowCount = w.h / config.lineHeight; + if (w.coverLine) { + rowCount -= this.session.getRowLineCount(w.row); + if (rowCount < 0) + rowCount = 0; + } + if (w.rowCount != rowCount) { + w.rowCount = rowCount; + if (w.row < min) + min = w.row; + } + } + if (min != Infinity) { + this.session._emit("changeFold", {data:{start:{row: min}}}); + this.session.lineWidgetWidth = null; + } + this.session._changedWidgets = []; + }; + + this.renderWidgets = function(e, renderer) { + var config = renderer.layerConfig; + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) + return; + var first = Math.min(this.firstRow, config.firstRow); + var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length); + + while (first > 0 && !lineWidgets[first]) + first--; + + this.firstRow = config.firstRow; + this.lastRow = config.lastRow; + + renderer.$cursorLayer.config = config; + for (var i = first; i <= last; i++) { + var w = lineWidgets[i]; + if (!w || !w.el) continue; + if (w.hidden) { + w.el.style.top = -100 - (w.pixelHeight || 0) + "px"; + continue; + } + if (!w._inDocument) { + w._inDocument = true; + renderer.container.appendChild(w.el); + } + var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top; + if (!w.coverLine) + top += config.lineHeight * this.session.getRowLineCount(w.row); + w.el.style.top = top - config.offset + "px"; + + var left = w.coverGutter ? 0 : renderer.gutterWidth; + if (!w.fixedWidth) + left -= renderer.scrollLeft; + w.el.style.left = left + "px"; + + if (w.fullWidth && w.screenWidth) { + w.el.style.minWidth = config.width + 2 * config.padding + "px"; + } + + if (w.fixedWidth) { + w.el.style.right = renderer.scrollBar.getWidth() + "px"; + } else { + w.el.style.right = ""; + } + } + }; + +}).call(LineWidgets.prototype); + + +exports.LineWidgets = LineWidgets; + +}); + +ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; +var LineWidgets = acequire("../line_widgets").LineWidgets; +var dom = acequire("../lib/dom"); +var Range = acequire("../range").Range; + +function binarySearch(array, needle, comparator) { + var first = 0; + var last = array.length - 1; + + while (first <= last) { + var mid = (first + last) >> 1; + var c = comparator(needle, array[mid]); + if (c > 0) + first = mid + 1; + else if (c < 0) + last = mid - 1; + else + return mid; + } + return -(first + 1); +} + +function findAnnotations(session, row, dir) { + var annotations = session.getAnnotations().sort(Range.comparePoints); + if (!annotations.length) + return; + + var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints); + if (i < 0) + i = -i - 1; + + if (i >= annotations.length) + i = dir > 0 ? 0 : annotations.length - 1; + else if (i === 0 && dir < 0) + i = annotations.length - 1; + + var annotation = annotations[i]; + if (!annotation || !dir) + return; + + if (annotation.row === row) { + do { + annotation = annotations[i += dir]; + } while (annotation && annotation.row === row); + if (!annotation) + return annotations.slice(); + } + + + var matched = []; + row = annotation.row; + do { + matched[dir < 0 ? "unshift" : "push"](annotation); + annotation = annotations[i += dir]; + } while (annotation && annotation.row == row); + return matched.length && matched; +} + +exports.showErrorMarker = function(editor, dir) { + var session = editor.session; + if (!session.widgetManager) { + session.widgetManager = new LineWidgets(session); + session.widgetManager.attach(editor); + } + + var pos = editor.getCursorPosition(); + var row = pos.row; + var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) { + return w.type == "errorMarker"; + })[0]; + if (oldWidget) { + oldWidget.destroy(); + } else { + row -= dir; + } + var annotations = findAnnotations(session, row, dir); + var gutterAnno; + if (annotations) { + var annotation = annotations[0]; + pos.column = (annotation.pos && typeof annotation.column != "number" + ? annotation.pos.sc + : annotation.column) || 0; + pos.row = annotation.row; + gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row]; + } else if (oldWidget) { + return; + } else { + gutterAnno = { + text: ["Looks good!"], + className: "ace_ok" + }; + } + editor.session.unfold(pos.row); + editor.selection.moveToPosition(pos); + + var w = { + row: pos.row, + fixedWidth: true, + coverGutter: true, + el: dom.createElement("div"), + type: "errorMarker" + }; + var el = w.el.appendChild(dom.createElement("div")); + var arrow = w.el.appendChild(dom.createElement("div")); + arrow.className = "error_widget_arrow " + gutterAnno.className; + + var left = editor.renderer.$cursorLayer + .getPixelPosition(pos).left; + arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px"; + + w.el.className = "error_widget_wrapper"; + el.className = "error_widget " + gutterAnno.className; + el.innerHTML = gutterAnno.text.join("
"); + + el.appendChild(dom.createElement("div")); + + var kb = function(_, hashId, keyString) { + if (hashId === 0 && (keyString === "esc" || keyString === "return")) { + w.destroy(); + return {command: "null"}; + } + }; + + w.destroy = function() { + if (editor.$mouseHandler.isMousePressed) + return; + editor.keyBinding.removeKeyboardHandler(kb); + session.widgetManager.removeLineWidget(w); + editor.off("changeSelection", w.destroy); + editor.off("changeSession", w.destroy); + editor.off("mouseup", w.destroy); + editor.off("change", w.destroy); + }; + + editor.keyBinding.addKeyboardHandler(kb); + editor.on("changeSelection", w.destroy); + editor.on("changeSession", w.destroy); + editor.on("mouseup", w.destroy); + editor.on("change", w.destroy); + + editor.session.widgetManager.addLineWidget(w); + + w.el.onmousedown = editor.focus.bind(editor); + + editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight}); +}; + + +dom.importCssString("\ + .error_widget_wrapper {\ + background: inherit;\ + color: inherit;\ + border:none\ + }\ + .error_widget {\ + border-top: solid 2px;\ + border-bottom: solid 2px;\ + margin: 5px 0;\ + padding: 10px 40px;\ + white-space: pre-wrap;\ + }\ + .error_widget.ace_error, .error_widget_arrow.ace_error{\ + border-color: #ff5a5a\ + }\ + .error_widget.ace_warning, .error_widget_arrow.ace_warning{\ + border-color: #F1D817\ + }\ + .error_widget.ace_info, .error_widget_arrow.ace_info{\ + border-color: #5a5a5a\ + }\ + .error_widget.ace_ok, .error_widget_arrow.ace_ok{\ + border-color: #5aaa5a\ + }\ + .error_widget_arrow {\ + position: absolute;\ + border: solid 5px;\ + border-top-color: transparent!important;\ + border-right-color: transparent!important;\ + border-left-color: transparent!important;\ + top: -5px;\ + }\ +", ""); + +}); + +ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); + +var Editor = acequire("./editor").Editor; +var EditSession = acequire("./edit_session").EditSession; +var UndoManager = acequire("./undomanager").UndoManager; +var Renderer = acequire("./virtual_renderer").VirtualRenderer; +acequire("./worker/worker_client"); +acequire("./keyboard/hash_handler"); +acequire("./placeholder"); +acequire("./multi_select"); +acequire("./mode/folding/fold_mode"); +acequire("./theme/textmate"); +acequire("./ext/error_marker"); + +exports.config = acequire("./config"); +exports.acequire = acequire; + +if (typeof define === "function") + exports.define = define; +exports.edit = function(el) { + if (typeof el == "string") { + var _id = el; + el = document.getElementById(_id); + if (!el) + throw new Error("ace.edit can't find div #" + _id); + } + + if (el && el.env && el.env.editor instanceof Editor) + return el.env.editor; + + var value = ""; + if (el && /input|textarea/i.test(el.tagName)) { + var oldNode = el; + value = oldNode.value; + el = dom.createElement("pre"); + oldNode.parentNode.replaceChild(el, oldNode); + } else if (el) { + value = dom.getInnerText(el); + el.innerHTML = ""; + } + + var doc = exports.createEditSession(value); + + var editor = new Editor(new Renderer(el)); + editor.setSession(doc); + + var env = { + document: doc, + editor: editor, + onResize: editor.resize.bind(editor, null) + }; + if (oldNode) env.textarea = oldNode; + event.addListener(window, "resize", env.onResize); + editor.on("destroy", function() { + event.removeListener(window, "resize", env.onResize); + env.editor.container.env = null; // prevent memory leak on old ie + }); + editor.container.env = editor.env = env; + return editor; +}; +exports.createEditSession = function(text, mode) { + var doc = new EditSession(text, mode); + doc.setUndoManager(new UndoManager()); + return doc; +} +exports.EditSession = EditSession; +exports.UndoManager = UndoManager; +exports.version = "1.2.6"; +}); + (function() { + ace.acequire(["ace/ace"], function(a) { + if (a) { + a.config.init(true); + a.define = ace.define; + } + if (!window.ace) + window.ace = a; + for (var key in a) if (a.hasOwnProperty(key)) + window.ace[key] = a[key]; + }); + })(); + +module.exports = window.ace.acequire("ace/ace"); +},{"w3c-blob":995}],206:[function(require,module,exports){ +ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; +var Search = acequire("./search").Search; +var EditSession = acequire("./edit_session").EditSession; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; +function Occur() {} + +oop.inherits(Occur, Search); + +(function() { + this.enter = function(editor, options) { + if (!options.needle) return false; + var pos = editor.getCursorPosition(); + this.displayOccurContent(editor, options); + var translatedPos = this.originalToOccurPosition(editor.session, pos); + editor.moveCursorToPosition(translatedPos); + return true; + } + this.exit = function(editor, options) { + var pos = options.translatePosition && editor.getCursorPosition(); + var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos); + this.displayOriginalContent(editor); + if (translatedPos) + editor.moveCursorToPosition(translatedPos); + return true; + } + + this.highlight = function(sess, regexp) { + var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker( + new SearchHighlight(null, "ace_occur-highlight", "text")); + hl.setRegexp(regexp); + sess._emit("changeBackMarker"); // force highlight layer redraw + } + + this.displayOccurContent = function(editor, options) { + this.$originalSession = editor.session; + var found = this.matchingLines(editor.session, options); + var lines = found.map(function(foundLine) { return foundLine.content; }); + var occurSession = new EditSession(lines.join('\n')); + occurSession.$occur = this; + occurSession.$occurMatchingLines = found; + editor.setSession(occurSession); + this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart; + occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; + this.highlight(occurSession, options.re); + occurSession._emit('changeBackMarker'); + } + + this.displayOriginalContent = function(editor) { + editor.setSession(this.$originalSession); + this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; + } + this.originalToOccurPosition = function(session, pos) { + var lines = session.$occurMatchingLines; + var nullPos = {row: 0, column: 0}; + if (!lines) return nullPos; + for (var i = 0; i < lines.length; i++) { + if (lines[i].row === pos.row) + return {row: i, column: pos.column}; + } + return nullPos; + } + this.occurToOriginalPosition = function(session, pos) { + var lines = session.$occurMatchingLines; + if (!lines || !lines[pos.row]) + return pos; + return {row: lines[pos.row].row, column: pos.column}; + } + + this.matchingLines = function(session, options) { + options = oop.mixin({}, options); + if (!session || !options.needle) return []; + var search = new Search(); + search.set(options); + return search.findAll(session).reduce(function(lines, range) { + var row = range.start.row; + var last = lines[lines.length-1]; + return last && last.row === row ? + lines : + lines.concat({row: row, content: session.getLine(row)}); + }, []); + } + +}).call(Occur.prototype); + +var dom = acequire('./lib/dom'); +dom.importCssString(".ace_occur-highlight {\n\ + border-radius: 4px;\n\ + background-color: rgba(87, 255, 8, 0.25);\n\ + position: absolute;\n\ + z-index: 4;\n\ + -moz-box-sizing: border-box;\n\ + -webkit-box-sizing: border-box;\n\ + box-sizing: border-box;\n\ + box-shadow: 0 0 4px rgb(91, 255, 50);\n\ +}\n\ +.ace_dark .ace_occur-highlight {\n\ + background-color: rgb(80, 140, 85);\n\ + box-shadow: 0 0 4px rgb(60, 120, 70);\n\ +}\n", "incremental-occur-highlighting"); + +exports.Occur = Occur; + +}); + +ace.define("ace/commands/occur_commands",["require","exports","module","ace/config","ace/occur","ace/keyboard/hash_handler","ace/lib/oop"], function(acequire, exports, module) { + +var config = acequire("../config"), + Occur = acequire("../occur").Occur; +var occurStartCommand = { + name: "occur", + exec: function(editor, options) { + var alreadyInOccur = !!editor.session.$occur; + var occurSessionActive = new Occur().enter(editor, options); + if (occurSessionActive && !alreadyInOccur) + OccurKeyboardHandler.installIn(editor); + }, + readOnly: true +}; + +var occurCommands = [{ + name: "occurexit", + bindKey: 'esc|Ctrl-G', + exec: function(editor) { + var occur = editor.session.$occur; + if (!occur) return; + occur.exit(editor, {}); + if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); + }, + readOnly: true +}, { + name: "occuraccept", + bindKey: 'enter', + exec: function(editor) { + var occur = editor.session.$occur; + if (!occur) return; + occur.exit(editor, {translatePosition: true}); + if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); + }, + readOnly: true +}]; + +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +var oop = acequire("../lib/oop"); + + +function OccurKeyboardHandler() {} + +oop.inherits(OccurKeyboardHandler, HashHandler); + +(function() { + + this.isOccurHandler = true; + + this.attach = function(editor) { + HashHandler.call(this, occurCommands, editor.commands.platform); + this.$editor = editor; + } + + var handleKeyboard$super = this.handleKeyboard; + this.handleKeyboard = function(data, hashId, key, keyCode) { + var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); + return (cmd && cmd.command) ? cmd : undefined; + } + +}).call(OccurKeyboardHandler.prototype); + +OccurKeyboardHandler.installIn = function(editor) { + var handler = new this(); + editor.keyBinding.addKeyboardHandler(handler); + editor.commands.addCommands(occurCommands); +} + +OccurKeyboardHandler.uninstallFrom = function(editor) { + editor.commands.removeCommands(occurCommands); + var handler = editor.getKeyboardHandler(); + if (handler.isOccurHandler) + editor.keyBinding.removeKeyboardHandler(handler); +} + +exports.occurStartCommand = occurStartCommand; + +}); + +ace.define("ace/commands/incremental_search_commands",["require","exports","module","ace/config","ace/lib/oop","ace/keyboard/hash_handler","ace/commands/occur_commands"], function(acequire, exports, module) { + +var config = acequire("../config"); +var oop = acequire("../lib/oop"); +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +var occurStartCommand = acequire("./occur_commands").occurStartCommand; +exports.iSearchStartCommands = [{ + name: "iSearch", + bindKey: {win: "Ctrl-F", mac: "Command-F"}, + exec: function(editor, options) { + config.loadModule(["core", "ace/incremental_search"], function(e) { + var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch(); + iSearch.activate(editor, options.backwards); + if (options.jumpToFirstMatch) iSearch.next(options); + }); + }, + readOnly: true +}, { + name: "iSearchBackwards", + exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); }, + readOnly: true +}, { + name: "iSearchAndGo", + bindKey: {win: "Ctrl-K", mac: "Command-G"}, + exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); }, + readOnly: true +}, { + name: "iSearchBackwardsAndGo", + bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"}, + exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); }, + readOnly: true +}]; +exports.iSearchCommands = [{ + name: "restartSearch", + bindKey: {win: "Ctrl-F", mac: "Command-F"}, + exec: function(iSearch) { + iSearch.cancelSearch(true); + } +}, { + name: "searchForward", + bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"}, + exec: function(iSearch, options) { + options.useCurrentOrPrevSearch = true; + iSearch.next(options); + } +}, { + name: "searchBackward", + bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"}, + exec: function(iSearch, options) { + options.useCurrentOrPrevSearch = true; + options.backwards = true; + iSearch.next(options); + } +}, { + name: "extendSearchTerm", + exec: function(iSearch, string) { + iSearch.addString(string); + } +}, { + name: "extendSearchTermSpace", + bindKey: "space", + exec: function(iSearch) { iSearch.addString(' '); } +}, { + name: "shrinkSearchTerm", + bindKey: "backspace", + exec: function(iSearch) { + iSearch.removeChar(); + } +}, { + name: 'confirmSearch', + bindKey: 'return', + exec: function(iSearch) { iSearch.deactivate(); } +}, { + name: 'cancelSearch', + bindKey: 'esc|Ctrl-G', + exec: function(iSearch) { iSearch.deactivate(true); } +}, { + name: 'occurisearch', + bindKey: 'Ctrl-O', + exec: function(iSearch) { + var options = oop.mixin({}, iSearch.$options); + iSearch.deactivate(); + occurStartCommand.exec(iSearch.$editor, options); + } +}, { + name: "yankNextWord", + bindKey: "Ctrl-w", + exec: function(iSearch) { + var ed = iSearch.$editor, + range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }), + string = ed.session.getTextRange(range); + iSearch.addString(string); + } +}, { + name: "yankNextChar", + bindKey: "Ctrl-Alt-y", + exec: function(iSearch) { + var ed = iSearch.$editor, + range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }), + string = ed.session.getTextRange(range); + iSearch.addString(string); + } +}, { + name: 'recenterTopBottom', + bindKey: 'Ctrl-l', + exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); } +}, { + name: 'selectAllMatches', + bindKey: 'Ctrl-space', + exec: function(iSearch) { + var ed = iSearch.$editor, + hl = ed.session.$isearchHighlight, + ranges = hl && hl.cache ? hl.cache + .reduce(function(ranges, ea) { + return ranges.concat(ea ? ea : []); }, []) : []; + iSearch.deactivate(false); + ranges.forEach(ed.selection.addRange.bind(ed.selection)); + } +}, { + name: 'searchAsRegExp', + bindKey: 'Alt-r', + exec: function(iSearch) { + iSearch.convertNeedleToRegExp(); + } +}].map(function(cmd) { + cmd.readOnly = true; + cmd.isIncrementalSearchCommand = true; + cmd.scrollIntoView = "animate-cursor"; + return cmd; +}); + +function IncrementalSearchKeyboardHandler(iSearch) { + this.$iSearch = iSearch; +} + +oop.inherits(IncrementalSearchKeyboardHandler, HashHandler); + +(function() { + + this.attach = function(editor) { + var iSearch = this.$iSearch; + HashHandler.call(this, exports.iSearchCommands, editor.commands.platform); + this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) { + if (!e.command.isIncrementalSearchCommand) + return iSearch.deactivate(); + e.stopPropagation(); + e.preventDefault(); + var scrollTop = editor.session.getScrollTop(); + var result = e.command.exec(iSearch, e.args || {}); + editor.renderer.scrollCursorIntoView(null, 0.5); + editor.renderer.animateScrolling(scrollTop); + return result; + }); + }; + + this.detach = function(editor) { + if (!this.$commandExecHandler) return; + editor.commands.removeEventListener('exec', this.$commandExecHandler); + delete this.$commandExecHandler; + }; + + var handleKeyboard$super = this.handleKeyboard; + this.handleKeyboard = function(data, hashId, key, keyCode) { + if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v') + || (hashId === 1/*ctrl*/ && key === 'y')) return null; + var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); + if (cmd.command) { return cmd; } + if (hashId == -1) { + var extendCmd = this.commands.extendSearchTerm; + if (extendCmd) { return {command: extendCmd, args: key}; } + } + return false; + }; + +}).call(IncrementalSearchKeyboardHandler.prototype); + + +exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler; + +}); + +ace.define("ace/incremental_search",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/search_highlight","ace/commands/incremental_search_commands","ace/lib/dom","ace/commands/command_manager","ace/editor","ace/config"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; +var Search = acequire("./search").Search; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; +var iSearchCommandModule = acequire("./commands/incremental_search_commands"); +var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler; +function IncrementalSearch() { + this.$options = {wrap: false, skipCurrent: false}; + this.$keyboardHandler = new ISearchKbd(this); +} + +oop.inherits(IncrementalSearch, Search); + +function isRegExp(obj) { + return obj instanceof RegExp; +} + +function regExpToObject(re) { + var string = String(re), + start = string.indexOf('/'), + flagStart = string.lastIndexOf('/'); + return { + expression: string.slice(start+1, flagStart), + flags: string.slice(flagStart+1) + } +} + +function stringToRegExp(string, flags) { + try { + return new RegExp(string, flags); + } catch (e) { return string; } +} + +function objectToRegExp(obj) { + return stringToRegExp(obj.expression, obj.flags); +} + +(function() { + + this.activate = function(ed, backwards) { + this.$editor = ed; + this.$startPos = this.$currentPos = ed.getCursorPosition(); + this.$options.needle = ''; + this.$options.backwards = backwards; + ed.keyBinding.addKeyboardHandler(this.$keyboardHandler); + this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this); + this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this)); + this.selectionFix(ed); + this.statusMessage(true); + }; + + this.deactivate = function(reset) { + this.cancelSearch(reset); + var ed = this.$editor; + ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler); + if (this.$mousedownHandler) { + ed.removeEventListener('mousedown', this.$mousedownHandler); + delete this.$mousedownHandler; + } + ed.onPaste = this.$originalEditorOnPaste; + this.message(''); + }; + + this.selectionFix = function(editor) { + if (editor.selection.isEmpty() && !editor.session.$emacsMark) { + editor.clearSelection(); + } + }; + + this.highlight = function(regexp) { + var sess = this.$editor.session, + hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker( + new SearchHighlight(null, "ace_isearch-result", "text")); + hl.setRegexp(regexp); + sess._emit("changeBackMarker"); // force highlight layer redraw + }; + + this.cancelSearch = function(reset) { + var e = this.$editor; + this.$prevNeedle = this.$options.needle; + this.$options.needle = ''; + if (reset) { + e.moveCursorToPosition(this.$startPos); + this.$currentPos = this.$startPos; + } else { + e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false); + } + this.highlight(null); + return Range.fromPoints(this.$currentPos, this.$currentPos); + }; + + this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) { + if (!this.$editor) return null; + var options = this.$options; + if (needleUpdateFunc) { + options.needle = needleUpdateFunc.call(this, options.needle || '') || ''; + } + if (options.needle.length === 0) { + this.statusMessage(true); + return this.cancelSearch(true); + } + options.start = this.$currentPos; + var session = this.$editor.session, + found = this.find(session), + shouldSelect = this.$editor.emacsMark ? + !!this.$editor.emacsMark() : !this.$editor.selection.isEmpty(); + if (found) { + if (options.backwards) found = Range.fromPoints(found.end, found.start); + this.$editor.selection.setRange(Range.fromPoints(shouldSelect ? this.$startPos : found.end, found.end)); + if (moveToNext) this.$currentPos = found.end; + this.highlight(options.re); + } + + this.statusMessage(found); + + return found; + }; + + this.addString = function(s) { + return this.highlightAndFindWithNeedle(false, function(needle) { + if (!isRegExp(needle)) + return needle + s; + var reObj = regExpToObject(needle); + reObj.expression += s; + return objectToRegExp(reObj); + }); + }; + + this.removeChar = function(c) { + return this.highlightAndFindWithNeedle(false, function(needle) { + if (!isRegExp(needle)) + return needle.substring(0, needle.length-1); + var reObj = regExpToObject(needle); + reObj.expression = reObj.expression.substring(0, reObj.expression.length-1); + return objectToRegExp(reObj); + }); + }; + + this.next = function(options) { + options = options || {}; + this.$options.backwards = !!options.backwards; + this.$currentPos = this.$editor.getCursorPosition(); + return this.highlightAndFindWithNeedle(true, function(needle) { + return options.useCurrentOrPrevSearch && needle.length === 0 ? + this.$prevNeedle || '' : needle; + }); + }; + + this.onMouseDown = function(evt) { + this.deactivate(); + return true; + }; + + this.onPaste = function(text) { + this.addString(text); + }; + + this.convertNeedleToRegExp = function() { + return this.highlightAndFindWithNeedle(false, function(needle) { + return isRegExp(needle) ? needle : stringToRegExp(needle, 'ig'); + }); + }; + + this.convertNeedleToString = function() { + return this.highlightAndFindWithNeedle(false, function(needle) { + return isRegExp(needle) ? regExpToObject(needle).expression : needle; + }); + }; + + this.statusMessage = function(found) { + var options = this.$options, msg = ''; + msg += options.backwards ? 'reverse-' : ''; + msg += 'isearch: ' + options.needle; + msg += found ? '' : ' (not found)'; + this.message(msg); + }; + + this.message = function(msg) { + if (this.$editor.showCommandLine) { + this.$editor.showCommandLine(msg); + this.$editor.focus(); + } else { + console.log(msg); + } + }; + +}).call(IncrementalSearch.prototype); + + +exports.IncrementalSearch = IncrementalSearch; + +var dom = acequire('./lib/dom'); +dom.importCssString && dom.importCssString("\ +.ace_marker-layer .ace_isearch-result {\ + position: absolute;\ + z-index: 6;\ + -moz-box-sizing: border-box;\ + -webkit-box-sizing: border-box;\ + box-sizing: border-box;\ +}\ +div.ace_isearch-result {\ + border-radius: 4px;\ + background-color: rgba(255, 200, 0, 0.5);\ + box-shadow: 0 0 4px rgb(255, 200, 0);\ +}\ +.ace_dark div.ace_isearch-result {\ + background-color: rgb(100, 110, 160);\ + box-shadow: 0 0 4px rgb(80, 90, 140);\ +}", "incremental-search-highlighting"); +var commands = acequire("./commands/command_manager"); +(function() { + this.setupIncrementalSearch = function(editor, val) { + if (this.usesIncrementalSearch == val) return; + this.usesIncrementalSearch = val; + var iSearchCommands = iSearchCommandModule.iSearchStartCommands; + var method = val ? 'addCommands' : 'removeCommands'; + this[method](iSearchCommands); + }; +}).call(commands.CommandManager.prototype); +var Editor = acequire("./editor").Editor; +acequire("./config").defineOptions(Editor.prototype, "editor", { + useIncrementalSearch: { + set: function(val) { + this.keyBinding.$handlers.forEach(function(handler) { + if (handler.setupIncrementalSearch) { + handler.setupIncrementalSearch(this, val); + } + }); + this._emit('incrementalSearchSettingChanged', {isEnabled: val}); + } + } +}); + +}); + +ace.define("ace/keyboard/emacs",["require","exports","module","ace/lib/dom","ace/incremental_search","ace/commands/incremental_search_commands","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +acequire("../incremental_search"); +var iSearchCommandModule = acequire("../commands/incremental_search_commands"); + + +var screenToTextBlockCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var col = Math.floor( + (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth + ); + var row = Math.floor( + (y + this.scrollTop - canvasPos.top) / this.lineHeight + ); + + return this.session.screenToDocumentPosition(row, col); +}; + +var HashHandler = acequire("./hash_handler").HashHandler; +exports.handler = new HashHandler(); + +exports.handler.isEmacs = true; +exports.handler.$id = "ace/keyboard/emacs"; + +var initialized = false; +var $formerLongWords; +var $formerLineStart; + +exports.handler.attach = function(editor) { + if (!initialized) { + initialized = true; + dom.importCssString('\ + .emacs-mode .ace_cursor{\ + border: 1px rgba(50,250,50,0.8) solid!important;\ + -moz-box-sizing: border-box!important;\ + -webkit-box-sizing: border-box!important;\ + box-sizing: border-box!important;\ + background-color: rgba(0,250,0,0.9);\ + opacity: 0.5;\ + }\ + .emacs-mode .ace_hidden-cursors .ace_cursor{\ + opacity: 1;\ + background-color: transparent;\ + }\ + .emacs-mode .ace_overwrite-cursors .ace_cursor {\ + opacity: 1;\ + background-color: transparent;\ + border-width: 0 0 2px 2px !important;\ + }\ + .emacs-mode .ace_text-layer {\ + z-index: 4\ + }\ + .emacs-mode .ace_cursor-layer {\ + z-index: 2\ + }', 'emacsMode' + ); + } + $formerLongWords = editor.session.$selectLongWords; + editor.session.$selectLongWords = true; + $formerLineStart = editor.session.$useEmacsStyleLineStart; + editor.session.$useEmacsStyleLineStart = true; + + editor.session.$emacsMark = null; // the active mark + editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || []; + + editor.emacsMark = function() { + return this.session.$emacsMark; + }; + + editor.setEmacsMark = function(p) { + this.session.$emacsMark = p; + }; + + editor.pushEmacsMark = function(p, activate) { + var prevMark = this.session.$emacsMark; + if (prevMark) + this.session.$emacsMarkRing.push(prevMark); + if (!p || activate) this.setEmacsMark(p); + else this.session.$emacsMarkRing.push(p); + }; + + editor.popEmacsMark = function() { + var mark = this.emacsMark(); + if (mark) { this.setEmacsMark(null); return mark; } + return this.session.$emacsMarkRing.pop(); + }; + + editor.getLastEmacsMark = function(p) { + return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0]; + }; + + editor.emacsMarkForSelection = function(replacement) { + var sel = this.selection, + multiRangeLength = this.multiSelect ? + this.multiSelect.getAllRanges().length : 1, + selIndex = sel.index || 0, + markRing = this.session.$emacsMarkRing, + markIndex = markRing.length - (multiRangeLength - selIndex), + lastMark = markRing[markIndex] || sel.anchor; + if (replacement) { + markRing.splice(markIndex, 1, + "row" in replacement && "column" in replacement ? + replacement : undefined); + } + return lastMark; + } + + editor.on("click", $resetMarkMode); + editor.on("changeSession", $kbSessionChange); + editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; + editor.setStyle("emacs-mode"); + editor.commands.addCommands(commands); + exports.handler.platform = editor.commands.platform; + editor.$emacsModeHandler = this; + editor.addEventListener('copy', this.onCopy); + editor.addEventListener('paste', this.onPaste); +}; + +exports.handler.detach = function(editor) { + delete editor.renderer.screenToTextCoordinates; + editor.session.$selectLongWords = $formerLongWords; + editor.session.$useEmacsStyleLineStart = $formerLineStart; + editor.removeEventListener("click", $resetMarkMode); + editor.removeEventListener("changeSession", $kbSessionChange); + editor.unsetStyle("emacs-mode"); + editor.commands.removeCommands(commands); + editor.removeEventListener('copy', this.onCopy); + editor.removeEventListener('paste', this.onPaste); + editor.$emacsModeHandler = null; +}; + +var $kbSessionChange = function(e) { + if (e.oldSession) { + e.oldSession.$selectLongWords = $formerLongWords; + e.oldSession.$useEmacsStyleLineStart = $formerLineStart; + } + + $formerLongWords = e.session.$selectLongWords; + e.session.$selectLongWords = true; + $formerLineStart = e.session.$useEmacsStyleLineStart; + e.session.$useEmacsStyleLineStart = true; + + if (!e.session.hasOwnProperty('$emacsMark')) + e.session.$emacsMark = null; + if (!e.session.hasOwnProperty('$emacsMarkRing')) + e.session.$emacsMarkRing = []; +}; + +var $resetMarkMode = function(e) { + e.editor.session.$emacsMark = null; +}; + +var keys = acequire("../lib/keys").KEY_MODS; +var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"}; +var combinations = ["C-S-M-CMD", + "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M", + "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S", + "CMD", "M", "S", "C"]; +combinations.forEach(function(c) { + var hashId = 0; + c.split("-").forEach(function(c) { + hashId = hashId | keys[eMods[c]]; + }); + eMods[hashId] = c.toLowerCase() + "-"; +}); + +exports.handler.onCopy = function(e, editor) { + if (editor.$handlesEmacsOnCopy) return; + editor.$handlesEmacsOnCopy = true; + exports.handler.commands.killRingSave.exec(editor); + editor.$handlesEmacsOnCopy = false; +}; + +exports.handler.onPaste = function(e, editor) { + editor.pushEmacsMark(editor.getCursorPosition()); +}; + +exports.handler.bindKey = function(key, command) { + if (typeof key == "object") + key = key[this.platform]; + if (!key) + return; + + var ckb = this.commandKeyBinding; + key.split("|").forEach(function(keyPart) { + keyPart = keyPart.toLowerCase(); + ckb[keyPart] = command; + var keyParts = keyPart.split(" ").slice(0,-1); + keyParts.reduce(function(keyMapKeys, keyPart, i) { + var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : ''; + return keyMapKeys.concat([prefix + keyPart]); + }, []).forEach(function(keyPart) { + if (!ckb[keyPart]) ckb[keyPart] = "null"; + }); + }, this); +}; + +exports.handler.getStatusText = function(editor, data) { + var str = ""; + if (data.count) + str += data.count; + if (data.keyChain) + str += " " + data.keyChain + return str; +}; + +exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { + if (keyCode === -1) return undefined; + + var editor = data.editor; + editor._signal("changeStatus"); + if (hashId == -1) { + editor.pushEmacsMark(); + if (data.count) { + var str = new Array(data.count + 1).join(key); + data.count = null; + return {command: "insertstring", args: str}; + } + } + + var modifier = eMods[hashId]; + if (modifier == "c-" || data.count) { + var count = parseInt(key[key.length - 1]); + if (typeof count === 'number' && !isNaN(count)) { + data.count = Math.max(data.count, 0) || 0; + data.count = 10 * data.count + count; + return {command: "null"}; + } + } + if (modifier) key = modifier + key; + if (data.keyChain) key = data.keyChain += " " + key; + var command = this.commandKeyBinding[key]; + data.keyChain = command == "null" ? key : ""; + if (!command) return undefined; + if (command === "null") return {command: "null"}; + + if (command === "universalArgument") { + data.count = -4; + return {command: "null"}; + } + var args; + if (typeof command !== "string") { + args = command.args; + if (command.command) command = command.command; + if (command === "goorselect") { + command = editor.emacsMark() ? args[1] : args[0]; + args = null; + } + } + + if (typeof command === "string") { + if (command === "insertstring" || + command === "splitline" || + command === "togglecomment") { + editor.pushEmacsMark(); + } + command = this.commands[command] || editor.commands.commands[command]; + if (!command) return undefined; + } + + if (!command.readOnly && !command.isYank) + data.lastCommand = null; + + if (!command.readOnly && editor.emacsMark()) + editor.setEmacsMark(null) + + if (data.count) { + var count = data.count; + data.count = 0; + if (!command || !command.handlesCount) { + return { + args: args, + command: { + exec: function(editor, args) { + for (var i = 0; i < count; i++) + command.exec(editor, args); + }, + multiSelectAction: command.multiSelectAction + } + }; + } else { + if (!args) args = {}; + if (typeof args === 'object') args.count = count; + } + } + + return {command: command, args: args}; +}; + +exports.emacsKeys = { + "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]}, + "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]}, + "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]}, + "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]}, + "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]}, + "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]}, + "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]}, + "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]}, + "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]}, + "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]}, + "S-Up|S-C-p" : "selectup", + "S-Down|S-C-n" : "selectdown", + "S-Left|S-C-b" : "selectleft", + "S-Right|S-C-f" : "selectright", + "S-C-Left|S-M-b" : "selectwordleft", + "S-C-Right|S-M-f" : "selectwordright", + "S-Home|S-C-a" : "selecttolinestart", + "S-End|S-C-e" : "selecttolineend", + "S-C-Home" : "selecttostart", + "S-C-End" : "selecttoend", + + "C-l" : "recenterTopBottom", + "M-s" : "centerselection", + "M-g": "gotoline", + "C-x C-p": "selectall", + "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, + "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]}, + "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, + "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]}, + "S-C-Down": "selectpagedown", + "S-C-Up": "selectpageup", + + "C-s": "iSearch", + "C-r": "iSearchBackwards", + + "M-C-s": "findnext", + "M-C-r": "findprevious", + "S-M-5": "replace", + "Backspace": "backspace", + "Delete|C-d": "del", + "Return|C-m": {command: "insertstring", args: "\n"}, // "newline" + "C-o": "splitline", + + "M-d|C-Delete": {command: "killWord", args: "right"}, + "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"}, + "C-k": "killLine", + + "C-y|S-Delete": "yank", + "M-y": "yankRotate", + "C-g": "keyboardQuit", + + "C-w|C-S-W": "killRegion", + "M-w": "killRingSave", + "C-Space": "setMark", + "C-x C-x": "exchangePointAndMark", + + "C-t": "transposeletters", + "M-u": "touppercase", // Doesn't work + "M-l": "tolowercase", + "M-/": "autocomplete", // Doesn't work + "C-u": "universalArgument", + + "M-;": "togglecomment", + + "C-/|C-x u|S-C--|C-z": "undo", + "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo? + "C-x r": "selectRectangularRegion", + "M-x": {command: "focusCommandLine", args: "M-x "} +}; + + +exports.handler.bindKeys(exports.emacsKeys); + +exports.handler.addCommands({ + recenterTopBottom: function(editor) { + var renderer = editor.renderer; + var pos = renderer.$cursorLayer.getPixelPosition(); + var h = renderer.$size.scrollerHeight - renderer.lineHeight; + var scrollTop = renderer.scrollTop; + if (Math.abs(pos.top - scrollTop) < 2) { + scrollTop = pos.top - h; + } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) { + scrollTop = pos.top; + } else { + scrollTop = pos.top - h * 0.5; + } + editor.session.setScrollTop(scrollTop); + }, + selectRectangularRegion: function(editor) { + editor.multiSelect.toggleBlockSelection(); + }, + setMark: { + exec: function(editor, args) { + + if (args && args.count) { + if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark); + else moveToMark(); + moveToMark(); + return; + } + + var mark = editor.emacsMark(), + ranges = editor.selection.getAllRanges(), + rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }), + transientMarkModeActive = true, + hasNoSelection = ranges.every(function(range) { return range.isEmpty(); }); + if (transientMarkModeActive && (mark || !hasNoSelection)) { + if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)}); + else editor.clearSelection(); + if (mark) editor.pushEmacsMark(null); + return; + } + + if (!mark) { + rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); }); + editor.setEmacsMark(rangePositions[rangePositions.length-1]); + return; + } + + function moveToMark() { + var mark = editor.popEmacsMark(); + mark && editor.moveCursorToPosition(mark); + } + + }, + readOnly: true, + handlesCount: true + }, + exchangePointAndMark: { + exec: function exchangePointAndMark$exec(editor, args) { + var sel = editor.selection; + if (!args.count && !sel.isEmpty()) { // just invert selection + sel.setSelectionRange(sel.getRange(), !sel.isBackwards()); + return; + } + + if (args.count) { // replace mark and point + var pos = {row: sel.lead.row, column: sel.lead.column}; + sel.clearSelection(); + sel.moveCursorToPosition(editor.emacsMarkForSelection(pos)); + } else { // create selection to last mark + sel.selectToPosition(editor.emacsMarkForSelection()); + } + }, + readOnly: true, + handlesCount: true, + multiSelectAction: "forEach" + }, + killWord: { + exec: function(editor, dir) { + editor.clearSelection(); + if (dir == "left") + editor.selection.selectWordLeft(); + else + editor.selection.selectWordRight(); + + var range = editor.getSelectionRange(); + var text = editor.session.getTextRange(range); + exports.killRing.add(text); + + editor.session.remove(range); + editor.clearSelection(); + }, + multiSelectAction: "forEach" + }, + killLine: function(editor) { + editor.pushEmacsMark(null); + editor.clearSelection(); + var range = editor.getSelectionRange(); + var line = editor.session.getLine(range.start.row); + range.end.column = line.length; + line = line.substr(range.start.column) + + var foldLine = editor.session.getFoldLine(range.start.row); + if (foldLine && range.end.row != foldLine.end.row) { + range.end.row = foldLine.end.row; + line = "x"; + } + if (/^\s*$/.test(line)) { + range.end.row++; + line = editor.session.getLine(range.end.row); + range.end.column = /^\s*$/.test(line) ? line.length : 0; + } + var text = editor.session.getTextRange(range); + if (editor.prevOp.command == this) + exports.killRing.append(text); + else + exports.killRing.add(text); + + editor.session.remove(range); + editor.clearSelection(); + }, + yank: function(editor) { + editor.onPaste(exports.killRing.get() || ''); + editor.keyBinding.$data.lastCommand = "yank"; + }, + yankRotate: function(editor) { + if (editor.keyBinding.$data.lastCommand != "yank") + return; + editor.undo(); + editor.session.$emacsMarkRing.pop(); // also undo recording mark + editor.onPaste(exports.killRing.rotate()); + editor.keyBinding.$data.lastCommand = "yank"; + }, + killRegion: { + exec: function(editor) { + exports.killRing.add(editor.getCopyText()); + editor.commands.byName.cut.exec(editor); + editor.setEmacsMark(null); + }, + readOnly: true, + multiSelectAction: "forEach" + }, + killRingSave: { + exec: function(editor) { + + editor.$handlesEmacsOnCopy = true; + var marks = editor.session.$emacsMarkRing.slice(), + deselectedMarks = []; + exports.killRing.add(editor.getCopyText()); + + setTimeout(function() { + function deselect() { + var sel = editor.selection, range = sel.getRange(), + pos = sel.isBackwards() ? range.end : range.start; + deselectedMarks.push({row: pos.row, column: pos.column}); + sel.clearSelection(); + } + editor.$handlesEmacsOnCopy = false; + if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect}); + else deselect(); + editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse()); + }, 0); + }, + readOnly: true + }, + keyboardQuit: function(editor) { + editor.selection.clearSelection(); + editor.setEmacsMark(null); + editor.keyBinding.$data.count = null; + }, + focusCommandLine: function(editor, arg) { + if (editor.showCommandLine) + editor.showCommandLine(arg); + } +}); + +exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands); + +var commands = exports.handler.commands; +commands.yank.isYank = true; +commands.yankRotate.isYank = true; + +exports.killRing = { + $data: [], + add: function(str) { + str && this.$data.push(str); + if (this.$data.length > 30) + this.$data.shift(); + }, + append: function(str) { + var idx = this.$data.length - 1; + var text = this.$data[idx] || ""; + if (str) text += str; + if (text) this.$data[idx] = text; + }, + get: function(n) { + n = n || 1; + return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n'); + }, + pop: function() { + if (this.$data.length > 1) + this.$data.pop(); + return this.get(); + }, + rotate: function() { + this.$data.unshift(this.$data.pop()); + return this.get(); + } +}; + +}); + +},{}],207:[function(require,module,exports){ +ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(acequire, exports, module) { + 'use strict'; + + function log() { + var d = ""; + function format(p) { + if (typeof p != "object") + return p + ""; + if ("line" in p) { + return p.line + ":" + p.ch; + } + if ("anchor" in p) { + return format(p.anchor) + "->" + format(p.head); + } + if (Array.isArray(p)) + return "[" + p.map(function(x) { + return format(x); + }) + "]"; + return JSON.stringify(p); + } + for (var i = 0; i < arguments.length; i++) { + var p = arguments[i]; + var f = format(p); + d += f + " "; + } + console.log(d); + } + var Range = acequire("../range").Range; + var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + var dom = acequire("../lib/dom"); + var oop = acequire("../lib/oop"); + var KEYS = acequire("../lib/keys"); + var event = acequire("../lib/event"); + var Search = acequire("../search").Search; + var useragent = acequire("../lib/useragent"); + var SearchHighlight = acequire("../search_highlight").SearchHighlight; + var multiSelectCommands = acequire("../commands/multi_select_commands"); + var TextModeTokenRe = acequire("../mode/text").Mode.prototype.tokenRe; + acequire("../multi_select"); + + var CodeMirror = function(ace) { + this.ace = ace; + this.state = {}; + this.marks = {}; + this.$uid = 0; + this.onChange = this.onChange.bind(this); + this.onSelectionChange = this.onSelectionChange.bind(this); + this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this); + this.ace.on('change', this.onChange); + this.ace.on('changeSelection', this.onSelectionChange); + this.ace.on('beforeEndOperation', this.onBeforeEndOperation); + }; + CodeMirror.Pos = function(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + CodeMirror.defineOption = function(name, val, setter) {}; + CodeMirror.commands = { + redo: function(cm) { cm.ace.redo(); }, + undo: function(cm) { cm.ace.undo(); }, + newlineAndIndent: function(cm) { cm.ace.insert("\n"); } + }; + CodeMirror.keyMap = {}; + CodeMirror.addClass = CodeMirror.rmClass = + CodeMirror.e_stop = function() {}; + CodeMirror.keyName = function(e) { + if (e.key) return e.key; + var key = (KEYS[e.keyCode] || ""); + if (key.length == 1) key = key.toUpperCase(); + key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) { + return m.toUpperCase(); + }) + key; + return key; + }; + CodeMirror.keyMap['default'] = function(key) { + return function(cm) { + var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()]; + return cmd && cm.ace.execCommand(cmd) !== false; + }; + }; + CodeMirror.lookupKey = function lookupKey(key, map, handle) { + if (typeof map == "string") + map = CodeMirror.keyMap[map]; + var found = typeof map == "function" ? map(key) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (!Array.isArray(map.fallthrough)) + return lookupKey(key, map.fallthrough, handle); + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle); + if (result) return result; + } + } + }; + + CodeMirror.signal = function(o, name, e) { return o._signal(name, e) }; + CodeMirror.on = event.addListener; + CodeMirror.off = event.removeListener; + CodeMirror.isWordChar = function(ch) { + if (ch < "\x7f") return /^\w$/.test(ch); + TextModeTokenRe.lastIndex = 0; + return TextModeTokenRe.test(ch); + }; + +(function() { + oop.implement(CodeMirror.prototype, EventEmitter); + + this.destroy = function() { + this.ace.off('change', this.onChange); + this.ace.off('changeSelection', this.onSelectionChange); + this.ace.off('beforeEndOperation', this.onBeforeEndOperation); + this.removeOverlay(); + }; + this.virtualSelectionMode = function() { + return this.ace.inVirtualSelectionMode && this.ace.selection.index; + }; + this.onChange = function(delta) { + var change = { text: delta.action[0] == 'i' ? delta.lines : [] }; + var curOp = this.curOp = this.curOp || {}; + if (!curOp.changeHandlers) + curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice(); + if (this.virtualSelectionMode()) return; + if (!curOp.lastChange) { + curOp.lastChange = curOp.change = change; + } else { + curOp.lastChange.next = curOp.lastChange = change; + } + this.$updateMarkers(delta); + }; + this.onSelectionChange = function() { + var curOp = this.curOp = this.curOp || {}; + if (!curOp.cursorActivityHandlers) + curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice(); + this.curOp.cursorActivity = true; + if (this.ace.inMultiSelectMode) { + this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler); + } + }; + this.operation = function(fn, force) { + if (!force && this.curOp || force && this.curOp && this.curOp.force) { + return fn(); + } + if (force || !this.ace.curOp) { + if (this.curOp) + this.onBeforeEndOperation(); + } + if (!this.ace.curOp) { + var prevOp = this.ace.prevOp; + this.ace.startOperation({ + command: { name: "vim", scrollIntoView: "cursor" } + }); + } + var curOp = this.curOp = this.curOp || {}; + this.curOp.force = force; + var result = fn(); + if (this.ace.curOp && this.ace.curOp.command.name == "vim") { + this.ace.endOperation(); + if (!curOp.cursorActivity && !curOp.lastChange && prevOp) + this.ace.prevOp = prevOp; + } + if (force || !this.ace.curOp) { + if (this.curOp) + this.onBeforeEndOperation(); + } + return result; + }; + this.onBeforeEndOperation = function() { + var op = this.curOp; + if (op) { + if (op.change) { this.signal("change", op.change, op); } + if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); } + this.curOp = null; + } + }; + + this.signal = function(eventName, e, handlers) { + var listeners = handlers ? handlers[eventName + "Handlers"] + : (this._eventRegistry || {})[eventName]; + if (!listeners) + return; + listeners = listeners.slice(); + for (var i=0; i 0) { + point.row += rowShift; + point.column += point.row == end.row ? colShift : 0; + continue; + } + if (!isInsert && cmp2 <= 0) { + point.row = start.row; + point.column = start.column; + if (cmp2 === 0) + point.bias = 1; + } + } + }; + var Marker = function(cm, id, row, column) { + this.cm = cm; + this.id = id; + this.row = row; + this.column = column; + cm.marks[this.id] = this; + }; + Marker.prototype.clear = function() { delete this.cm.marks[this.id] }; + Marker.prototype.find = function() { return toCmPos(this) }; + this.setBookmark = function(cursor, options) { + var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch); + if (!options || !options.insertLeft) + bm.$insertRight = true; + this.marks[bm.id] = bm; + return bm; + }; + this.moveH = function(increment, unit) { + if (unit == 'char') { + var sel = this.ace.selection; + sel.clearSelection(); + sel.moveCursorBy(0, increment); + } + }; + this.findPosV = function(start, amount, unit, goalColumn) { + if (unit == 'page') { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + amount = amount * Math.floor(config.height / config.lineHeight); + unit = 'line'; + } + if (unit == 'line') { + var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch); + if (goalColumn != null) + screenPos.column = goalColumn; + screenPos.row += amount; + screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1); + var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column); + return toCmPos(pos); + } else { + debugger; + } + }; + this.charCoords = function(pos, mode) { + if (mode == 'div' || !mode) { + var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); + return {left: sc.column, top: sc.row}; + }if (mode == 'local') { + var renderer = this.ace.renderer; + var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); + var lh = renderer.layerConfig.lineHeight; + var cw = renderer.layerConfig.characterWidth; + var top = lh * sc.row; + return {left: sc.column * cw, top: top, bottom: top + lh}; + } + }; + this.coordsChar = function(pos, mode) { + var renderer = this.ace.renderer; + if (mode == 'local') { + var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight)); + var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth)); + var ch = renderer.session.screenToDocumentPosition(row, col); + return toCmPos(ch); + } else if (mode == 'div') { + throw "not implemented"; + } + }; + this.getSearchCursor = function(query, pos, caseFold) { + var caseSensitive = false; + var isRegexp = false; + if (query instanceof RegExp && !query.global) { + caseSensitive = !query.ignoreCase; + query = query.source; + isRegexp = true; + } + var search = new Search(); + if (pos.ch == undefined) pos.ch = Number.MAX_VALUE; + var acePos = {row: pos.line, column: pos.ch}; + var cm = this; + var last = null; + return { + findNext: function() { return this.find(false) }, + findPrevious: function() {return this.find(true) }, + find: function(back) { + search.setOptions({ + needle: query, + caseSensitive: caseSensitive, + wrap: false, + backwards: back, + regExp: isRegexp, + start: last || acePos + }); + var range = search.find(cm.ace.session); + if (range && range.isEmpty()) { + if (cm.getLine(range.start.row).length == range.start.column) { + search.$options.start = range; + range = search.find(cm.ace.session); + } + } + last = range; + return last; + }, + from: function() { return last && toCmPos(last.start) }, + to: function() { return last && toCmPos(last.end) }, + replace: function(text) { + if (last) { + last.end = cm.ace.session.doc.replace(last, text); + } + } + }; + }; + this.scrollTo = function(x, y) { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + var maxHeight = config.maxHeight; + maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd; + if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight))); + if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width))); + }; + this.scrollInfo = function() { return 0; }; + this.scrollIntoView = function(pos, margin) { + if (pos) { + var renderer = this.ace.renderer; + var viewMargin = { "top": 0, "bottom": margin }; + renderer.scrollCursorIntoView(toAcePos(pos), + (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin); + } + }; + this.getLine = function(row) { return this.ace.session.getLine(row) }; + this.getRange = function(s, e) { + return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch)); + }; + this.replaceRange = function(text, s, e) { + if (!e) e = s; + return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text); + }; + this.replaceSelections = function(p) { + var sel = this.ace.selection; + if (this.ace.inVirtualSelectionMode) { + this.ace.session.replace(sel.getRange(), p[0] || ""); + return; + } + sel.inVirtualSelectionMode = true; + var ranges = sel.rangeList.ranges; + if (!ranges.length) ranges = [this.ace.multiSelect.getRange()]; + for (var i = ranges.length; i--;) + this.ace.session.replace(ranges[i], p[i] || ""); + sel.inVirtualSelectionMode = false; + }; + this.getSelection = function() { + return this.ace.getSelectedText(); + }; + this.getSelections = function() { + return this.listSelections().map(function(x) { + return this.getRange(x.anchor, x.head); + }, this); + }; + this.getInputField = function() { + return this.ace.textInput.getElement(); + }; + this.getWrapperElement = function() { + return this.ace.containter; + }; + var optMap = { + indentWithTabs: "useSoftTabs", + indentUnit: "tabSize", + tabSize: "tabSize", + firstLineNumber: "firstLineNumber", + readOnly: "readOnly" + }; + this.setOption = function(name, val) { + this.state[name] = val; + switch (name) { + case 'indentWithTabs': + name = optMap[name]; + val = !val; + break; + default: + name = optMap[name]; + } + if (name) + this.ace.setOption(name, val); + }; + this.getOption = function(name, val) { + var aceOpt = optMap[name]; + if (aceOpt) + val = this.ace.getOption(aceOpt); + switch (name) { + case 'indentWithTabs': + name = optMap[name]; + return !val; + } + return aceOpt ? val : this.state[name]; + }; + this.toggleOverwrite = function(on) { + this.state.overwrite = on; + return this.ace.setOverwrite(on); + }; + this.addOverlay = function(o) { + if (!this.$searchHighlight || !this.$searchHighlight.session) { + var highlight = new SearchHighlight(null, "ace_highlight-marker", "text"); + var marker = this.ace.session.addDynamicMarker(highlight); + highlight.id = marker.id; + highlight.session = this.ace.session; + highlight.destroy = function(o) { + highlight.session.off("change", highlight.updateOnChange); + highlight.session.off("changeEditor", highlight.destroy); + highlight.session.removeMarker(highlight.id); + highlight.session = null; + }; + highlight.updateOnChange = function(delta) { + var row = delta.start.row; + if (row == delta.end.row) highlight.cache[row] = undefined; + else highlight.cache.splice(row, highlight.cache.length); + }; + highlight.session.on("changeEditor", highlight.destroy); + highlight.session.on("change", highlight.updateOnChange); + } + var re = new RegExp(o.query.source, "gmi"); + this.$searchHighlight = o.highlight = highlight; + this.$searchHighlight.setRegexp(re); + this.ace.renderer.updateBackMarkers(); + }; + this.removeOverlay = function(o) { + if (this.$searchHighlight && this.$searchHighlight.session) { + this.$searchHighlight.destroy(); + } + }; + this.getScrollInfo = function() { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + return { + left: renderer.scrollLeft, + top: renderer.scrollTop, + height: config.maxHeight, + width: config.width, + clientHeight: config.height, + clientWidth: config.width + }; + }; + this.getValue = function() { + return this.ace.getValue(); + }; + this.setValue = function(v) { + return this.ace.setValue(v); + }; + this.getTokenTypeAt = function(pos) { + var token = this.ace.session.getTokenAt(pos.line, pos.ch); + return token && /comment|string/.test(token.type) ? "string" : ""; + }; + this.findMatchingBracket = function(pos) { + var m = this.ace.session.findMatchingBracket(toAcePos(pos)); + return {to: m && toCmPos(m)}; + }; + this.indentLine = function(line, method) { + if (method === true) + this.ace.session.indentRows(line, line, "\t"); + else if (method === false) + this.ace.session.outdentRows(new Range(line, 0, line, 0)); + }; + this.indexFromPos = function(pos) { + return this.ace.session.doc.positionToIndex(toAcePos(pos)); + }; + this.posFromIndex = function(index) { + return toCmPos(this.ace.session.doc.indexToPosition(index)); + }; + this.focus = function(index) { + return this.ace.focus(); + }; + this.blur = function(index) { + return this.ace.blur(); + }; + this.defaultTextHeight = function(index) { + return this.ace.renderer.layerConfig.lineHeight; + }; + this.scanForBracket = function(pos, dir, _, options) { + var re = options.bracketRegex.source; + if (dir == 1) { + var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/); + } else { + var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/); + } + return m && {pos: toCmPos(m)}; + }; + this.refresh = function() { + return this.ace.resize(true); + }; + this.getMode = function() { + return { name : this.getOption("mode") }; + } +}).call(CodeMirror.prototype); + function toAcePos(cmPos) { + return {row: cmPos.line, column: cmPos.ch}; + } + function toCmPos(acePos) { + return new Pos(acePos.row, acePos.column); + } + + var StringStream = CodeMirror.StringStream = function(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + throw "not implemented"; + }, + indentation: function() { + throw "not implemented"; + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + } + }; +CodeMirror.defineExtension = function(name, fn) { + CodeMirror.prototype[name] = fn; +}; +dom.importCssString(".normal-mode .ace_cursor{\ + border: 1px solid red;\ + background-color: red;\ + opacity: 0.5;\ +}\ +.normal-mode .ace_hidden-cursors .ace_cursor{\ + background-color: transparent;\ +}\ +.ace_dialog {\ + position: absolute;\ + left: 0; right: 0;\ + background: white;\ + z-index: 15;\ + padding: .1em .8em;\ + overflow: hidden;\ + color: #333;\ +}\ +.ace_dialog-top {\ + border-bottom: 1px solid #eee;\ + top: 0;\ +}\ +.ace_dialog-bottom {\ + border-top: 1px solid #eee;\ + bottom: 0;\ +}\ +.ace_dialog input {\ + border: none;\ + outline: none;\ + background: transparent;\ + width: 20em;\ + color: inherit;\ + font-family: monospace;\ +}", "vimMode"); +(function() { + function dialogDiv(cm, template, bottom) { + var wrap = cm.ace.container; + var dialog; + dialog = wrap.appendChild(document.createElement("div")); + if (bottom) + dialog.className = "ace_dialog ace_dialog-bottom"; + else + dialog.className = "ace_dialog ace_dialog-top"; + + if (typeof template == "string") { + dialog.innerHTML = template; + } else { // Assuming it's a detached DOM element. + dialog.appendChild(template); + } + return dialog; + } + + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) + cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + + CodeMirror.defineExtension("openDialog", function(template, callback, options) { + if (this.virtualSelectionMode()) return; + if (!options) options = {}; + + closeNotification(this, null); + + var dialog = dialogDiv(this, template, options.bottom); + var closed = false, me = this; + function close(newVal) { + if (typeof newVal == 'string') { + inp.value = newVal; + } else { + if (closed) return; + closed = true; + dialog.parentNode.removeChild(dialog); + me.focus(); + + if (options.onClose) options.onClose(dialog); + } + } + + var inp = dialog.getElementsByTagName("input")[0], button; + if (inp) { + if (options.value) { + inp.value = options.value; + if (options.select !== false) inp.select(); + } + + if (options.onInput) + CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); + if (options.onKeyUp) + CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); + + CodeMirror.on(inp, "keydown", function(e) { + if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } + if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); + + inp.focus(); + } else if (button = dialog.getElementsByTagName("button")[0]) { + CodeMirror.on(button, "click", function() { + close(); + me.focus(); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); + + button.focus(); + } + return close; + }); + + CodeMirror.defineExtension("openNotification", function(template, options) { + if (this.virtualSelectionMode()) return; + closeNotification(this, close); + var dialog = dialogDiv(this, template, options && options.bottom); + var closed = false, doneTimer; + var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; + + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + dialog.parentNode.removeChild(dialog); + } + + CodeMirror.on(dialog, 'click', function(e) { + CodeMirror.e_preventDefault(e); + close(); + }); + + if (duration) + doneTimer = setTimeout(close, duration); + + return close; + }); +})(); + + + var defaultKeymap = [ + { keys: '', type: 'keyToKey', toKeys: 'h' }, + { keys: '', type: 'keyToKey', toKeys: 'l' }, + { keys: '', type: 'keyToKey', toKeys: 'k' }, + { keys: '', type: 'keyToKey', toKeys: 'j' }, + { keys: '', type: 'keyToKey', toKeys: 'l' }, + { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'}, + { keys: '', type: 'keyToKey', toKeys: 'W' }, + { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' }, + { keys: '', type: 'keyToKey', toKeys: 'w' }, + { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' }, + { keys: '', type: 'keyToKey', toKeys: 'j' }, + { keys: '', type: 'keyToKey', toKeys: 'k' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, + { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, + { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, + { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, + { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, + { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, + { keys: '', type: 'keyToKey', toKeys: '0' }, + { keys: '', type: 'keyToKey', toKeys: '$' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, + { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, + { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, + { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, + { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, + { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, + { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, + { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, + { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, + { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, + { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, + { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, + { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, + { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, + { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, + { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, + { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, + { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, + { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, + { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, + { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, + { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, + { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, + { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, + { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, + { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, + { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, + { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, + { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, + { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, + { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, + { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, + { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, + { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, + { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, + { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, + { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, + { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, + { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, + { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, + { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, + { keys: '|', type: 'motion', motion: 'moveToColumn'}, + { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, + { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, + { keys: 'd', type: 'operator', operator: 'delete' }, + { keys: 'y', type: 'operator', operator: 'yank' }, + { keys: 'c', type: 'operator', operator: 'change' }, + { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, + { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, + { keys: 'g~', type: 'operator', operator: 'changeCase' }, + { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, + { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, + { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, + { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, + { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, + { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, + { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, + { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, + { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, + { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, + { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, + { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, + { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, + { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, + { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, + { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, + { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, + { keys: 'v', type: 'action', action: 'toggleVisualMode' }, + { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, + { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, + { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, + { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, + { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, + { keys: 'r', type: 'action', action: 'replace', isEdit: true }, + { keys: '@', type: 'action', action: 'replayMacro' }, + { keys: 'q', type: 'action', action: 'enterMacroRecordMode' }, + { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, + { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, + { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, + { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, + { keys: '', type: 'action', action: 'redo' }, + { keys: 'm', type: 'action', action: 'setMark' }, + { keys: '"', type: 'action', action: 'setRegister' }, + { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, + { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, + { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, + { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '.', type: 'action', action: 'repeatLastEdit' }, + { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, + { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, + { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, + { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, + { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, + { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, + { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, + { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, + { keys: ':', type: 'ex' } + ]; + var defaultExCommandMap = [ + { name: 'colorscheme', shortName: 'colo' }, + { name: 'map' }, + { name: 'imap', shortName: 'im' }, + { name: 'nmap', shortName: 'nm' }, + { name: 'vmap', shortName: 'vm' }, + { name: 'unmap' }, + { name: 'write', shortName: 'w' }, + { name: 'undo', shortName: 'u' }, + { name: 'redo', shortName: 'red' }, + { name: 'set', shortName: 'se' }, + { name: 'set', shortName: 'se' }, + { name: 'setlocal', shortName: 'setl' }, + { name: 'setglobal', shortName: 'setg' }, + { name: 'sort', shortName: 'sor' }, + { name: 'substitute', shortName: 's', possiblyAsync: true }, + { name: 'nohlsearch', shortName: 'noh' }, + { name: 'delmarks', shortName: 'delm' }, + { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, + { name: 'global', shortName: 'g' } + ]; + + var Pos = CodeMirror.Pos; + + var Vim = function() { return vimApi; } //{ + function enterVimMode(cm) { + cm.setOption('disableInput', true); + cm.setOption('showCursorWhenSelecting', false); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + cm.on('cursorActivity', onCursorActivity); + maybeInitVimState(cm); + CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); + } + + function leaveVimMode(cm) { + cm.setOption('disableInput', false); + cm.off('cursorActivity', onCursorActivity); + CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); + cm.state.vim = null; + } + + function detachVimMap(cm, next) { + if (this == CodeMirror.keyMap.vim) + CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); + + if (!next || next.attach != attachVimMap) + leaveVimMode(cm, false); + } + function attachVimMap(cm, prev) { + if (this == CodeMirror.keyMap.vim) + CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); + + if (!prev || prev.attach != attachVimMap) + enterVimMode(cm); + } + CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { + if (val && cm.getOption("keyMap") != "vim") + cm.setOption("keyMap", "vim"); + else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) + cm.setOption("keyMap", "default"); + }); + + function cmKey(key, cm) { + if (!cm) { return undefined; } + var vimKey = cmKeyToVimKey(key); + if (!vimKey) { + return false; + } + var cmd = CodeMirror.Vim.findKey(cm, vimKey); + if (typeof cmd == 'function') { + CodeMirror.signal(cm, 'vim-keypress', vimKey); + } + return cmd; + } + + var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; + var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'}; + function cmKeyToVimKey(key) { + if (key.charAt(0) == '\'') { + return key.charAt(1); + } + var pieces = key.split(/-(?!$)/); + var lastPiece = pieces[pieces.length - 1]; + if (pieces.length == 1 && pieces[0].length == 1) { + return false; + } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { + return false; + } + var hasCharacter = false; + for (var i = 0; i < pieces.length; i++) { + var piece = pieces[i]; + if (piece in modifiers) { pieces[i] = modifiers[piece]; } + else { hasCharacter = true; } + if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } + } + if (!hasCharacter) { + return false; + } + if (isUpperCase(lastPiece)) { + pieces[pieces.length - 1] = lastPiece.toLowerCase(); + } + return '<' + pieces.join('-') + '>'; + } + + function getOnPasteFn(cm) { + var vim = cm.state.vim; + if (!vim.onPasteFn) { + vim.onPasteFn = function() { + if (!vim.insertMode) { + cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); + actions.enterInsertMode(cm, {}, vim); + } + }; + } + return vim.onPasteFn; + } + + var numberRegex = /[\d]/; + var wordCharTest = [CodeMirror.isWordChar, function(ch) { + return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); + }], bigWordCharTest = [function(ch) { + return /\S/.test(ch); + }]; + function makeKeyRange(start, size) { + var keys = []; + for (var i = start; i < start + size; i++) { + keys.push(String.fromCharCode(i)); + } + return keys; + } + var upperCaseAlphabet = makeKeyRange(65, 26); + var lowerCaseAlphabet = makeKeyRange(97, 26); + var numbers = makeKeyRange(48, 10); + var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); + var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); + + function isLine(cm, line) { + return line >= cm.firstLine() && line <= cm.lastLine(); + } + function isLowerCase(k) { + return (/^[a-z]$/).test(k); + } + function isMatchableSymbol(k) { + return '()[]{}'.indexOf(k) != -1; + } + function isNumber(k) { + return numberRegex.test(k); + } + function isUpperCase(k) { + return (/^[A-Z]$/).test(k); + } + function isWhiteSpaceString(k) { + return (/^\s*$/).test(k); + } + function inArray(val, arr) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] == val) { + return true; + } + } + return false; + } + + var options = {}; + function defineOption(name, defaultValue, type, aliases, callback) { + if (defaultValue === undefined && !callback) { + throw Error('defaultValue is acequired unless callback is provided'); + } + if (!type) { type = 'string'; } + options[name] = { + type: type, + defaultValue: defaultValue, + callback: callback + }; + if (aliases) { + for (var i = 0; i < aliases.length; i++) { + options[aliases[i]] = options[name]; + } + } + if (defaultValue) { + setOption(name, defaultValue); + } + } + + function setOption(name, value, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + throw Error('Unknown option: ' + name); + } + if (option.type == 'boolean') { + if (value && value !== true) { + throw Error('Invalid argument: ' + name + '=' + value); + } else if (value !== false) { + value = true; + } + } + if (option.callback) { + if (scope !== 'local') { + option.callback(value, undefined); + } + if (scope !== 'global' && cm) { + option.callback(value, cm); + } + } else { + if (scope !== 'local') { + option.value = option.type == 'boolean' ? !!value : value; + } + if (scope !== 'global' && cm) { + cm.state.vim.options[name] = {value: value}; + } + } + } + + function getOption(name, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + throw Error('Unknown option: ' + name); + } + if (option.callback) { + var local = cm && option.callback(undefined, cm); + if (scope !== 'global' && local !== undefined) { + return local; + } + if (scope !== 'local') { + return option.callback(); + } + return; + } else { + var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); + return (local || (scope !== 'local') && option || {}).value; + } + } + + defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { + if (cm === undefined) { + return; + } + if (name === undefined) { + var mode = cm.getOption('mode'); + return mode == 'null' ? '' : mode; + } else { + var mode = name == '' ? 'null' : name; + cm.setOption('mode', mode); + } + }); + + var createCircularJumpList = function() { + var size = 100; + var pointer = -1; + var head = 0; + var tail = 0; + var buffer = new Array(size); + function add(cm, oldCur, newCur) { + var current = pointer % size; + var curMark = buffer[current]; + function useNextSlot(cursor) { + var next = ++pointer % size; + var trashMark = buffer[next]; + if (trashMark) { + trashMark.clear(); + } + buffer[next] = cm.setBookmark(cursor); + } + if (curMark) { + var markPos = curMark.find(); + if (markPos && !cursorEqual(markPos, oldCur)) { + useNextSlot(oldCur); + } + } else { + useNextSlot(oldCur); + } + useNextSlot(newCur); + head = pointer; + tail = pointer - size + 1; + if (tail < 0) { + tail = 0; + } + } + function move(cm, offset) { + pointer += offset; + if (pointer > head) { + pointer = head; + } else if (pointer < tail) { + pointer = tail; + } + var mark = buffer[(size + pointer) % size]; + if (mark && !mark.find()) { + var inc = offset > 0 ? 1 : -1; + var newCur; + var oldCur = cm.getCursor(); + do { + pointer += inc; + mark = buffer[(size + pointer) % size]; + if (mark && + (newCur = mark.find()) && + !cursorEqual(oldCur, newCur)) { + break; + } + } while (pointer < head && pointer > tail); + } + return mark; + } + return { + cachedCursor: undefined, //used for # and * jumps + add: add, + move: move + }; + }; + var createInsertModeChanges = function(c) { + if (c) { + return { + changes: c.changes, + expectCursorActivityForChange: c.expectCursorActivityForChange + }; + } + return { + changes: [], + expectCursorActivityForChange: false + }; + }; + + function MacroModeState() { + this.latestRegister = undefined; + this.isPlaying = false; + this.isRecording = false; + this.replaySearchQueries = []; + this.onRecordingDone = undefined; + this.lastInsertModeChanges = createInsertModeChanges(); + } + MacroModeState.prototype = { + exitMacroRecordMode: function() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.onRecordingDone) { + macroModeState.onRecordingDone(); // close dialog + } + macroModeState.onRecordingDone = undefined; + macroModeState.isRecording = false; + }, + enterMacroRecordMode: function(cm, registerName) { + var register = + vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.clear(); + this.latestRegister = registerName; + if (cm.openDialog) { + this.onRecordingDone = cm.openDialog( + '(recording)['+registerName+']', null, {bottom:true}); + } + this.isRecording = true; + } + } + }; + + function maybeInitVimState(cm) { + if (!cm.state.vim) { + cm.state.vim = { + inputState: new InputState(), + lastEditInputState: undefined, + lastEditActionCommand: undefined, + lastHPos: -1, + lastHSPos: -1, + lastMotion: null, + marks: {}, + fakeCursor: null, + insertMode: false, + insertModeRepeat: undefined, + visualMode: false, + visualLine: false, + visualBlock: false, + lastSelection: null, + lastPastedText: null, + sel: {}, + options: {} + }; + } + return cm.state.vim; + } + var vimGlobalState; + function resetVimGlobalState() { + vimGlobalState = { + searchQuery: null, + searchIsReversed: false, + lastSubstituteReplacePart: undefined, + jumpList: createCircularJumpList(), + macroModeState: new MacroModeState, + lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''}, + registerController: new RegisterController({}), + searchHistoryController: new HistoryController({}), + exCommandHistoryController : new HistoryController({}) + }; + for (var optionName in options) { + var option = options[optionName]; + option.value = option.defaultValue; + } + } + + var lastInsertModeKeyTimer; + var vimApi= { + buildKeyMap: function() { + }, + getRegisterController: function() { + return vimGlobalState.registerController; + }, + resetVimGlobalState_: resetVimGlobalState, + getVimGlobalState_: function() { + return vimGlobalState; + }, + maybeInitVimState_: maybeInitVimState, + + suppressErrorLogging: false, + + InsertModeKey: InsertModeKey, + map: function(lhs, rhs, ctx) { + exCommandDispatcher.map(lhs, rhs, ctx); + }, + unmap: function(lhs, ctx) { + exCommandDispatcher.unmap(lhs, ctx); + }, + setOption: setOption, + getOption: getOption, + defineOption: defineOption, + defineEx: function(name, prefix, func){ + if (!prefix) { + prefix = name; + } else if (name.indexOf(prefix) !== 0) { + throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); + } + exCommands[name]=func; + exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; + }, + handleKey: function (cm, key, origin) { + var command = this.findKey(cm, key, origin); + if (typeof command === 'function') { + return command(); + } + }, + findKey: function(cm, key, origin) { + var vim = maybeInitVimState(cm); + function handleMacroRecording() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + if (key == 'q') { + macroModeState.exitMacroRecordMode(); + clearInputState(cm); + return true; + } + if (origin != 'mapping') { + logKey(macroModeState, key); + } + } + } + function handleEsc() { + if (key == '') { + clearInputState(cm); + if (vim.visualMode) { + exitVisualMode(cm); + } else if (vim.insertMode) { + exitInsertMode(cm); + } + return true; + } + } + function doKeyToKey(keys) { + var match; + while (keys) { + match = (/<\w+-.+?>|<\w+>|./).exec(keys); + key = match[0]; + keys = keys.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'mapping'); + } + } + + function handleKeyInsertMode() { + if (handleEsc()) { return true; } + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + var keysAreChars = key.length == 1; + var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + while (keys.length > 1 && match.type != 'full') { + var keys = vim.inputState.keyBuffer = keys.slice(1); + var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + if (thisMatch.type != 'none') { match = thisMatch; } + } + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + lastInsertModeKeyTimer = window.setTimeout( + function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, + getOption('insertModeEscKeysTimeout')); + return !keysAreChars; + } + + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + if (keysAreChars) { + var selections = cm.listSelections(); + for (var i = 0; i < selections.length; i++) { + var here = selections[i].head; + cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); + } + vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); + } + clearInputState(cm); + return match.command; + } + + function handleKeyNonInsertMode() { + if (handleMacroRecording() || handleEsc()) { return true; } + + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + if (/^[1-9]\d*$/.test(keys)) { return true; } + + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (!keysMatcher) { clearInputState(cm); return false; } + var context = vim.visualMode ? 'visual' : + 'normal'; + var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { return true; } + + vim.inputState.keyBuffer = ''; + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (keysMatcher[1] && keysMatcher[1] != '0') { + vim.inputState.pushRepeatDigit(keysMatcher[1]); + } + return match.command; + } + + var command; + if (vim.insertMode) { command = handleKeyInsertMode(); } + else { command = handleKeyNonInsertMode(); } + if (command === false) { + return undefined; + } else if (command === true) { + return function() { return true; }; + } else { + return function() { + if ((command.operator || command.isEdit) && cm.getOption('readOnly')) + return; // ace_patch + return cm.operation(function() { + cm.curOp.isVimOp = true; + try { + if (command.type == 'keyToKey') { + doKeyToKey(command.toKeys); + } else { + commandDispatcher.processCommand(cm, vim, command); + } + } catch (e) { + cm.state.vim = undefined; + maybeInitVimState(cm); + if (!CodeMirror.Vim.suppressErrorLogging) { + console['log'](e); + } + throw e; + } + return true; + }); + }; + } + }, + handleEx: function(cm, input) { + exCommandDispatcher.processCommand(cm, input); + }, + + defineMotion: defineMotion, + defineAction: defineAction, + defineOperator: defineOperator, + mapCommand: mapCommand, + _mapCommand: _mapCommand, + + defineRegister: defineRegister, + + exitVisualMode: exitVisualMode, + exitInsertMode: exitInsertMode + }; + function InputState() { + this.prefixRepeat = []; + this.motionRepeat = []; + + this.operator = null; + this.operatorArgs = null; + this.motion = null; + this.motionArgs = null; + this.keyBuffer = []; // For matching multi-key commands. + this.registerName = null; // Defaults to the unnamed register. + } + InputState.prototype.pushRepeatDigit = function(n) { + if (!this.operator) { + this.prefixRepeat = this.prefixRepeat.concat(n); + } else { + this.motionRepeat = this.motionRepeat.concat(n); + } + }; + InputState.prototype.getRepeat = function() { + var repeat = 0; + if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { + repeat = 1; + if (this.prefixRepeat.length > 0) { + repeat *= parseInt(this.prefixRepeat.join(''), 10); + } + if (this.motionRepeat.length > 0) { + repeat *= parseInt(this.motionRepeat.join(''), 10); + } + } + return repeat; + }; + + function clearInputState(cm, reason) { + cm.state.vim.inputState = new InputState(); + CodeMirror.signal(cm, 'vim-command-done', reason); + } + function Register(text, linewise, blockwise) { + this.clear(); + this.keyBuffer = [text || '']; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + } + Register.prototype = { + setText: function(text, linewise, blockwise) { + this.keyBuffer = [text || '']; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + }, + pushText: function(text, linewise) { + if (linewise) { + if (!this.linewise) { + this.keyBuffer.push('\n'); + } + this.linewise = true; + } + this.keyBuffer.push(text); + }, + pushInsertModeChanges: function(changes) { + this.insertModeChanges.push(createInsertModeChanges(changes)); + }, + pushSearchQuery: function(query) { + this.searchQueries.push(query); + }, + clear: function() { + this.keyBuffer = []; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = false; + }, + toString: function() { + return this.keyBuffer.join(''); + } + }; + function defineRegister(name, register) { + var registers = vimGlobalState.registerController.registers[name]; + if (!name || name.length != 1) { + throw Error('Register name must be 1 character'); + } + registers[name] = register; + validRegisters.push(name); + } + function RegisterController(registers) { + this.registers = registers; + this.unnamedRegister = registers['"'] = new Register(); + registers['.'] = new Register(); + registers[':'] = new Register(); + registers['/'] = new Register(); + } + RegisterController.prototype = { + pushText: function(registerName, operator, text, linewise, blockwise) { + if (linewise && text.charAt(0) == '\n') { + text = text.slice(1) + '\n'; + } + if (linewise && text.charAt(text.length - 1) !== '\n'){ + text += '\n'; + } + var register = this.isValidRegister(registerName) ? + this.getRegister(registerName) : null; + if (!register) { + switch (operator) { + case 'yank': + this.registers['0'] = new Register(text, linewise, blockwise); + break; + case 'delete': + case 'change': + if (text.indexOf('\n') == -1) { + this.registers['-'] = new Register(text, linewise); + } else { + this.shiftNumericRegisters_(); + this.registers['1'] = new Register(text, linewise); + } + break; + } + this.unnamedRegister.setText(text, linewise, blockwise); + return; + } + var append = isUpperCase(registerName); + if (append) { + register.pushText(text, linewise); + } else { + register.setText(text, linewise, blockwise); + } + this.unnamedRegister.setText(register.toString(), linewise); + }, + getRegister: function(name) { + if (!this.isValidRegister(name)) { + return this.unnamedRegister; + } + name = name.toLowerCase(); + if (!this.registers[name]) { + this.registers[name] = new Register(); + } + return this.registers[name]; + }, + isValidRegister: function(name) { + return name && inArray(name, validRegisters); + }, + shiftNumericRegisters_: function() { + for (var i = 9; i >= 2; i--) { + this.registers[i] = this.getRegister('' + (i - 1)); + } + } + }; + function HistoryController() { + this.historyBuffer = []; + this.iterator; + this.initialPrefix = null; + } + HistoryController.prototype = { + nextMatch: function (input, up) { + var historyBuffer = this.historyBuffer; + var dir = up ? -1 : 1; + if (this.initialPrefix === null) this.initialPrefix = input; + for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { + var element = historyBuffer[i]; + for (var j = 0; j <= element.length; j++) { + if (this.initialPrefix == element.substring(0, j)) { + this.iterator = i; + return element; + } + } + } + if (i >= historyBuffer.length) { + this.iterator = historyBuffer.length; + return this.initialPrefix; + } + if (i < 0 ) return input; + }, + pushInput: function(input) { + var index = this.historyBuffer.indexOf(input); + if (index > -1) this.historyBuffer.splice(index, 1); + if (input.length) this.historyBuffer.push(input); + }, + reset: function() { + this.initialPrefix = null; + this.iterator = this.historyBuffer.length; + } + }; + var commandDispatcher = { + matchCommand: function(keys, keyMap, inputState, context) { + var matches = commandMatches(keys, keyMap, context, inputState); + if (!matches.full && !matches.partial) { + return {type: 'none'}; + } else if (!matches.full && matches.partial) { + return {type: 'partial'}; + } + + var bestMatch; + for (var i = 0; i < matches.full.length; i++) { + var match = matches.full[i]; + if (!bestMatch) { + bestMatch = match; + } + } + if (bestMatch.keys.slice(-11) == '') { + inputState.selectedCharacter = lastChar(keys); + } + return {type: 'full', command: bestMatch}; + }, + processCommand: function(cm, vim, command) { + vim.inputState.repeatOverride = command.repeatOverride; + switch (command.type) { + case 'motion': + this.processMotion(cm, vim, command); + break; + case 'operator': + this.processOperator(cm, vim, command); + break; + case 'operatorMotion': + this.processOperatorMotion(cm, vim, command); + break; + case 'action': + this.processAction(cm, vim, command); + break; + case 'search': + this.processSearch(cm, vim, command); + break; + case 'ex': + case 'keyToEx': + this.processEx(cm, vim, command); + break; + default: + break; + } + }, + processMotion: function(cm, vim, command) { + vim.inputState.motion = command.motion; + vim.inputState.motionArgs = copyArgs(command.motionArgs); + this.evalInput(cm, vim); + }, + processOperator: function(cm, vim, command) { + var inputState = vim.inputState; + if (inputState.operator) { + if (inputState.operator == command.operator) { + inputState.motion = 'expandToLine'; + inputState.motionArgs = { linewise: true }; + this.evalInput(cm, vim); + return; + } else { + clearInputState(cm); + } + } + inputState.operator = command.operator; + inputState.operatorArgs = copyArgs(command.operatorArgs); + if (vim.visualMode) { + this.evalInput(cm, vim); + } + }, + processOperatorMotion: function(cm, vim, command) { + var visualMode = vim.visualMode; + var operatorMotionArgs = copyArgs(command.operatorMotionArgs); + if (operatorMotionArgs) { + if (visualMode && operatorMotionArgs.visualLine) { + vim.visualLine = true; + } + } + this.processOperator(cm, vim, command); + if (!visualMode) { + this.processMotion(cm, vim, command); + } + }, + processAction: function(cm, vim, command) { + var inputState = vim.inputState; + var repeat = inputState.getRepeat(); + var repeatIsExplicit = !!repeat; + var actionArgs = copyArgs(command.actionArgs) || {}; + if (inputState.selectedCharacter) { + actionArgs.selectedCharacter = inputState.selectedCharacter; + } + if (command.operator) { + this.processOperator(cm, vim, command); + } + if (command.motion) { + this.processMotion(cm, vim, command); + } + if (command.motion || command.operator) { + this.evalInput(cm, vim); + } + actionArgs.repeat = repeat || 1; + actionArgs.repeatIsExplicit = repeatIsExplicit; + actionArgs.registerName = inputState.registerName; + clearInputState(cm); + vim.lastMotion = null; + if (command.isEdit) { + this.recordLastEdit(vim, inputState, command); + } + actions[command.action](cm, actionArgs, vim); + }, + processSearch: function(cm, vim, command) { + if (!cm.getSearchCursor) { + return; + } + var forward = command.searchArgs.forward; + var wholeWordOnly = command.searchArgs.wholeWordOnly; + getSearchState(cm).setReversed(!forward); + var promptPrefix = (forward) ? '/' : '?'; + var originalQuery = getSearchState(cm).getQuery(); + var originalScrollPos = cm.getScrollInfo(); + function handleQuery(query, ignoreCase, smartCase) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + try { + updateSearchQuery(cm, query, ignoreCase, smartCase); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + query); + clearInputState(cm); + return; + } + commandDispatcher.processMotion(cm, vim, { + type: 'motion', + motion: 'findNext', + motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } + }); + } + function onPromptClose(query) { + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + handleQuery(query, true /** ignoreCase */, true /** smartCase */); + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + logSearchQuery(macroModeState, query); + } + } + function onPromptKeyUp(e, query, close) { + var keyName = CodeMirror.keyName(e), up; + if (keyName == 'Up' || keyName == 'Down') { + up = keyName == 'Up' ? true : false; + query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; + close(query); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.searchHistoryController.reset(); + } + var parsedQuery; + try { + parsedQuery = updateSearchQuery(cm, query, + true /** ignoreCase */, true /** smartCase */); + } catch (e) { + } + if (parsedQuery) { + cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); + } else { + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + } + } + function onPromptKeyDown(e, query, close) { + var keyName = CodeMirror.keyName(e); + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && query == '')) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + updateSearchQuery(cm, originalQuery); + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } else if (keyName == 'Ctrl-U') { + CodeMirror.e_stop(e); + close(''); + } + } + switch (command.searchArgs.querySrc) { + case 'prompt': + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { + var query = macroModeState.replaySearchQueries.shift(); + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + } else { + showPrompt(cm, { + onClose: onPromptClose, + prefix: promptPrefix, + desc: searchPromptDesc, + onKeyUp: onPromptKeyUp, + onKeyDown: onPromptKeyDown + }); + } + break; + case 'wordUnderCursor': + var word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + true /** noSymbol */); + var isKeyword = true; + if (!word) { + word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + false /** noSymbol */); + isKeyword = false; + } + if (!word) { + return; + } + var query = cm.getLine(word.start.line).substring(word.start.ch, + word.end.ch); + if (isKeyword && wholeWordOnly) { + query = '\\b' + query + '\\b'; + } else { + query = escapeRegex(query); + } + vimGlobalState.jumpList.cachedCursor = cm.getCursor(); + cm.setCursor(word.start); + + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + break; + } + }, + processEx: function(cm, vim, command) { + function onPromptClose(input) { + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + exCommandDispatcher.processCommand(cm, input); + } + function onPromptKeyDown(e, input, close) { + var keyName = CodeMirror.keyName(e), up; + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && input == '')) { + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } + if (keyName == 'Up' || keyName == 'Down') { + up = keyName == 'Up' ? true : false; + input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; + close(input); + } else if (keyName == 'Ctrl-U') { + CodeMirror.e_stop(e); + close(''); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.exCommandHistoryController.reset(); + } + } + if (command.type == 'keyToEx') { + exCommandDispatcher.processCommand(cm, command.exArgs.input); + } else { + if (vim.visualMode) { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', + onKeyDown: onPromptKeyDown}); + } else { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', + onKeyDown: onPromptKeyDown}); + } + } + }, + evalInput: function(cm, vim) { + var inputState = vim.inputState; + var motion = inputState.motion; + var motionArgs = inputState.motionArgs || {}; + var operator = inputState.operator; + var operatorArgs = inputState.operatorArgs || {}; + var registerName = inputState.registerName; + var sel = vim.sel; + var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); + var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); + var oldHead = copyCursor(origHead); + var oldAnchor = copyCursor(origAnchor); + var newHead, newAnchor; + var repeat; + if (operator) { + this.recordLastEdit(vim, inputState); + } + if (inputState.repeatOverride !== undefined) { + repeat = inputState.repeatOverride; + } else { + repeat = inputState.getRepeat(); + } + if (repeat > 0 && motionArgs.explicitRepeat) { + motionArgs.repeatIsExplicit = true; + } else if (motionArgs.noRepeat || + (!motionArgs.explicitRepeat && repeat === 0)) { + repeat = 1; + motionArgs.repeatIsExplicit = false; + } + if (inputState.selectedCharacter) { + motionArgs.selectedCharacter = operatorArgs.selectedCharacter = + inputState.selectedCharacter; + } + motionArgs.repeat = repeat; + clearInputState(cm); + if (motion) { + var motionResult = motions[motion](cm, origHead, motionArgs, vim); + vim.lastMotion = motions[motion]; + if (!motionResult) { + return; + } + if (motionArgs.toJumplist) { + if (!operator && cm.ace.curOp != null) + cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch + var jumpList = vimGlobalState.jumpList; + var cachedCursor = jumpList.cachedCursor; + if (cachedCursor) { + recordJumpPosition(cm, cachedCursor, motionResult); + delete jumpList.cachedCursor; + } else { + recordJumpPosition(cm, origHead, motionResult); + } + } + if (motionResult instanceof Array) { + newAnchor = motionResult[0]; + newHead = motionResult[1]; + } else { + newHead = motionResult; + } + if (!newHead) { + newHead = copyCursor(origHead); + } + if (vim.visualMode) { + if (!(vim.visualBlock && newHead.ch === Infinity)) { + newHead = clipCursorToContent(cm, newHead, vim.visualBlock); + } + if (newAnchor) { + newAnchor = clipCursorToContent(cm, newAnchor, true); + } + newAnchor = newAnchor || oldAnchor; + sel.anchor = newAnchor; + sel.head = newHead; + updateCmSelection(cm); + updateMark(cm, vim, '<', + cursorIsBefore(newAnchor, newHead) ? newAnchor + : newHead); + updateMark(cm, vim, '>', + cursorIsBefore(newAnchor, newHead) ? newHead + : newAnchor); + } else if (!operator) { + newHead = clipCursorToContent(cm, newHead); + cm.setCursor(newHead.line, newHead.ch); + } + } + if (operator) { + if (operatorArgs.lastSel) { + newAnchor = oldAnchor; + var lastSel = operatorArgs.lastSel; + var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); + var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); + if (lastSel.visualLine) { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } else if (lastSel.visualBlock) { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); + } else if (lastSel.head.line == lastSel.anchor.line) { + newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); + } else { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } + vim.visualMode = true; + vim.visualLine = lastSel.visualLine; + vim.visualBlock = lastSel.visualBlock; + sel = vim.sel = { + anchor: newAnchor, + head: newHead + }; + updateCmSelection(cm); + } else if (vim.visualMode) { + operatorArgs.lastSel = { + anchor: copyCursor(sel.anchor), + head: copyCursor(sel.head), + visualBlock: vim.visualBlock, + visualLine: vim.visualLine + }; + } + var curStart, curEnd, linewise, mode; + var cmSel; + if (vim.visualMode) { + curStart = cursorMin(sel.head, sel.anchor); + curEnd = cursorMax(sel.head, sel.anchor); + linewise = vim.visualLine || operatorArgs.linewise; + mode = vim.visualBlock ? 'block' : + linewise ? 'line' : + 'char'; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode); + if (linewise) { + var ranges = cmSel.ranges; + if (mode == 'block') { + for (var i = 0; i < ranges.length; i++) { + ranges[i].head.ch = lineLength(cm, ranges[i].head.line); + } + } else if (mode == 'line') { + ranges[0].head = Pos(ranges[0].head.line + 1, 0); + } + } + } else { + curStart = copyCursor(newAnchor || oldAnchor); + curEnd = copyCursor(newHead || oldHead); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curStart; + curStart = curEnd; + curEnd = tmp; + } + linewise = motionArgs.linewise || operatorArgs.linewise; + if (linewise) { + expandSelectionToLine(cm, curStart, curEnd); + } else if (motionArgs.forward) { + clipToLine(cm, curStart, curEnd); + } + mode = 'char'; + var exclusive = !motionArgs.inclusive || linewise; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode, exclusive); + } + cm.setSelections(cmSel.ranges, cmSel.primary); + vim.lastMotion = null; + operatorArgs.repeat = repeat; // For indent in visual mode. + operatorArgs.registerName = registerName; + operatorArgs.linewise = linewise; + var operatorMoveTo = operators[operator]( + cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); + if (vim.visualMode) { + exitVisualMode(cm, operatorMoveTo != null); + } + if (operatorMoveTo) { + cm.setCursor(operatorMoveTo); + } + } + }, + recordLastEdit: function(vim, inputState, actionCommand) { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + vim.lastEditInputState = inputState; + vim.lastEditActionCommand = actionCommand; + macroModeState.lastInsertModeChanges.changes = []; + macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; + } + }; + var motions = { + moveToTopLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToMiddleLine: function(cm) { + var range = getUserVisibleLines(cm); + var line = Math.floor((range.top + range.bottom) * 0.5); + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToBottomLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + expandToLine: function(_cm, head, motionArgs) { + var cur = head; + return Pos(cur.line + motionArgs.repeat - 1, Infinity); + }, + findNext: function(cm, _head, motionArgs) { + var state = getSearchState(cm); + var query = state.getQuery(); + if (!query) { + return; + } + var prev = !motionArgs.forward; + prev = (state.isReversed()) ? !prev : prev; + highlightSearchMatches(cm, query); + return findNext(cm, prev/** prev */, query, motionArgs.repeat); + }, + goToMark: function(cm, _head, motionArgs, vim) { + var mark = vim.marks[motionArgs.selectedCharacter]; + if (mark) { + var pos = mark.find(); + return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; + } + return null; + }, + moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { + if (vim.visualBlock && motionArgs.sameLine) { + var sel = vim.sel; + return [ + clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), + clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) + ]; + } else { + return ([vim.sel.head, vim.sel.anchor]); + } + }, + jumpToMark: function(cm, head, motionArgs, vim) { + var best = head; + for (var i = 0; i < motionArgs.repeat; i++) { + var cursor = best; + for (var key in vim.marks) { + if (!isLowerCase(key)) { + continue; + } + var mark = vim.marks[key].find(); + var isWrongDirection = (motionArgs.forward) ? + cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); + + if (isWrongDirection) { + continue; + } + if (motionArgs.linewise && (mark.line == cursor.line)) { + continue; + } + + var equal = cursorEqual(cursor, best); + var between = (motionArgs.forward) ? + cursorIsBetween(cursor, mark, best) : + cursorIsBetween(best, mark, cursor); + + if (equal || between) { + best = mark; + } + } + } + + if (motionArgs.linewise) { + best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); + } + return best; + }, + moveByCharacters: function(_cm, head, motionArgs) { + var cur = head; + var repeat = motionArgs.repeat; + var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; + return Pos(cur.line, ch); + }, + moveByLines: function(cm, head, motionArgs, vim) { + var cur = head; + var endCh = cur.ch; + switch (vim.lastMotion) { + case this.moveByLines: + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveToColumn: + case this.moveToEol: + endCh = vim.lastHPos; + break; + default: + vim.lastHPos = endCh; + } + var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); + var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; + var first = cm.firstLine(); + var last = cm.lastLine(); + if ((line < first && cur.line == first) || + (line > last && cur.line == last)) { + return; + } + var fold = cm.ace.session.getFoldLine(line); + if (fold) { + if (motionArgs.forward) { + if (line > fold.start.row) + line = fold.end.row + 1; + } else { + line = fold.start.row; + } + } + if (motionArgs.toFirstChar){ + endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); + vim.lastHPos = endCh; + } + vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; + return Pos(line, endCh); + }, + moveByDisplayLines: function(cm, head, motionArgs, vim) { + var cur = head; + switch (vim.lastMotion) { + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveByLines: + case this.moveToColumn: + case this.moveToEol: + break; + default: + vim.lastHSPos = cm.charCoords(cur,'div').left; + } + var repeat = motionArgs.repeat; + var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); + if (res.hitSide) { + if (motionArgs.forward) { + var lastCharCoords = cm.charCoords(res, 'div'); + var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; + var res = cm.coordsChar(goalCoords, 'div'); + } else { + var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); + resCoords.left = vim.lastHSPos; + res = cm.coordsChar(resCoords, 'div'); + } + } + vim.lastHPos = res.ch; + return res; + }, + moveByPage: function(cm, head, motionArgs) { + var curStart = head; + var repeat = motionArgs.repeat; + return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); + }, + moveByParagraph: function(cm, head, motionArgs) { + var dir = motionArgs.forward ? 1 : -1; + return findParagraph(cm, head, motionArgs.repeat, dir); + }, + moveByScroll: function(cm, head, motionArgs, vim) { + var scrollbox = cm.getScrollInfo(); + var curEnd = null; + var repeat = motionArgs.repeat; + if (!repeat) { + repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); + } + var orig = cm.charCoords(head, 'local'); + motionArgs.repeat = repeat; + var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); + if (!curEnd) { + return null; + } + var dest = cm.charCoords(curEnd, 'local'); + cm.scrollTo(null, scrollbox.top + dest.top - orig.top); + return curEnd; + }, + moveByWords: function(cm, head, motionArgs) { + return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, + !!motionArgs.wordEnd, !!motionArgs.bigWord); + }, + moveTillCharacter: function(cm, _head, motionArgs) { + var repeat = motionArgs.repeat; + var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + var increment = motionArgs.forward ? -1 : 1; + recordLastCharacterSearch(increment, motionArgs); + if (!curEnd) return null; + curEnd.ch += increment; + return curEnd; + }, + moveToCharacter: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + recordLastCharacterSearch(0, motionArgs); + return moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToSymbol: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + return findSymbol(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToColumn: function(cm, head, motionArgs, vim) { + var repeat = motionArgs.repeat; + vim.lastHPos = repeat - 1; + vim.lastHSPos = cm.charCoords(head,'div').left; + return moveToColumn(cm, repeat); + }, + moveToEol: function(cm, head, motionArgs, vim) { + var cur = head; + vim.lastHPos = Infinity; + var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); + var end=cm.clipPos(retval); + end.ch--; + vim.lastHSPos = cm.charCoords(end,'div').left; + return retval; + }, + moveToFirstNonWhiteSpaceCharacter: function(cm, head) { + var cursor = head; + return Pos(cursor.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); + }, + moveToMatchedSymbol: function(cm, head) { + var cursor = head; + var line = cursor.line; + var ch = cursor.ch; + var lineText = cm.getLine(line); + var symbol; + do { + symbol = lineText.charAt(ch++); + if (symbol && isMatchableSymbol(symbol)) { + var style = cm.getTokenTypeAt(Pos(line, ch)); + if (style !== "string" && style !== "comment") { + break; + } + } + } while (symbol); + if (symbol) { + var matched = cm.findMatchingBracket(Pos(line, ch)); + return matched.to; + } else { + return cursor; + } + }, + moveToStartOfLine: function(_cm, head) { + return Pos(head.line, 0); + }, + moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { + var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); + if (motionArgs.repeatIsExplicit) { + lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); + } + return Pos(lineNum, + findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); + }, + textObjectManipulation: function(cm, head, motionArgs, vim) { + var mirroredPairs = {'(': ')', ')': '(', + '{': '}', '}': '{', + '[': ']', ']': '['}; + var selfPaired = {'\'': true, '"': true}; + + var character = motionArgs.selectedCharacter; + if (character == 'b') { + character = '('; + } else if (character == 'B') { + character = '{'; + } + var inclusive = !motionArgs.textObjectInner; + + var tmp; + if (mirroredPairs[character]) { + tmp = selectCompanionObject(cm, head, character, inclusive); + } else if (selfPaired[character]) { + tmp = findBeginningAndEnd(cm, head, character, inclusive); + } else if (character === 'W') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + true /** bigWord */); + } else if (character === 'w') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + false /** bigWord */); + } else if (character === 'p') { + tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); + motionArgs.linewise = true; + if (vim.visualMode) { + if (!vim.visualLine) { vim.visualLine = true; } + } else { + var operatorArgs = vim.inputState.operatorArgs; + if (operatorArgs) { operatorArgs.linewise = true; } + tmp.end.line--; + } + } else { + return null; + } + + if (!cm.state.vim.visualMode) { + return [tmp.start, tmp.end]; + } else { + return expandSelection(cm, tmp.start, tmp.end); + } + }, + + repeatLastCharacterSearch: function(cm, head, motionArgs) { + var lastSearch = vimGlobalState.lastChararacterSearch; + var repeat = motionArgs.repeat; + var forward = motionArgs.forward === lastSearch.forward; + var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); + cm.moveH(-increment, 'char'); + motionArgs.inclusive = forward ? true : false; + var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); + if (!curEnd) { + cm.moveH(increment, 'char'); + return head; + } + curEnd.ch += increment; + return curEnd; + } + }; + + function defineMotion(name, fn) { + motions[name] = fn; + } + + function fillArray(val, times) { + var arr = []; + for (var i = 0; i < times; i++) { + arr.push(val); + } + return arr; + } + var operators = { + change: function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; + if (!vim.visualMode) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + text = cm.getRange(anchor, head); + var lastState = vim.lastEditInputState || {}; + if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { + var match = (/\s+$/).exec(text); + if (match && lastState.motionArgs && lastState.motionArgs.forward) { + head = offsetCursor(head, 0, - match[0].length); + text = text.slice(0, - match[0].length); + } + } + var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); + var wasLastLine = cm.firstLine() == cm.lastLine(); + if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { + cm.replaceRange('', prevLineEnd, head); + } else { + cm.replaceRange('', anchor, head); + } + if (args.linewise) { + if (!wasLastLine) { + cm.setCursor(prevLineEnd); + CodeMirror.commands.newlineAndIndent(cm); + } + anchor.ch = Number.MAX_VALUE; + } + finalHead = anchor; + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = cursorMin(ranges[0].head, ranges[0].anchor); + } + vimGlobalState.registerController.pushText( + args.registerName, 'change', text, + args.linewise, ranges.length > 1); + actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); + }, + 'delete': function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + if (!vim.visualBlock) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + if (args.linewise && + head.line != cm.firstLine() && + anchor.line == cm.lastLine() && + anchor.line == head.line - 1) { + if (anchor.line == cm.firstLine()) { + anchor.ch = 0; + } else { + anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); + } + } + text = cm.getRange(anchor, head); + cm.replaceRange('', anchor, head); + finalHead = anchor; + if (args.linewise) { + finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); + } + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = ranges[0].anchor; + } + vimGlobalState.registerController.pushText( + args.registerName, 'delete', text, + args.linewise, vim.visualBlock); + return clipCursorToContent(cm, finalHead); + }, + indent: function(cm, args, ranges) { + var vim = cm.state.vim; + var startLine = ranges[0].anchor.line; + var endLine = vim.visualBlock ? + ranges[ranges.length - 1].anchor.line : + ranges[0].head.line; + var repeat = (vim.visualMode) ? args.repeat : 1; + if (args.linewise) { + endLine--; + } + for (var i = startLine; i <= endLine; i++) { + for (var j = 0; j < repeat; j++) { + cm.indentLine(i, args.indentRight); + } + } + return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); + }, + changeCase: function(cm, args, ranges, oldAnchor, newHead) { + var selections = cm.getSelections(); + var swapped = []; + var toLower = args.toLower; + for (var j = 0; j < selections.length; j++) { + var toSwap = selections[j]; + var text = ''; + if (toLower === true) { + text = toSwap.toLowerCase(); + } else if (toLower === false) { + text = toSwap.toUpperCase(); + } else { + for (var i = 0; i < toSwap.length; i++) { + var character = toSwap.charAt(i); + text += isUpperCase(character) ? character.toLowerCase() : + character.toUpperCase(); + } + } + swapped.push(text); + } + cm.replaceSelections(swapped); + if (args.shouldMoveCursor){ + return newHead; + } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { + return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); + } else if (args.linewise){ + return oldAnchor; + } else { + return cursorMin(ranges[0].anchor, ranges[0].head); + } + }, + yank: function(cm, args, ranges, oldAnchor) { + var vim = cm.state.vim; + var text = cm.getSelection(); + var endPos = vim.visualMode + ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) + : oldAnchor; + vimGlobalState.registerController.pushText( + args.registerName, 'yank', + text, args.linewise, vim.visualBlock); + return endPos; + } + }; + + function defineOperator(name, fn) { + operators[name] = fn; + } + + var actions = { + jumpListWalk: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat; + var forward = actionArgs.forward; + var jumpList = vimGlobalState.jumpList; + + var mark = jumpList.move(cm, forward ? repeat : -repeat); + var markPos = mark ? mark.find() : undefined; + markPos = markPos ? markPos : cm.getCursor(); + cm.setCursor(markPos); + cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch + }, + scroll: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat || 1; + var lineHeight = cm.defaultTextHeight(); + var top = cm.getScrollInfo().top; + var delta = lineHeight * repeat; + var newPos = actionArgs.forward ? top + delta : top - delta; + var cursor = copyCursor(cm.getCursor()); + var cursorCoords = cm.charCoords(cursor, 'local'); + if (actionArgs.forward) { + if (newPos > cursorCoords.top) { + cursor.line += (newPos - cursorCoords.top) / lineHeight; + cursor.line = Math.ceil(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo(null, cursorCoords.top); + } else { + cm.scrollTo(null, newPos); + } + } else { + var newBottom = newPos + cm.getScrollInfo().clientHeight; + if (newBottom < cursorCoords.bottom) { + cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; + cursor.line = Math.floor(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo( + null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); + } else { + cm.scrollTo(null, newPos); + } + } + }, + scrollToCursor: function(cm, actionArgs) { + var lineNum = cm.getCursor().line; + var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); + var height = cm.getScrollInfo().clientHeight; + var y = charCoords.top; + var lineHeight = charCoords.bottom - y; + switch (actionArgs.position) { + case 'center': y = y - (height / 2) + lineHeight; + break; + case 'bottom': y = y - height + lineHeight*1.4; + break; + case 'top': y = y + lineHeight*0.4; + break; + } + cm.scrollTo(null, y); + }, + replayMacro: function(cm, actionArgs, vim) { + var registerName = actionArgs.selectedCharacter; + var repeat = actionArgs.repeat; + var macroModeState = vimGlobalState.macroModeState; + if (registerName == '@') { + registerName = macroModeState.latestRegister; + } + while(repeat--){ + executeMacroRegister(cm, vim, macroModeState, registerName); + } + }, + enterMacroRecordMode: function(cm, actionArgs) { + var macroModeState = vimGlobalState.macroModeState; + var registerName = actionArgs.selectedCharacter; + macroModeState.enterMacroRecordMode(cm, registerName); + }, + enterInsertMode: function(cm, actionArgs, vim) { + if (cm.getOption('readOnly')) { return; } + vim.insertMode = true; + vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; + var insertAt = (actionArgs) ? actionArgs.insertAt : null; + var sel = vim.sel; + var head = actionArgs.head || cm.getCursor('head'); + var height = cm.listSelections().length; + if (insertAt == 'eol') { + head = Pos(head.line, lineLength(cm, head.line)); + } else if (insertAt == 'charAfter') { + head = offsetCursor(head, 0, 1); + } else if (insertAt == 'firstNonBlank') { + head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); + } else if (insertAt == 'startOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line < sel.anchor.line) { + head = sel.head; + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.min(sel.head.ch, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'endOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line >= sel.anchor.line) { + head = offsetCursor(sel.head, 0, 1); + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.max(sel.head.ch + 1, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'inplace') { + if (vim.visualMode){ + return; + } + } + cm.setOption('keyMap', 'vim-insert'); + cm.setOption('disableInput', false); + if (actionArgs && actionArgs.replace) { + cm.toggleOverwrite(true); + cm.setOption('keyMap', 'vim-replace'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); + } else { + cm.setOption('keyMap', 'vim-insert'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); + } + if (!vimGlobalState.macroModeState.isPlaying) { + cm.on('change', onChange); + CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (vim.visualMode) { + exitVisualMode(cm); + } + selectForInsert(cm, head, height); + }, + toggleVisualMode: function(cm, actionArgs, vim) { + var repeat = actionArgs.repeat; + var anchor = cm.getCursor(); + var head; + if (!vim.visualMode) { + vim.visualMode = true; + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + head = clipCursorToContent( + cm, Pos(anchor.line, anchor.ch + repeat - 1), + true /** includeLineBreak */); + vim.sel = { + anchor: anchor, + head: head + }; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + } else if (vim.visualLine ^ actionArgs.linewise || + vim.visualBlock ^ actionArgs.blockwise) { + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + } else { + exitVisualMode(cm); + } + }, + reselectLastSelection: function(cm, _actionArgs, vim) { + var lastSelection = vim.lastSelection; + if (vim.visualMode) { + updateLastSelection(cm, vim); + } + if (lastSelection) { + var anchor = lastSelection.anchorMark.find(); + var head = lastSelection.headMark.find(); + if (!anchor || !head) { + return; + } + vim.sel = { + anchor: anchor, + head: head + }; + vim.visualMode = true; + vim.visualLine = lastSelection.visualLine; + vim.visualBlock = lastSelection.visualBlock; + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + CodeMirror.signal(cm, 'vim-mode-change', { + mode: 'visual', + subMode: vim.visualLine ? 'linewise' : + vim.visualBlock ? 'blockwise' : ''}); + } + }, + joinLines: function(cm, actionArgs, vim) { + var curStart, curEnd; + if (vim.visualMode) { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curEnd; + curEnd = curStart; + curStart = tmp; + } + curEnd.ch = lineLength(cm, curEnd.line) - 1; + } else { + var repeat = Math.max(actionArgs.repeat, 2); + curStart = cm.getCursor(); + curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, + Infinity)); + } + var finalCh = 0; + for (var i = curStart.line; i < curEnd.line; i++) { + finalCh = lineLength(cm, curStart.line); + var tmp = Pos(curStart.line + 1, + lineLength(cm, curStart.line + 1)); + var text = cm.getRange(curStart, tmp); + text = text.replace(/\n\s*/g, ' '); + cm.replaceRange(text, curStart, tmp); + } + var curFinalPos = Pos(curStart.line, finalCh); + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curFinalPos); + }, + newLineAndEnterInsertMode: function(cm, actionArgs, vim) { + vim.insertMode = true; + var insertAt = copyCursor(cm.getCursor()); + if (insertAt.line === cm.firstLine() && !actionArgs.after) { + cm.replaceRange('\n', Pos(cm.firstLine(), 0)); + cm.setCursor(cm.firstLine(), 0); + } else { + insertAt.line = (actionArgs.after) ? insertAt.line : + insertAt.line - 1; + insertAt.ch = lineLength(cm, insertAt.line); + cm.setCursor(insertAt); + var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + newlineFn(cm); + } + this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); + }, + paste: function(cm, actionArgs, vim) { + var cur = copyCursor(cm.getCursor()); + var register = vimGlobalState.registerController.getRegister( + actionArgs.registerName); + var text = register.toString(); + if (!text) { + return; + } + if (actionArgs.matchIndent) { + var tabSize = cm.getOption("tabSize"); + var whitespaceLength = function(str) { + var tabs = (str.split("\t").length - 1); + var spaces = (str.split(" ").length - 1); + return tabs * tabSize + spaces * 1; + }; + var currentLine = cm.getLine(cm.getCursor().line); + var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); + var chompedText = text.replace(/\n$/, ''); + var wasChomped = text !== chompedText; + var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); + var text = chompedText.replace(/^\s*/gm, function(wspace) { + var newIndent = indent + (whitespaceLength(wspace) - firstIndent); + if (newIndent < 0) { + return ""; + } + else if (cm.getOption("indentWithTabs")) { + var quotient = Math.floor(newIndent / tabSize); + return Array(quotient + 1).join('\t'); + } + else { + return Array(newIndent + 1).join(' '); + } + }); + text += wasChomped ? "\n" : ""; + } + if (actionArgs.repeat > 1) { + var text = Array(actionArgs.repeat + 1).join(text); + } + var linewise = register.linewise; + var blockwise = register.blockwise; + if (linewise && !blockwise) { + if(vim.visualMode) { + text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; + } else if (actionArgs.after) { + text = '\n' + text.slice(0, text.length - 1); + cur.ch = lineLength(cm, cur.line); + } else { + cur.ch = 0; + } + } else { + if (blockwise) { + text = text.split('\n'); + for (var i = 0; i < text.length; i++) { + text[i] = (text[i] == '') ? ' ' : text[i]; + } + } + cur.ch += actionArgs.after ? 1 : 0; + } + var curPosFinal; + var idx; + if (vim.visualMode) { + vim.lastPastedText = text; + var lastSelectionCurEnd; + var selectedArea = getSelectedAreaRange(cm, vim); + var selectionStart = selectedArea[0]; + var selectionEnd = selectedArea[1]; + var selectedText = cm.getSelection(); + var selections = cm.listSelections(); + var emptyStrings = new Array(selections.length).join('1').split('1'); + if (vim.lastSelection) { + lastSelectionCurEnd = vim.lastSelection.headMark.find(); + } + vimGlobalState.registerController.unnamedRegister.setText(selectedText); + if (blockwise) { + cm.replaceSelections(emptyStrings); + selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); + cm.setCursor(selectionStart); + selectBlock(cm, selectionEnd); + cm.replaceSelections(text); + curPosFinal = selectionStart; + } else if (vim.visualBlock) { + cm.replaceSelections(emptyStrings); + cm.setCursor(selectionStart); + cm.replaceRange(text, selectionStart, selectionStart); + curPosFinal = selectionStart; + } else { + cm.replaceRange(text, selectionStart, selectionEnd); + curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); + } + if(lastSelectionCurEnd) { + vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); + } + if (linewise) { + curPosFinal.ch=0; + } + } else { + if (blockwise) { + cm.setCursor(cur); + for (var i = 0; i < text.length; i++) { + var line = cur.line+i; + if (line > cm.lastLine()) { + cm.replaceRange('\n', Pos(line, 0)); + } + var lastCh = lineLength(cm, line); + if (lastCh < cur.ch) { + extendLineToColumn(cm, line, cur.ch); + } + } + cm.setCursor(cur); + selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); + cm.replaceSelections(text); + curPosFinal = cur; + } else { + cm.replaceRange(text, cur); + if (linewise && actionArgs.after) { + curPosFinal = Pos( + cur.line + 1, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); + } else if (linewise && !actionArgs.after) { + curPosFinal = Pos( + cur.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); + } else if (!linewise && actionArgs.after) { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length - 1); + } else { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length); + } + } + } + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curPosFinal); + }, + undo: function(cm, actionArgs) { + cm.operation(function() { + repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); + cm.setCursor(cm.getCursor('anchor')); + }); + }, + redo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); + }, + setRegister: function(_cm, actionArgs, vim) { + vim.inputState.registerName = actionArgs.selectedCharacter; + }, + setMark: function(cm, actionArgs, vim) { + var markName = actionArgs.selectedCharacter; + updateMark(cm, vim, markName, cm.getCursor()); + }, + replace: function(cm, actionArgs, vim) { + var replaceWith = actionArgs.selectedCharacter; + var curStart = cm.getCursor(); + var replaceTo; + var curEnd; + var selections = cm.listSelections(); + if (vim.visualMode) { + curStart = cm.getCursor('start'); + curEnd = cm.getCursor('end'); + } else { + var line = cm.getLine(curStart.line); + replaceTo = curStart.ch + actionArgs.repeat; + if (replaceTo > line.length) { + replaceTo=line.length; + } + curEnd = Pos(curStart.line, replaceTo); + } + if (replaceWith=='\n') { + if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); + (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); + } else { + var replaceWithStr = cm.getRange(curStart, curEnd); + replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); + if (vim.visualBlock) { + var spaces = new Array(cm.getOption("tabSize")+1).join(' '); + replaceWithStr = cm.getSelection(); + replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); + cm.replaceSelections(replaceWithStr); + } else { + cm.replaceRange(replaceWithStr, curStart, curEnd); + } + if (vim.visualMode) { + curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? + selections[0].anchor : selections[0].head; + cm.setCursor(curStart); + exitVisualMode(cm, false); + } else { + cm.setCursor(offsetCursor(curEnd, 0, -1)); + } + } + }, + incrementNumberToken: function(cm, actionArgs) { + var cur = cm.getCursor(); + var lineStr = cm.getLine(cur.line); + var re = /-?\d+/g; + var match; + var start; + var end; + var numberStr; + var token; + while ((match = re.exec(lineStr)) !== null) { + token = match[0]; + start = match.index; + end = start + token.length; + if (cur.ch < end)break; + } + if (!actionArgs.backtrack && (end <= cur.ch))return; + if (token) { + var increment = actionArgs.increase ? 1 : -1; + var number = parseInt(token) + (increment * actionArgs.repeat); + var from = Pos(cur.line, start); + var to = Pos(cur.line, end); + numberStr = number.toString(); + cm.replaceRange(numberStr, from, to); + } else { + return; + } + cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); + }, + repeatLastEdit: function(cm, actionArgs, vim) { + var lastEditInputState = vim.lastEditInputState; + if (!lastEditInputState) { return; } + var repeat = actionArgs.repeat; + if (repeat && actionArgs.repeatIsExplicit) { + vim.lastEditInputState.repeatOverride = repeat; + } else { + repeat = vim.lastEditInputState.repeatOverride || repeat; + } + repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); + }, + exitInsertMode: exitInsertMode + }; + + function defineAction(name, fn) { + actions[name] = fn; + } + function clipCursorToContent(cm, cur, includeLineBreak) { + var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); + var maxCh = lineLength(cm, line) - 1; + maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; + var ch = Math.min(Math.max(0, cur.ch), maxCh); + return Pos(line, ch); + } + function copyArgs(args) { + var ret = {}; + for (var prop in args) { + if (args.hasOwnProperty(prop)) { + ret[prop] = args[prop]; + } + } + return ret; + } + function offsetCursor(cur, offsetLine, offsetCh) { + if (typeof offsetLine === 'object') { + offsetCh = offsetLine.ch; + offsetLine = offsetLine.line; + } + return Pos(cur.line + offsetLine, cur.ch + offsetCh); + } + function getOffset(anchor, head) { + return { + line: head.line - anchor.line, + ch: head.line - anchor.line + }; + } + function commandMatches(keys, keyMap, context, inputState) { + var match, partial = [], full = []; + for (var i = 0; i < keyMap.length; i++) { + var command = keyMap[i]; + if (context == 'insert' && command.context != 'insert' || + command.context && command.context != context || + inputState.operator && command.type == 'action' || + !(match = commandMatch(keys, command.keys))) { continue; } + if (match == 'partial') { partial.push(command); } + if (match == 'full') { full.push(command); } + } + return { + partial: partial.length && partial, + full: full.length && full + }; + } + function commandMatch(pressed, mapped) { + if (mapped.slice(-11) == '') { + var prefixLen = mapped.length - 11; + var pressedPrefix = pressed.slice(0, prefixLen); + var mappedPrefix = mapped.slice(0, prefixLen); + return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : + mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; + } else { + return pressed == mapped ? 'full' : + mapped.indexOf(pressed) == 0 ? 'partial' : false; + } + } + function lastChar(keys) { + var match = /^.*(<[\w\-]+>)$/.exec(keys); + var selectedCharacter = match ? match[1] : keys.slice(-1); + if (selectedCharacter.length > 1){ + switch(selectedCharacter){ + case '': + selectedCharacter='\n'; + break; + case '': + selectedCharacter=' '; + break; + default: + break; + } + } + return selectedCharacter; + } + function repeatFn(cm, fn, repeat) { + return function() { + for (var i = 0; i < repeat; i++) { + fn(cm); + } + }; + } + function copyCursor(cur) { + return Pos(cur.line, cur.ch); + } + function cursorEqual(cur1, cur2) { + return cur1.ch == cur2.ch && cur1.line == cur2.line; + } + function cursorIsBefore(cur1, cur2) { + if (cur1.line < cur2.line) { + return true; + } + if (cur1.line == cur2.line && cur1.ch < cur2.ch) { + return true; + } + return false; + } + function cursorMin(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur1 : cur2; + } + function cursorMax(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur2 : cur1; + } + function cursorIsBetween(cur1, cur2, cur3) { + var cur1before2 = cursorIsBefore(cur1, cur2); + var cur2before3 = cursorIsBefore(cur2, cur3); + return cur1before2 && cur2before3; + } + function lineLength(cm, lineNum) { + return cm.getLine(lineNum).length; + } + function trim(s) { + if (s.trim) { + return s.trim(); + } + return s.replace(/^\s+|\s+$/g, ''); + } + function escapeRegex(s) { + return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); + } + function extendLineToColumn(cm, lineNum, column) { + var endCh = lineLength(cm, lineNum); + var spaces = new Array(column-endCh+1).join(' '); + cm.setCursor(Pos(lineNum, endCh)); + cm.replaceRange(spaces, cm.getCursor()); + } + function selectBlock(cm, selectionEnd) { + var selections = [], ranges = cm.listSelections(); + var head = copyCursor(cm.clipPos(selectionEnd)); + var isClipped = !cursorEqual(selectionEnd, head); + var curHead = cm.getCursor('head'); + var primIndex = getIndex(ranges, curHead); + var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); + var max = ranges.length - 1; + var index = max - primIndex > primIndex ? max : 0; + var base = ranges[index].anchor; + + var firstLine = Math.min(base.line, head.line); + var lastLine = Math.max(base.line, head.line); + var baseCh = base.ch, headCh = head.ch; + + var dir = ranges[index].head.ch - baseCh; + var newDir = headCh - baseCh; + if (dir > 0 && newDir <= 0) { + baseCh++; + if (!isClipped) { headCh--; } + } else if (dir < 0 && newDir >= 0) { + baseCh--; + if (!wasClipped) { headCh++; } + } else if (dir < 0 && newDir == -1) { + baseCh--; + headCh++; + } + for (var line = firstLine; line <= lastLine; line++) { + var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; + selections.push(range); + } + primIndex = head.line == lastLine ? selections.length - 1 : 0; + cm.setSelections(selections); + selectionEnd.ch = headCh; + base.ch = baseCh; + return base; + } + function selectForInsert(cm, head, height) { + var sel = []; + for (var i = 0; i < height; i++) { + var lineHead = offsetCursor(head, i, 0); + sel.push({anchor: lineHead, head: lineHead}); + } + cm.setSelections(sel, 0); + } + function getIndex(ranges, cursor, end) { + for (var i = 0; i < ranges.length; i++) { + var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); + var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); + if (atAnchor || atHead) { + return i; + } + } + return -1; + } + function getSelectedAreaRange(cm, vim) { + var lastSelection = vim.lastSelection; + var getCurrentSelectedAreaRange = function() { + var selections = cm.listSelections(); + var start = selections[0]; + var end = selections[selections.length-1]; + var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; + var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; + return [selectionStart, selectionEnd]; + }; + var getLastSelectedAreaRange = function() { + var selectionStart = cm.getCursor(); + var selectionEnd = cm.getCursor(); + var block = lastSelection.visualBlock; + if (block) { + var width = block.width; + var height = block.height; + selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); + var selections = []; + for (var i = selectionStart.line; i < selectionEnd.line; i++) { + var anchor = Pos(i, selectionStart.ch); + var head = Pos(i, selectionEnd.ch); + var range = {anchor: anchor, head: head}; + selections.push(range); + } + cm.setSelections(selections); + } else { + var start = lastSelection.anchorMark.find(); + var end = lastSelection.headMark.find(); + var line = end.line - start.line; + var ch = end.ch - start.ch; + selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; + if (lastSelection.visualLine) { + selectionStart = Pos(selectionStart.line, 0); + selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); + } + cm.setSelection(selectionStart, selectionEnd); + } + return [selectionStart, selectionEnd]; + }; + if (!vim.visualMode) { + return getLastSelectedAreaRange(); + } else { + return getCurrentSelectedAreaRange(); + } + } + function updateLastSelection(cm, vim) { + var anchor = vim.sel.anchor; + var head = vim.sel.head; + if (vim.lastPastedText) { + head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); + vim.lastPastedText = null; + } + vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), + 'headMark': cm.setBookmark(head), + 'anchor': copyCursor(anchor), + 'head': copyCursor(head), + 'visualMode': vim.visualMode, + 'visualLine': vim.visualLine, + 'visualBlock': vim.visualBlock}; + } + function expandSelection(cm, start, end) { + var sel = cm.state.vim.sel; + var head = sel.head; + var anchor = sel.anchor; + var tmp; + if (cursorIsBefore(end, start)) { + tmp = end; + end = start; + start = tmp; + } + if (cursorIsBefore(head, anchor)) { + head = cursorMin(start, head); + anchor = cursorMax(anchor, end); + } else { + anchor = cursorMin(start, anchor); + head = cursorMax(head, end); + head = offsetCursor(head, 0, -1); + if (head.ch == -1 && head.line != cm.firstLine()) { + head = Pos(head.line - 1, lineLength(cm, head.line - 1)); + } + } + return [anchor, head]; + } + function updateCmSelection(cm, sel, mode) { + var vim = cm.state.vim; + sel = sel || vim.sel; + var mode = mode || + vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; + var cmSel = makeCmSelection(cm, sel, mode); + cm.setSelections(cmSel.ranges, cmSel.primary); + updateFakeCursor(cm); + } + function makeCmSelection(cm, sel, mode, exclusive) { + var head = copyCursor(sel.head); + var anchor = copyCursor(sel.anchor); + if (mode == 'char') { + var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + head = offsetCursor(sel.head, 0, headOffset); + anchor = offsetCursor(sel.anchor, 0, anchorOffset); + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'line') { + if (!cursorIsBefore(sel.head, sel.anchor)) { + anchor.ch = 0; + + var lastLine = cm.lastLine(); + if (head.line > lastLine) { + head.line = lastLine; + } + head.ch = lineLength(cm, head.line); + } else { + head.ch = 0; + anchor.ch = lineLength(cm, anchor.line); + } + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'block') { + var top = Math.min(anchor.line, head.line), + left = Math.min(anchor.ch, head.ch), + bottom = Math.max(anchor.line, head.line), + right = Math.max(anchor.ch, head.ch) + 1; + var height = bottom - top + 1; + var primary = head.line == top ? 0 : height - 1; + var ranges = []; + for (var i = 0; i < height; i++) { + ranges.push({ + anchor: Pos(top + i, left), + head: Pos(top + i, right) + }); + } + return { + ranges: ranges, + primary: primary + }; + } + } + function getHead(cm) { + var cur = cm.getCursor('head'); + if (cm.getSelection().length == 1) { + cur = cursorMin(cur, cm.getCursor('anchor')); + } + return cur; + } + function exitVisualMode(cm, moveHead) { + var vim = cm.state.vim; + if (moveHead !== false) { + cm.setCursor(clipCursorToContent(cm, vim.sel.head)); + } + updateLastSelection(cm, vim); + vim.visualMode = false; + vim.visualLine = false; + vim.visualBlock = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + } + function clipToLine(cm, curStart, curEnd) { + var selection = cm.getRange(curStart, curEnd); + if (/\n\s*$/.test(selection)) { + var lines = selection.split('\n'); + lines.pop(); + var line; + for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { + curEnd.line--; + curEnd.ch = 0; + } + if (line) { + curEnd.line--; + curEnd.ch = lineLength(cm, curEnd.line); + } else { + curEnd.ch = 0; + } + } + } + function expandSelectionToLine(_cm, curStart, curEnd) { + curStart.ch = 0; + curEnd.ch = 0; + curEnd.line++; + } + + function findFirstNonWhiteSpaceCharacter(text) { + if (!text) { + return 0; + } + var firstNonWS = text.search(/\S/); + return firstNonWS == -1 ? text.length : firstNonWS; + } + + function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { + var cur = getHead(cm); + var line = cm.getLine(cur.line); + var idx = cur.ch; + var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; + while (!test(line.charAt(idx))) { + idx++; + if (idx >= line.length) { return null; } + } + + if (bigWord) { + test = bigWordCharTest[0]; + } else { + test = wordCharTest[0]; + if (!test(line.charAt(idx))) { + test = wordCharTest[1]; + } + } + + var end = idx, start = idx; + while (test(line.charAt(end)) && end < line.length) { end++; } + while (test(line.charAt(start)) && start >= 0) { start--; } + start++; + + if (inclusive) { + var wordEnd = end; + while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } + if (wordEnd == end) { + var wordStart = start; + while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } + if (!start) { start = wordStart; } + } + } + return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; + } + + function recordJumpPosition(cm, oldCur, newCur) { + if (!cursorEqual(oldCur, newCur)) { + vimGlobalState.jumpList.add(cm, oldCur, newCur); + } + } + + function recordLastCharacterSearch(increment, args) { + vimGlobalState.lastChararacterSearch.increment = increment; + vimGlobalState.lastChararacterSearch.forward = args.forward; + vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter; + } + + var symbolToMode = { + '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', + '[': 'section', ']': 'section', + '*': 'comment', '/': 'comment', + 'm': 'method', 'M': 'method', + '#': 'preprocess' + }; + var findSymbolModes = { + bracket: { + isComplete: function(state) { + if (state.nextCh === state.symb) { + state.depth++; + if (state.depth >= 1)return true; + } else if (state.nextCh === state.reverseSymb) { + state.depth--; + } + return false; + } + }, + section: { + init: function(state) { + state.curMoveThrough = true; + state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; + }, + isComplete: function(state) { + return state.index === 0 && state.nextCh === state.symb; + } + }, + comment: { + isComplete: function(state) { + var found = state.lastCh === '*' && state.nextCh === '/'; + state.lastCh = state.nextCh; + return found; + } + }, + method: { + init: function(state) { + state.symb = (state.symb === 'm' ? '{' : '}'); + state.reverseSymb = state.symb === '{' ? '}' : '{'; + }, + isComplete: function(state) { + if (state.nextCh === state.symb)return true; + return false; + } + }, + preprocess: { + init: function(state) { + state.index = 0; + }, + isComplete: function(state) { + if (state.nextCh === '#') { + var token = state.lineText.match(/#(\w+)/)[1]; + if (token === 'endif') { + if (state.forward && state.depth === 0) { + return true; + } + state.depth++; + } else if (token === 'if') { + if (!state.forward && state.depth === 0) { + return true; + } + state.depth--; + } + if (token === 'else' && state.depth === 0)return true; + } + return false; + } + } + }; + function findSymbol(cm, repeat, forward, symb) { + var cur = copyCursor(cm.getCursor()); + var increment = forward ? 1 : -1; + var endLine = forward ? cm.lineCount() : -1; + var curCh = cur.ch; + var line = cur.line; + var lineText = cm.getLine(line); + var state = { + lineText: lineText, + nextCh: lineText.charAt(curCh), + lastCh: null, + index: curCh, + symb: symb, + reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], + forward: forward, + depth: 0, + curMoveThrough: false + }; + var mode = symbolToMode[symb]; + if (!mode)return cur; + var init = findSymbolModes[mode].init; + var isComplete = findSymbolModes[mode].isComplete; + if (init) { init(state); } + while (line !== endLine && repeat) { + state.index += increment; + state.nextCh = state.lineText.charAt(state.index); + if (!state.nextCh) { + line += increment; + state.lineText = cm.getLine(line) || ''; + if (increment > 0) { + state.index = 0; + } else { + var lineLen = state.lineText.length; + state.index = (lineLen > 0) ? (lineLen-1) : 0; + } + state.nextCh = state.lineText.charAt(state.index); + } + if (isComplete(state)) { + cur.line = line; + cur.ch = state.index; + repeat--; + } + } + if (state.nextCh || state.curMoveThrough) { + return Pos(line, state.index); + } + return cur; + } + function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { + var lineNum = cur.line; + var pos = cur.ch; + var line = cm.getLine(lineNum); + var dir = forward ? 1 : -1; + var charTests = bigWord ? bigWordCharTest: wordCharTest; + + if (emptyLineIsWord && line == '') { + lineNum += dir; + line = cm.getLine(lineNum); + if (!isLine(cm, lineNum)) { + return null; + } + pos = (forward) ? 0 : line.length; + } + + while (true) { + if (emptyLineIsWord && line == '') { + return { from: 0, to: 0, line: lineNum }; + } + var stop = (dir > 0) ? line.length : -1; + var wordStart = stop, wordEnd = stop; + while (pos != stop) { + var foundWord = false; + for (var i = 0; i < charTests.length && !foundWord; ++i) { + if (charTests[i](line.charAt(pos))) { + wordStart = pos; + while (pos != stop && charTests[i](line.charAt(pos))) { + pos += dir; + } + wordEnd = pos; + foundWord = wordStart != wordEnd; + if (wordStart == cur.ch && lineNum == cur.line && + wordEnd == wordStart + dir) { + continue; + } else { + return { + from: Math.min(wordStart, wordEnd + 1), + to: Math.max(wordStart, wordEnd), + line: lineNum }; + } + } + } + if (!foundWord) { + pos += dir; + } + } + lineNum += dir; + if (!isLine(cm, lineNum)) { + return null; + } + line = cm.getLine(lineNum); + pos = (dir > 0) ? 0 : line.length; + } + throw new Error('The impossible happened.'); + } + function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { + var curStart = copyCursor(cur); + var words = []; + if (forward && !wordEnd || !forward && wordEnd) { + repeat++; + } + var emptyLineIsWord = !(forward && wordEnd); + for (var i = 0; i < repeat; i++) { + var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); + if (!word) { + var eodCh = lineLength(cm, cm.lastLine()); + words.push(forward + ? {line: cm.lastLine(), from: eodCh, to: eodCh} + : {line: 0, from: 0, to: 0}); + break; + } + words.push(word); + cur = Pos(word.line, forward ? (word.to - 1) : word.from); + } + var shortCircuit = words.length != repeat; + var firstWord = words[0]; + var lastWord = words.pop(); + if (forward && !wordEnd) { + if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.from); + } else if (forward && wordEnd) { + return Pos(lastWord.line, lastWord.to - 1); + } else if (!forward && wordEnd) { + if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.to); + } else { + return Pos(lastWord.line, lastWord.from); + } + } + + function moveToCharacter(cm, repeat, forward, character) { + var cur = cm.getCursor(); + var start = cur.ch; + var idx; + for (var i = 0; i < repeat; i ++) { + var line = cm.getLine(cur.line); + idx = charIdxInLine(start, line, character, forward, true); + if (idx == -1) { + return null; + } + start = idx; + } + return Pos(cm.getCursor().line, idx); + } + + function moveToColumn(cm, repeat) { + var line = cm.getCursor().line; + return clipCursorToContent(cm, Pos(line, repeat - 1)); + } + + function updateMark(cm, vim, markName, pos) { + if (!inArray(markName, validMarks)) { + return; + } + if (vim.marks[markName]) { + vim.marks[markName].clear(); + } + vim.marks[markName] = cm.setBookmark(pos); + } + + function charIdxInLine(start, line, character, forward, includeChar) { + var idx; + if (forward) { + idx = line.indexOf(character, start + 1); + if (idx != -1 && !includeChar) { + idx -= 1; + } + } else { + idx = line.lastIndexOf(character, start - 1); + if (idx != -1 && !includeChar) { + idx += 1; + } + } + return idx; + } + + function findParagraph(cm, head, repeat, dir, inclusive) { + var line = head.line; + var min = cm.firstLine(); + var max = cm.lastLine(); + var start, end, i = line; + function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch + function isBoundary(i, dir, any) { + if (any) { return isEmpty(i) != isEmpty(i + dir); } + return !isEmpty(i) && isEmpty(i + dir); + } + function skipFold(i) { + dir = dir > 0 ? 1 : -1; + var foldLine = cm.ace.session.getFoldLine(i); + if (foldLine) { + if (i + dir > foldLine.start.row && i + dir < foldLine.end.row) + dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i; + } + } + if (dir) { + while (min <= i && i <= max && repeat > 0) { + skipFold(i); + if (isBoundary(i, dir)) { repeat--; } + i += dir; + } + return new Pos(i, 0); + } + + var vim = cm.state.vim; + if (vim.visualLine && isBoundary(line, 1, true)) { + var anchor = vim.sel.anchor; + if (isBoundary(anchor.line, -1, true)) { + if (!inclusive || anchor.line != line) { + line += 1; + } + } + } + var startState = isEmpty(line); + for (i = line; i <= max && repeat; i++) { + if (isBoundary(i, 1, true)) { + if (!inclusive || isEmpty(i) != startState) { + repeat--; + } + } + } + end = new Pos(i, 0); + if (i > max && !startState) { startState = true; } + else { inclusive = false; } + for (i = line; i > min; i--) { + if (!inclusive || isEmpty(i) == startState || i == line) { + if (isBoundary(i, -1, true)) { break; } + } + } + start = new Pos(i, 0); + return { start: start, end: end }; + } + function selectCompanionObject(cm, head, symb, inclusive) { + var cur = head, start, end; + + var bracketRegexp = ({ + '(': /[()]/, ')': /[()]/, + '[': /[[\]]/, ']': /[[\]]/, + '{': /[{}]/, '}': /[{}]/})[symb]; + var openSym = ({ + '(': '(', ')': '(', + '[': '[', ']': '[', + '{': '{', '}': '{'})[symb]; + var curChar = cm.getLine(cur.line).charAt(cur.ch); + var offset = curChar === openSym ? 1 : 0; + + start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp}); + end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp}); + + if (!start || !end) { + return { start: cur, end: cur }; + } + + start = start.pos; + end = end.pos; + + if ((start.line == end.line && start.ch > end.ch) + || (start.line > end.line)) { + var tmp = start; + start = end; + end = tmp; + } + + if (inclusive) { + end.ch += 1; + } else { + start.ch += 1; + } + + return { start: start, end: end }; + } + function findBeginningAndEnd(cm, head, symb, inclusive) { + var cur = copyCursor(head); + var line = cm.getLine(cur.line); + var chars = line.split(''); + var start, end, i, len; + var firstIndex = chars.indexOf(symb); + if (cur.ch < firstIndex) { + cur.ch = firstIndex; + } + else if (firstIndex < cur.ch && chars[cur.ch] == symb) { + end = cur.ch; // assign end to the current cursor + --cur.ch; // make sure to look backwards + } + if (chars[cur.ch] == symb && !end) { + start = cur.ch + 1; // assign start to ahead of the cursor + } else { + for (i = cur.ch; i > -1 && !start; i--) { + if (chars[i] == symb) { + start = i + 1; + } + } + } + if (start && !end) { + for (i = start, len = chars.length; i < len && !end; i++) { + if (chars[i] == symb) { + end = i; + } + } + } + if (!start || !end) { + return { start: cur, end: cur }; + } + if (inclusive) { + --start; ++end; + } + + return { + start: Pos(cur.line, start), + end: Pos(cur.line, end) + }; + } + defineOption('pcre', true, 'boolean'); + function SearchState() {} + SearchState.prototype = { + getQuery: function() { + return vimGlobalState.query; + }, + setQuery: function(query) { + vimGlobalState.query = query; + }, + getOverlay: function() { + return this.searchOverlay; + }, + setOverlay: function(overlay) { + this.searchOverlay = overlay; + }, + isReversed: function() { + return vimGlobalState.isReversed; + }, + setReversed: function(reversed) { + vimGlobalState.isReversed = reversed; + }, + getScrollbarAnnotate: function() { + return this.annotate; + }, + setScrollbarAnnotate: function(annotate) { + this.annotate = annotate; + } + }; + function getSearchState(cm) { + var vim = cm.state.vim; + return vim.searchState_ || (vim.searchState_ = new SearchState()); + } + function dialog(cm, template, shortText, onClose, options) { + if (cm.openDialog) { + cm.openDialog(template, onClose, { bottom: true, value: options.value, + onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, + selectValueOnOpen: false}); + } + else { + onClose(prompt(shortText, '')); + } + } + function splitBySlash(argString) { + var slashes = findUnescapedSlashes(argString) || []; + if (!slashes.length) return []; + var tokens = []; + if (slashes[0] !== 0) return; + for (var i = 0; i < slashes.length; i++) { + if (typeof slashes[i] == 'number') + tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); + } + return tokens; + } + + function findUnescapedSlashes(str) { + var escapeNextChar = false; + var slashes = []; + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + if (!escapeNextChar && c == '/') { + slashes.push(i); + } + escapeNextChar = !escapeNextChar && (c == '\\'); + } + return slashes; + } + function translateRegex(str) { + var specials = '|(){'; + var unescape = '}'; + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + var specialComesNext = (n && specials.indexOf(n) != -1); + if (escapeNextChar) { + if (c !== '\\' || !specialComesNext) { + out.push(c); + } + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + if (n && unescape.indexOf(n) != -1) { + specialComesNext = true; + } + if (!specialComesNext || n === '\\') { + out.push(c); + } + } else { + out.push(c); + if (specialComesNext && n !== '\\') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function translateRegexReplace(str) { + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + if (charUnescapes[c + n]) { + out.push(charUnescapes[c+n]); + i++; + } else if (escapeNextChar) { + out.push(c); + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + if ((isNumber(n) || n === '$')) { + out.push('$'); + } else if (n !== '/' && n !== '\\') { + out.push('\\'); + } + } else { + if (c === '$') { + out.push('$'); + } + out.push(c); + if (n === '/') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function unescapeRegexReplace(str) { + var stream = new CodeMirror.StringStream(str); + var output = []; + while (!stream.eol()) { + while (stream.peek() && stream.peek() != '\\') { + output.push(stream.next()); + } + var matched = false; + for (var matcher in unescapes) { + if (stream.match(matcher, true)) { + matched = true; + output.push(unescapes[matcher]); + break; + } + } + if (!matched) { + output.push(stream.next()); + } + } + return output.join(''); + } + function parseQuery(query, ignoreCase, smartCase) { + var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); + lastSearchRegister.setText(query); + if (query instanceof RegExp) { return query; } + var slashes = findUnescapedSlashes(query); + var regexPart; + var forceIgnoreCase; + if (!slashes.length) { + regexPart = query; + } else { + regexPart = query.substring(0, slashes[0]); + var flagsPart = query.substring(slashes[0]); + forceIgnoreCase = (flagsPart.indexOf('i') != -1); + } + if (!regexPart) { + return null; + } + if (!getOption('pcre')) { + regexPart = translateRegex(regexPart); + } + if (smartCase) { + ignoreCase = (/^[^A-Z]*$/).test(regexPart); + } + var regexp = new RegExp(regexPart, + (ignoreCase || forceIgnoreCase) ? 'i' : undefined); + return regexp; + } + function showConfirm(cm, text) { + if (cm.openNotification) { + cm.openNotification('' + text + '', + {bottom: true, duration: 5000}); + } else { + alert(text); + } + } + function makePrompt(prefix, desc) { + var raw = ''; + if (prefix) { + raw += '' + prefix + ''; + } + raw += ' ' + + ''; + if (desc) { + raw += ''; + raw += desc; + raw += ''; + } + return raw; + } + var searchPromptDesc = '(Javascript regexp)'; + function showPrompt(cm, options) { + var shortText = (options.prefix || '') + ' ' + (options.desc || ''); + var prompt = makePrompt(options.prefix, options.desc); + dialog(cm, prompt, shortText, options.onClose, options); + } + function regexEqual(r1, r2) { + if (r1 instanceof RegExp && r2 instanceof RegExp) { + var props = ['global', 'multiline', 'ignoreCase', 'source']; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (r1[prop] !== r2[prop]) { + return false; + } + } + return true; + } + return false; + } + function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { + if (!rawQuery) { + return; + } + var state = getSearchState(cm); + var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); + if (!query) { + return; + } + highlightSearchMatches(cm, query); + if (regexEqual(query, state.getQuery())) { + return query; + } + state.setQuery(query); + return query; + } + function searchOverlay(query) { + if (query.source.charAt(0) == '^') { + var matchSol = true; + } + return { + token: function(stream) { + if (matchSol && !stream.sol()) { + stream.skipToEnd(); + return; + } + var match = stream.match(query, false); + if (match) { + if (match[0].length == 0) { + stream.next(); + return 'searching'; + } + if (!stream.sol()) { + stream.backUp(1); + if (!query.exec(stream.next() + match[0])) { + stream.next(); + return null; + } + } + stream.match(query); + return 'searching'; + } + while (!stream.eol()) { + stream.next(); + if (stream.match(query, false)) break; + } + }, + query: query + }; + } + function highlightSearchMatches(cm, query) { + var searchState = getSearchState(cm); + var overlay = searchState.getOverlay(); + if (!overlay || query != overlay.query) { + if (overlay) { + cm.removeOverlay(overlay); + } + overlay = searchOverlay(query); + cm.addOverlay(overlay); + if (cm.showMatchesOnScrollbar) { + if (searchState.getScrollbarAnnotate()) { + searchState.getScrollbarAnnotate().clear(); + } + searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); + } + searchState.setOverlay(overlay); + } + } + function findNext(cm, prev, query, repeat) { + if (repeat === undefined) { repeat = 1; } + return cm.operation(function() { + var pos = cm.getCursor(); + var cursor = cm.getSearchCursor(query, pos); + for (var i = 0; i < repeat; i++) { + var found = cursor.find(prev); + if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } + if (!found) { + cursor = cm.getSearchCursor(query, + (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); + if (!cursor.find(prev)) { + return; + } + } + } + return cursor.from(); + }); + } + function clearSearchHighlight(cm) { + var state = getSearchState(cm); + cm.removeOverlay(getSearchState(cm).getOverlay()); + state.setOverlay(null); + if (state.getScrollbarAnnotate()) { + state.getScrollbarAnnotate().clear(); + state.setScrollbarAnnotate(null); + } + } + function isInRange(pos, start, end) { + if (typeof pos != 'number') { + pos = pos.line; + } + if (start instanceof Array) { + return inArray(pos, start); + } else { + if (end) { + return (pos >= start && pos <= end); + } else { + return pos == start; + } + } + } + function getUserVisibleLines(cm) { + var renderer = cm.ace.renderer; + return { + top: renderer.getFirstFullyVisibleRow(), + bottom: renderer.getLastFullyVisibleRow() + } + } + + var ExCommandDispatcher = function() { + this.buildCommandMap_(); + }; + ExCommandDispatcher.prototype = { + processCommand: function(cm, input, opt_params) { + var that = this; + cm.operation(function () { + cm.curOp.isVimOp = true; + that._processCommand(cm, input, opt_params); + }); + }, + _processCommand: function(cm, input, opt_params) { + var vim = cm.state.vim; + var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); + var previousCommand = commandHistoryRegister.toString(); + if (vim.visualMode) { + exitVisualMode(cm); + } + var inputStream = new CodeMirror.StringStream(input); + commandHistoryRegister.setText(input); + var params = opt_params || {}; + params.input = input; + try { + this.parseInput_(cm, inputStream, params); + } catch(e) { + showConfirm(cm, e); + throw e; + } + var command; + var commandName; + if (!params.commandName) { + if (params.line !== undefined) { + commandName = 'move'; + } + } else { + command = this.matchCommand_(params.commandName); + if (command) { + commandName = command.name; + if (command.excludeFromCommandHistory) { + commandHistoryRegister.setText(previousCommand); + } + this.parseCommandArgs_(inputStream, params, command); + if (command.type == 'exToKey') { + for (var i = 0; i < command.toKeys.length; i++) { + CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); + } + return; + } else if (command.type == 'exToEx') { + this.processCommand(cm, command.toInput); + return; + } + } + } + if (!commandName) { + showConfirm(cm, 'Not an editor command ":' + input + '"'); + return; + } + try { + exCommands[commandName](cm, params); + if ((!command || !command.possiblyAsync) && params.callback) { + params.callback(); + } + } catch(e) { + showConfirm(cm, e); + throw e; + } + }, + parseInput_: function(cm, inputStream, result) { + inputStream.eatWhile(':'); + if (inputStream.eat('%')) { + result.line = cm.firstLine(); + result.lineEnd = cm.lastLine(); + } else { + result.line = this.parseLineSpec_(cm, inputStream); + if (result.line !== undefined && inputStream.eat(',')) { + result.lineEnd = this.parseLineSpec_(cm, inputStream); + } + } + var commandMatch = inputStream.match(/^(\w+)/); + if (commandMatch) { + result.commandName = commandMatch[1]; + } else { + result.commandName = inputStream.match(/.*/)[0]; + } + + return result; + }, + parseLineSpec_: function(cm, inputStream) { + var numberMatch = inputStream.match(/^(\d+)/); + if (numberMatch) { + return parseInt(numberMatch[1], 10) - 1; + } + switch (inputStream.next()) { + case '.': + return cm.getCursor().line; + case '$': + return cm.lastLine(); + case '\'': + var mark = cm.state.vim.marks[inputStream.next()]; + if (mark && mark.find()) { + return mark.find().line; + } + throw new Error('Mark not set'); + default: + inputStream.backUp(1); + return undefined; + } + }, + parseCommandArgs_: function(inputStream, params, command) { + if (inputStream.eol()) { + return; + } + params.argString = inputStream.match(/.*/)[0]; + var delim = command.argDelimiter || /\s+/; + var args = trim(params.argString).split(delim); + if (args.length && args[0]) { + params.args = args; + } + }, + matchCommand_: function(commandName) { + for (var i = commandName.length; i > 0; i--) { + var prefix = commandName.substring(0, i); + if (this.commandMap_[prefix]) { + var command = this.commandMap_[prefix]; + if (command.name.indexOf(commandName) === 0) { + return command; + } + } + } + return null; + }, + buildCommandMap_: function() { + this.commandMap_ = {}; + for (var i = 0; i < defaultExCommandMap.length; i++) { + var command = defaultExCommandMap[i]; + var key = command.shortName || command.name; + this.commandMap_[key] = command; + } + }, + map: function(lhs, rhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (rhs != ':' && rhs.charAt(0) == ':') { + this.commandMap_[commandName] = { + name: commandName, + type: 'exToEx', + toInput: rhs.substring(1), + user: true + }; + } else { + this.commandMap_[commandName] = { + name: commandName, + type: 'exToKey', + toKeys: rhs, + user: true + }; + } + } else { + if (rhs != ':' && rhs.charAt(0) == ':') { + var mapping = { + keys: lhs, + type: 'keyToEx', + exArgs: { input: rhs.substring(1) }, + user: true}; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } else { + var mapping = { + keys: lhs, + type: 'keyToKey', + toKeys: rhs, + user: true + }; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } + } + }, + unmap: function(lhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { + delete this.commandMap_[commandName]; + return; + } + } else { + var keys = lhs; + for (var i = 0; i < defaultKeymap.length; i++) { + if (keys == defaultKeymap[i].keys + && defaultKeymap[i].context === ctx + && defaultKeymap[i].user) { + defaultKeymap.splice(i, 1); + return; + } + } + } + } + }; + + var exCommands = { + colorscheme: function(cm, params) { + if (!params.args || params.args.length < 1) { + showConfirm(cm, cm.getOption('theme')); + return; + } + cm.setOption('theme', params.args[0]); + }, + map: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 2) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); + }, + imap: function(cm, params) { this.map(cm, params, 'insert'); }, + nmap: function(cm, params) { this.map(cm, params, 'normal'); }, + vmap: function(cm, params) { this.map(cm, params, 'visual'); }, + unmap: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 1) { + if (cm) { + showConfirm(cm, 'No such mapping: ' + params.input); + } + return; + } + exCommandDispatcher.unmap(mapArgs[0], ctx); + }, + move: function(cm, params) { + commandDispatcher.processCommand(cm, cm.state.vim, { + type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, + linewise: true }, + repeatOverride: params.line+1}); + }, + set: function(cm, params) { + var setArgs = params.args; + var setCfg = params.setCfg || {}; + if (!setArgs || setArgs.length < 1) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + var expr = setArgs[0].split('='); + var optionName = expr[0]; + var value = expr[1]; + var forceGet = false; + + if (optionName.charAt(optionName.length - 1) == '?') { + if (value) { throw Error('Trailing characters: ' + params.argString); } + optionName = optionName.substring(0, optionName.length - 1); + forceGet = true; + } + if (value === undefined && optionName.substring(0, 2) == 'no') { + optionName = optionName.substring(2); + value = false; + } + + var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; + if (optionIsBoolean && value == undefined) { + value = true; + } + if (!optionIsBoolean && value === undefined || forceGet) { + var oldValue = getOption(optionName, cm, setCfg); + if (oldValue === true || oldValue === false) { + showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); + } else { + showConfirm(cm, ' ' + optionName + '=' + oldValue); + } + } else { + setOption(optionName, value, cm, setCfg); + } + }, + setlocal: function (cm, params) { + params.setCfg = {scope: 'local'}; + this.set(cm, params); + }, + setglobal: function (cm, params) { + params.setCfg = {scope: 'global'}; + this.set(cm, params); + }, + registers: function(cm, params) { + var regArgs = params.args; + var registers = vimGlobalState.registerController.registers; + var regInfo = '----------Registers----------

'; + if (!regArgs) { + for (var registerName in registers) { + var text = registers[registerName].toString(); + if (text.length) { + regInfo += '"' + registerName + ' ' + text + '
'; + } + } + } else { + var registerName; + regArgs = regArgs.join(''); + for (var i = 0; i < regArgs.length; i++) { + registerName = regArgs.charAt(i); + if (!vimGlobalState.registerController.isValidRegister(registerName)) { + continue; + } + var register = registers[registerName] || new Register(); + regInfo += '"' + registerName + ' ' + register.toString() + '
'; + } + } + showConfirm(cm, regInfo); + }, + sort: function(cm, params) { + var reverse, ignoreCase, unique, number; + function parseArgs() { + if (params.argString) { + var args = new CodeMirror.StringStream(params.argString); + if (args.eat('!')) { reverse = true; } + if (args.eol()) { return; } + if (!args.eatSpace()) { return 'Invalid arguments'; } + var opts = args.match(/[a-z]+/); + if (opts) { + opts = opts[0]; + ignoreCase = opts.indexOf('i') != -1; + unique = opts.indexOf('u') != -1; + var decimal = opts.indexOf('d') != -1 && 1; + var hex = opts.indexOf('x') != -1 && 1; + var octal = opts.indexOf('o') != -1 && 1; + if (decimal + hex + octal > 1) { return 'Invalid arguments'; } + number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; + } + if (args.match(/\/.*\//)) { return 'patterns not supported'; } + } + } + var err = parseArgs(); + if (err) { + showConfirm(cm, err + ': ' + params.argString); + return; + } + var lineStart = params.line || cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + if (lineStart == lineEnd) { return; } + var curStart = Pos(lineStart, 0); + var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); + var text = cm.getRange(curStart, curEnd).split('\n'); + var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ : + (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : + (number == 'octal') ? /([0-7]+)/ : null; + var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; + var numPart = [], textPart = []; + if (number) { + for (var i = 0; i < text.length; i++) { + if (numberRegex.exec(text[i])) { + numPart.push(text[i]); + } else { + textPart.push(text[i]); + } + } + } else { + textPart = text; + } + function compareFn(a, b) { + if (reverse) { var tmp; tmp = a; a = b; b = tmp; } + if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } + var anum = number && numberRegex.exec(a); + var bnum = number && numberRegex.exec(b); + if (!anum) { return a < b ? -1 : 1; } + anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); + bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); + return anum - bnum; + } + numPart.sort(compareFn); + textPart.sort(compareFn); + text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); + if (unique) { // Remove duplicate lines + var textOld = text; + var lastLine; + text = []; + for (var i = 0; i < textOld.length; i++) { + if (textOld[i] != lastLine) { + text.push(textOld[i]); + } + lastLine = textOld[i]; + } + } + cm.replaceRange(text.join('\n'), curStart, curEnd); + }, + global: function(cm, params) { + var argString = params.argString; + if (!argString) { + showConfirm(cm, 'Regular Expression missing from global'); + return; + } + var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + var tokens = splitBySlash(argString); + var regexPart = argString, cmd; + if (tokens.length) { + regexPart = tokens[0]; + cmd = tokens.slice(1, tokens.length).join('/'); + } + if (regexPart) { + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + var query = getSearchState(cm).getQuery(); + var matchedLines = [], content = ''; + for (var i = lineStart; i <= lineEnd; i++) { + var matched = query.test(cm.getLine(i)); + if (matched) { + matchedLines.push(i+1); + content+= cm.getLine(i) + '
'; + } + } + if (!cmd) { + showConfirm(cm, content); + return; + } + var index = 0; + var nextCommand = function() { + if (index < matchedLines.length) { + var command = matchedLines[index] + cmd; + exCommandDispatcher.processCommand(cm, command, { + callback: nextCommand + }); + } + index++; + }; + nextCommand(); + }, + substitute: function(cm, params) { + if (!cm.getSearchCursor) { + throw new Error('Search feature not available. Requires searchcursor.js or ' + + 'any other getSearchCursor implementation.'); + } + var argString = params.argString; + var tokens = argString ? splitBySlash(argString) : []; + var regexPart, replacePart = '', trailing, flagsPart, count; + var confirm = false; // Whether to confirm each replace. + var global = false; // True to replace all instances on a line, false to replace only 1. + if (tokens.length) { + regexPart = tokens[0]; + replacePart = tokens[1]; + if (replacePart !== undefined) { + if (getOption('pcre')) { + replacePart = unescapeRegexReplace(replacePart); + } else { + replacePart = translateRegexReplace(replacePart); + } + vimGlobalState.lastSubstituteReplacePart = replacePart; + } + trailing = tokens[2] ? tokens[2].split(' ') : []; + } else { + if (argString && argString.length) { + showConfirm(cm, 'Substitutions should be of the form ' + + ':s/pattern/replace/'); + return; + } + } + if (trailing) { + flagsPart = trailing[0]; + count = parseInt(trailing[1]); + if (flagsPart) { + if (flagsPart.indexOf('c') != -1) { + confirm = true; + flagsPart.replace('c', ''); + } + if (flagsPart.indexOf('g') != -1) { + global = true; + flagsPart.replace('g', ''); + } + regexPart = regexPart + '/' + flagsPart; + } + } + if (regexPart) { + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; + if (replacePart === undefined) { + showConfirm(cm, 'No previous substitute regular expression'); + return; + } + var state = getSearchState(cm); + var query = state.getQuery(); + var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; + var lineEnd = params.lineEnd || lineStart; + if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { + lineEnd = Infinity; + } + if (count) { + lineStart = lineEnd; + lineEnd = lineStart + count - 1; + } + var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); + var cursor = cm.getSearchCursor(query, startPos); + doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); + }, + redo: CodeMirror.commands.redo, + undo: CodeMirror.commands.undo, + write: function(cm) { + if (CodeMirror.commands.save) { + CodeMirror.commands.save(cm); + } else { + cm.save(); + } + }, + nohlsearch: function(cm) { + clearSearchHighlight(cm); + }, + delmarks: function(cm, params) { + if (!params.argString || !trim(params.argString)) { + showConfirm(cm, 'Argument acequired'); + return; + } + + var state = cm.state.vim; + var stream = new CodeMirror.StringStream(trim(params.argString)); + while (!stream.eol()) { + stream.eatSpace(); + var count = stream.pos; + + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var sym = stream.next(); + if (stream.match('-', true)) { + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var startMark = sym; + var finishMark = stream.next(); + if (isLowerCase(startMark) && isLowerCase(finishMark) || + isUpperCase(startMark) && isUpperCase(finishMark)) { + var start = startMark.charCodeAt(0); + var finish = finishMark.charCodeAt(0); + if (start >= finish) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + for (var j = 0; j <= finish - start; j++) { + var mark = String.fromCharCode(start + j); + delete state.marks[mark]; + } + } else { + showConfirm(cm, 'Invalid argument: ' + startMark + '-'); + return; + } + } else { + delete state.marks[sym]; + } + } + } + }; + + var exCommandDispatcher = new ExCommandDispatcher(); + function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, + replaceWith, callback) { + cm.state.vim.exMode = true; + var done = false; + var lastPos = searchCursor.from(); + function replaceAll() { + cm.operation(function() { + while (!done) { + replace(); + next(); + } + stop(); + }); + } + function replace() { + var text = cm.getRange(searchCursor.from(), searchCursor.to()); + var newText = text.replace(query, replaceWith); + searchCursor.replace(newText); + } + function next() { + while(searchCursor.findNext() && + isInRange(searchCursor.from(), lineStart, lineEnd)) { + if (!global && lastPos && searchCursor.from().line == lastPos.line) { + continue; + } + cm.scrollIntoView(searchCursor.from(), 30); + cm.setSelection(searchCursor.from(), searchCursor.to()); + lastPos = searchCursor.from(); + done = false; + return; + } + done = true; + } + function stop(close) { + if (close) { close(); } + cm.focus(); + if (lastPos) { + cm.setCursor(lastPos); + var vim = cm.state.vim; + vim.exMode = false; + vim.lastHPos = vim.lastHSPos = lastPos.ch; + } + if (callback) { callback(); } + } + function onPromptKeyDown(e, _value, close) { + CodeMirror.e_stop(e); + var keyName = CodeMirror.keyName(e); + switch (keyName) { + case 'Y': + replace(); next(); break; + case 'N': + next(); break; + case 'A': + var savedCallback = callback; + callback = undefined; + cm.operation(replaceAll); + callback = savedCallback; + break; + case 'L': + replace(); + case 'Q': + case 'Esc': + case 'Ctrl-C': + case 'Ctrl-[': + stop(close); + break; + } + if (done) { stop(close); } + return true; + } + next(); + if (done) { + showConfirm(cm, 'No matches for ' + query.source); + return; + } + if (!confirm) { + replaceAll(); + if (callback) { callback(); } + return; + } + showPrompt(cm, { + prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', + onKeyDown: onPromptKeyDown + }); + } + + CodeMirror.keyMap.vim = { + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function exitInsertMode(cm) { + var vim = cm.state.vim; + var macroModeState = vimGlobalState.macroModeState; + var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); + var isPlaying = macroModeState.isPlaying; + var lastChange = macroModeState.lastInsertModeChanges; + var text = []; + if (!isPlaying) { + var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1; + var changes = lastChange.changes; + var text = []; + var i = 0; + while (i < changes.length) { + text.push(changes[i]); + if (changes[i] instanceof InsertModeKey) { + i++; + } else { + i+= selLength; + } + } + lastChange.changes = text; + cm.off('change', onChange); + CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (!isPlaying && vim.insertModeRepeat > 1) { + repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, + true /** repeatForInsert */); + vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; + } + delete vim.insertModeRepeat; + vim.insertMode = false; + cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); + cm.setOption('keyMap', 'vim'); + cm.setOption('disableInput', true); + cm.toggleOverwrite(false); // exit replace mode if we were in it. + insertModeChangeRegister.setText(lastChange.changes.join('')); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (macroModeState.isRecording) { + logInsertModeChange(macroModeState); + } + } + + function _mapCommand(command) { + defaultKeymap.unshift(command); + } + + function mapCommand(keys, type, name, args, extra) { + var command = {keys: keys, type: type}; + command[type] = name; + command[type + "Args"] = args; + for (var key in extra) + command[key] = extra[key]; + _mapCommand(command); + } + defineOption('insertModeEscKeysTimeout', 200, 'number'); + + CodeMirror.keyMap['vim-insert'] = { + 'Ctrl-N': 'autocomplete', + 'Ctrl-P': 'autocomplete', + 'Enter': function(cm) { + var fn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + fn(cm); + }, + fallthrough: ['default'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + CodeMirror.keyMap['vim-replace'] = { + 'Backspace': 'goCharLeft', + fallthrough: ['vim-insert'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function executeMacroRegister(cm, vim, macroModeState, registerName) { + var register = vimGlobalState.registerController.getRegister(registerName); + if (registerName == ':') { + if (register.keyBuffer[0]) { + exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); + } + macroModeState.isPlaying = false; + return; + } + var keyBuffer = register.keyBuffer; + var imc = 0; + macroModeState.isPlaying = true; + macroModeState.replaySearchQueries = register.searchQueries.slice(0); + for (var i = 0; i < keyBuffer.length; i++) { + var text = keyBuffer[i]; + var match, key; + while (text) { + match = (/<\w+-.+?>|<\w+>|./).exec(text); + key = match[0]; + text = text.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'macro'); + if (vim.insertMode) { + var changes = register.insertModeChanges[imc++].changes; + vimGlobalState.macroModeState.lastInsertModeChanges.changes = + changes; + repeatInsertModeChanges(cm, changes, 1); + exitInsertMode(cm); + } + } + } + macroModeState.isPlaying = false; + } + + function logKey(macroModeState, key) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.pushText(key); + } + } + + function logInsertModeChange(macroModeState) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushInsertModeChanges) { + register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); + } + } + + function logSearchQuery(macroModeState, query) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushSearchQuery) { + register.pushSearchQuery(query); + } + } + function onChange(_cm, changeObj) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + if (!macroModeState.isPlaying) { + while(changeObj) { + lastChange.expectCursorActivityForChange = true; + if (changeObj.origin == '+input' || changeObj.origin == 'paste' + || changeObj.origin === undefined /* only in testing */) { + var text = changeObj.text.join('\n'); + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + lastChange.changes.push(text); + } + changeObj = changeObj.next; + } + } + } + function onCursorActivity(cm) { + var vim = cm.state.vim; + if (vim.insertMode) { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + var lastChange = macroModeState.lastInsertModeChanges; + if (lastChange.expectCursorActivityForChange) { + lastChange.expectCursorActivityForChange = false; + } else { + lastChange.maybeReset = true; + } + } else if (!cm.curOp.isVimOp) { + handleExternalSelection(cm, vim); + } + if (vim.visualMode) { + updateFakeCursor(cm); + } + } + function updateFakeCursor(cm) { + var vim = cm.state.vim; + var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); + var to = offsetCursor(from, 0, 1); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); + } + function handleExternalSelection(cm, vim) { + var anchor = cm.getCursor('anchor'); + var head = cm.getCursor('head'); + if (vim.visualMode && !cm.somethingSelected()) { + exitVisualMode(cm, false); + } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { + vim.visualMode = true; + vim.visualLine = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); + } + if (vim.visualMode) { + var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; + var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; + head = offsetCursor(head, 0, headOffset); + anchor = offsetCursor(anchor, 0, anchorOffset); + vim.sel = { + anchor: anchor, + head: head + }; + updateMark(cm, vim, '<', cursorMin(head, anchor)); + updateMark(cm, vim, '>', cursorMax(head, anchor)); + } else if (!vim.insertMode) { + vim.lastHPos = cm.getCursor().ch; + } + } + function InsertModeKey(keyName) { + this.keyName = keyName; + } + function onKeyEventTargetKeyDown(e) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + var keyName = CodeMirror.keyName(e); + if (!keyName) { return; } + function onKeyFound() { + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + lastChange.changes.push(new InsertModeKey(keyName)); + return true; + } + if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { + CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); + } + } + function repeatLastEdit(cm, vim, repeat, repeatForInsert) { + var macroModeState = vimGlobalState.macroModeState; + macroModeState.isPlaying = true; + var isAction = !!vim.lastEditActionCommand; + var cachedInputState = vim.inputState; + function repeatCommand() { + if (isAction) { + commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); + } else { + commandDispatcher.evalInput(cm, vim); + } + } + function repeatInsert(repeat) { + if (macroModeState.lastInsertModeChanges.changes.length > 0) { + repeat = !vim.lastEditActionCommand ? 1 : repeat; + var changeObject = macroModeState.lastInsertModeChanges; + repeatInsertModeChanges(cm, changeObject.changes, repeat); + } + } + vim.inputState = vim.lastEditInputState; + if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { + for (var i = 0; i < repeat; i++) { + repeatCommand(); + repeatInsert(1); + } + } else { + if (!repeatForInsert) { + repeatCommand(); + } + repeatInsert(repeat); + } + vim.inputState = cachedInputState; + if (vim.insertMode && !repeatForInsert) { + exitInsertMode(cm); + } + macroModeState.isPlaying = false; + } + + function repeatInsertModeChanges(cm, changes, repeat) { + function keyHandler(binding) { + if (typeof binding == 'string') { + CodeMirror.commands[binding](cm); + } else { + binding(cm); + } + return true; + } + var head = cm.getCursor('head'); + var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; + if (inVisualBlock) { + var vim = cm.state.vim; + var lastSel = vim.lastSelection; + var offset = getOffset(lastSel.anchor, lastSel.head); + selectForInsert(cm, head, offset.line + 1); + repeat = cm.listSelections().length; + cm.setCursor(head); + } + for (var i = 0; i < repeat; i++) { + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, i, 0)); + } + for (var j = 0; j < changes.length; j++) { + var change = changes[j]; + if (change instanceof InsertModeKey) { + CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); + } else { + var cur = cm.getCursor(); + cm.replaceRange(change, cur, cur); + } + } + } + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, 0, 1)); + } + } + + resetVimGlobalState(); + CodeMirror.Vim = Vim(); + + Vim = CodeMirror.Vim; + + var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc', + left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space', + home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR' + }; + function lookupKey(hashId, key, e) { + if (key.length > 1 && key[0] == "n") { + key = key.replace("numpad", ""); + } + key = specialKey[key] || key; + var name = ''; + if (e.ctrlKey) { name += 'C-'; } + if (e.altKey) { name += 'A-'; } + if (e.shiftKey) { name += 'S-'; } + + name += key; + if (name.length > 1) { name = '<' + name + '>'; } + return name; + } + var handleKey = Vim.handleKey.bind(Vim); + Vim.handleKey = function(cm, key, origin) { + return cm.operation(function() { + return handleKey(cm, key, origin); + }, true); + } + function cloneVimState(state) { + var n = new state.constructor(); + Object.keys(state).forEach(function(key) { + var o = state[key]; + if (Array.isArray(o)) + o = o.slice(); + else if (o && typeof o == "object" && o.constructor != Object) + o = cloneVimState(o); + n[key] = o; + }); + if (state.sel) { + n.sel = { + head: state.sel.head && copyCursor(state.sel.head), + anchor: state.sel.anchor && copyCursor(state.sel.anchor) + }; + } + return n; + } + function multiSelectHandleKey(cm, key, origin) { + var isHandled = false; + var vim = Vim.maybeInitVimState_(cm); + var visualBlock = vim.visualBlock || vim.wasInVisualBlock; + if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) { + vim.wasInVisualBlock = false; + } else if (cm.ace.inMultiSelectMode && vim.visualBlock) { + vim.wasInVisualBlock = true; + } + + if (key == '' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) { + cm.ace.exitMultiSelectMode(); + } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) { + isHandled = Vim.handleKey(cm, key, origin); + } else { + var old = cloneVimState(vim); + cm.operation(function() { + cm.ace.forEachSelection(function() { + var sel = cm.ace.selection; + cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn; + var head = cm.getCursor("head"); + var anchor = cm.getCursor("anchor"); + var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; + var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; + head = offsetCursor(head, 0, headOffset); + anchor = offsetCursor(anchor, 0, anchorOffset); + cm.state.vim.sel.head = head; + cm.state.vim.sel.anchor = anchor; + + isHandled = handleKey(cm, key, origin); + sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos; + if (cm.virtualSelectionMode()) { + cm.state.vim = cloneVimState(old); + } + }); + if (cm.curOp.cursorActivity && !isHandled) + cm.curOp.cursorActivity = false; + }, true); + } + return isHandled; + } + exports.CodeMirror = CodeMirror; + var getVim = Vim.maybeInitVimState_; + exports.handler = { + $id: "ace/keyboard/vim", + drawCursor: function(style, pixelPos, config, sel, session) { + var vim = this.state.vim || {}; + var w = config.characterWidth; + var h = config.lineHeight; + var top = pixelPos.top; + var left = pixelPos.left; + if (!vim.insertMode) { + var isbackwards = !sel.cursor + ? session.selection.isBackwards() || session.selection.isEmpty() + : Range.comparePoints(sel.cursor, sel.start) <= 0; + if (!isbackwards && left > w) + left -= w; + } + if (!vim.insertMode && vim.status) { + h = h / 2; + top += h; + } + style.left = left + "px"; + style.top = top + "px"; + style.width = w + "px"; + style.height = h + "px"; + }, + handleKeyboard: function(data, hashId, key, keyCode, e) { + var editor = data.editor; + var cm = editor.state.cm; + var vim = getVim(cm); + if (keyCode == -1) return; + + if (key == "c" && hashId == 1) { // key == "ctrl-c" + if (!useragent.isMac && editor.getCopyText()) { + editor.once("copy", function() { + editor.selection.clearSelection(); + }); + return {command: "null", passEvent: true}; + } + } else if (!vim.insertMode) { + if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) { + hashId = -1; + key = data.inputChar; + } + } + + if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) { + var insertMode = vim.insertMode; + var name = lookupKey(hashId, key, e || {}); + if (vim.status == null) + vim.status = ""; + var isHandled = multiSelectHandleKey(cm, name, 'user'); + vim = getVim(cm); // may be changed by multiSelectHandleKey + if (isHandled && vim.status != null) + vim.status += name; + else if (vim.status == null) + vim.status = ""; + cm._signal("changeStatus"); + if (!isHandled && (hashId != -1 || insertMode)) + return; + return {command: "null", passEvent: !isHandled}; + } + }, + attach: function(editor) { + if (!editor.state) editor.state = {}; + var cm = new CodeMirror(editor); + editor.state.cm = cm; + editor.$vimModeHandler = this; + CodeMirror.keyMap.vim.attach(cm); + getVim(cm).status = null; + cm.on('vim-command-done', function() { + if (cm.virtualSelectionMode()) return; + getVim(cm).status = null; + cm.ace._signal("changeStatus"); + cm.ace.session.markUndoGroup(); + }); + cm.on("changeStatus", function() { + cm.ace.renderer.updateCursor(); + cm.ace._signal("changeStatus"); + }); + cm.on("vim-mode-change", function() { + if (cm.virtualSelectionMode()) return; + cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); + cm._signal("changeStatus"); + }); + cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); + editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm); + this.updateMacCompositionHandlers(editor, true); + }, + detach: function(editor) { + var cm = editor.state.cm; + CodeMirror.keyMap.vim.detach(cm); + cm.destroy(); + editor.state.cm = null; + editor.$vimModeHandler = null; + editor.renderer.$cursorLayer.drawCursor = null; + editor.renderer.setStyle("normal-mode", false); + this.updateMacCompositionHandlers(editor, false); + }, + getStatusText: function(editor) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (vim.insertMode) + return "INSERT"; + var status = ""; + if (vim.visualMode) { + status += "VISUAL"; + if (vim.visualLine) + status += " LINE"; + if (vim.visualBlock) + status += " BLOCK"; + } + if (vim.status) + status += (status ? " " : "") + vim.status; + return status; + }, + handleMacRepeat: function(data, hashId, key) { + if (hashId == -1) { + data.inputChar = key; + data.lastEvent = "input"; + } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { + if (data.lastEvent == "input") { + data.lastEvent = "input1"; + } else if (data.lastEvent == "input1") { + return true; + } + } else { + data.$lastHash = hashId; + data.$lastKey = key; + data.lastEvent = "keypress"; + } + }, + updateMacCompositionHandlers: function(editor, enable) { + var onCompositionUpdateOverride = function(text) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (!vim.insertMode) { + var el = this.textInput.getElement(); + el.blur(); + el.focus(); + el.value = text; + } else { + this.onCompositionUpdateOrig(text); + } + }; + var onCompositionStartOverride = function(text) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (!vim.insertMode) { + this.onCompositionStartOrig(text); + } + }; + if (enable) { + if (!editor.onCompositionUpdateOrig) { + editor.onCompositionUpdateOrig = editor.onCompositionUpdate; + editor.onCompositionUpdate = onCompositionUpdateOverride; + editor.onCompositionStartOrig = editor.onCompositionStart; + editor.onCompositionStart = onCompositionStartOverride; + } + } else { + if (editor.onCompositionUpdateOrig) { + editor.onCompositionUpdate = editor.onCompositionUpdateOrig; + editor.onCompositionUpdateOrig = null; + editor.onCompositionStart = editor.onCompositionStartOrig; + editor.onCompositionStartOrig = null; + } + } + } + }; + var renderVirtualNumbers = { + getText: function(session, row) { + return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + ""; + }, + getWidth: function(session, lastLineNumber, config) { + return session.getLength().toString().length * config.characterWidth; + }, + update: function(e, editor) { + editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER); + }, + attach: function(editor) { + editor.renderer.$gutterLayer.$renderer = this; + editor.on("changeSelection", this.update); + }, + detach: function(editor) { + editor.renderer.$gutterLayer.$renderer = null; + editor.off("changeSelection", this.update); + } + }; + Vim.defineOption({ + name: "wrap", + set: function(value, cm) { + if (cm) {cm.ace.setOption("wrap", value)} + }, + type: "boolean" + }, false); + Vim.defineEx('write', 'w', function() { + console.log(':write is not implemented') + }); + defaultKeymap.push( + { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } }, + { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } }, + { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } }, + { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } }, + { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } }, + { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } } + ); + actions.aceCommand = function(cm, actionArgs, vim) { + cm.vimCmd = actionArgs; + if (cm.ace.inVirtualSelectionMode) + cm.ace.on("beforeEndOperation", delayedExecAceCommand); + else + delayedExecAceCommand(null, cm.ace); + }; + function delayedExecAceCommand(op, ace) { + ace.off("beforeEndOperation", delayedExecAceCommand); + var cmd = ace.state.cm.vimCmd; + if (cmd) { + ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args); + } + ace.curOp = ace.prevOp; + } + actions.fold = function(cm, actionArgs, vim) { + cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall' + ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]); + }; + + exports.handler.defaultKeymap = defaultKeymap; + exports.handler.actions = actions; + exports.Vim = Vim; + + Vim.map("Y", "yy", "normal"); +}); + +},{}],208:[function(require,module,exports){ +ace.define("ace/mode/bro_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var BroHighlightRules = function() { + + this.$rules = { + start: [{ + token: "punctuation.definition.comment.bro", + regex: /#/, + push: [{ + token: "comment.line.number-sign.bro", + regex: /$/, + next: "pop" + }, { + defaultToken: "comment.line.number-sign.bro" + }] + }, { + token: "keyword.control.bro", + regex: /\b(?:break|case|continue|else|for|if|return|switch|next|when|timeout|schedule)\b/ + }, { + token: [ + "meta.function.bro", + "meta.function.bro", + "storage.type.bro", + "meta.function.bro", + "entity.name.function.bro", + "meta.function.bro" + ], + regex: /^(\s*)(?:function|hook|event)(\s*)(.*)(\s*\()(.*)(\).*$)/ + }, { + token: "storage.type.bro", + regex: /\b(?:bool|enum|double|int|count|port|addr|subnet|any|file|interval|time|string|table|vector|set|record|pattern|hook)\b/ + }, { + token: "storage.modifier.bro", + regex: /\b(?:global|const|redef|local|&(?:optional|rotate_interval|rotate_size|add_func|del_func|expire_func|expire_create|expire_read|expire_write|persistent|synchronized|encrypt|mergeable|priority|group|type_column|log|error_handler))\b/ + }, { + token: "keyword.operator.bro", + regex: /\s*(?:\||&&|(?:>|<|!)=?|==)\s*|\b!?in\b/ + }, { + token: "constant.language.bro", + regex: /\b(?:T|F)\b/ + }, { + token: "constant.numeric.bro", + regex: /\b(?:0(?:x|X)[0-9a-fA-F]*|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:(?:e|E)(?:\+|-)?[0-9]+)?)(?:\/(?:tcp|udp|icmp)|\s*(?:u?sec|min|hr|day)s?)?\b/ + }, { + token: "punctuation.definition.string.begin.bro", + regex: /"/, + push: [{ + token: "punctuation.definition.string.end.bro", + regex: /"/, + next: "pop" + }, { + include: "#string_escaped_char" + }, { + include: "#string_placeholder" + }, { + defaultToken: "string.quoted.double.bro" + }] + }, { + token: "punctuation.definition.string.begin.bro", + regex: /\//, + push: [{ + token: "punctuation.definition.string.end.bro", + regex: /\//, + next: "pop" + }, { + include: "#string_escaped_char" + }, { + include: "#string_placeholder" + }, { + defaultToken: "string.quoted.regex.bro" + }] + }, { + token: [ + "meta.preprocessor.bro.load", + "keyword.other.special-method.bro" + ], + regex: /^(\s*)(\@load(?:-sigs)?)\b/, + push: [{ + token: [], + regex: /(?=\#)|$/, + next: "pop" + }, { + defaultToken: "meta.preprocessor.bro.load" + }] + }, { + token: [ + "meta.preprocessor.bro.if", + "keyword.other.special-method.bro", + "meta.preprocessor.bro.if" + ], + regex: /^(\s*)(\@endif|\@if(?:n?def)?)(.*$)/, + push: [{ + token: [], + regex: /$/, + next: "pop" + }, { + defaultToken: "meta.preprocessor.bro.if" + }] + }], + "#disabled": [{ + token: "text", + regex: /^\s*\@if(?:n?def)?\b.*$/, + push: [{ + token: "text", + regex: /^\s*\@endif\b.*$/, + next: "pop" + }, { + include: "#disabled" + }, { + include: "#pragma-mark" + }], + comment: "eat nested preprocessor ifdefs" + }], + "#preprocessor-rule-other": [{ + token: [ + "text", + "meta.preprocessor.bro", + "meta.preprocessor.bro", + "text" + ], + regex: /^(\s*)(@if)((?:n?def)?)\b(.*?)(?:(?=)|$)/, + push: [{ + token: ["text", "meta.preprocessor.bro", "text"], + regex: /^(\s*)(@endif)\b(.*$)/, + next: "pop" + }, { + include: "$base" + }] + }], + "#string_escaped_char": [{ + token: "constant.character.escape.bro", + regex: /\\(?:\\|[abefnprtv'"?]|[0-3]\d{,2}|[4-7]\d?|x[a-fA-F0-9]{,2})/ + }, { + token: "invalid.illegal.unknown-escape.bro", + regex: /\\./ + }], + "#string_placeholder": [{ + token: "constant.other.placeholder.bro", + regex: /%(?:\d+\$)?[#0\- +']*[,;:_]?(?:-?\d+|\*(?:-?\d+\$)?)?(?:\.(?:-?\d+|\*(?:-?\d+\$)?)?)?(?:hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)?[diouxXDOUeEfFgGaACcSspn%]/ + }, { + token: "invalid.illegal.placeholder.bro", + regex: /%/ + }] + } + + this.normalizeRules(); +}; + +BroHighlightRules.metaData = { + fileTypes: ["bro"], + foldingStartMarker: "^(\\@if(n?def)?)", + foldingStopMarker: "^\\@endif", + keyEquivalent: "@B", + name: "Bro", + scopeName: "source.bro" +} + + +oop.inherits(BroHighlightRules, TextHighlightRules); + +exports.BroHighlightRules = BroHighlightRules; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/bro",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/bro_highlight_rules","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var BroHighlightRules = acequire("./bro_highlight_rules").BroHighlightRules; +var FoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = BroHighlightRules; + this.foldingRules = new FoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + this.$id = "ace/mode/bro" +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],209:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/c_cpp_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var cFunctions = exports.cFunctions = "\\b(?:hypot(?:f|l)?|s(?:scanf|ystem|nprintf|ca(?:nf|lb(?:n(?:f|l)?|ln(?:f|l)?))|i(?:n(?:h(?:f|l)?|f|l)?|gn(?:al|bit))|tr(?:s(?:tr|pn)|nc(?:py|at|mp)|c(?:spn|hr|oll|py|at|mp)|to(?:imax|d|u(?:l(?:l)?|max)|k|f|l(?:d|l)?)|error|pbrk|ftime|len|rchr|xfrm)|printf|et(?:jmp|vbuf|locale|buf)|qrt(?:f|l)?|w(?:scanf|printf)|rand)|n(?:e(?:arbyint(?:f|l)?|xt(?:toward(?:f|l)?|after(?:f|l)?))|an(?:f|l)?)|c(?:s(?:in(?:h(?:f|l)?|f|l)?|qrt(?:f|l)?)|cos(?:h(?:f)?|f|l)?|imag(?:f|l)?|t(?:ime|an(?:h(?:f|l)?|f|l)?)|o(?:s(?:h(?:f|l)?|f|l)?|nj(?:f|l)?|pysign(?:f|l)?)|p(?:ow(?:f|l)?|roj(?:f|l)?)|e(?:il(?:f|l)?|xp(?:f|l)?)|l(?:o(?:ck|g(?:f|l)?)|earerr)|a(?:sin(?:h(?:f|l)?|f|l)?|cos(?:h(?:f|l)?|f|l)?|tan(?:h(?:f|l)?|f|l)?|lloc|rg(?:f|l)?|bs(?:f|l)?)|real(?:f|l)?|brt(?:f|l)?)|t(?:ime|o(?:upper|lower)|an(?:h(?:f|l)?|f|l)?|runc(?:f|l)?|gamma(?:f|l)?|mp(?:nam|file))|i(?:s(?:space|n(?:ormal|an)|cntrl|inf|digit|u(?:nordered|pper)|p(?:unct|rint)|finite|w(?:space|c(?:ntrl|type)|digit|upper|p(?:unct|rint)|lower|al(?:num|pha)|graph|xdigit|blank)|l(?:ower|ess(?:equal|greater)?)|al(?:num|pha)|gr(?:eater(?:equal)?|aph)|xdigit|blank)|logb(?:f|l)?|max(?:div|abs))|di(?:v|fftime)|_Exit|unget(?:c|wc)|p(?:ow(?:f|l)?|ut(?:s|c(?:har)?|wc(?:har)?)|error|rintf)|e(?:rf(?:c(?:f|l)?|f|l)?|x(?:it|p(?:2(?:f|l)?|f|l|m1(?:f|l)?)?))|v(?:s(?:scanf|nprintf|canf|printf|w(?:scanf|printf))|printf|f(?:scanf|printf|w(?:scanf|printf))|w(?:scanf|printf)|a_(?:start|copy|end|arg))|qsort|f(?:s(?:canf|e(?:tpos|ek))|close|tell|open|dim(?:f|l)?|p(?:classify|ut(?:s|c|w(?:s|c))|rintf)|e(?:holdexcept|set(?:e(?:nv|xceptflag)|round)|clearexcept|testexcept|of|updateenv|r(?:aiseexcept|ror)|get(?:e(?:nv|xceptflag)|round))|flush|w(?:scanf|ide|printf|rite)|loor(?:f|l)?|abs(?:f|l)?|get(?:s|c|pos|w(?:s|c))|re(?:open|e|ad|xp(?:f|l)?)|m(?:in(?:f|l)?|od(?:f|l)?|a(?:f|l|x(?:f|l)?)?))|l(?:d(?:iv|exp(?:f|l)?)|o(?:ngjmp|cal(?:time|econv)|g(?:1(?:p(?:f|l)?|0(?:f|l)?)|2(?:f|l)?|f|l|b(?:f|l)?)?)|abs|l(?:div|abs|r(?:int(?:f|l)?|ound(?:f|l)?))|r(?:int(?:f|l)?|ound(?:f|l)?)|gamma(?:f|l)?)|w(?:scanf|c(?:s(?:s(?:tr|pn)|nc(?:py|at|mp)|c(?:spn|hr|oll|py|at|mp)|to(?:imax|d|u(?:l(?:l)?|max)|k|f|l(?:d|l)?|mbs)|pbrk|ftime|len|r(?:chr|tombs)|xfrm)|to(?:b|mb)|rtomb)|printf|mem(?:set|c(?:hr|py|mp)|move))|a(?:s(?:sert|ctime|in(?:h(?:f|l)?|f|l)?)|cos(?:h(?:f|l)?|f|l)?|t(?:o(?:i|f|l(?:l)?)|exit|an(?:h(?:f|l)?|2(?:f|l)?|f|l)?)|b(?:s|ort))|g(?:et(?:s|c(?:har)?|env|wc(?:har)?)|mtime)|r(?:int(?:f|l)?|ound(?:f|l)?|e(?:name|alloc|wind|m(?:ove|quo(?:f|l)?|ainder(?:f|l)?))|a(?:nd|ise))|b(?:search|towc)|m(?:odf(?:f|l)?|em(?:set|c(?:hr|py|mp)|move)|ktime|alloc|b(?:s(?:init|towcs|rtowcs)|towc|len|r(?:towc|len))))\\b" + +var c_cppHighlightRules = function() { + + var keywordControls = ( + "break|case|continue|default|do|else|for|goto|if|_Pragma|" + + "return|switch|while|catch|operator|try|throw|using" + ); + + var storageType = ( + "asm|__asm__|auto|bool|_Bool|char|_Complex|double|enum|float|" + + "_Imaginary|int|long|short|signed|struct|typedef|union|unsigned|void|" + + "class|wchar_t|template|char16_t|char32_t" + ); + + var storageModifiers = ( + "const|extern|register|restrict|static|volatile|inline|private|" + + "protected|public|friend|explicit|virtual|export|mutable|typename|" + + "constexpr|new|delete|alignas|alignof|decltype|noexcept|thread_local" + ); + + var keywordOperators = ( + "and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|typeid|xor|xor_eq" + + "const_cast|dynamic_cast|reinterpret_cast|static_cast|sizeof|namespace" + ); + + var builtinConstants = ( + "NULL|true|false|TRUE|FALSE|nullptr" + ); + + var keywordMapper = this.$keywords = this.createKeywordMapper({ + "keyword.control" : keywordControls, + "storage.type" : storageType, + "storage.modifier" : storageModifiers, + "keyword.operator" : keywordOperators, + "variable.language": "this", + "constant.language": builtinConstants + }, "identifier"); + + var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; + var escapeRe = /\\(?:['"?\\abfnrtv]|[0-7]{1,3}|x[a-fA-F\d]{2}|u[a-fA-F\d]{4}U[a-fA-F\d]{8}|.)/.source; + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "//$", + next : "start" + }, { + token : "comment", + regex : "//", + next : "singleLineComment" + }, + DocCommentHighlightRules.getStartRule("doc-start"), + { + token : "comment", // multi line comment + regex : "\\/\\*", + next : "comment" + }, { + token : "string", // character + regex : "'(?:" + escapeRe + "|.)?'" + }, { + token : "string.start", + regex : '"', + stateName: "qqstring", + next: [ + { token: "string", regex: /\\\s*$/, next: "qqstring" }, + { token: "constant.language.escape", regex: escapeRe }, + { token: "constant.language.escape", regex: /%[^'"\\]/ }, + { token: "string.end", regex: '"|$', next: "start" }, + { defaultToken: "string"} + ] + }, { + token : "string.start", + regex : 'R"\\(', + stateName: "rawString", + next: [ + { token: "string.end", regex: '\\)"', next: "start" }, + { defaultToken: "string"} + ] + }, { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F]+(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b" + }, { + token : "keyword", // pre-compiler directives + regex : "#\\s*(?:include|import|pragma|line|define|undef)\\b", + next : "directive" + }, { + token : "keyword", // special case pre-compiler directive + regex : "#\\s*(?:endif|if|ifdef|else|elif|ifndef)\\b" + }, { + token : "support.function.C99.c", + regex : cFunctions + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*" + }, { + token : "keyword.operator", + regex : /--|\+\+|<<=|>>=|>>>=|<>|&&|\|\||\?:|[*%\/+\-&\^|~!<>=]=?/ + }, { + token : "punctuation.operator", + regex : "\\?|\\:|\\,|\\;|\\." + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + regex : ".+" + } + ], + "singleLineComment" : [ + { + token : "comment", + regex : /\\$/, + next : "singleLineComment" + }, { + token : "comment", + regex : /$/, + next : "start" + }, { + defaultToken: "comment" + } + ], + "directive" : [ + { + token : "constant.other.multiline", + regex : /\\/ + }, + { + token : "constant.other.multiline", + regex : /.*\\/ + }, + { + token : "constant.other", + regex : "\\s*<.+?>", + next : "start" + }, + { + token : "constant.other", // single line + regex : '\\s*["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]', + next : "start" + }, + { + token : "constant.other", // single line + regex : "\\s*['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']", + next : "start" + }, + { + token : "constant.other", + regex : /[^\\\/]+/, + next : "start" + } + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("start") ]); + this.normalizeRules(); +}; + +oop.inherits(c_cppHighlightRules, TextHighlightRules); + +exports.c_cppHighlightRules = c_cppHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/c_cpp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/c_cpp_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var c_cppHighlightRules = acequire("./c_cpp_highlight_rules").c_cppHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var Range = acequire("../range").Range; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = c_cppHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.$id = "ace/mode/c_cpp"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],210:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/csharp_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var CSharpHighlightRules = function() { + var keywordMapper = this.createKeywordMapper({ + "variable.language": "this", + "keyword": "abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string|var|dynamic", + "constant.language": "null|true|false" + }, "identifier"); + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "\\/\\/.*$" + }, + DocCommentHighlightRules.getStartRule("doc-start"), + { + token : "comment", // multi line comment + regex : "\\/\\*", + next : "comment" + }, { + token : "string", // character + regex : /'(?:.|\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n]))'/ + }, { + token : "string", start : '"', end : '"|$', next: [ + {token: "constant.language.escape", regex: /\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n])/}, + {token: "invalid", regex: /\\./} + ] + }, { + token : "string", start : '@"', end : '"', next:[ + {token: "constant.language.escape", regex: '""'} + ] + }, { + token : "string", start : /\$"/, end : '"|$', next: [ + {token: "constant.language.escape", regex: /\\(:?$)|{{/}, + {token: "constant.language.escape", regex: /\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n])/}, + {token: "invalid", regex: /\\./} + ] + }, { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "constant.language.boolean", + regex : "(?:true|false)\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" + }, { + token : "keyword", + regex : "^\\s*#(if|else|elif|endif|define|undef|warning|error|line|region|endregion|pragma)" + }, { + token : "punctuation.operator", + regex : "\\?|\\:|\\,|\\;|\\." + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + regex : ".+" + } + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("start") ]); + this.normalizeRules(); +}; + +oop.inherits(CSharpHighlightRules, TextHighlightRules); + +exports.CSharpHighlightRules = CSharpHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/folding/csharp",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var CFoldMode = acequire("./cstyle").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, CFoldMode); + +(function() { + this.usingRe = /^\s*using \S/; + + this.getFoldWidgetRangeBase = this.getFoldWidgetRange; + this.getFoldWidgetBase = this.getFoldWidget; + + this.getFoldWidget = function(session, foldStyle, row) { + var fw = this.getFoldWidgetBase(session, foldStyle, row); + if (!fw) { + var line = session.getLine(row); + if (/^\s*#region\b/.test(line)) + return "start"; + var usingRe = this.usingRe; + if (usingRe.test(line)) { + var prev = session.getLine(row - 1); + var next = session.getLine(row + 1); + if (!usingRe.test(prev) && usingRe.test(next)) + return "start" + } + } + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var range = this.getFoldWidgetRangeBase(session, foldStyle, row); + if (range) + return range; + + var line = session.getLine(row); + if (this.usingRe.test(line)) + return this.getUsingStatementBlock(session, line, row); + + if (/^\s*#region\b/.test(line)) + return this.getRegionBlock(session, line, row); + }; + + this.getUsingStatementBlock = function(session, line, row) { + var startColumn = line.match(this.usingRe)[0].length - 1; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + line = session.getLine(row); + if (/^\s*$/.test(line)) + continue; + if (!this.usingRe.test(line)) + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + + this.getRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*#(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) + continue; + if (m[1]) + depth--; + else + depth++; + + if (!depth) + break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/csharp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/csharp_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/csharp"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var CSharpHighlightRules = acequire("./csharp_highlight_rules").CSharpHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/csharp").FoldMode; + +var Mode = function() { + this.HighlightRules = CSharpHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + + this.createWorker = function(session) { + return null; + }; + + this.$id = "ace/mode/csharp"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],211:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : "support.function.dom", + regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "support.constant", + regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start" || state == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/javascript"), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; +var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; +var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; +var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; +var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; + +var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; +var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; +var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|acequired|root|target|valid|visited)\\b"; + +var CssHighlightRules = function() { + + var keywordMapper = this.createKeywordMapper({ + "support.function": supportFunction, + "support.constant": supportConstant, + "support.type": supportType, + "support.constant.color": supportConstantColor, + "support.constant.fonts": supportConstantFonts + }, "text", true); + + this.$rules = { + "start" : [{ + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token: "paren.lparen", + regex: "\\{", + push: "ruleset" + }, { + token: "string", + regex: "@.*?{", + push: "media" + }, { + token: "keyword", + regex: "#[a-z0-9-_]+" + }, { + token: "variable", + regex: "\\.[a-z0-9-_]+" + }, { + token: "string", + regex: ":[a-z0-9-_]+" + }, { + token: "constant", + regex: "[a-z0-9-_]+" + }, { + caseInsensitive: true + }], + + "media" : [{ + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token: "paren.lparen", + regex: "\\{", + push: "ruleset" + }, { + token: "string", + regex: "\\}", + next: "pop" + }, { + token: "keyword", + regex: "#[a-z0-9-_]+" + }, { + token: "variable", + regex: "\\.[a-z0-9-_]+" + }, { + token: "string", + regex: ":[a-z0-9-_]+" + }, { + token: "constant", + regex: "[a-z0-9-_]+" + }, { + caseInsensitive: true + }], + + "comment" : [{ + token : "comment", + regex : "\\*\\/", + next : "pop" + }, { + defaultToken : "comment" + }], + + "ruleset" : [ + { + token : "paren.rparen", + regex : "\\}", + next: "pop" + }, { + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : "constant.numeric", + regex : numRe + }, { + token : "constant.numeric", // hex6 color + regex : "#[a-f0-9]{6}" + }, { + token : "constant.numeric", // hex3 color + regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses + }, { + token : ["support.function", "string", "support.function"], + regex : "(url\\()(.*)(\\))" + }, { + token : keywordMapper, + regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" + }, { + caseInsensitive: true + }] + }; + + this.normalizeRules(); +}; + +oop.inherits(CssHighlightRules, TextHighlightRules); + +exports.CssHighlightRules = CssHighlightRules; + +}); + +ace.define("ace/mode/css_completions",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var propertyMap = { + "background": {"#$0": 1}, + "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, + "background-image": {"url('/$0')": 1}, + "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, + "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, + "background-attachment": {"scroll": 1, "fixed": 1}, + "background-size": {"cover": 1, "contain": 1}, + "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, + "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, + "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, + "border-color": {"#$0": 1}, + "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, + "border-collapse": {"collapse": 1, "separate": 1}, + "bottom": {"px": 1, "em": 1, "%": 1}, + "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, + "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, + "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, + "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, + "empty-cells": {"show": 1, "hide": 1}, + "float": {"left": 1, "right": 1, "none": 1}, + "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, + "font-size": {"px": 1, "em": 1, "%": 1}, + "font-weight": {"bold": 1, "normal": 1}, + "font-style": {"italic": 1, "normal": 1}, + "font-variant": {"normal": 1, "small-caps": 1}, + "height": {"px": 1, "em": 1, "%": 1}, + "left": {"px": 1, "em": 1, "%": 1}, + "letter-spacing": {"normal": 1}, + "line-height": {"normal": 1}, + "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, + "margin": {"px": 1, "em": 1, "%": 1}, + "margin-right": {"px": 1, "em": 1, "%": 1}, + "margin-left": {"px": 1, "em": 1, "%": 1}, + "margin-top": {"px": 1, "em": 1, "%": 1}, + "margin-bottom": {"px": 1, "em": 1, "%": 1}, + "max-height": {"px": 1, "em": 1, "%": 1}, + "max-width": {"px": 1, "em": 1, "%": 1}, + "min-height": {"px": 1, "em": 1, "%": 1}, + "min-width": {"px": 1, "em": 1, "%": 1}, + "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "padding": {"px": 1, "em": 1, "%": 1}, + "padding-top": {"px": 1, "em": 1, "%": 1}, + "padding-right": {"px": 1, "em": 1, "%": 1}, + "padding-bottom": {"px": 1, "em": 1, "%": 1}, + "padding-left": {"px": 1, "em": 1, "%": 1}, + "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, + "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, + "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, + "right": {"px": 1, "em": 1, "%": 1}, + "table-layout": {"fixed": 1, "auto": 1}, + "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, + "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, + "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, + "top": {"px": 1, "em": 1, "%": 1}, + "vertical-align": {"top": 1, "bottom": 1}, + "visibility": {"hidden": 1, "visible": 1}, + "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, + "width": {"px": 1, "em": 1, "%": 1}, + "word-spacing": {"normal": 1}, + "filter": {"alpha(opacity=$0100)": 1}, + + "text-shadow": {"$02px 2px 2px #777": 1}, + "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, + "-moz-border-radius": 1, + "-moz-border-radius-topright": 1, + "-moz-border-radius-bottomright": 1, + "-moz-border-radius-topleft": 1, + "-moz-border-radius-bottomleft": 1, + "-webkit-border-radius": 1, + "-webkit-border-top-right-radius": 1, + "-webkit-border-top-left-radius": 1, + "-webkit-border-bottom-right-radius": 1, + "-webkit-border-bottom-left-radius": 1, + "-moz-box-shadow": 1, + "-webkit-box-shadow": 1, + "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, + "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, + "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } +}; + +var CssCompletions = function() { + +}; + +(function() { + + this.completionsDefined = false; + + this.defineCompletions = function() { + if (document) { + var style = document.createElement('c').style; + + for (var i in style) { + if (typeof style[i] !== 'string') + continue; + + var name = i.replace(/[A-Z]/g, function(x) { + return '-' + x.toLowerCase(); + }); + + if (!propertyMap.hasOwnProperty(name)) + propertyMap[name] = 1; + } + } + + this.completionsDefined = true; + } + + this.getCompletions = function(state, session, pos, prefix) { + if (!this.completionsDefined) { + this.defineCompletions(); + } + + var token = session.getTokenAt(pos.row, pos.column); + + if (!token) + return []; + if (state==='ruleset'){ + var line = session.getLine(pos.row).substr(0, pos.column); + if (/:[^;]+$/.test(line)) { + /([\w\-]+):[^:]*$/.test(line); + + return this.getPropertyValueCompletions(state, session, pos, prefix); + } else { + return this.getPropertyCompletions(state, session, pos, prefix); + } + } + + return []; + }; + + this.getPropertyCompletions = function(state, session, pos, prefix) { + var properties = Object.keys(propertyMap); + return properties.map(function(property){ + return { + caption: property, + snippet: property + ': $0', + meta: "property", + score: Number.MAX_VALUE + }; + }); + }; + + this.getPropertyValueCompletions = function(state, session, pos, prefix) { + var line = session.getLine(pos.row).substr(0, pos.column); + var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; + + if (!property) + return []; + var values = []; + if (property in propertyMap && typeof propertyMap[property] === "object") { + values = Object.keys(propertyMap[property]); + } + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "property value", + score: Number.MAX_VALUE + }; + }); + }; + +}).call(CssCompletions.prototype); + +exports.CssCompletions = CssCompletions; +}); + +ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var CstyleBehaviour = acequire("./cstyle").CstyleBehaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; + +var CssBehaviour = function () { + + this.inherit(CstyleBehaviour); + + this.add("colon", "insertion", function (state, action, editor, session, text) { + if (text === ':') { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + if (token && token.value.match(/\s+/)) { + token = iterator.stepBackward(); + } + if (token && token.type === 'support.type') { + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === ':') { + return { + text: '', + selection: [1, 1] + } + } + if (!line.substring(cursor.column).match(/^\s*;/)) { + return { + text: ':;', + selection: [1, 1] + } + } + } + } + }); + + this.add("colon", "deletion", function (state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected === ':') { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + if (token && token.value.match(/\s+/)) { + token = iterator.stepBackward(); + } + if (token && token.type === 'support.type') { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.end.column, range.end.column + 1); + if (rightChar === ';') { + range.end.column ++; + return range; + } + } + } + }); + + this.add("semicolon", "insertion", function (state, action, editor, session, text) { + if (text === ';') { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === ';') { + return { + text: '', + selection: [1, 1] + } + } + } + }); + +} +oop.inherits(CssBehaviour, CstyleBehaviour); + +exports.CssBehaviour = CssBehaviour; +}); + +ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var CssHighlightRules = acequire("./css_highlight_rules").CssHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CssCompletions = acequire("./css_completions").CssCompletions; +var CssBehaviour = acequire("./behaviour/css").CssBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = CssHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CssBehaviour(); + this.$completer = new CssCompletions(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.foldingRules = "cStyle"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + var tokens = this.getTokenizer().getLineTokens(line, state).tokens; + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + var match = line.match(/^.*\{\s*$/); + if (match) { + indent += tab; + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.getCompletions = function(state, session, pos, prefix) { + return this.$completer.getCompletions(state, session, pos, prefix); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/css"), "Worker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/css"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); + +ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var XmlHighlightRules = function(normalize) { + var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; + + this.$rules = { + start : [ + {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, + { + token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], + regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true + }, + { + token : ["punctuation.instruction.xml", "keyword.instruction.xml"], + regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" + }, + {token : "comment.xml", regex : "<\\!--", next : "comment"}, + { + token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], + regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true + }, + {include : "tag"}, + {token : "text.end-tag-open.xml", regex: "", + next : "start" + }], + + processing_instruction : [ + {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, + {defaultToken : "instruction.xml"} + ], + + doctype : [ + {include : "whitespace"}, + {include : "string"}, + {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, + {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, + {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} + ], + + int_subset : [{ + token : "text.xml", + regex : "\\s+" + }, { + token: "punctuation.int-subset.xml", + regex: "]", + next: "pop" + }, { + token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], + regex : "(<\\!)(" + tagRegex + ")", + push : [{ + token : "text", + regex : "\\s+" + }, + { + token : "punctuation.markup-decl.xml", + regex : ">", + next : "pop" + }, + {include : "string"}] + }], + + cdata : [ + {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, + {token : "text.xml", regex : "\\s+"}, + {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} + ], + + comment : [ + {token : "comment.xml", regex : "-->", next : "start"}, + {defaultToken : "comment.xml"} + ], + + reference : [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + attr_reference : [{ + token : "constant.language.escape.reference.attribute-value.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + tag : [{ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], + regex : "(?:(<)|(", next : "start"} + ] + }], + + tag_whitespace : [ + {token : "text.tag-whitespace.xml", regex : "\\s+"} + ], + whitespace : [ + {token : "text.whitespace.xml", regex : "\\s+"} + ], + string: [{ + token : "string.xml", + regex : "'", + push : [ + {token : "string.xml", regex: "'", next: "pop"}, + {defaultToken : "string.xml"} + ] + }, { + token : "string.xml", + regex : '"', + push : [ + {token : "string.xml", regex: '"', next: "pop"}, + {defaultToken : "string.xml"} + ] + }], + + attributes: [{ + token : "entity.other.attribute-name.xml", + regex : "(?:" + tagRegex + ":)?" + tagRegex + "" + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + include: "tag_whitespace" + }, { + include: "attribute_value" + }], + + attribute_value: [{ + token : "string.attribute-value.xml", + regex : "'", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }] + }; + + if (this.constructor === XmlHighlightRules) + this.normalizeRules(); +}; + + +(function() { + + this.embedTagRules = function(HighlightRules, prefix, tag){ + this.$rules.tag.unshift({ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(<)(" + tag + "(?=\\s|>|$))", + next: [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} + ] + }); + + this.$rules[tag + "-end"] = [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", + onMatch : function(value, currentState, stack) { + stack.splice(0); + return this.token; + }} + ] + + this.embedRules(HighlightRules, prefix, [{ + token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(|$))", + next: tag + "-end" + }, { + token: "string.cdata.xml", + regex : "<\\!\\[CDATA\\[" + }, { + token: "string.cdata.xml", + regex : "\\]\\]>" + }]); + }; + +}).call(TextHighlightRules.prototype); + +oop.inherits(XmlHighlightRules, TextHighlightRules); + +exports.XmlHighlightRules = XmlHighlightRules; +}); + +ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var CssHighlightRules = acequire("./css_highlight_rules").CssHighlightRules; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var XmlHighlightRules = acequire("./xml_highlight_rules").XmlHighlightRules; + +var tagMap = lang.createMap({ + a : 'anchor', + button : 'form', + form : 'form', + img : 'image', + input : 'form', + label : 'form', + option : 'form', + script : 'script', + select : 'form', + textarea : 'form', + style : 'style', + table : 'table', + tbody : 'table', + td : 'table', + tfoot : 'table', + th : 'table', + tr : 'table' +}); + +var HtmlHighlightRules = function() { + XmlHighlightRules.call(this); + + this.addRules({ + attributes: [{ + include : "tag_whitespace" + }, { + token : "entity.other.attribute-name.xml", + regex : "[-_a-zA-Z0-9:.]+" + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=", + push : [{ + include: "tag_whitespace" + }, { + token : "string.unquoted.attribute-value.html", + regex : "[^<>='\"`\\s]+", + next : "pop" + }, { + token : "empty", + regex : "", + next : "pop" + }] + }, { + include : "attribute_value" + }], + tag: [{ + token : function(start, tag) { + var group = tagMap[tag]; + return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", + "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; + }, + regex : "(", next : "start"} + ] + }); + + this.embedTagRules(CssHighlightRules, "css-", "style"); + this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); + + if (this.constructor === HtmlHighlightRules) + this.normalizeRules(); +}; + +oop.inherits(HtmlHighlightRules, XmlHighlightRules); + +exports.HtmlHighlightRules = HtmlHighlightRules; +}); + +ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +function is(token, type) { + return token.type.lastIndexOf(type + ".xml") > -1; +} + +var XmlBehaviour = function () { + + this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { + if (text == '"' || text == "'") { + var quote = text; + var selected = session.doc.getTextRange(editor.getSelectionRange()); + if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { + return { + text: quote + selected + quote, + selection: false + }; + } + + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { + return { + text: "", + selection: [1, 1] + }; + } + + if (!token) + token = iterator.stepBackward(); + + if (!token) + return; + + while (is(token, "tag-whitespace") || is(token, "whitespace")) { + token = iterator.stepBackward(); + } + var rightSpace = !rightChar || rightChar.match(/\s/); + if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { + return { + text: quote + quote, + selection: [1, 1] + }; + } + } + }); + + this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + + this.add("autoclosing", "insertion", function (state, action, editor, session, text) { + if (text == '>') { + var position = editor.getSelectionRange().start; + var iterator = new TokenIterator(session, position.row, position.column); + var token = iterator.getCurrentToken() || iterator.stepBackward(); + if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) + return; + if (is(token, "reference.attribute-value")) + return; + if (is(token, "attribute-value")) { + var firstChar = token.value.charAt(0); + if (firstChar == '"' || firstChar == "'") { + var lastChar = token.value.charAt(token.value.length - 1); + var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; + if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) + return; + } + } + while (!is(token, "tag-name")) { + token = iterator.stepBackward(); + if (token.value == "<") { + token = iterator.stepForward(); + break; + } + } + + var tokenRow = iterator.getCurrentTokenRow(); + var tokenColumn = iterator.getCurrentTokenColumn(); + if (is(iterator.stepBackward(), "end-tag-open")) + return; + + var element = token.value; + if (tokenRow == position.row) + element = element.substring(0, position.column - tokenColumn); + + if (this.voidElements.hasOwnProperty(element.toLowerCase())) + return; + + return { + text: ">" + "", + selection: [1, 1] + }; + } + }); + + this.add("autoindent", "insertion", function (state, action, editor, session, text) { + if (text == "\n") { + var cursor = editor.getCursorPosition(); + var line = session.getLine(cursor.row); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (token && token.type.indexOf("tag-close") !== -1) { + if (token.value == "/>") + return; + while (token && token.type.indexOf("tag-name") === -1) { + token = iterator.stepBackward(); + } + + if (!token) { + return; + } + + var tag = token.value; + var row = iterator.getCurrentTokenRow(); + token = iterator.stepBackward(); + if (!token || token.type.indexOf("end-tag") !== -1) { + return; + } + + if (this.voidElements && !this.voidElements[tag]) { + var nextToken = session.getTokenAt(cursor.row, cursor.column+1); + var line = session.getLine(row); + var nextIndent = this.$getIndent(line); + var indent = nextIndent + session.getTabString(); + + if (nextToken && nextToken.value === " -1; +} + +(function() { + + this.getFoldWidget = function(session, foldStyle, row) { + var tag = this._getFirstTagInLine(session, row); + + if (!tag) + return ""; + + if (tag.closing || (!tag.tagName && tag.selfClosing)) + return foldStyle == "markbeginend" ? "end" : ""; + + if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) + return ""; + + if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) + return ""; + + return "start"; + }; + this._getFirstTagInLine = function(session, row) { + var tokens = session.getTokens(row); + var tag = new Tag(); + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (is(token, "tag-open")) { + tag.end.column = tag.start.column + token.value.length; + tag.closing = is(token, "end-tag-open"); + token = tokens[++i]; + if (!token) + return null; + tag.tagName = token.value; + tag.end.column += token.value.length; + for (i++; i < tokens.length; i++) { + token = tokens[i]; + tag.end.column += token.value.length; + if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + break; + } + } + return tag; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + return tag; + } + tag.start.column += token.value.length; + } + + return null; + }; + + this._findEndTagInLine = function(session, row, tagName, startColumn) { + var tokens = session.getTokens(row); + var column = 0; + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + column += token.value.length; + if (column < startColumn) + continue; + if (is(token, "end-tag-open")) { + token = tokens[i + 1]; + if (token && token.value == tagName) + return true; + } + } + return false; + }; + this._readTagForward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + iterator.stepForward(); + return tag; + } + } while(token = iterator.stepForward()); + + return null; + }; + + this._readTagBackward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + iterator.stepBackward(); + return tag; + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + } + } while(token = iterator.stepBackward()); + + return null; + }; + + this._pop = function(stack, tag) { + while (stack.length) { + + var top = stack[stack.length-1]; + if (!tag || top.tagName == tag.tagName) { + return stack.pop(); + } + else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { + stack.pop(); + continue; + } else { + return null; + } + } + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var firstTag = this._getFirstTagInLine(session, row); + + if (!firstTag) + return null; + + var isBackward = firstTag.closing || firstTag.selfClosing; + var stack = []; + var tag; + + if (!isBackward) { + var iterator = new TokenIterator(session, row, firstTag.start.column); + var start = { + row: row, + column: firstTag.start.column + firstTag.tagName.length + 2 + }; + if (firstTag.start.row == firstTag.end.row) + start.column = firstTag.end.column; + while (tag = this._readTagForward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) + return Range.fromPoints(start, tag.start); + } + else { + stack.push(tag); + } + } + } + else { + var iterator = new TokenIterator(session, row, firstTag.end.column); + var end = { + row: row, + column: firstTag.start.column + }; + + while (tag = this._readTagBackward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (!tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) { + tag.start.column += tag.tagName.length + 2; + if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) + tag.start.column = tag.end.column; + return Range.fromPoints(tag.start, end); + } + } + else { + stack.push(tag); + } + } + } + + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var MixedFoldMode = acequire("./mixed").FoldMode; +var XmlFoldMode = acequire("./xml").FoldMode; +var CStyleFoldMode = acequire("./cstyle").FoldMode; + +var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { + MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { + "js-": new CStyleFoldMode(), + "css-": new CStyleFoldMode() + }); +}; + +oop.inherits(FoldMode, MixedFoldMode); + +}); + +ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var TokenIterator = acequire("../token_iterator").TokenIterator; + +var commonAttributes = [ + "accesskey", + "class", + "contenteditable", + "contextmenu", + "dir", + "draggable", + "dropzone", + "hidden", + "id", + "inert", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "lang", + "spellcheck", + "style", + "tabindex", + "title", + "translate" +]; + +var eventAttributes = [ + "onabort", + "onblur", + "oncancel", + "oncanplay", + "oncanplaythrough", + "onchange", + "onclick", + "onclose", + "oncontextmenu", + "oncuechange", + "ondblclick", + "ondrag", + "ondragend", + "ondragenter", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onended", + "onerror", + "onfocus", + "oninput", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeyup", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadstart", + "onmousedown", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onpause", + "onplay", + "onplaying", + "onprogress", + "onratechange", + "onreset", + "onscroll", + "onseeked", + "onseeking", + "onselect", + "onshow", + "onstalled", + "onsubmit", + "onsuspend", + "ontimeupdate", + "onvolumechange", + "onwaiting" +]; + +var globalAttributes = commonAttributes.concat(eventAttributes); + +var attributeMap = { + "html": {"manifest": 1}, + "head": {}, + "title": {}, + "base": {"href": 1, "target": 1}, + "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, + "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, + "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, + "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, + "noscript": {"href": 1}, + "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, + "section": {}, + "nav": {}, + "article": {"pubdate": 1}, + "aside": {}, + "h1": {}, + "h2": {}, + "h3": {}, + "h4": {}, + "h5": {}, + "h6": {}, + "header": {}, + "footer": {}, + "address": {}, + "main": {}, + "p": {}, + "hr": {}, + "pre": {}, + "blockquote": {"cite": 1}, + "ol": {"start": 1, "reversed": 1}, + "ul": {}, + "li": {"value": 1}, + "dl": {}, + "dt": {}, + "dd": {}, + "figure": {}, + "figcaption": {}, + "div": {}, + "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, + "em": {}, + "strong": {}, + "small": {}, + "s": {}, + "cite": {}, + "q": {"cite": 1}, + "dfn": {}, + "abbr": {}, + "data": {}, + "time": {"datetime": 1}, + "code": {}, + "var": {}, + "samp": {}, + "kbd": {}, + "sub": {}, + "sup": {}, + "i": {}, + "b": {}, + "u": {}, + "mark": {}, + "ruby": {}, + "rt": {}, + "rp": {}, + "bdi": {}, + "bdo": {}, + "span": {}, + "br": {}, + "wbr": {}, + "ins": {"cite": 1, "datetime": 1}, + "del": {"cite": 1, "datetime": 1}, + "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, + "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, + "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, + "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, + "param": {"name": 1, "value": 1}, + "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, + "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, + "source": {"src": 1, "type": 1, "media": 1}, + "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, + "canvas": {"width": 1, "height": 1}, + "map": {"name": 1}, + "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, + "svg": {}, + "math": {}, + "table": {"summary": 1}, + "caption": {}, + "colgroup": {"span": 1}, + "col": {"span": 1}, + "tbody": {}, + "thead": {}, + "tfoot": {}, + "tr": {}, + "td": {"headers": 1, "rowspan": 1, "colspan": 1}, + "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, + "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, + "fieldset": {"disabled": 1, "form": 1, "name": 1}, + "legend": {}, + "label": {"form": 1, "for": 1}, + "input": { + "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, + "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "acequired": {"acequired": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, + "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, + "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, + "datalist": {}, + "optgroup": {"disabled": 1, "label": 1}, + "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, + "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "acequired": {"acequired": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, + "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, + "output": {"for": 1, "form": 1, "name": 1}, + "progress": {"value": 1, "max": 1}, + "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, + "details": {"open": 1}, + "summary": {}, + "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, + "menu": {"type": 1, "label": 1}, + "dialog": {"open": 1} +}; + +var elements = Object.keys(attributeMap); + +function is(token, type) { + return token.type.lastIndexOf(type + ".xml") > -1; +} + +function findTagName(session, pos) { + var iterator = new TokenIterator(session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + while (token && !is(token, "tag-name")){ + token = iterator.stepBackward(); + } + if (token) + return token.value; +} + +function findAttributeName(session, pos) { + var iterator = new TokenIterator(session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + while (token && !is(token, "attribute-name")){ + token = iterator.stepBackward(); + } + if (token) + return token.value; +} + +var HtmlCompletions = function() { + +}; + +(function() { + + this.getCompletions = function(state, session, pos, prefix) { + var token = session.getTokenAt(pos.row, pos.column); + + if (!token) + return []; + if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) + return this.getTagCompletions(state, session, pos, prefix); + if (is(token, "tag-whitespace") || is(token, "attribute-name")) + return this.getAttributeCompletions(state, session, pos, prefix); + if (is(token, "attribute-value")) + return this.getAttributeValueCompletions(state, session, pos, prefix); + var line = session.getLine(pos.row).substr(0, pos.column); + if (/&[a-z]*$/i.test(line)) + return this.getHTMLEntityCompletions(state, session, pos, prefix); + + return []; + }; + + this.getTagCompletions = function(state, session, pos, prefix) { + return elements.map(function(element){ + return { + value: element, + meta: "tag", + score: Number.MAX_VALUE + }; + }); + }; + + this.getAttributeCompletions = function(state, session, pos, prefix) { + var tagName = findTagName(session, pos); + if (!tagName) + return []; + var attributes = globalAttributes; + if (tagName in attributeMap) { + attributes = attributes.concat(Object.keys(attributeMap[tagName])); + } + return attributes.map(function(attribute){ + return { + caption: attribute, + snippet: attribute + '="$0"', + meta: "attribute", + score: Number.MAX_VALUE + }; + }); + }; + + this.getAttributeValueCompletions = function(state, session, pos, prefix) { + var tagName = findTagName(session, pos); + var attributeName = findAttributeName(session, pos); + + if (!tagName) + return []; + var values = []; + if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { + values = Object.keys(attributeMap[tagName][attributeName]); + } + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "attribute value", + score: Number.MAX_VALUE + }; + }); + }; + + this.getHTMLEntityCompletions = function(state, session, pos, prefix) { + var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; + + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "html entity", + score: Number.MAX_VALUE + }; + }); + }; + +}).call(HtmlCompletions.prototype); + +exports.HtmlCompletions = HtmlCompletions; +}); + +ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextMode = acequire("./text").Mode; +var JavaScriptMode = acequire("./javascript").Mode; +var CssMode = acequire("./css").Mode; +var HtmlHighlightRules = acequire("./html_highlight_rules").HtmlHighlightRules; +var XmlBehaviour = acequire("./behaviour/xml").XmlBehaviour; +var HtmlFoldMode = acequire("./folding/html").FoldMode; +var HtmlCompletions = acequire("./html_completions").HtmlCompletions; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; +var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; + +var Mode = function(options) { + this.fragmentContext = options && options.fragmentContext; + this.HighlightRules = HtmlHighlightRules; + this.$behaviour = new XmlBehaviour(); + this.$completer = new HtmlCompletions(); + + this.createModeDelegates({ + "js-": JavaScriptMode, + "css-": CssMode + }); + + this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.blockComment = {start: ""}; + + this.voidElements = lang.arrayToMap(voidElements); + + this.getNextLineIndent = function(state, line, tab) { + return this.$getIndent(line); + }; + + this.checkOutdent = function(state, line, input) { + return false; + }; + + this.getCompletions = function(state, session, pos, prefix) { + return this.$completer.getCompletions(state, session, pos, prefix); + }; + + this.createWorker = function(session) { + if (this.constructor != Mode) + return; + var worker = new WorkerClient(["ace"], require("../worker/html"), "Worker"); + worker.attachToDocument(session.getDocument()); + + if (this.fragmentContext) + worker.call("setOptions", [{context: this.fragmentContext}]); + + worker.on("error", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/html"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/css":234,"../worker/html":235,"../worker/javascript":236}],212:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : "support.function.dom", + regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "support.constant", + regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start" || state == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/javascript"), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/mode/java_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var JavaHighlightRules = function() { + var keywords = ( + "abstract|continue|for|new|switch|" + + "assert|default|goto|package|synchronized|" + + "boolean|do|if|private|this|" + + "break|double|implements|protected|throw|" + + "byte|else|import|public|throws|" + + "case|enum|instanceof|return|transient|" + + "catch|extends|int|short|try|" + + "char|final|interface|static|void|" + + "class|finally|long|strictfp|volatile|" + + "const|float|native|super|while" + ); + + var buildinConstants = ("null|Infinity|NaN|undefined"); + + + var langClasses = ( + "AbstractMethodError|AssertionError|ClassCircularityError|"+ + "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ + "ExceptionInInitializerError|IllegalAccessError|"+ + "IllegalThreadStateException|InstantiationError|InternalError|"+ + "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ + "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ + "SuppressWarnings|TypeNotPresentException|UnknownError|"+ + "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ + "InstantiationException|IndexOutOfBoundsException|"+ + "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ + "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ + "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ + "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ + "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ + "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ + "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ + "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ + "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ + "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ + "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ + "ArrayStoreException|ClassCastException|LinkageError|"+ + "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ + "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ + "Cloneable|Class|CharSequence|Comparable|String|Object" + ); + + var keywordMapper = this.createKeywordMapper({ + "variable.language": "this", + "keyword": keywords, + "constant.language": buildinConstants, + "support.function": langClasses + }, "identifier"); + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "\\/\\/.*$" + }, + DocCommentHighlightRules.getStartRule("doc-start"), + { + token : "comment", // multi line comment + regex : "\\/\\*", + next : "comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F][0-9a-fA-F_]*|[bB][01][01_]*)[LlSsDdFfYy]?\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.[\d_]*)?(?:[eE][+-]?[\d_]+)?)?[LlSsDdFfYy]?\b/ + }, { + token : "constant.language.boolean", + regex : "(?:true|false)\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" + }, { + token : "lparen", + regex : "[[({]" + }, { + token : "rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + regex : ".+" + } + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("start") ]); +}; + +oop.inherits(JavaHighlightRules, TextHighlightRules); + +exports.JavaHighlightRules = JavaHighlightRules; +}); + +ace.define("ace/mode/java",["require","exports","module","ace/lib/oop","ace/mode/javascript","ace/mode/java_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var JavaScriptMode = acequire("./javascript").Mode; +var JavaHighlightRules = acequire("./java_highlight_rules").JavaHighlightRules; + +var Mode = function() { + JavaScriptMode.call(this); + this.HighlightRules = JavaHighlightRules; +}; +oop.inherits(Mode, JavaScriptMode); + +(function() { + + this.createWorker = function(session) { + return null; + }; + + this.$id = "ace/mode/java"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/javascript":236}],213:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : "support.function.dom", + regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "support.constant", + regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start" || state == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/javascript"), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/javascript":236}],214:[function(require,module,exports){ +ace.define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var JsonHighlightRules = function() { + this.$rules = { + "start" : [ + { + token : "variable", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)' + }, { + token : "string", // single line + regex : '"', + next : "string" + }, { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "constant.language.boolean", + regex : "(?:true|false)\\b" + }, { + token : "invalid.illegal", // single quoted strings are not allowed + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "invalid.illegal", // comments are not allowed + regex : "\\/\\/.*$" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "string" : [ + { + token : "constant.language.escape", + regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|["\\\/bfnrt])/ + }, { + token : "string", + regex : '[^"\\\\]+' + }, { + token : "string", + regex : '"', + next : "start" + }, { + token : "string", + regex : "", + next : "start" + } + ] + }; + +}; + +oop.inherits(JsonHighlightRules, TextHighlightRules); + +exports.JsonHighlightRules = JsonHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var HighlightRules = acequire("./json_highlight_rules").JsonHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; + +var Mode = function() { + this.HighlightRules = HighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/json"), "JsonWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + + this.$id = "ace/mode/json"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/json":237}],215:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ + }, { + token : "support.function.dom", + regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "support.constant", + regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ + }, { + token : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + var endState = tokenizedLine.state; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start" || state == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + return ""; + } + var match = line.match(/^\s*(\/?)\*/); + if (match) { + if (match[1]) { + indent += " "; + } + indent += "* "; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/javascript"), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var XmlHighlightRules = function(normalize) { + var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; + + this.$rules = { + start : [ + {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, + { + token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], + regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true + }, + { + token : ["punctuation.instruction.xml", "keyword.instruction.xml"], + regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" + }, + {token : "comment.xml", regex : "<\\!--", next : "comment"}, + { + token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], + regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true + }, + {include : "tag"}, + {token : "text.end-tag-open.xml", regex: "", + next : "start" + }], + + processing_instruction : [ + {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, + {defaultToken : "instruction.xml"} + ], + + doctype : [ + {include : "whitespace"}, + {include : "string"}, + {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, + {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, + {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} + ], + + int_subset : [{ + token : "text.xml", + regex : "\\s+" + }, { + token: "punctuation.int-subset.xml", + regex: "]", + next: "pop" + }, { + token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], + regex : "(<\\!)(" + tagRegex + ")", + push : [{ + token : "text", + regex : "\\s+" + }, + { + token : "punctuation.markup-decl.xml", + regex : ">", + next : "pop" + }, + {include : "string"}] + }], + + cdata : [ + {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, + {token : "text.xml", regex : "\\s+"}, + {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} + ], + + comment : [ + {token : "comment.xml", regex : "-->", next : "start"}, + {defaultToken : "comment.xml"} + ], + + reference : [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + attr_reference : [{ + token : "constant.language.escape.reference.attribute-value.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + tag : [{ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], + regex : "(?:(<)|(", next : "start"} + ] + }], + + tag_whitespace : [ + {token : "text.tag-whitespace.xml", regex : "\\s+"} + ], + whitespace : [ + {token : "text.whitespace.xml", regex : "\\s+"} + ], + string: [{ + token : "string.xml", + regex : "'", + push : [ + {token : "string.xml", regex: "'", next: "pop"}, + {defaultToken : "string.xml"} + ] + }, { + token : "string.xml", + regex : '"', + push : [ + {token : "string.xml", regex: '"', next: "pop"}, + {defaultToken : "string.xml"} + ] + }], + + attributes: [{ + token : "entity.other.attribute-name.xml", + regex : "(?:" + tagRegex + ":)?" + tagRegex + "" + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + include: "tag_whitespace" + }, { + include: "attribute_value" + }], + + attribute_value: [{ + token : "string.attribute-value.xml", + regex : "'", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }] + }; + + if (this.constructor === XmlHighlightRules) + this.normalizeRules(); +}; + + +(function() { + + this.embedTagRules = function(HighlightRules, prefix, tag){ + this.$rules.tag.unshift({ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(<)(" + tag + "(?=\\s|>|$))", + next: [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} + ] + }); + + this.$rules[tag + "-end"] = [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", + onMatch : function(value, currentState, stack) { + stack.splice(0); + return this.token; + }} + ] + + this.embedRules(HighlightRules, prefix, [{ + token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(|$))", + next: tag + "-end" + }, { + token: "string.cdata.xml", + regex : "<\\!\\[CDATA\\[" + }, { + token: "string.cdata.xml", + regex : "\\]\\]>" + }]); + }; + +}).call(TextHighlightRules.prototype); + +oop.inherits(XmlHighlightRules, TextHighlightRules); + +exports.XmlHighlightRules = XmlHighlightRules; +}); + +ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +function is(token, type) { + return token.type.lastIndexOf(type + ".xml") > -1; +} + +var XmlBehaviour = function () { + + this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { + if (text == '"' || text == "'") { + var quote = text; + var selected = session.doc.getTextRange(editor.getSelectionRange()); + if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { + return { + text: quote + selected + quote, + selection: false + }; + } + + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { + return { + text: "", + selection: [1, 1] + }; + } + + if (!token) + token = iterator.stepBackward(); + + if (!token) + return; + + while (is(token, "tag-whitespace") || is(token, "whitespace")) { + token = iterator.stepBackward(); + } + var rightSpace = !rightChar || rightChar.match(/\s/); + if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { + return { + text: quote + quote, + selection: [1, 1] + }; + } + } + }); + + this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + + this.add("autoclosing", "insertion", function (state, action, editor, session, text) { + if (text == '>') { + var position = editor.getSelectionRange().start; + var iterator = new TokenIterator(session, position.row, position.column); + var token = iterator.getCurrentToken() || iterator.stepBackward(); + if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) + return; + if (is(token, "reference.attribute-value")) + return; + if (is(token, "attribute-value")) { + var firstChar = token.value.charAt(0); + if (firstChar == '"' || firstChar == "'") { + var lastChar = token.value.charAt(token.value.length - 1); + var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; + if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) + return; + } + } + while (!is(token, "tag-name")) { + token = iterator.stepBackward(); + if (token.value == "<") { + token = iterator.stepForward(); + break; + } + } + + var tokenRow = iterator.getCurrentTokenRow(); + var tokenColumn = iterator.getCurrentTokenColumn(); + if (is(iterator.stepBackward(), "end-tag-open")) + return; + + var element = token.value; + if (tokenRow == position.row) + element = element.substring(0, position.column - tokenColumn); + + if (this.voidElements.hasOwnProperty(element.toLowerCase())) + return; + + return { + text: ">" + "", + selection: [1, 1] + }; + } + }); + + this.add("autoindent", "insertion", function (state, action, editor, session, text) { + if (text == "\n") { + var cursor = editor.getCursorPosition(); + var line = session.getLine(cursor.row); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (token && token.type.indexOf("tag-close") !== -1) { + if (token.value == "/>") + return; + while (token && token.type.indexOf("tag-name") === -1) { + token = iterator.stepBackward(); + } + + if (!token) { + return; + } + + var tag = token.value; + var row = iterator.getCurrentTokenRow(); + token = iterator.stepBackward(); + if (!token || token.type.indexOf("end-tag") !== -1) { + return; + } + + if (this.voidElements && !this.voidElements[tag]) { + var nextToken = session.getTokenAt(cursor.row, cursor.column+1); + var line = session.getLine(row); + var nextIndent = this.$getIndent(line); + var indent = nextIndent + session.getTabString(); + + if (nextToken && nextToken.value === " -1; +} + +(function() { + + this.getFoldWidget = function(session, foldStyle, row) { + var tag = this._getFirstTagInLine(session, row); + + if (!tag) + return ""; + + if (tag.closing || (!tag.tagName && tag.selfClosing)) + return foldStyle == "markbeginend" ? "end" : ""; + + if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) + return ""; + + if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) + return ""; + + return "start"; + }; + this._getFirstTagInLine = function(session, row) { + var tokens = session.getTokens(row); + var tag = new Tag(); + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (is(token, "tag-open")) { + tag.end.column = tag.start.column + token.value.length; + tag.closing = is(token, "end-tag-open"); + token = tokens[++i]; + if (!token) + return null; + tag.tagName = token.value; + tag.end.column += token.value.length; + for (i++; i < tokens.length; i++) { + token = tokens[i]; + tag.end.column += token.value.length; + if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + break; + } + } + return tag; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + return tag; + } + tag.start.column += token.value.length; + } + + return null; + }; + + this._findEndTagInLine = function(session, row, tagName, startColumn) { + var tokens = session.getTokens(row); + var column = 0; + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + column += token.value.length; + if (column < startColumn) + continue; + if (is(token, "end-tag-open")) { + token = tokens[i + 1]; + if (token && token.value == tagName) + return true; + } + } + return false; + }; + this._readTagForward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + iterator.stepForward(); + return tag; + } + } while(token = iterator.stepForward()); + + return null; + }; + + this._readTagBackward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + iterator.stepBackward(); + return tag; + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + } + } while(token = iterator.stepBackward()); + + return null; + }; + + this._pop = function(stack, tag) { + while (stack.length) { + + var top = stack[stack.length-1]; + if (!tag || top.tagName == tag.tagName) { + return stack.pop(); + } + else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { + stack.pop(); + continue; + } else { + return null; + } + } + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var firstTag = this._getFirstTagInLine(session, row); + + if (!firstTag) + return null; + + var isBackward = firstTag.closing || firstTag.selfClosing; + var stack = []; + var tag; + + if (!isBackward) { + var iterator = new TokenIterator(session, row, firstTag.start.column); + var start = { + row: row, + column: firstTag.start.column + firstTag.tagName.length + 2 + }; + if (firstTag.start.row == firstTag.end.row) + start.column = firstTag.end.column; + while (tag = this._readTagForward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) + return Range.fromPoints(start, tag.start); + } + else { + stack.push(tag); + } + } + } + else { + var iterator = new TokenIterator(session, row, firstTag.end.column); + var end = { + row: row, + column: firstTag.start.column + }; + + while (tag = this._readTagBackward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (!tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) { + tag.start.column += tag.tagName.length + 2; + if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) + tag.start.column = tag.end.column; + return Range.fromPoints(tag.start, end); + } + } + else { + stack.push(tag); + } + } + } + + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextMode = acequire("./text").Mode; +var XmlHighlightRules = acequire("./xml_highlight_rules").XmlHighlightRules; +var XmlBehaviour = acequire("./behaviour/xml").XmlBehaviour; +var XmlFoldMode = acequire("./folding/xml").FoldMode; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; + +var Mode = function() { + this.HighlightRules = XmlHighlightRules; + this.$behaviour = new XmlBehaviour(); + this.foldingRules = new XmlFoldMode(); +}; + +oop.inherits(Mode, TextMode); + +(function() { + + this.voidElements = lang.arrayToMap([]); + + this.blockComment = {start: ""}; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/xml"), "Worker"); + worker.attachToDocument(session.getDocument()); + + worker.on("error", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/xml"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; +var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; +var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; +var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; +var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; + +var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; +var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; +var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|acequired|root|target|valid|visited)\\b"; + +var CssHighlightRules = function() { + + var keywordMapper = this.createKeywordMapper({ + "support.function": supportFunction, + "support.constant": supportConstant, + "support.type": supportType, + "support.constant.color": supportConstantColor, + "support.constant.fonts": supportConstantFonts + }, "text", true); + + this.$rules = { + "start" : [{ + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token: "paren.lparen", + regex: "\\{", + push: "ruleset" + }, { + token: "string", + regex: "@.*?{", + push: "media" + }, { + token: "keyword", + regex: "#[a-z0-9-_]+" + }, { + token: "variable", + regex: "\\.[a-z0-9-_]+" + }, { + token: "string", + regex: ":[a-z0-9-_]+" + }, { + token: "constant", + regex: "[a-z0-9-_]+" + }, { + caseInsensitive: true + }], + + "media" : [{ + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token: "paren.lparen", + regex: "\\{", + push: "ruleset" + }, { + token: "string", + regex: "\\}", + next: "pop" + }, { + token: "keyword", + regex: "#[a-z0-9-_]+" + }, { + token: "variable", + regex: "\\.[a-z0-9-_]+" + }, { + token: "string", + regex: ":[a-z0-9-_]+" + }, { + token: "constant", + regex: "[a-z0-9-_]+" + }, { + caseInsensitive: true + }], + + "comment" : [{ + token : "comment", + regex : "\\*\\/", + next : "pop" + }, { + defaultToken : "comment" + }], + + "ruleset" : [ + { + token : "paren.rparen", + regex : "\\}", + next: "pop" + }, { + token : "comment", // multi line comment + regex : "\\/\\*", + push : "comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : ["constant.numeric", "keyword"], + regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" + }, { + token : "constant.numeric", + regex : numRe + }, { + token : "constant.numeric", // hex6 color + regex : "#[a-f0-9]{6}" + }, { + token : "constant.numeric", // hex3 color + regex : "#[a-f0-9]{3}" + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], + regex : pseudoElements + }, { + token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], + regex : pseudoClasses + }, { + token : ["support.function", "string", "support.function"], + regex : "(url\\()(.*)(\\))" + }, { + token : keywordMapper, + regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" + }, { + caseInsensitive: true + }] + }; + + this.normalizeRules(); +}; + +oop.inherits(CssHighlightRules, TextHighlightRules); + +exports.CssHighlightRules = CssHighlightRules; + +}); + +ace.define("ace/mode/css_completions",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var propertyMap = { + "background": {"#$0": 1}, + "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, + "background-image": {"url('/$0')": 1}, + "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, + "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, + "background-attachment": {"scroll": 1, "fixed": 1}, + "background-size": {"cover": 1, "contain": 1}, + "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, + "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, + "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, + "border-color": {"#$0": 1}, + "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, + "border-collapse": {"collapse": 1, "separate": 1}, + "bottom": {"px": 1, "em": 1, "%": 1}, + "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, + "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, + "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, + "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, + "empty-cells": {"show": 1, "hide": 1}, + "float": {"left": 1, "right": 1, "none": 1}, + "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, + "font-size": {"px": 1, "em": 1, "%": 1}, + "font-weight": {"bold": 1, "normal": 1}, + "font-style": {"italic": 1, "normal": 1}, + "font-variant": {"normal": 1, "small-caps": 1}, + "height": {"px": 1, "em": 1, "%": 1}, + "left": {"px": 1, "em": 1, "%": 1}, + "letter-spacing": {"normal": 1}, + "line-height": {"normal": 1}, + "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, + "margin": {"px": 1, "em": 1, "%": 1}, + "margin-right": {"px": 1, "em": 1, "%": 1}, + "margin-left": {"px": 1, "em": 1, "%": 1}, + "margin-top": {"px": 1, "em": 1, "%": 1}, + "margin-bottom": {"px": 1, "em": 1, "%": 1}, + "max-height": {"px": 1, "em": 1, "%": 1}, + "max-width": {"px": 1, "em": 1, "%": 1}, + "min-height": {"px": 1, "em": 1, "%": 1}, + "min-width": {"px": 1, "em": 1, "%": 1}, + "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, + "padding": {"px": 1, "em": 1, "%": 1}, + "padding-top": {"px": 1, "em": 1, "%": 1}, + "padding-right": {"px": 1, "em": 1, "%": 1}, + "padding-bottom": {"px": 1, "em": 1, "%": 1}, + "padding-left": {"px": 1, "em": 1, "%": 1}, + "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, + "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, + "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, + "right": {"px": 1, "em": 1, "%": 1}, + "table-layout": {"fixed": 1, "auto": 1}, + "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, + "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, + "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, + "top": {"px": 1, "em": 1, "%": 1}, + "vertical-align": {"top": 1, "bottom": 1}, + "visibility": {"hidden": 1, "visible": 1}, + "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, + "width": {"px": 1, "em": 1, "%": 1}, + "word-spacing": {"normal": 1}, + "filter": {"alpha(opacity=$0100)": 1}, + + "text-shadow": {"$02px 2px 2px #777": 1}, + "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, + "-moz-border-radius": 1, + "-moz-border-radius-topright": 1, + "-moz-border-radius-bottomright": 1, + "-moz-border-radius-topleft": 1, + "-moz-border-radius-bottomleft": 1, + "-webkit-border-radius": 1, + "-webkit-border-top-right-radius": 1, + "-webkit-border-top-left-radius": 1, + "-webkit-border-bottom-right-radius": 1, + "-webkit-border-bottom-left-radius": 1, + "-moz-box-shadow": 1, + "-webkit-box-shadow": 1, + "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, + "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, + "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } +}; + +var CssCompletions = function() { + +}; + +(function() { + + this.completionsDefined = false; + + this.defineCompletions = function() { + if (document) { + var style = document.createElement('c').style; + + for (var i in style) { + if (typeof style[i] !== 'string') + continue; + + var name = i.replace(/[A-Z]/g, function(x) { + return '-' + x.toLowerCase(); + }); + + if (!propertyMap.hasOwnProperty(name)) + propertyMap[name] = 1; + } + } + + this.completionsDefined = true; + } + + this.getCompletions = function(state, session, pos, prefix) { + if (!this.completionsDefined) { + this.defineCompletions(); + } + + var token = session.getTokenAt(pos.row, pos.column); + + if (!token) + return []; + if (state==='ruleset'){ + var line = session.getLine(pos.row).substr(0, pos.column); + if (/:[^;]+$/.test(line)) { + /([\w\-]+):[^:]*$/.test(line); + + return this.getPropertyValueCompletions(state, session, pos, prefix); + } else { + return this.getPropertyCompletions(state, session, pos, prefix); + } + } + + return []; + }; + + this.getPropertyCompletions = function(state, session, pos, prefix) { + var properties = Object.keys(propertyMap); + return properties.map(function(property){ + return { + caption: property, + snippet: property + ': $0', + meta: "property", + score: Number.MAX_VALUE + }; + }); + }; + + this.getPropertyValueCompletions = function(state, session, pos, prefix) { + var line = session.getLine(pos.row).substr(0, pos.column); + var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; + + if (!property) + return []; + var values = []; + if (property in propertyMap && typeof propertyMap[property] === "object") { + values = Object.keys(propertyMap[property]); + } + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "property value", + score: Number.MAX_VALUE + }; + }); + }; + +}).call(CssCompletions.prototype); + +exports.CssCompletions = CssCompletions; +}); + +ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var CstyleBehaviour = acequire("./cstyle").CstyleBehaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; + +var CssBehaviour = function () { + + this.inherit(CstyleBehaviour); + + this.add("colon", "insertion", function (state, action, editor, session, text) { + if (text === ':') { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + if (token && token.value.match(/\s+/)) { + token = iterator.stepBackward(); + } + if (token && token.type === 'support.type') { + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === ':') { + return { + text: '', + selection: [1, 1] + } + } + if (!line.substring(cursor.column).match(/^\s*;/)) { + return { + text: ':;', + selection: [1, 1] + } + } + } + } + }); + + this.add("colon", "deletion", function (state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected === ':') { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + if (token && token.value.match(/\s+/)) { + token = iterator.stepBackward(); + } + if (token && token.type === 'support.type') { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.end.column, range.end.column + 1); + if (rightChar === ';') { + range.end.column ++; + return range; + } + } + } + }); + + this.add("semicolon", "insertion", function (state, action, editor, session, text) { + if (text === ';') { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + if (rightChar === ';') { + return { + text: '', + selection: [1, 1] + } + } + } + }); + +} +oop.inherits(CssBehaviour, CstyleBehaviour); + +exports.CssBehaviour = CssBehaviour; +}); + +ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var CssHighlightRules = acequire("./css_highlight_rules").CssHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CssCompletions = acequire("./css_completions").CssCompletions; +var CssBehaviour = acequire("./behaviour/css").CssBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = CssHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CssBehaviour(); + this.$completer = new CssCompletions(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.foldingRules = "cStyle"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + var tokens = this.getTokenizer().getLineTokens(line, state).tokens; + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + var match = line.match(/^.*\{\s*$/); + if (match) { + indent += tab; + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.getCompletions = function(state, session, pos, prefix) { + return this.$completer.getCompletions(state, session, pos, prefix); + }; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/css"), "Worker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/css"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); + +ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var CssHighlightRules = acequire("./css_highlight_rules").CssHighlightRules; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var XmlHighlightRules = acequire("./xml_highlight_rules").XmlHighlightRules; + +var tagMap = lang.createMap({ + a : 'anchor', + button : 'form', + form : 'form', + img : 'image', + input : 'form', + label : 'form', + option : 'form', + script : 'script', + select : 'form', + textarea : 'form', + style : 'style', + table : 'table', + tbody : 'table', + td : 'table', + tfoot : 'table', + th : 'table', + tr : 'table' +}); + +var HtmlHighlightRules = function() { + XmlHighlightRules.call(this); + + this.addRules({ + attributes: [{ + include : "tag_whitespace" + }, { + token : "entity.other.attribute-name.xml", + regex : "[-_a-zA-Z0-9:.]+" + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=", + push : [{ + include: "tag_whitespace" + }, { + token : "string.unquoted.attribute-value.html", + regex : "[^<>='\"`\\s]+", + next : "pop" + }, { + token : "empty", + regex : "", + next : "pop" + }] + }, { + include : "attribute_value" + }], + tag: [{ + token : function(start, tag) { + var group = tagMap[tag]; + return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", + "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; + }, + regex : "(", next : "start"} + ] + }); + + this.embedTagRules(CssHighlightRules, "css-", "style"); + this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); + + if (this.constructor === HtmlHighlightRules) + this.normalizeRules(); +}; + +oop.inherits(HtmlHighlightRules, XmlHighlightRules); + +exports.HtmlHighlightRules = HtmlHighlightRules; +}); + +ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(defaultMode, subModes) { + this.defaultMode = defaultMode; + this.subModes = subModes; +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + + this.$getMode = function(state) { + if (typeof state != "string") + state = state[0]; + for (var key in this.subModes) { + if (state.indexOf(key) === 0) + return this.subModes[key]; + } + return null; + }; + + this.$tryMode = function(state, session, foldStyle, row) { + var mode = this.$getMode(state); + return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); + }; + + this.getFoldWidget = function(session, foldStyle, row) { + return ( + this.$tryMode(session.getState(row-1), session, foldStyle, row) || + this.$tryMode(session.getState(row), session, foldStyle, row) || + this.defaultMode.getFoldWidget(session, foldStyle, row) + ); + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var mode = this.$getMode(session.getState(row-1)); + + if (!mode || !mode.getFoldWidget(session, foldStyle, row)) + mode = this.$getMode(session.getState(row)); + + if (!mode || !mode.getFoldWidget(session, foldStyle, row)) + mode = this.defaultMode; + + return mode.getFoldWidgetRange(session, foldStyle, row); + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var MixedFoldMode = acequire("./mixed").FoldMode; +var XmlFoldMode = acequire("./xml").FoldMode; +var CStyleFoldMode = acequire("./cstyle").FoldMode; + +var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { + MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { + "js-": new CStyleFoldMode(), + "css-": new CStyleFoldMode() + }); +}; + +oop.inherits(FoldMode, MixedFoldMode); + +}); + +ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var TokenIterator = acequire("../token_iterator").TokenIterator; + +var commonAttributes = [ + "accesskey", + "class", + "contenteditable", + "contextmenu", + "dir", + "draggable", + "dropzone", + "hidden", + "id", + "inert", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "lang", + "spellcheck", + "style", + "tabindex", + "title", + "translate" +]; + +var eventAttributes = [ + "onabort", + "onblur", + "oncancel", + "oncanplay", + "oncanplaythrough", + "onchange", + "onclick", + "onclose", + "oncontextmenu", + "oncuechange", + "ondblclick", + "ondrag", + "ondragend", + "ondragenter", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onended", + "onerror", + "onfocus", + "oninput", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeyup", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadstart", + "onmousedown", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onpause", + "onplay", + "onplaying", + "onprogress", + "onratechange", + "onreset", + "onscroll", + "onseeked", + "onseeking", + "onselect", + "onshow", + "onstalled", + "onsubmit", + "onsuspend", + "ontimeupdate", + "onvolumechange", + "onwaiting" +]; + +var globalAttributes = commonAttributes.concat(eventAttributes); + +var attributeMap = { + "html": {"manifest": 1}, + "head": {}, + "title": {}, + "base": {"href": 1, "target": 1}, + "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, + "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, + "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, + "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, + "noscript": {"href": 1}, + "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, + "section": {}, + "nav": {}, + "article": {"pubdate": 1}, + "aside": {}, + "h1": {}, + "h2": {}, + "h3": {}, + "h4": {}, + "h5": {}, + "h6": {}, + "header": {}, + "footer": {}, + "address": {}, + "main": {}, + "p": {}, + "hr": {}, + "pre": {}, + "blockquote": {"cite": 1}, + "ol": {"start": 1, "reversed": 1}, + "ul": {}, + "li": {"value": 1}, + "dl": {}, + "dt": {}, + "dd": {}, + "figure": {}, + "figcaption": {}, + "div": {}, + "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, + "em": {}, + "strong": {}, + "small": {}, + "s": {}, + "cite": {}, + "q": {"cite": 1}, + "dfn": {}, + "abbr": {}, + "data": {}, + "time": {"datetime": 1}, + "code": {}, + "var": {}, + "samp": {}, + "kbd": {}, + "sub": {}, + "sup": {}, + "i": {}, + "b": {}, + "u": {}, + "mark": {}, + "ruby": {}, + "rt": {}, + "rp": {}, + "bdi": {}, + "bdo": {}, + "span": {}, + "br": {}, + "wbr": {}, + "ins": {"cite": 1, "datetime": 1}, + "del": {"cite": 1, "datetime": 1}, + "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, + "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, + "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, + "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, + "param": {"name": 1, "value": 1}, + "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, + "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, + "source": {"src": 1, "type": 1, "media": 1}, + "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, + "canvas": {"width": 1, "height": 1}, + "map": {"name": 1}, + "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, + "svg": {}, + "math": {}, + "table": {"summary": 1}, + "caption": {}, + "colgroup": {"span": 1}, + "col": {"span": 1}, + "tbody": {}, + "thead": {}, + "tfoot": {}, + "tr": {}, + "td": {"headers": 1, "rowspan": 1, "colspan": 1}, + "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, + "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, + "fieldset": {"disabled": 1, "form": 1, "name": 1}, + "legend": {}, + "label": {"form": 1, "for": 1}, + "input": { + "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, + "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "acequired": {"acequired": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, + "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, + "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, + "datalist": {}, + "optgroup": {"disabled": 1, "label": 1}, + "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, + "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "acequired": {"acequired": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, + "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, + "output": {"for": 1, "form": 1, "name": 1}, + "progress": {"value": 1, "max": 1}, + "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, + "details": {"open": 1}, + "summary": {}, + "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, + "menu": {"type": 1, "label": 1}, + "dialog": {"open": 1} +}; + +var elements = Object.keys(attributeMap); + +function is(token, type) { + return token.type.lastIndexOf(type + ".xml") > -1; +} + +function findTagName(session, pos) { + var iterator = new TokenIterator(session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + while (token && !is(token, "tag-name")){ + token = iterator.stepBackward(); + } + if (token) + return token.value; +} + +function findAttributeName(session, pos) { + var iterator = new TokenIterator(session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + while (token && !is(token, "attribute-name")){ + token = iterator.stepBackward(); + } + if (token) + return token.value; +} + +var HtmlCompletions = function() { + +}; + +(function() { + + this.getCompletions = function(state, session, pos, prefix) { + var token = session.getTokenAt(pos.row, pos.column); + + if (!token) + return []; + if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) + return this.getTagCompletions(state, session, pos, prefix); + if (is(token, "tag-whitespace") || is(token, "attribute-name")) + return this.getAttributeCompletions(state, session, pos, prefix); + if (is(token, "attribute-value")) + return this.getAttributeValueCompletions(state, session, pos, prefix); + var line = session.getLine(pos.row).substr(0, pos.column); + if (/&[a-z]*$/i.test(line)) + return this.getHTMLEntityCompletions(state, session, pos, prefix); + + return []; + }; + + this.getTagCompletions = function(state, session, pos, prefix) { + return elements.map(function(element){ + return { + value: element, + meta: "tag", + score: Number.MAX_VALUE + }; + }); + }; + + this.getAttributeCompletions = function(state, session, pos, prefix) { + var tagName = findTagName(session, pos); + if (!tagName) + return []; + var attributes = globalAttributes; + if (tagName in attributeMap) { + attributes = attributes.concat(Object.keys(attributeMap[tagName])); + } + return attributes.map(function(attribute){ + return { + caption: attribute, + snippet: attribute + '="$0"', + meta: "attribute", + score: Number.MAX_VALUE + }; + }); + }; + + this.getAttributeValueCompletions = function(state, session, pos, prefix) { + var tagName = findTagName(session, pos); + var attributeName = findAttributeName(session, pos); + + if (!tagName) + return []; + var values = []; + if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { + values = Object.keys(attributeMap[tagName][attributeName]); + } + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "attribute value", + score: Number.MAX_VALUE + }; + }); + }; + + this.getHTMLEntityCompletions = function(state, session, pos, prefix) { + var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; + + return values.map(function(value){ + return { + caption: value, + snippet: value, + meta: "html entity", + score: Number.MAX_VALUE + }; + }); + }; + +}).call(HtmlCompletions.prototype); + +exports.HtmlCompletions = HtmlCompletions; +}); + +ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextMode = acequire("./text").Mode; +var JavaScriptMode = acequire("./javascript").Mode; +var CssMode = acequire("./css").Mode; +var HtmlHighlightRules = acequire("./html_highlight_rules").HtmlHighlightRules; +var XmlBehaviour = acequire("./behaviour/xml").XmlBehaviour; +var HtmlFoldMode = acequire("./folding/html").FoldMode; +var HtmlCompletions = acequire("./html_completions").HtmlCompletions; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; +var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; + +var Mode = function(options) { + this.fragmentContext = options && options.fragmentContext; + this.HighlightRules = HtmlHighlightRules; + this.$behaviour = new XmlBehaviour(); + this.$completer = new HtmlCompletions(); + + this.createModeDelegates({ + "js-": JavaScriptMode, + "css-": CssMode + }); + + this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.blockComment = {start: ""}; + + this.voidElements = lang.arrayToMap(voidElements); + + this.getNextLineIndent = function(state, line, tab) { + return this.$getIndent(line); + }; + + this.checkOutdent = function(state, line, input) { + return false; + }; + + this.getCompletions = function(state, session, pos, prefix) { + return this.$completer.getCompletions(state, session, pos, prefix); + }; + + this.createWorker = function(session) { + if (this.constructor != Mode) + return; + var worker = new WorkerClient(["ace"], require("../worker/html"), "Worker"); + worker.attachToDocument(session.getDocument()); + + if (this.fragmentContext) + worker.call("setOptions", [{context: this.fragmentContext}]); + + worker.on("error", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/html"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/mode/markdown_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/html_highlight_rules","ace/mode/css_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var XmlHighlightRules = acequire("./xml_highlight_rules").XmlHighlightRules; +var HtmlHighlightRules = acequire("./html_highlight_rules").HtmlHighlightRules; +var CssHighlightRules = acequire("./css_highlight_rules").CssHighlightRules; + +var escaped = function(ch) { + return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*"; +} + +function github_embed(tag, prefix) { + return { // Github style block + token : "support.function", + regex : "^\\s*```" + tag + "\\s*$", + push : prefix + "start" + }; +} + +var MarkdownHighlightRules = function() { + HtmlHighlightRules.call(this); + + this.$rules["start"].unshift({ + token : "empty_line", + regex : '^$', + next: "allowBlock" + }, { // h1 + token: "markup.heading.1", + regex: "^=+(?=\\s*$)" + }, { // h2 + token: "markup.heading.2", + regex: "^\\-+(?=\\s*$)" + }, { + token : function(value) { + return "markup.heading." + value.length; + }, + regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/, + next : "header" + }, + github_embed("(?:javascript|js)", "jscode-"), + github_embed("xml", "xmlcode-"), + github_embed("html", "htmlcode-"), + github_embed("css", "csscode-"), + { // Github style block + token : "support.function", + regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$", + next : "githubblock" + }, { // block quote + token : "string.blockquote", + regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", + next : "blockquote" + }, { // HR * - _ + token : "constant", + regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$", + next: "allowBlock" + }, { // list + token : "markup.list", + regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", + next : "listblock-start" + }, { + include : "basic" + }); + + this.addRules({ + "basic" : [{ + token : "constant.language.escape", + regex : /\\[\\`*_{}\[\]()#+\-.!]/ + }, { // code span ` + token : "support.function", + regex : "(`+)(.*?[^`])(\\1)" + }, { // reference + token : ["text", "constant", "text", "url", "string", "text"], + regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$" + }, { // link by reference + token : ["text", "string", "text", "constant", "text"], + regex : "(\\[)(" + escaped("]") + ")(\\]\\s*\\[)("+ escaped("]") + ")(\\])" + }, { // link by url + token : ["text", "string", "text", "markup.underline", "string", "text"], + regex : "(\\[)(" + // [ + escaped("]") + // link text + ")(\\]\\()"+ // ]( + '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' + // href + '(\\s*"' + escaped('"') + '"\\s*)?' + // "title" + "(\\))" // ) + }, { // strong ** __ + token : "string.strong", + regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)" + }, { // emphasis * _ + token : "string.emphasis", + regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)" + }, { // + token : ["text", "url", "text"], + regex : "(<)("+ + "(?:https?|ftp|dict):[^'\">\\s]+"+ + "|"+ + "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+ + ")(>)" + }], + "allowBlock": [ + {token : "support.function", regex : "^ {4}.+", next : "allowBlock"}, + {token : "empty_line", regex : '^$', next: "allowBlock"}, + {token : "empty", regex : "", next : "start"} + ], + + "header" : [{ + regex: "$", + next : "start" + }, { + include: "basic" + }, { + defaultToken : "heading" + } ], + + "listblock-start" : [{ + token : "support.variable", + regex : /(?:\[[ x]\])?/, + next : "listblock" + }], + + "listblock" : [ { // Lists only escape on completely blank lines. + token : "empty_line", + regex : "^$", + next : "start" + }, { // list + token : "markup.list", + regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", + next : "listblock-start" + }, { + include : "basic", noEscape: true + }, { // Github style block + token : "support.function", + regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$", + next : "githubblock" + }, { + defaultToken : "list" //do not use markup.list to allow stling leading `*` differntly + } ], + + "blockquote" : [ { // Blockquotes only escape on blank lines. + token : "empty_line", + regex : "^\\s*$", + next : "start" + }, { // block quote + token : "string.blockquote", + regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", + next : "blockquote" + }, { + include : "basic", noEscape: true + }, { + defaultToken : "string.blockquote" + } ], + + "githubblock" : [ { + token : "support.function", + regex : "^\\s*```", + next : "start" + }, { + token : "support.function", + regex : ".+" + } ] + }); + + this.embedRules(JavaScriptHighlightRules, "jscode-", [{ + token : "support.function", + regex : "^\\s*```", + next : "pop" + }]); + + this.embedRules(HtmlHighlightRules, "htmlcode-", [{ + token : "support.function", + regex : "^\\s*```", + next : "pop" + }]); + + this.embedRules(CssHighlightRules, "csscode-", [{ + token : "support.function", + regex : "^\\s*```", + next : "pop" + }]); + + this.embedRules(XmlHighlightRules, "xmlcode-", [{ + token : "support.function", + regex : "^\\s*```", + next : "pop" + }]); + + this.normalizeRules(); +}; +oop.inherits(MarkdownHighlightRules, TextHighlightRules); + +exports.MarkdownHighlightRules = MarkdownHighlightRules; +}); + +ace.define("ace/mode/folding/markdown",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + this.foldingStartMarker = /^(?:[=-]+\s*$|#{1,6} |`{3})/; + + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + if (!this.foldingStartMarker.test(line)) + return ""; + + if (line[0] == "`") { + if (session.bgTokenizer.getState(row) == "start") + return "end"; + return "start"; + } + + return "start"; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var line = session.getLine(row); + var startColumn = line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + if (!line.match(this.foldingStartMarker)) + return; + + if (line[0] == "`") { + if (session.bgTokenizer.getState(row) !== "start") { + while (++row < maxRow) { + line = session.getLine(row); + if (line[0] == "`" & line.substring(0, 3) == "```") + break; + } + return new Range(startRow, startColumn, row, 0); + } else { + while (row -- > 0) { + line = session.getLine(row); + if (line[0] == "`" & line.substring(0, 3) == "```") + break; + } + return new Range(row, line.length, startRow, 0); + } + } + + var token; + function isHeading(row) { + token = session.getTokens(row)[0]; + return token && token.type.lastIndexOf(heading, 0) === 0; + } + + var heading = "markup.heading"; + function getLevel() { + var ch = token.value[0]; + if (ch == "=") return 6; + if (ch == "-") return 5; + return 7 - token.value.search(/[^#]/); + } + + if (isHeading(row)) { + var startHeadingLevel = getLevel(); + while (++row < maxRow) { + if (!isHeading(row)) + continue; + var level = getLevel(); + if (level >= startHeadingLevel) + break; + } + + endRow = row - (!token || ["=", "-"].indexOf(token.value[0]) == -1 ? 1 : 2); + + if (endRow > startRow) { + while (endRow > startRow && /^\s*$/.test(session.getLine(endRow))) + endRow--; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/markdown",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/xml","ace/mode/html","ace/mode/markdown_highlight_rules","ace/mode/folding/markdown"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptMode = acequire("./javascript").Mode; +var XmlMode = acequire("./xml").Mode; +var HtmlMode = acequire("./html").Mode; +var MarkdownHighlightRules = acequire("./markdown_highlight_rules").MarkdownHighlightRules; +var MarkdownFoldMode = acequire("./folding/markdown").FoldMode; + +var Mode = function() { + this.HighlightRules = MarkdownHighlightRules; + + this.createModeDelegates({ + "js-": JavaScriptMode, + "xml-": XmlMode, + "html-": HtmlMode + }); + + this.foldingRules = new MarkdownFoldMode(); + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + this.type = "text"; + this.blockComment = {start: ""}; + + this.getNextLineIndent = function(state, line, tab) { + if (state == "listblock") { + var match = /^(\s*)(?:([-+*])|(\d+)\.)(\s+)/.exec(line); + if (!match) + return ""; + var marker = match[2]; + if (!marker) + marker = parseInt(match[3], 10) + 1 + "."; + return match[1] + marker + match[4]; + } else { + return this.$getIndent(line); + } + }; + this.$id = "ace/mode/markdown"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/css":234,"../worker/html":235,"../worker/javascript":236,"../worker/xml":238}],216:[function(require,module,exports){ +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/mysql_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var MysqlHighlightRules = function() { + + var mySqlKeywords = /*sql*/ "alter|and|as|asc|between|count|create|delete|desc|distinct|drop|from|having|in|insert|into|is|join|like|not|on|or|order|select|set|table|union|update|values|where" + "|accessible|action|add|after|algorithm|all|analyze|asensitive|at|authors|auto_increment|autocommit|avg|avg_row_length|before|binary|binlog|both|btree|cache|call|cascade|cascaded|case|catalog_name|chain|change|changed|character|check|checkpoint|checksum|class_origin|client_statistics|close|coalesce|code|collate|collation|collations|column|columns|comment|commit|committed|completion|concurrent|condition|connection|consistent|constraint|contains|continue|contributors|convert|cross|current_date|current_time|current_timestamp|current_user|cursor|data|database|databases|day_hour|day_microsecond|day_minute|day_second|deallocate|dec|declare|default|delay_key_write|delayed|delimiter|des_key_file|describe|deterministic|dev_pop|dev_samp|deviance|directory|disable|discard|distinctrow|div|dual|dumpfile|each|elseif|enable|enclosed|end|ends|engine|engines|enum|errors|escape|escaped|even|event|events|every|execute|exists|exit|explain|extended|fast|fetch|field|fields|first|flush|for|force|foreign|found_rows|full|fulltext|function|general|global|grant|grants|group|groupby_concat|handler|hash|help|high_priority|hosts|hour_microsecond|hour_minute|hour_second|if|ignore|ignore_server_ids|import|index|index_statistics|infile|inner|innodb|inout|insensitive|insert_method|install|interval|invoker|isolation|iterate|key|keys|kill|language|last|leading|leave|left|level|limit|linear|lines|list|load|local|localtime|localtimestamp|lock|logs|low_priority|master|master_heartbeat_period|master_ssl_verify_server_cert|masters|match|max|max_rows|maxvalue|message_text|middleint|migrate|min|min_rows|minute_microsecond|minute_second|mod|mode|modifies|modify|mutex|mysql_errno|natural|next|no|no_write_to_binlog|offline|offset|one|online|open|optimize|option|optionally|out|outer|outfile|pack_keys|parser|partition|partitions|password|phase|plugin|plugins|prepare|preserve|prev|primary|privileges|procedure|processlist|profile|profiles|purge|query|quick|range|read|read_write|reads|real|rebuild|recover|references|regexp|relaylog|release|remove|rename|reorganize|repair|repeatable|replace|acequire|resignal|restrict|resume|return|returns|revoke|right|rlike|rollback|rollup|row|row_format|rtree|savepoint|schedule|schema|schema_name|schemas|second_microsecond|security|sensitive|separator|serializable|server|session|share|show|signal|slave|slow|smallint|snapshot|soname|spatial|specific|sql|sql_big_result|sql_buffer_result|sql_cache|sql_calc_found_rows|sql_no_cache|sql_small_result|sqlexception|sqlstate|sqlwarning|ssl|start|starting|starts|status|std|stddev|stddev_pop|stddev_samp|storage|straight_join|subclass_origin|sum|suspend|table_name|table_statistics|tables|tablespace|temporary|terminated|to|trailing|transaction|trigger|triggers|truncate|uncommitted|undo|uninstall|unique|unlock|upgrade|usage|use|use_frm|user|user_resources|user_statistics|using|utc_date|utc_time|utc_timestamp|value|variables|varying|view|views|warnings|when|while|with|work|write|xa|xor|year_month|zerofill|begin|do|then|else|loop|repeat"; + var builtins = "by|bool|boolean|bit|blob|decimal|double|enum|float|long|longblob|longtext|medium|mediumblob|mediumint|mediumtext|time|timestamp|tinyblob|tinyint|tinytext|text|bigint|int|int1|int2|int3|int4|int8|integer|float|float4|float8|double|char|varbinary|varchar|varcharacter|precision|date|datetime|year|unsigned|signed|numeric|ucase|lcase|mid|len|round|rank|now|format|coalesce|ifnull|isnull|nvl" + var variable = "charset|clear|connect|edit|ego|exit|go|help|nopager|notee|nowarning|pager|print|prompt|quit|rehash|source|status|system|tee" + + var keywordMapper = this.createKeywordMapper({ + "support.function": builtins, + "keyword": mySqlKeywords, + "constant": "false|true|null|unknown|date|time|timestamp|ODBCdotTable|zerolessFloat", + "variable.language": variable + }, "identifier", true); + + + function string(rule) { + var start = rule.start; + var escapeSeq = rule.escape; + return { + token: "string.start", + regex: start, + next: [ + {token: "constant.language.escape", regex: escapeSeq}, + {token: "string.end", next: "start", regex: start}, + {defaultToken: "string"} + ] + }; + } + + this.$rules = { + "start" : [ { + token : "comment", regex : "(?:-- |#).*$" + }, + string({start: '"', escape: /\\[0'"bnrtZ\\%_]?/}), + string({start: "'", escape: /\\[0'"bnrtZ\\%_]?/}), + DocCommentHighlightRules.getStartRule("doc-start"), + { + token : "comment", // multi line comment + regex : /\/\*/, + next : "comment" + }, { + token : "constant.numeric", // hex + regex : /0[xX][0-9a-fA-F]+|[xX]'[0-9a-fA-F]+'|0[bB][01]+|[bB]'[01]+'/ + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "constant.class", + regex : "@@?[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "constant.buildin", + regex : "`[^`]*`" + }, { + token : "keyword.operator", + regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" + }, { + token : "paren.lparen", + regex : "[\\(]" + }, { + token : "paren.rparen", + regex : "[\\)]" + }, { + token : "text", + regex : "\\s+" + } ], + "comment" : [ + {token : "comment", regex : "\\*\\/", next : "start"}, + {defaultToken : "comment"} + ] + }; + + this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); + this.normalizeRules(); +}; + +oop.inherits(MysqlHighlightRules, TextHighlightRules); + +exports.MysqlHighlightRules = MysqlHighlightRules; +}); + +ace.define("ace/mode/mysql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/mysql_highlight_rules"], function(acequire, exports, module) { + +var oop = acequire("../lib/oop"); +var TextMode = acequire("../mode/text").Mode; +var MysqlHighlightRules = acequire("./mysql_highlight_rules").MysqlHighlightRules; + +var Mode = function() { + this.HighlightRules = MysqlHighlightRules; + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + this.lineCommentStart = ["--", "#"]; // todo space + this.blockComment = {start: "/*", end: "*/"}; + + this.$id = "ace/mode/mysql"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],217:[function(require,module,exports){ +ace.define("ace/mode/perl_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var PerlHighlightRules = function() { + + var keywords = ( + "base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + + "no|package|parent|redo|acequire|scalar|sub|unless|until|while|use|vars" + ); + + var buildinConstants = ("ARGV|ENV|INC|SIG"); + + var builtinFunctions = ( + "getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + + "map|die|uc|lc|do" + ); + + var keywordMapper = this.createKeywordMapper({ + "keyword": keywords, + "constant.language": buildinConstants, + "support.function": builtinFunctions + }, "identifier"); + + this.$rules = { + "start" : [ + { + token : "comment.doc", + regex : "^=(?:begin|item)\\b", + next : "block_comment" + }, { + token : "string.regexp", + regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // multi line string start + regex : '["].*\\\\$', + next : "qqstring" + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "string", // multi line string start + regex : "['].*\\\\$", + next : "qstring" + }, { + token : "constant.numeric", // hex + regex : "0x[0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "%#|\\$#|\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" + }, { + token : "comment", + regex : "#.*$" + }, { + token : "lparen", + regex : "[[({]" + }, { + token : "rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "qqstring" : [ + { + token : "string", + regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', + next : "start" + }, { + token : "string", + regex : '.+' + } + ], + "qstring" : [ + { + token : "string", + regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", + next : "start" + }, { + token : "string", + regex : '.+' + } + ], + "block_comment": [ + { + token: "comment.doc", + regex: "^=cut\\b", + next: "start" + }, + { + defaultToken: "comment.doc" + } + ] + }; +}; + +oop.inherits(PerlHighlightRules, TextHighlightRules); + +exports.PerlHighlightRules = PerlHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/perl",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/perl_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var PerlHighlightRules = acequire("./perl_highlight_rules").PerlHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = PerlHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.foldingRules = new CStyleFoldMode({start: "^=(begin|item)\\b", end: "^=(cut)\\b"}); + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + this.blockComment = [ + {start: "=begin", end: "=cut", lineStartOnly: true}, + {start: "=item", end: "=cut", lineStartOnly: true} + ]; + + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[:]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + this.$id = "ace/mode/perl"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],218:[function(require,module,exports){ +ace.define("ace/mode/powershell_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var PowershellHighlightRules = function() { + var keywords = ( + "begin|break|catch|continue|data|do|dynamicparam|else|elseif|end|exit|filter|" + + "finally|for|foreach|from|function|if|in|inlinescript|hidden|parallel|param|" + + "process|return|sequence|switch|throw|trap|try|until|while|workflow" + ); + var builtinFunctions = ( + "Get-AppBackgroundTask|Start-AppBackgroundTask|Unregister-AppBackgroundTask|Disable-AppBackgroundTaskDiagnosticLog|Enable-AppBackgroundTaskDiagnosticLog|Set-AppBackgroundTaskResourcePolicy|" + + "Get-AppLockerFileInformation|Get-AppLockerPolicy|New-AppLockerPolicy|Set-AppLockerPolicy|Test-AppLockerPolicy|" + + "Get-AppxLastError|Get-AppxLog|Add-AppxPackage|Add-AppxVolume|Dismount-AppxVolume|Get-AppxDefaultVolume|Get-AppxPackage|Get-AppxPackageManifest|Get-AppxVolume|Mount-AppxVolume|Move-AppxPackage|Remove-AppxPackage|Remove-AppxVolume|Set-AppxDefaultVolume|" + + "Clear-AssignedAccess|Get-AssignedAccess|Set-AssignedAccess|" + + "Add-BitLockerKeyProtector|Backup-BitLockerKeyProtector|Clear-BitLockerAutoUnlock|Disable-BitLocker|Disable-BitLockerAutoUnlock|Enable-BitLocker|Enable-BitLockerAutoUnlock|Get-BitLockerVolume|Lock-BitLocker|Remove-BitLockerKeyProtector|Resume-BitLocker|Suspend-BitLocker|Unlock-BitLocker|" + + "Add-BitsFile|Complete-BitsTransfer|Get-BitsTransfer|Remove-BitsTransfer|Resume-BitsTransfer|Set-BitsTransfer|Start-BitsTransfer|Suspend-BitsTransfer|" + + "Add-BCDataCacheExtension|Clear-BCCache|Disable-BC|Disable-BCDowngrading|Disable-BCServeOnBattery|Enable-BCDistributed|Enable-BCDowngrading|Enable-BCHostedClient|Enable-BCHostedServer|Enable-BCLocal|Enable-BCServeOnBattery|Export-BCCachePackage|Export-BCSecretKey|Get-BCClientConfiguration|Get-BCContentServerConfiguration|Get-BCDataCache|Get-BCDataCacheExtension|Get-BCHashCache|Get-BCHostedCacheServerConfiguration|Get-BCNetworkConfiguration|Get-BCStatus|Import-BCCachePackage|Import-BCSecretKey|Publish-BCFileContent|Publish-BCWebContent|Remove-BCDataCacheExtension|Reset-BC|Set-BCAuthentication|Set-BCCache|Set-BCDataCacheEntryMaxAge|Set-BCMinSMBLatency|Set-BCSecretKey|" + + "Export-BinaryMiLog|Get-CimAssociatedInstance|Get-CimClass|Get-CimInstance|Get-CimSession|Import-BinaryMiLog|Invoke-CimMethod|New-CimInstance|New-CimSession|New-CimSessionOption|Register-CimIndicationEvent|Remove-CimInstance|Remove-CimSession|Set-CimInstance|" + + "ConvertFrom-CIPolicy|" + + "Add-SignerRule|Edit-CIPolicyRule|Get-CIPolicy|Get-CIPolicyInfo|Get-SystemDriver|Merge-CIPolicy|New-CIPolicy|New-CIPolicyRule|Remove-CIPolicyRule|Set-CIPolicyVersion|Set-HVCIOptions|Set-RuleOption|" + + "Add-MpPreference|Get-MpComputerStatus|Get-MpPreference|Get-MpThreat|Get-MpThreatCatalog|Get-MpThreatDetection|Remove-MpPreference|Remove-MpThreat|Set-MpPreference|Start-MpScan|Start-MpWDOScan|Update-MpSignature|" + + "Disable-DAManualEntryPointSelection|Enable-DAManualEntryPointSelection|Get-DAClientExperienceConfiguration|Get-DAEntryPointTableItem|New-DAEntryPointTableItem|Remove-DAEntryPointTableItem|Rename-DAEntryPointTableItem|Reset-DAClientExperienceConfiguration|Reset-DAEntryPointTableItem|Set-DAClientExperienceConfiguration|Set-DAEntryPointTableItem|" + + "Add-ProvisionedAppxPackage|Apply-WindowsUnattend|Get-ProvisionedAppxPackage|Remove-ProvisionedAppxPackage|Add-AppxProvisionedPackage|Add-WindowsCapability|Add-WindowsDriver|Add-WindowsImage|Add-WindowsPackage|Clear-WindowsCorruptMountPoint|Disable-WindowsOptionalFeature|Dismount-WindowsImage|Enable-WindowsOptionalFeature|Expand-WindowsCustomDataImage|Expand-WindowsImage|Export-WindowsDriver|Export-WindowsImage|Get-AppxProvisionedPackage|Get-WIMBootEntry|Get-WindowsCapability|Get-WindowsDriver|Get-WindowsEdition|Get-WindowsImage|Get-WindowsImageContent|Get-WindowsOptionalFeature|Get-WindowsPackage|Mount-WindowsImage|New-WindowsCustomImage|New-WindowsImage|Optimize-WindowsImage|Remove-AppxProvisionedPackage|Remove-WindowsCapability|Remove-WindowsDriver|Remove-WindowsImage|Remove-WindowsPackage|Repair-WindowsImage|Save-WindowsImage|Set-AppXProvisionedDataFile|Set-WindowsEdition|Set-WindowsProductKey|Split-WindowsImage|Update-WIMBootEntry|Use-WindowsUnattend|" + + "Add-DnsClientNrptRule|Clear-DnsClientCache|Get-DnsClient|Get-DnsClientCache|Get-DnsClientGlobalSetting|Get-DnsClientNrptGlobal|Get-DnsClientNrptPolicy|Get-DnsClientNrptRule|Get-DnsClientServerAddress|Register-DnsClient|Remove-DnsClientNrptRule|Set-DnsClient|Set-DnsClientGlobalSetting|Set-DnsClientNrptGlobal|Set-DnsClientNrptRule|Set-DnsClientServerAddress|Resolve-DnsName|" + + "Add-EtwTraceProvider|Get-AutologgerConfig|Get-EtwTraceProvider|Get-EtwTraceSession|New-AutologgerConfig|New-EtwTraceSession|Remove-AutologgerConfig|Remove-EtwTraceProvider|Remove-EtwTraceSession|Send-EtwTraceSession|Set-AutologgerConfig|Set-EtwTraceProvider|Set-EtwTraceSession|" + + "Get-WinAcceptLanguageFromLanguageListOptOut|Get-WinCultureFromLanguageListOptOut|Get-WinDefaultInputMethodOverride|Get-WinHomeLocation|Get-WinLanguageBarOption|Get-WinSystemLocale|Get-WinUILanguageOverride|Get-WinUserLanguageList|New-WinUserLanguageList|Set-Culture|Set-WinAcceptLanguageFromLanguageListOptOut|Set-WinCultureFromLanguageListOptOut|Set-WinDefaultInputMethodOverride|Set-WinHomeLocation|Set-WinLanguageBarOption|Set-WinSystemLocale|Set-WinUILanguageOverride|Set-WinUserLanguageList|" + + "Connect-IscsiTarget|Disconnect-IscsiTarget|Get-IscsiConnection|Get-IscsiSession|Get-IscsiTarget|Get-IscsiTargetPortal|New-IscsiTargetPortal|Register-IscsiSession|Remove-IscsiTargetPortal|Set-IscsiChapSecret|Unregister-IscsiSession|Update-IscsiTarget|Update-IscsiTargetPortal|" + + "Get-IseSnippet|Import-IseSnippet|New-IseSnippet|" + + "Add-KdsRootKey|Clear-KdsCache|Get-KdsConfiguration|Get-KdsRootKey|Set-KdsConfiguration|Test-KdsRootKey|" + + "Compress-Archive|Expand-Archive|" + + "Export-Counter|Get-Counter|Get-WinEvent|Import-Counter|New-WinEvent|" + + "Start-Transcript|Stop-Transcript|" + + "Add-Computer|Add-Content|Checkpoint-Computer|Clear-Content|Clear-EventLog|Clear-Item|Clear-ItemProperty|Clear-RecycleBin|Complete-Transaction|Convert-Path|Copy-Item|Copy-ItemProperty|Debug-Process|Disable-ComputerRestore|Enable-ComputerRestore|Get-ChildItem|Get-Clipboard|Get-ComputerRestorePoint|Get-Content|Get-ControlPanelItem|Get-EventLog|Get-HotFix|Get-Item|Get-ItemProperty|Get-ItemPropertyValue|Get-Location|Get-Process|Get-PSDrive|Get-PSProvider|Get-Service|Get-Transaction|Get-WmiObject|Invoke-Item|Invoke-WmiMethod|Join-Path|Limit-EventLog|Move-Item|Move-ItemProperty|New-EventLog|New-Item|New-ItemProperty|New-PSDrive|New-Service|New-WebServiceProxy|Pop-Location|Push-Location|Register-WmiEvent|Remove-Computer|Remove-EventLog|Remove-Item|Remove-ItemProperty|Remove-PSDrive|Remove-WmiObject|Rename-Computer|Rename-Item|Rename-ItemProperty|Reset-ComputerMachinePassword|Resolve-Path|Restart-Computer|Restart-Service|Restore-Computer|Resume-Service|Set-Clipboard|Set-Content|Set-Item|Set-ItemProperty|Set-Location|Set-Service|Set-WmiInstance|Show-ControlPanelItem|Show-EventLog|Split-Path|Start-Process|Start-Service|Start-Transaction|Stop-Computer|Stop-Process|Stop-Service|Suspend-Service|Test-ComputerSecureChannel|Test-Connection|Test-Path|Undo-Transaction|Use-Transaction|Wait-Process|Write-EventLog|" + + "Export-ODataEndpointProxy|" + + "ConvertFrom-SecureString|ConvertTo-SecureString|Get-Acl|Get-AuthenticodeSignature|Get-CmsMessage|Get-Credential|Get-ExecutionPolicy|Get-PfxCertificate|Protect-CmsMessage|Set-Acl|Set-AuthenticodeSignature|Set-ExecutionPolicy|Unprotect-CmsMessage|" + + "ConvertFrom-SddlString|Format-Hex|Get-FileHash|Import-PowerShellDataFile|New-Guid|New-TemporaryFile|Add-Member|Add-Type|Clear-Variable|Compare-Object|ConvertFrom-Csv|ConvertFrom-Json|ConvertFrom-String|ConvertFrom-StringData|Convert-String|ConvertTo-Csv|ConvertTo-Html|ConvertTo-Json|ConvertTo-Xml|Debug-Runspace|Disable-PSBreakpoint|Disable-RunspaceDebug|Enable-PSBreakpoint|Enable-RunspaceDebug|Export-Alias|Export-Clixml|Export-Csv|Export-FormatData|Export-PSSession|Format-Custom|Format-List|Format-Table|Format-Wide|Get-Alias|Get-Culture|Get-Date|Get-Event|Get-EventSubscriber|Get-FormatData|Get-Host|Get-Member|Get-PSBreakpoint|Get-PSCallStack|Get-Random|Get-Runspace|Get-RunspaceDebug|Get-TraceSource|Get-TypeData|Get-UICulture|Get-Unique|Get-Variable|Group-Object|Import-Alias|Import-Clixml|Import-Csv|Import-LocalizedData|Import-PSSession|Invoke-Expression|Invoke-RestMethod|Invoke-WebRequest|Measure-Command|Measure-Object|New-Alias|New-Event|New-Object|New-TimeSpan|New-Variable|Out-File|Out-GridView|Out-Printer|Out-String|Read-Host|Register-EngineEvent|Register-ObjectEvent|Remove-Event|Remove-PSBreakpoint|Remove-TypeData|Remove-Variable|Select-Object|Select-String|Select-Xml|Send-MailMessage|Set-Alias|Set-Date|Set-PSBreakpoint|Set-TraceSource|Set-Variable|Show-Command|Sort-Object|Start-Sleep|Tee-Object|Trace-Command|Unblock-File|Unregister-Event|Update-FormatData|Update-List|Update-TypeData|Wait-Debugger|Wait-Event|Write-Debug|Write-Error|Write-Host|Write-Information|Write-Output|Write-Progress|Write-Verbose|Write-Warning|" + + "Connect-WSMan|Disable-WSManCredSSP|Disconnect-WSMan|Enable-WSManCredSSP|Get-WSManCredSSP|Get-WSManInstance|Invoke-WSManAction|New-WSManInstance|New-WSManSessionOption|Remove-WSManInstance|Set-WSManInstance|Set-WSManQuickConfig|Test-WSMan|" + + "Debug-MMAppPrelaunch|Disable-MMAgent|Enable-MMAgent|Get-MMAgent|Set-MMAgent|" + + "Add-DtcClusterTMMapping|Get-Dtc|Get-DtcAdvancedHostSetting|Get-DtcAdvancedSetting|Get-DtcClusterDefault|Get-DtcClusterTMMapping|Get-DtcDefault|Get-DtcLog|Get-DtcNetworkSetting|Get-DtcTransaction|Get-DtcTransactionsStatistics|Get-DtcTransactionsTraceSession|Get-DtcTransactionsTraceSetting|Install-Dtc|Remove-DtcClusterTMMapping|Reset-DtcLog|Set-DtcAdvancedHostSetting|Set-DtcAdvancedSetting|Set-DtcClusterDefault|Set-DtcClusterTMMapping|Set-DtcDefault|Set-DtcLog|Set-DtcNetworkSetting|Set-DtcTransaction|Set-DtcTransactionsTraceSession|Set-DtcTransactionsTraceSetting|Start-Dtc|Start-DtcTransactionsTraceSession|Stop-Dtc|Stop-DtcTransactionsTraceSession|Test-Dtc|Uninstall-Dtc|Write-DtcTransactionsTraceSession|Complete-DtcDiagnosticTransaction|Join-DtcDiagnosticResourceManager|New-DtcDiagnosticTransaction|Receive-DtcDiagnosticTransaction|Send-DtcDiagnosticTransaction|Start-DtcDiagnosticResourceManager|Stop-DtcDiagnosticResourceManager|Undo-DtcDiagnosticTransaction|" + + "Disable-NetAdapter|Disable-NetAdapterBinding|Disable-NetAdapterChecksumOffload|Disable-NetAdapterEncapsulatedPacketTaskOffload|Disable-NetAdapterIPsecOffload|Disable-NetAdapterLso|Disable-NetAdapterPacketDirect|Disable-NetAdapterPowerManagement|Disable-NetAdapterQos|Disable-NetAdapterRdma|Disable-NetAdapterRsc|Disable-NetAdapterRss|Disable-NetAdapterSriov|Disable-NetAdapterVmq|Enable-NetAdapter|Enable-NetAdapterBinding|Enable-NetAdapterChecksumOffload|Enable-NetAdapterEncapsulatedPacketTaskOffload|Enable-NetAdapterIPsecOffload|Enable-NetAdapterLso|Enable-NetAdapterPacketDirect|Enable-NetAdapterPowerManagement|Enable-NetAdapterQos|Enable-NetAdapterRdma|Enable-NetAdapterRsc|Enable-NetAdapterRss|Enable-NetAdapterSriov|Enable-NetAdapterVmq|Get-NetAdapter|Get-NetAdapterAdvancedProperty|Get-NetAdapterBinding|Get-NetAdapterChecksumOffload|Get-NetAdapterEncapsulatedPacketTaskOffload|Get-NetAdapterHardwareInfo|Get-NetAdapterIPsecOffload|Get-NetAdapterLso|Get-NetAdapterPacketDirect|Get-NetAdapterPowerManagement|Get-NetAdapterQos|Get-NetAdapterRdma|Get-NetAdapterRsc|Get-NetAdapterRss|Get-NetAdapterSriov|Get-NetAdapterSriovVf|Get-NetAdapterStatistics|Get-NetAdapterVmq|Get-NetAdapterVmqQueue|Get-NetAdapterVPort|New-NetAdapterAdvancedProperty|Remove-NetAdapterAdvancedProperty|Rename-NetAdapter|Reset-NetAdapterAdvancedProperty|Restart-NetAdapter|Set-NetAdapter|Set-NetAdapterAdvancedProperty|Set-NetAdapterBinding|Set-NetAdapterChecksumOffload|Set-NetAdapterEncapsulatedPacketTaskOffload|Set-NetAdapterIPsecOffload|Set-NetAdapterLso|Set-NetAdapterPacketDirect|Set-NetAdapterPowerManagement|Set-NetAdapterQos|Set-NetAdapterRdma|Set-NetAdapterRsc|Set-NetAdapterRss|Set-NetAdapterSriov|Set-NetAdapterVmq|" + + "Get-NetConnectionProfile|Set-NetConnectionProfile|" + + "Add-NetEventNetworkAdapter|Add-NetEventPacketCaptureProvider|Add-NetEventProvider|Add-NetEventVmNetworkAdapter|Add-NetEventVmSwitch|Add-NetEventWFPCaptureProvider|Get-NetEventNetworkAdapter|Get-NetEventPacketCaptureProvider|Get-NetEventProvider|Get-NetEventSession|Get-NetEventVmNetworkAdapter|Get-NetEventVmSwitch|Get-NetEventWFPCaptureProvider|New-NetEventSession|Remove-NetEventNetworkAdapter|Remove-NetEventPacketCaptureProvider|Remove-NetEventProvider|Remove-NetEventSession|Remove-NetEventVmNetworkAdapter|Remove-NetEventVmSwitch|Remove-NetEventWFPCaptureProvider|Set-NetEventPacketCaptureProvider|Set-NetEventProvider|Set-NetEventSession|Set-NetEventWFPCaptureProvider|Start-NetEventSession|Stop-NetEventSession|" + + "Add-NetLbfoTeamMember|Add-NetLbfoTeamNic|Get-NetLbfoTeam|Get-NetLbfoTeamMember|Get-NetLbfoTeamNic|New-NetLbfoTeam|Remove-NetLbfoTeam|Remove-NetLbfoTeamMember|Remove-NetLbfoTeamNic|Rename-NetLbfoTeam|Set-NetLbfoTeam|Set-NetLbfoTeamMember|Set-NetLbfoTeamNic|" + + "Add-NetNatExternalAddress|Add-NetNatStaticMapping|Get-NetNat|Get-NetNatExternalAddress|Get-NetNatGlobal|Get-NetNatSession|Get-NetNatStaticMapping|New-NetNat|Remove-NetNat|Remove-NetNatExternalAddress|Remove-NetNatStaticMapping|Set-NetNat|Set-NetNatGlobal|" + + "Get-NetQosPolicy|New-NetQosPolicy|Remove-NetQosPolicy|Set-NetQosPolicy|" + + "Copy-NetFirewallRule|Copy-NetIPsecMainModeCryptoSet|Copy-NetIPsecMainModeRule|Copy-NetIPsecPhase1AuthSet|Copy-NetIPsecPhase2AuthSet|Copy-NetIPsecQuickModeCryptoSet|Copy-NetIPsecRule|Disable-NetFirewallRule|Disable-NetIPsecMainModeRule|Disable-NetIPsecRule|Enable-NetFirewallRule|Enable-NetIPsecMainModeRule|Enable-NetIPsecRule|Find-NetIPsecRule|Get-NetFirewallAddressFilter|Get-NetFirewallApplicationFilter|Get-NetFirewallInterfaceFilter|Get-NetFirewallInterfaceTypeFilter|Get-NetFirewallPortFilter|Get-NetFirewallProfile|Get-NetFirewallRule|Get-NetFirewallSecurityFilter|Get-NetFirewallServiceFilter|Get-NetFirewallSetting|Get-NetIPsecDospSetting|Get-NetIPsecMainModeCryptoSet|Get-NetIPsecMainModeRule|Get-NetIPsecMainModeSA|Get-NetIPsecPhase1AuthSet|Get-NetIPsecPhase2AuthSet|Get-NetIPsecQuickModeCryptoSet|Get-NetIPsecQuickModeSA|Get-NetIPsecRule|New-NetFirewallRule|New-NetIPsecDospSetting|New-NetIPsecMainModeCryptoSet|New-NetIPsecMainModeRule|New-NetIPsecPhase1AuthSet|New-NetIPsecPhase2AuthSet|New-NetIPsecQuickModeCryptoSet|New-NetIPsecRule|Open-NetGPO|Remove-NetFirewallRule|Remove-NetIPsecDospSetting|Remove-NetIPsecMainModeCryptoSet|Remove-NetIPsecMainModeRule|Remove-NetIPsecMainModeSA|Remove-NetIPsecPhase1AuthSet|Remove-NetIPsecPhase2AuthSet|Remove-NetIPsecQuickModeCryptoSet|Remove-NetIPsecQuickModeSA|Remove-NetIPsecRule|Rename-NetFirewallRule|Rename-NetIPsecMainModeCryptoSet|Rename-NetIPsecMainModeRule|Rename-NetIPsecPhase1AuthSet|Rename-NetIPsecPhase2AuthSet|Rename-NetIPsecQuickModeCryptoSet|Rename-NetIPsecRule|Save-NetGPO|Set-NetFirewallAddressFilter|Set-NetFirewallApplicationFilter|Set-NetFirewallInterfaceFilter|Set-NetFirewallInterfaceTypeFilter|Set-NetFirewallPortFilter|Set-NetFirewallProfile|Set-NetFirewallRule|Set-NetFirewallSecurityFilter|Set-NetFirewallServiceFilter|Set-NetFirewallSetting|Set-NetIPsecDospSetting|Set-NetIPsecMainModeCryptoSet|Set-NetIPsecMainModeRule|Set-NetIPsecPhase1AuthSet|Set-NetIPsecPhase2AuthSet|Set-NetIPsecQuickModeCryptoSet|Set-NetIPsecRule|Show-NetFirewallRule|Show-NetIPsecRule|Sync-NetIPsecRule|Update-NetIPsecRule|Get-DAPolicyChange|New-NetIPsecAuthProposal|New-NetIPsecMainModeCryptoProposal|New-NetIPsecQuickModeCryptoProposal|" + + "Add-NetSwitchTeamMember|Get-NetSwitchTeam|Get-NetSwitchTeamMember|New-NetSwitchTeam|Remove-NetSwitchTeam|Remove-NetSwitchTeamMember|Rename-NetSwitchTeam|" + + "Find-NetRoute|Get-NetCompartment|Get-NetIPAddress|Get-NetIPConfiguration|Get-NetIPInterface|Get-NetIPv4Protocol|Get-NetIPv6Protocol|Get-NetNeighbor|Get-NetOffloadGlobalSetting|Get-NetPrefixPolicy|Get-NetRoute|Get-NetTCPConnection|Get-NetTCPSetting|Get-NetTransportFilter|Get-NetUDPEndpoint|Get-NetUDPSetting|New-NetIPAddress|New-NetNeighbor|New-NetRoute|New-NetTransportFilter|Remove-NetIPAddress|Remove-NetNeighbor|Remove-NetRoute|Remove-NetTransportFilter|Set-NetIPAddress|Set-NetIPInterface|Set-NetIPv4Protocol|Set-NetIPv6Protocol|Set-NetNeighbor|Set-NetOffloadGlobalSetting|Set-NetRoute|Set-NetTCPSetting|Set-NetUDPSetting|Test-NetConnection|" + + "Get-DAConnectionStatus|Get-NCSIPolicyConfiguration|Reset-NCSIPolicyConfiguration|Set-NCSIPolicyConfiguration|" + + "Disable-NetworkSwitchEthernetPort|Disable-NetworkSwitchFeature|Disable-NetworkSwitchVlan|Enable-NetworkSwitchEthernetPort|Enable-NetworkSwitchFeature|Enable-NetworkSwitchVlan|Get-NetworkSwitchEthernetPort|Get-NetworkSwitchFeature|Get-NetworkSwitchGlobalData|Get-NetworkSwitchVlan|New-NetworkSwitchVlan|Remove-NetworkSwitchEthernetPortIPAddress|Remove-NetworkSwitchVlan|Restore-NetworkSwitchConfiguration|Save-NetworkSwitchConfiguration|Set-NetworkSwitchEthernetPortIPAddress|Set-NetworkSwitchPortMode|Set-NetworkSwitchPortProperty|Set-NetworkSwitchVlanProperty|" + + "Add-NetIPHttpsCertBinding|Disable-NetDnsTransitionConfiguration|Disable-NetIPHttpsProfile|Disable-NetNatTransitionConfiguration|Enable-NetDnsTransitionConfiguration|Enable-NetIPHttpsProfile|Enable-NetNatTransitionConfiguration|Get-Net6to4Configuration|Get-NetDnsTransitionConfiguration|Get-NetDnsTransitionMonitoring|Get-NetIPHttpsConfiguration|Get-NetIPHttpsState|Get-NetIsatapConfiguration|Get-NetNatTransitionConfiguration|Get-NetNatTransitionMonitoring|Get-NetTeredoConfiguration|Get-NetTeredoState|New-NetIPHttpsConfiguration|New-NetNatTransitionConfiguration|Remove-NetIPHttpsCertBinding|Remove-NetIPHttpsConfiguration|Remove-NetNatTransitionConfiguration|Rename-NetIPHttpsConfiguration|Reset-Net6to4Configuration|Reset-NetDnsTransitionConfiguration|Reset-NetIPHttpsConfiguration|Reset-NetIsatapConfiguration|Reset-NetTeredoConfiguration|Set-Net6to4Configuration|Set-NetDnsTransitionConfiguration|Set-NetIPHttpsConfiguration|Set-NetIsatapConfiguration|Set-NetNatTransitionConfiguration|Set-NetTeredoConfiguration|" + + "Find-Package|Find-PackageProvider|Get-Package|Get-PackageProvider|Get-PackageSource|Import-PackageProvider|Install-Package|Install-PackageProvider|Register-PackageSource|Save-Package|Set-PackageSource|Uninstall-Package|Unregister-PackageSource|" + + "Clear-PcsvDeviceLog|Get-PcsvDevice|Get-PcsvDeviceLog|Restart-PcsvDevice|Set-PcsvDeviceBootConfiguration|Set-PcsvDeviceNetworkConfiguration|Set-PcsvDeviceUserPassword|Start-PcsvDevice|Stop-PcsvDevice|" + + "AfterAll|AfterEach|Assert-MockCalled|Assert-VerifiableMocks|BeforeAll|BeforeEach|Context|Describe|Get-MockDynamicParameters|Get-TestDriveItem|In|InModuleScope|Invoke-Mock|Invoke-Pester|It|Mock|New-Fixture|Set-DynamicParameterVariables|Setup|Should|" + + "Add-CertificateEnrollmentPolicyServer|Export-Certificate|Export-PfxCertificate|Get-Certificate|Get-CertificateAutoEnrollmentPolicy|Get-CertificateEnrollmentPolicyServer|Get-CertificateNotificationTask|Get-PfxData|Import-Certificate|Import-PfxCertificate|New-CertificateNotificationTask|New-SelfSignedCertificate|Remove-CertificateEnrollmentPolicyServer|Remove-CertificateNotificationTask|Set-CertificateAutoEnrollmentPolicy|Switch-Certificate|Test-Certificate|" + + "Disable-PnpDevice|Enable-PnpDevice|Get-PnpDevice|Get-PnpDeviceProperty|" + + "Find-DscResource|Find-Module|Find-Script|Get-InstalledModule|Get-InstalledScript|Get-PSRepository|Install-Module|Install-Script|New-ScriptFileInfo|Publish-Module|Publish-Script|Register-PSRepository|Save-Module|Save-Script|Set-PSRepository|Test-ScriptFileInfo|Uninstall-Module|Uninstall-Script|Unregister-PSRepository|Update-Module|Update-ModuleManifest|Update-Script|Update-ScriptFileInfo|" + + "Add-Printer|Add-PrinterDriver|Add-PrinterPort|Get-PrintConfiguration|Get-Printer|Get-PrinterDriver|Get-PrinterPort|Get-PrinterProperty|Get-PrintJob|Read-PrinterNfcTag|Remove-Printer|Remove-PrinterDriver|Remove-PrinterPort|Remove-PrintJob|Rename-Printer|Restart-PrintJob|Resume-PrintJob|Set-PrintConfiguration|Set-Printer|Set-PrinterProperty|Suspend-PrintJob|Write-PrinterNfcTag|" + + "Configuration|Disable-DscDebug|Enable-DscDebug|Get-DscConfiguration|Get-DscConfigurationStatus|Get-DscLocalConfigurationManager|Get-DscResource|New-DscChecksum|Remove-DscConfigurationDocument|Restore-DscConfiguration|Stop-DscConfiguration|Invoke-DscResource|Publish-DscConfiguration|Set-DscLocalConfigurationManager|Start-DscConfiguration|Test-DscConfiguration|Update-DscConfiguration|" + + "Disable-PSTrace|Disable-PSWSManCombinedTrace|Disable-WSManTrace|Enable-PSTrace|Enable-PSWSManCombinedTrace|Enable-WSManTrace|Get-LogProperties|Set-LogProperties|Start-Trace|Stop-Trace|" + + "PSConsoleHostReadline|Get-PSReadlineKeyHandler|Get-PSReadlineOption|Remove-PSReadlineKeyHandler|Set-PSReadlineKeyHandler|Set-PSReadlineOption|" + + "Add-JobTrigger|Disable-JobTrigger|Disable-ScheduledJob|Enable-JobTrigger|Enable-ScheduledJob|Get-JobTrigger|Get-ScheduledJob|Get-ScheduledJobOption|New-JobTrigger|New-ScheduledJobOption|Register-ScheduledJob|Remove-JobTrigger|Set-JobTrigger|Set-ScheduledJob|Set-ScheduledJobOption|Unregister-ScheduledJob|" + + "New-PSWorkflowSession|New-PSWorkflowExecutionOption|" + + "Invoke-AsWorkflow|" + + "Disable-ScheduledTask|Enable-ScheduledTask|Export-ScheduledTask|Get-ClusteredScheduledTask|Get-ScheduledTask|Get-ScheduledTaskInfo|New-ScheduledTask|New-ScheduledTaskAction|New-ScheduledTaskPrincipal|New-ScheduledTaskSettingsSet|New-ScheduledTaskTrigger|Register-ClusteredScheduledTask|Register-ScheduledTask|Set-ClusteredScheduledTask|Set-ScheduledTask|Start-ScheduledTask|Stop-ScheduledTask|Unregister-ClusteredScheduledTask|Unregister-ScheduledTask|" + + "Confirm-SecureBootUEFI|Format-SecureBootUEFI|Get-SecureBootPolicy|Get-SecureBootUEFI|Set-SecureBootUEFI|" + + "Block-SmbShareAccess|Close-SmbOpenFile|Close-SmbSession|Disable-SmbDelegation|Enable-SmbDelegation|Get-SmbBandwidthLimit|Get-SmbClientConfiguration|Get-SmbClientNetworkInterface|Get-SmbConnection|Get-SmbDelegation|Get-SmbMapping|Get-SmbMultichannelConnection|Get-SmbMultichannelConstraint|Get-SmbOpenFile|Get-SmbServerConfiguration|Get-SmbServerNetworkInterface|Get-SmbSession|Get-SmbShare|Get-SmbShareAccess|Grant-SmbShareAccess|New-SmbMapping|New-SmbMultichannelConstraint|New-SmbShare|Remove-SmbBandwidthLimit|Remove-SmbMapping|Remove-SmbMultichannelConstraint|Remove-SmbShare|Revoke-SmbShareAccess|Set-SmbBandwidthLimit|Set-SmbClientConfiguration|Set-SmbPathAcl|Set-SmbServerConfiguration|Set-SmbShare|Unblock-SmbShareAccess|Update-SmbMultichannelConnection|" + + "Move-SmbClient|Get-SmbWitnessClient|Move-SmbWitnessClient|" + + "Get-StartApps|Export-StartLayout|Import-StartLayout|" + + "Disable-PhysicalDiskIndication|Disable-StorageDiagnosticLog|Enable-PhysicalDiskIndication|Enable-StorageDiagnosticLog|Flush-Volume|Get-DiskSNV|Get-PhysicalDiskSNV|Get-StorageEnclosureSNV|Initialize-Volume|Write-FileSystemCache|Add-InitiatorIdToMaskingSet|Add-PartitionAccessPath|Add-PhysicalDisk|Add-TargetPortToMaskingSet|Add-VirtualDiskToMaskingSet|Block-FileShareAccess|Clear-Disk|Clear-FileStorageTier|Clear-StorageDiagnosticInfo|Connect-VirtualDisk|Debug-FileShare|Debug-StorageSubSystem|Debug-Volume|Disable-PhysicalDiskIdentification|Disable-StorageEnclosureIdentification|Disable-StorageHighAvailability|Disconnect-VirtualDisk|Dismount-DiskImage|Enable-PhysicalDiskIdentification|Enable-StorageEnclosureIdentification|Enable-StorageHighAvailability|Format-Volume|Get-DedupProperties|Get-Disk|Get-DiskImage|Get-DiskStorageNodeView|Get-FileIntegrity|Get-FileShare|Get-FileShareAccessControlEntry|Get-FileStorageTier|Get-InitiatorId|Get-InitiatorPort|Get-MaskingSet|Get-OffloadDataTransferSetting|Get-Partition|Get-PartitionSupportedSize|Get-PhysicalDisk|Get-PhysicalDiskStorageNodeView|Get-ResiliencySetting|Get-StorageAdvancedProperty|Get-StorageDiagnosticInfo|Get-StorageEnclosure|Get-StorageEnclosureStorageNodeView|Get-StorageEnclosureVendorData|Get-StorageFaultDomain|Get-StorageFileServer|Get-StorageFirmwareInformation|Get-StorageHealthAction|Get-StorageHealthReport|Get-StorageHealthSetting|Get-StorageJob|Get-StorageNode|Get-StoragePool|Get-StorageProvider|Get-StorageReliabilityCounter|Get-StorageSetting|Get-StorageSubSystem|Get-StorageTier|Get-StorageTierSupportedSize|Get-SupportedClusterSizes|Get-SupportedFileSystems|Get-TargetPort|Get-TargetPortal|Get-VirtualDisk|Get-VirtualDiskSupportedSize|Get-Volume|Get-VolumeCorruptionCount|Get-VolumeScrubPolicy|Grant-FileShareAccess|Hide-VirtualDisk|Initialize-Disk|Mount-DiskImage|New-FileShare|New-MaskingSet|New-Partition|New-StorageFileServer|New-StoragePool|New-StorageSubsystemVirtualDisk|New-StorageTier|New-VirtualDisk|New-VirtualDiskClone|New-VirtualDiskSnapshot|New-Volume|Optimize-StoragePool|Optimize-Volume|Register-StorageSubsystem|Remove-FileShare|Remove-InitiatorId|Remove-InitiatorIdFromMaskingSet|Remove-MaskingSet|Remove-Partition|Remove-PartitionAccessPath|Remove-PhysicalDisk|Remove-StorageFileServer|Remove-StorageHealthSetting|Remove-StoragePool|Remove-StorageTier|Remove-TargetPortFromMaskingSet|Remove-VirtualDisk|Remove-VirtualDiskFromMaskingSet|Rename-MaskingSet|Repair-FileIntegrity|Repair-VirtualDisk|Repair-Volume|Reset-PhysicalDisk|Reset-StorageReliabilityCounter|Resize-Partition|Resize-StorageTier|Resize-VirtualDisk|Revoke-FileShareAccess|Set-Disk|Set-FileIntegrity|Set-FileShare|Set-FileStorageTier|Set-InitiatorPort|Set-Partition|Set-PhysicalDisk|Set-ResiliencySetting|Set-StorageFileServer|Set-StorageHealthSetting|Set-StoragePool|Set-StorageProvider|Set-StorageSetting|Set-StorageSubSystem|Set-StorageTier|Set-VirtualDisk|Set-Volume|Set-VolumeScrubPolicy|Show-VirtualDisk|Start-StorageDiagnosticLog|Stop-StorageDiagnosticLog|Stop-StorageJob|Unblock-FileShareAccess|Unregister-StorageSubsystem|Update-Disk|Update-HostStorageCache|Update-StorageFirmware|Update-StoragePool|Update-StorageProviderCache|Write-VolumeCache|" + + "Disable-TlsCipherSuite|Disable-TlsSessionTicketKey|Enable-TlsCipherSuite|Enable-TlsSessionTicketKey|Export-TlsSessionTicketKey|Get-TlsCipherSuite|New-TlsSessionTicketKey|" + + "Get-TroubleshootingPack|Invoke-TroubleshootingPack|" + + "Clear-Tpm|ConvertTo-TpmOwnerAuth|Disable-TpmAutoProvisioning|Enable-TpmAutoProvisioning|Get-Tpm|Get-TpmEndorsementKeyInfo|Get-TpmSupportedFeature|Import-TpmOwnerAuth|Initialize-Tpm|Set-TpmOwnerAuth|Unblock-Tpm|" + + "Add-VpnConnection|Add-VpnConnectionRoute|Add-VpnConnectionTriggerApplication|Add-VpnConnectionTriggerDnsConfiguration|Add-VpnConnectionTriggerTrustedNetwork|Get-VpnConnection|Get-VpnConnectionTrigger|New-EapConfiguration|New-VpnServerAddress|Remove-VpnConnection|Remove-VpnConnectionRoute|Remove-VpnConnectionTriggerApplication|Remove-VpnConnectionTriggerDnsConfiguration|Remove-VpnConnectionTriggerTrustedNetwork|Set-VpnConnection|Set-VpnConnectionIPsecConfiguration|Set-VpnConnectionProxy|Set-VpnConnectionTriggerDnsConfiguration|Set-VpnConnectionTriggerTrustedNetwork|" + + "Add-OdbcDsn|Disable-OdbcPerfCounter|Disable-WdacBidTrace|Enable-OdbcPerfCounter|Enable-WdacBidTrace|Get-OdbcDriver|Get-OdbcDsn|Get-OdbcPerfCounter|Get-WdacBidTrace|Remove-OdbcDsn|Set-OdbcDriver|Set-OdbcDsn|" + + "Get-WindowsDeveloperLicense|Show-WindowsDeveloperLicenseRegistration|Unregister-WindowsDeveloperLicense|" + + "Disable-WindowsErrorReporting|Enable-WindowsErrorReporting|Get-WindowsErrorReporting|" + + "Get-WindowsSearchSetting|Set-WindowsSearchSetting|" + + "Get-WindowsUpdateLog" + ); + + var keywordMapper = this.createKeywordMapper({ + "support.function": builtinFunctions, + "keyword": keywords + }, "identifier"); + var binaryOperatorsRe = ( + "eq|ne|gt|lt|le|ge|like|notlike|match|notmatch|contains|notcontains|in|notin|band|bor|bxor|bnot|" + + "ceq|cne|cgt|clt|cle|cge|clike|cnotlike|cmatch|cnotmatch|ccontains|cnotcontains|cin|cnotin|" + + "ieq|ine|igt|ilt|ile|ige|ilike|inotlike|imatch|inotmatch|icontains|inotcontains|iin|inotin|" + + "and|or|xor|not|" + + "split|join|replace|f|" + + "csplit|creplace|" + + "isplit|ireplace|" + + "is|isnot|as|" + + "shl|shr" + ); + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "#.*$" + }, { + token : "comment.start", + regex : "<#", + next : "comment" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F]+\\b" + }, { + token : "constant.numeric", // float + regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" + }, { + token : "constant.language.boolean", + regex : "[$](?:[Tt]rue|[Ff]alse)\\b" + }, { + token : "constant.language", + regex : "[$][Nn]ull\\b" + }, { + token : "variable.instance", + regex : "[$][a-zA-Z][a-zA-Z0-9_]*\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b" + }, { + token : "keyword.operator", + regex : "\\-(?:" + binaryOperatorsRe + ")" + }, { + token : "keyword.operator", + regex : "&|\\+|\\-|\\*|\\/|\\%|\\=|\\>|\\&|\\!|\\|" + }, { + token : "lparen", + regex : "[[({]" + }, { + token : "rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment.end", + regex : "#>", + next : "start" + }, { + token : "doc.comment.tag", + regex : "^\\.\\w+" + }, { + defaultToken : "comment" + } + ] + }; +}; + +oop.inherits(PowershellHighlightRules, TextHighlightRules); + +exports.PowershellHighlightRules = PowershellHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, row); + + var match = line.match(this.foldingStartMarker); + if (match) { + var i = match.index; + + if (match[1]) + return this.openingBracketBlock(session, match[1], row, i); + + var range = session.getCommentFoldRange(row, i + match[0].length, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/powershell",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/powershell_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var PowershellHighlightRules = acequire("./powershell_highlight_rules").PowershellHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = PowershellHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode({start: "^\\s*(<#)", end: "^[#\\s]>\\s*$"}); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + this.blockComment = {start: "<#", end: "#>"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + + this.createWorker = function(session) { + return null; + }; + + this.$id = "ace/mode/powershell"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],219:[function(require,module,exports){ +ace.define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var PythonHighlightRules = function() { + + var keywords = ( + "and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + + "raise|return|try|while|with|yield" + ); + + var builtinConstants = ( + "True|False|None|NotImplemented|Ellipsis|__debug__" + ); + + var builtinFunctions = ( + "abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern" + ); + var keywordMapper = this.createKeywordMapper({ + "invalid.deprecated": "debugger", + "support.function": builtinFunctions, + "constant.language": builtinConstants, + "keyword": keywords + }, "identifier"); + + var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; + + var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; + var octInteger = "(?:0[oO]?[0-7]+)"; + var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; + var binInteger = "(?:0[bB][01]+)"; + var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; + + var exponent = "(?:[eE][+-]?\\d+)"; + var fraction = "(?:\\.\\d+)"; + var intPart = "(?:\\d+)"; + var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; + var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; + var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; + + var stringEscape = "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})"; + + this.$rules = { + "start" : [ { + token : "comment", + regex : "#.*$" + }, { + token : "string", // multi line """ string start + regex : strPre + '"{3}', + next : "qqstring3" + }, { + token : "string", // " string + regex : strPre + '"(?=.)', + next : "qqstring" + }, { + token : "string", // multi line ''' string start + regex : strPre + "'{3}", + next : "qstring3" + }, { + token : "string", // ' string + regex : strPre + "'(?=.)", + next : "qstring" + }, { + token : "constant.numeric", // imaginary + regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" + }, { + token : "constant.numeric", // float + regex : floatNumber + }, { + token : "constant.numeric", // long integer + regex : integer + "[lL]\\b" + }, { + token : "constant.numeric", // integer + regex : integer + "\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "keyword.operator", + regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" + }, { + token : "paren.lparen", + regex : "[\\[\\(\\{]" + }, { + token : "paren.rparen", + regex : "[\\]\\)\\}]" + }, { + token : "text", + regex : "\\s+" + } ], + "qqstring3" : [ { + token : "constant.language.escape", + regex : stringEscape + }, { + token : "string", // multi line """ string end + regex : '"{3}', + next : "start" + }, { + defaultToken : "string" + } ], + "qstring3" : [ { + token : "constant.language.escape", + regex : stringEscape + }, { + token : "string", // multi line ''' string end + regex : "'{3}", + next : "start" + }, { + defaultToken : "string" + } ], + "qqstring" : [{ + token : "constant.language.escape", + regex : stringEscape + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "start" + }, { + defaultToken: "string" + }], + "qstring" : [{ + token : "constant.language.escape", + regex : stringEscape + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "start" + }, { + defaultToken: "string" + }] + }; +}; + +oop.inherits(PythonHighlightRules, TextHighlightRules); + +exports.PythonHighlightRules = PythonHighlightRules; +}); + +ace.define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(markers) { + this.foldingStartMarker = new RegExp("([\\[{])(?:\\s*)$|(" + markers + ")(?:\\s*)(?:#.*)?$"); +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var line = session.getLine(row); + var match = line.match(this.foldingStartMarker); + if (match) { + if (match[1]) + return this.openingBracketBlock(session, match[1], row, match.index); + if (match[2]) + return this.indentationBlock(session, row, match.index + match[2].length); + return this.indentationBlock(session, row); + } + } + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/python",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/python_highlight_rules","ace/mode/folding/pythonic","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var PythonHighlightRules = acequire("./python_highlight_rules").PythonHighlightRules; +var PythonFoldMode = acequire("./folding/pythonic").FoldMode; +var Range = acequire("../range").Range; + +var Mode = function() { + this.HighlightRules = PythonHighlightRules; + this.foldingRules = new PythonFoldMode("\\:"); + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[:]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + var outdents = { + "pass": 1, + "return": 1, + "raise": 1, + "break": 1, + "continue": 1 + }; + + this.checkOutdent = function(state, line, input) { + if (input !== "\r\n" && input !== "\r" && input !== "\n") + return false; + + var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; + + if (!tokens) + return false; + do { + var last = tokens.pop(); + } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); + + if (!last) + return false; + + return (last.type == "keyword" && outdents[last.value]); + }; + + this.autoOutdent = function(state, doc, row) { + + row += 1; + var indent = this.$getIndent(doc.getLine(row)); + var tab = doc.getTabString(); + if (indent.slice(-tab.length) == tab) + doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); + }; + + this.$id = "ace/mode/python"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],220:[function(require,module,exports){ +ace.define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var constantOtherSymbol = exports.constantOtherSymbol = { + token : "constant.other.symbol.ruby", // symbol + regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" +}; + +var qString = exports.qString = { + token : "string", // single line + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" +}; + +var qqString = exports.qqString = { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' +}; + +var tString = exports.tString = { + token : "string", // backtick string + regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" +}; + +var constantNumericHex = exports.constantNumericHex = { + token : "constant.numeric", // hex + regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" +}; + +var constantNumericFloat = exports.constantNumericFloat = { + token : "constant.numeric", // float + regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" +}; + +var RubyHighlightRules = function() { + + var builtinFunctions = ( + "abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + + "gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" + + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + + "raw|readline|readlines|redirect?|request_via_redirect|acequire|scan|select|" + + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + + "translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" + + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + + "has_many|has_one|belongs_to|has_and_belongs_to_many" + ); + + var keywords = ( + "alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield" + ); + + var buildinConstants = ( + "true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING" + ); + + var builtinVariables = ( + "$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|" + + "$!|root_url|flash|session|cookies|params|request|response|logger|self" + ); + + var keywordMapper = this.$keywords = this.createKeywordMapper({ + "keyword": keywords, + "constant.language": buildinConstants, + "variable.language": builtinVariables, + "support.function": builtinFunctions, + "invalid.deprecated": "debugger" // TODO is this a remnant from js mode? + }, "identifier"); + + this.$rules = { + "start" : [ + { + token : "comment", + regex : "#.*$" + }, { + token : "comment", // multi line comment + regex : "^=begin(?:$|\\s.*$)", + next : "comment" + }, { + token : "string.regexp", + regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" + }, + + [{ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + return "paren.lparen"; + } + if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1) + return "paren.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.start", + regex : /"/, + push : [{ + token : "constant.language.escape", + regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ + }, { + token : "paren.start", + regex : /#{/, + push : "start" + }, { + token : "string.end", + regex : /"/, + next : "pop" + }, { + defaultToken: "string" + }] + }, { + token : "string.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ + }, { + token : "paren.start", + regex : /#{/, + push : "start" + }, { + token : "string.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string" + }] + }, { + token : "string.start", + regex : /'/, + push : [{ + token : "constant.language.escape", + regex : /\\['\\]/ + }, { + token : "string.end", + regex : /'/, + next : "pop" + }, { + defaultToken: "string" + }] + }], + + { + token : "text", // namespaces aren't symbols + regex : "::" + }, { + token : "variable.instance", // instance variable + regex : "@{1,2}[a-zA-Z_\\d]+" + }, { + token : "support.class", // class name + regex : "[A-Z][a-zA-Z_\\d]+" + }, + + constantOtherSymbol, + constantNumericHex, + constantNumericFloat, + + { + token : "constant.language.boolean", + regex : "(?:true|false)\\b" + }, { + token : keywordMapper, + regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" + }, { + token : "punctuation.separator.key-value", + regex : "=>" + }, { + stateName: "heredoc", + onMatch : function(value, currentState, stack) { + var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; + var tokens = value.split(this.splitRegex); + stack.push(next, tokens[3]); + return [ + {type:"constant", value: tokens[1]}, + {type:"string", value: tokens[2]}, + {type:"support.class", value: tokens[3]}, + {type:"string", value: tokens[4]} + ]; + }, + regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)", + rules: { + heredoc: [{ + onMatch: function(value, currentState, stack) { + if (value === stack[1]) { + stack.shift(); + stack.shift(); + this.next = stack[0] || "start"; + return "support.class"; + } + this.next = ""; + return "string"; + }, + regex: ".*$", + next: "start" + }], + indentedHeredoc: [{ + token: "string", + regex: "^ +" + }, { + onMatch: function(value, currentState, stack) { + if (value === stack[1]) { + stack.shift(); + stack.shift(); + this.next = stack[0] || "start"; + return "support.class"; + } + this.next = ""; + return "string"; + }, + regex: ".*$", + next: "start" + }] + } + }, { + regex : "$", + token : "empty", + next : function(currentState, stack) { + if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") + return stack[0]; + return currentState; + } + }, { + token : "string.character", + regex : "\\B\\?." + }, { + token : "keyword.operator", + regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : "^=end(?:$|\\s.*$)", + next : "start" + }, { + token : "comment", // comment spanning whole line + regex : ".+" + } + ] + }; + + this.normalizeRules(); +}; + +oop.inherits(RubyHighlightRules, TextHighlightRules); + +exports.RubyHighlightRules = RubyHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var range = this.indentationBlock(session, row); + if (range) + return range; + + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1 || line[startLevel] != "#") + return; + + var startColumn = line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + line = session.getLine(row); + var level = line.search(re); + + if (level == -1) + continue; + + if (line[level] != "#") + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + var indent = line.search(/\S/); + var next = session.getLine(row + 1); + var prev = session.getLine(row - 1); + var prevIndent = prev.search(/\S/); + var nextIndent = next.search(/\S/); + + if (indent == -1) { + session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; + return ""; + } + if (prevIndent == -1) { + if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { + session.foldWidgets[row - 1] = ""; + session.foldWidgets[row + 1] = ""; + return "start"; + } + } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { + if (session.getLine(row - 2).search(/\S/) == -1) { + session.foldWidgets[row - 1] = "start"; + session.foldWidgets[row + 1] = ""; + return ""; + } + } + + if (prevIndent!= -1 && prevIndent < indent) + session.foldWidgets[row - 1] = "start"; + else + session.foldWidgets[row - 1] = ""; + + if (indent < nextIndent) + return "start"; + else + return ""; + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/coffee"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var RubyHighlightRules = acequire("./ruby_highlight_rules").RubyHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var Range = acequire("../range").Range; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var FoldMode = acequire("./folding/coffee").FoldMode; + +var Mode = function() { + this.HighlightRules = RubyHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new FoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + + this.lineCommentStart = "#"; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/); + var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/); + var startingConditional = line.match(/^\s*(if|else|when)\s*/) + if (match || startingClassOrMethod || startingDoBlock || startingConditional) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return /^\s+(end|else)$/.test(line + input) || this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, session, row) { + var line = session.getLine(row); + if (/}/.test(line)) + return this.$outdent.autoOutdent(session, row); + var indent = this.$getIndent(line); + var prevLine = session.getLine(row - 1); + var prevIndent = this.$getIndent(prevLine); + var tab = session.getTabString(); + if (prevIndent.length <= indent.length) { + if (indent.slice(-tab.length) == tab) + session.remove(new Range(row, indent.length-tab.length, row, indent.length)); + } + }; + + this.$id = "ace/mode/ruby"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{}],221:[function(require,module,exports){ +ace.define("ace/mode/scss_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var ScssHighlightRules = function() { + + var properties = lang.arrayToMap( (function () { + + var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); + + var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + + "background-size|binding|border-bottom-colors|border-left-colors|" + + "border-right-colors|border-top-colors|border-end|border-end-color|" + + "border-end-style|border-end-width|border-image|border-start|" + + "border-start-color|border-start-style|border-start-width|box-align|" + + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + + "font-feature-settings|font-language-override|force-broken-image-icon|" + + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + + "outline-offset|outline-radius|outline-radius-bottomleft|" + + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + + "text-decoration-style|transform|transform-origin|transition|" + + "transition-delay|transition-duration|transition-property|" + + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + + "window-shadow|border-radius").split("|"); + + var properties = ("azimuth|background-attachment|background-color|background-image|" + + "background-position|background-repeat|background|border-bottom-color|" + + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + + "border-color|border-left-color|border-left-style|border-left-width|" + + "border-left|border-right-color|border-right-style|border-right-width|" + + "border-right|border-spacing|border-style|border-top-color|" + + "border-top-style|border-top-width|border-top|border-width|border|bottom|" + + "box-shadow|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + + "letter-spacing|line-height|list-style-image|list-style-position|" + + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + + "min-width|opacity|orphans|outline-color|" + + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + + "padding-left|padding-right|padding-top|padding|page-break-after|" + + "page-break-before|page-break-inside|page|pause-after|pause-before|" + + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + + "stress|table-layout|text-align|text-decoration|text-indent|" + + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + + "z-index").split("|"); + var ret = []; + for (var i=0, ln=browserPrefix.length; i|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + }, { + token : "text", + regex : "\\s+" + }, { + caseInsensitive: true + } + ], + "comment" : [ + { + token : "comment", // closing comment + regex : ".*?\\*\\/", + next : "start" + }, { + token : "comment", // comment spanning whole line + regex : ".+" + } + ], + "qqstring" : [ + { + token : "string", + regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', + next : "start" + }, { + token : "string", + regex : '.+' + } + ], + "qstring" : [ + { + token : "string", + regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", + next : "start" + }, { + token : "string", + regex : '.+' + } + ] + }; +}; + +oop.inherits(ScssHighlightRules, TextHighlightRules); + +exports.ScssHighlightRules = ScssHighlightRules; + +}); + +ace.define("ace/mode/sass_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/scss_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var ScssHighlightRules = acequire("./scss_highlight_rules").ScssHighlightRules; + +var SassHighlightRules = function() { + ScssHighlightRules.call(this); + var start = this.$rules.start; + if (start[1].token == "comment") { + start.splice(1, 1, { + onMatch: function(value, currentState, stack) { + stack.unshift(this.next, -1, value.length - 2, currentState); + return "comment"; + }, + regex: /^\s*\/\*/, + next: "comment" + }, { + token: "error.invalid", + regex: "/\\*|[{;}]" + }, { + token: "support.type", + regex: /^\s*:[\w\-]+\s/ + }); + + this.$rules.comment = [ + {regex: /^\s*/, onMatch: function(value, currentState, stack) { + if (stack[1] === -1) + stack[1] = Math.max(stack[2], value.length - 1); + if (value.length <= stack[1]) {stack.shift();stack.shift();stack.shift(); + this.next = stack.shift(); + return "text"; + } else { + this.next = ""; + return "comment"; + } + }, next: "start"}, + {defaultToken: "comment"} + ] + } +}; + +oop.inherits(SassHighlightRules, ScssHighlightRules); + +exports.SassHighlightRules = SassHighlightRules; + +}); + +ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var range = this.indentationBlock(session, row); + if (range) + return range; + + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1 || line[startLevel] != "#") + return; + + var startColumn = line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + line = session.getLine(row); + var level = line.search(re); + + if (level == -1) + continue; + + if (line[level] != "#") + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + var indent = line.search(/\S/); + var next = session.getLine(row + 1); + var prev = session.getLine(row - 1); + var prevIndent = prev.search(/\S/); + var nextIndent = next.search(/\S/); + + if (indent == -1) { + session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; + return ""; + } + if (prevIndent == -1) { + if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { + session.foldWidgets[row - 1] = ""; + session.foldWidgets[row + 1] = ""; + return "start"; + } + } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { + if (session.getLine(row - 2).search(/\S/) == -1) { + session.foldWidgets[row - 1] = "start"; + session.foldWidgets[row + 1] = ""; + return ""; + } + } + + if (prevIndent!= -1 && prevIndent < indent) + session.foldWidgets[row - 1] = "start"; + else + session.foldWidgets[row - 1] = ""; + + if (indent < nextIndent) + return "start"; + else + return ""; + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/sass",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sass_highlight_rules","ace/mode/folding/coffee"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var SassHighlightRules = acequire("./sass_highlight_rules").SassHighlightRules; +var FoldMode = acequire("./folding/coffee").FoldMode; + +var Mode = function() { + this.HighlightRules = SassHighlightRules; + this.foldingRules = new FoldMode(); + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + this.lineCommentStart = "//"; + this.$id = "ace/mode/sass"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); + +},{}],222:[function(require,module,exports){ +ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var XmlHighlightRules = function(normalize) { + var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; + + this.$rules = { + start : [ + {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, + { + token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], + regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true + }, + { + token : ["punctuation.instruction.xml", "keyword.instruction.xml"], + regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" + }, + {token : "comment.xml", regex : "<\\!--", next : "comment"}, + { + token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], + regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true + }, + {include : "tag"}, + {token : "text.end-tag-open.xml", regex: "", + next : "start" + }], + + processing_instruction : [ + {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, + {defaultToken : "instruction.xml"} + ], + + doctype : [ + {include : "whitespace"}, + {include : "string"}, + {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, + {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, + {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} + ], + + int_subset : [{ + token : "text.xml", + regex : "\\s+" + }, { + token: "punctuation.int-subset.xml", + regex: "]", + next: "pop" + }, { + token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], + regex : "(<\\!)(" + tagRegex + ")", + push : [{ + token : "text", + regex : "\\s+" + }, + { + token : "punctuation.markup-decl.xml", + regex : ">", + next : "pop" + }, + {include : "string"}] + }], + + cdata : [ + {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, + {token : "text.xml", regex : "\\s+"}, + {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} + ], + + comment : [ + {token : "comment.xml", regex : "-->", next : "start"}, + {defaultToken : "comment.xml"} + ], + + reference : [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + attr_reference : [{ + token : "constant.language.escape.reference.attribute-value.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }], + + tag : [{ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], + regex : "(?:(<)|(", next : "start"} + ] + }], + + tag_whitespace : [ + {token : "text.tag-whitespace.xml", regex : "\\s+"} + ], + whitespace : [ + {token : "text.whitespace.xml", regex : "\\s+"} + ], + string: [{ + token : "string.xml", + regex : "'", + push : [ + {token : "string.xml", regex: "'", next: "pop"}, + {defaultToken : "string.xml"} + ] + }, { + token : "string.xml", + regex : '"', + push : [ + {token : "string.xml", regex: '"', next: "pop"}, + {defaultToken : "string.xml"} + ] + }], + + attributes: [{ + token : "entity.other.attribute-name.xml", + regex : "(?:" + tagRegex + ":)?" + tagRegex + "" + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + include: "tag_whitespace" + }, { + include: "attribute_value" + }], + + attribute_value: [{ + token : "string.attribute-value.xml", + regex : "'", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "attr_reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }] + }; + + if (this.constructor === XmlHighlightRules) + this.normalizeRules(); +}; + + +(function() { + + this.embedTagRules = function(HighlightRules, prefix, tag){ + this.$rules.tag.unshift({ + token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(<)(" + tag + "(?=\\s|>|$))", + next: [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} + ] + }); + + this.$rules[tag + "-end"] = [ + {include : "attributes"}, + {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", + onMatch : function(value, currentState, stack) { + stack.splice(0); + return this.token; + }} + ] + + this.embedRules(HighlightRules, prefix, [{ + token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], + regex : "(|$))", + next: tag + "-end" + }, { + token: "string.cdata.xml", + regex : "<\\!\\[CDATA\\[" + }, { + token: "string.cdata.xml", + regex : "\\]\\]>" + }]); + }; + +}).call(TextHighlightRules.prototype); + +oop.inherits(XmlHighlightRules, TextHighlightRules); + +exports.XmlHighlightRules = XmlHighlightRules; +}); + +ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +function is(token, type) { + return token.type.lastIndexOf(type + ".xml") > -1; +} + +var XmlBehaviour = function () { + + this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { + if (text == '"' || text == "'") { + var quote = text; + var selected = session.doc.getTextRange(editor.getSelectionRange()); + if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { + return { + text: quote + selected + quote, + selection: false + }; + } + + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var rightChar = line.substring(cursor.column, cursor.column + 1); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { + return { + text: "", + selection: [1, 1] + }; + } + + if (!token) + token = iterator.stepBackward(); + + if (!token) + return; + + while (is(token, "tag-whitespace") || is(token, "whitespace")) { + token = iterator.stepBackward(); + } + var rightSpace = !rightChar || rightChar.match(/\s/); + if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { + return { + text: quote + quote, + selection: [1, 1] + }; + } + } + }); + + this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && (selected == '"' || selected == "'")) { + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + + this.add("autoclosing", "insertion", function (state, action, editor, session, text) { + if (text == '>') { + var position = editor.getSelectionRange().start; + var iterator = new TokenIterator(session, position.row, position.column); + var token = iterator.getCurrentToken() || iterator.stepBackward(); + if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) + return; + if (is(token, "reference.attribute-value")) + return; + if (is(token, "attribute-value")) { + var firstChar = token.value.charAt(0); + if (firstChar == '"' || firstChar == "'") { + var lastChar = token.value.charAt(token.value.length - 1); + var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; + if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) + return; + } + } + while (!is(token, "tag-name")) { + token = iterator.stepBackward(); + if (token.value == "<") { + token = iterator.stepForward(); + break; + } + } + + var tokenRow = iterator.getCurrentTokenRow(); + var tokenColumn = iterator.getCurrentTokenColumn(); + if (is(iterator.stepBackward(), "end-tag-open")) + return; + + var element = token.value; + if (tokenRow == position.row) + element = element.substring(0, position.column - tokenColumn); + + if (this.voidElements.hasOwnProperty(element.toLowerCase())) + return; + + return { + text: ">" + "", + selection: [1, 1] + }; + } + }); + + this.add("autoindent", "insertion", function (state, action, editor, session, text) { + if (text == "\n") { + var cursor = editor.getCursorPosition(); + var line = session.getLine(cursor.row); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + if (token && token.type.indexOf("tag-close") !== -1) { + if (token.value == "/>") + return; + while (token && token.type.indexOf("tag-name") === -1) { + token = iterator.stepBackward(); + } + + if (!token) { + return; + } + + var tag = token.value; + var row = iterator.getCurrentTokenRow(); + token = iterator.stepBackward(); + if (!token || token.type.indexOf("end-tag") !== -1) { + return; + } + + if (this.voidElements && !this.voidElements[tag]) { + var nextToken = session.getTokenAt(cursor.row, cursor.column+1); + var line = session.getLine(row); + var nextIndent = this.$getIndent(line); + var indent = nextIndent + session.getTabString(); + + if (nextToken && nextToken.value === " -1; +} + +(function() { + + this.getFoldWidget = function(session, foldStyle, row) { + var tag = this._getFirstTagInLine(session, row); + + if (!tag) + return ""; + + if (tag.closing || (!tag.tagName && tag.selfClosing)) + return foldStyle == "markbeginend" ? "end" : ""; + + if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) + return ""; + + if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) + return ""; + + return "start"; + }; + this._getFirstTagInLine = function(session, row) { + var tokens = session.getTokens(row); + var tag = new Tag(); + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (is(token, "tag-open")) { + tag.end.column = tag.start.column + token.value.length; + tag.closing = is(token, "end-tag-open"); + token = tokens[++i]; + if (!token) + return null; + tag.tagName = token.value; + tag.end.column += token.value.length; + for (i++; i < tokens.length; i++) { + token = tokens[i]; + tag.end.column += token.value.length; + if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + break; + } + } + return tag; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == '/>'; + return tag; + } + tag.start.column += token.value.length; + } + + return null; + }; + + this._findEndTagInLine = function(session, row, tagName, startColumn) { + var tokens = session.getTokens(row); + var column = 0; + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + column += token.value.length; + if (column < startColumn) + continue; + if (is(token, "end-tag-open")) { + token = tokens[i + 1]; + if (token && token.value == tagName) + return true; + } + } + return false; + }; + this._readTagForward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + iterator.stepForward(); + return tag; + } + } while(token = iterator.stepForward()); + + return null; + }; + + this._readTagBackward = function(iterator) { + var token = iterator.getCurrentToken(); + if (!token) + return null; + + var tag = new Tag(); + do { + if (is(token, "tag-open")) { + tag.closing = is(token, "end-tag-open"); + tag.start.row = iterator.getCurrentTokenRow(); + tag.start.column = iterator.getCurrentTokenColumn(); + iterator.stepBackward(); + return tag; + } else if (is(token, "tag-name")) { + tag.tagName = token.value; + } else if (is(token, "tag-close")) { + tag.selfClosing = token.value == "/>"; + tag.end.row = iterator.getCurrentTokenRow(); + tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; + } + } while(token = iterator.stepBackward()); + + return null; + }; + + this._pop = function(stack, tag) { + while (stack.length) { + + var top = stack[stack.length-1]; + if (!tag || top.tagName == tag.tagName) { + return stack.pop(); + } + else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { + stack.pop(); + continue; + } else { + return null; + } + } + }; + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var firstTag = this._getFirstTagInLine(session, row); + + if (!firstTag) + return null; + + var isBackward = firstTag.closing || firstTag.selfClosing; + var stack = []; + var tag; + + if (!isBackward) { + var iterator = new TokenIterator(session, row, firstTag.start.column); + var start = { + row: row, + column: firstTag.start.column + firstTag.tagName.length + 2 + }; + if (firstTag.start.row == firstTag.end.row) + start.column = firstTag.end.column; + while (tag = this._readTagForward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) + return Range.fromPoints(start, tag.start); + } + else { + stack.push(tag); + } + } + } + else { + var iterator = new TokenIterator(session, row, firstTag.end.column); + var end = { + row: row, + column: firstTag.start.column + }; + + while (tag = this._readTagBackward(iterator)) { + if (tag.selfClosing) { + if (!stack.length) { + tag.start.column += tag.tagName.length + 2; + tag.end.column -= 2; + return Range.fromPoints(tag.start, tag.end); + } else + continue; + } + + if (!tag.closing) { + this._pop(stack, tag); + if (stack.length == 0) { + tag.start.column += tag.tagName.length + 2; + if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) + tag.start.column = tag.end.column; + return Range.fromPoints(tag.start, end); + } + } + else { + stack.push(tag); + } + } + } + + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var TextMode = acequire("./text").Mode; +var XmlHighlightRules = acequire("./xml_highlight_rules").XmlHighlightRules; +var XmlBehaviour = acequire("./behaviour/xml").XmlBehaviour; +var XmlFoldMode = acequire("./folding/xml").FoldMode; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; + +var Mode = function() { + this.HighlightRules = XmlHighlightRules; + this.$behaviour = new XmlBehaviour(); + this.foldingRules = new XmlFoldMode(); +}; + +oop.inherits(Mode, TextMode); + +(function() { + + this.voidElements = lang.arrayToMap([]); + + this.blockComment = {start: ""}; + + this.createWorker = function(session) { + var worker = new WorkerClient(["ace"], require("../worker/xml"), "Worker"); + worker.attachToDocument(session.getDocument()); + + worker.on("error", function(e) { + session.setAnnotations(e.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/xml"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +},{"../worker/xml":238}],223:[function(require,module,exports){ +ace.define("ace/mode/yaml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var YamlHighlightRules = function() { + this.$rules = { + "start" : [ + { + token : "comment", + regex : "#.*$" + }, { + token : "list.markup", + regex : /^(?:-{3}|\.{3})\s*(?=#|$)/ + }, { + token : "list.markup", + regex : /^\s*[\-?](?:$|\s)/ + }, { + token: "constant", + regex: "!![\\w//]+" + }, { + token: "constant.language", + regex: "[&\\*][a-zA-Z0-9-_]+" + }, { + token: ["meta.tag", "keyword"], + regex: /^(\s*\w.*?)(:(?:\s+|$))/ + },{ + token: ["meta.tag", "keyword"], + regex: /(\w+?)(\s*:(?:\s+|$))/ + }, { + token : "keyword.operator", + regex : "<<\\w*:\\w*" + }, { + token : "keyword.operator", + regex : "-\\s*(?=[{])" + }, { + token : "string", // single line + regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' + }, { + token : "string", // multi line string start + regex : '[|>][-+\\d\\s]*$', + next : "qqstring" + }, { + token : "string", // single quoted string + regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" + }, { + token : "constant.numeric", // float + regex : /(\b|[+\-\.])[\d_]+(?:(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)/ + }, { + token : "constant.numeric", // other number + regex : /[+\-]?\.inf\b|NaN\b|0x[\dA-Fa-f_]+|0b[10_]+/ + }, { + token : "constant.language.boolean", + regex : "\\b(?:true|false|TRUE|FALSE|True|False|yes|no)\\b" + }, { + token : "paren.lparen", + regex : "[[({]" + }, { + token : "paren.rparen", + regex : "[\\])}]" + } + ], + "qqstring" : [ + { + token : "string", + regex : '(?=(?:(?:\\\\.)|(?:[^:]))*?:)', + next : "start" + }, { + token : "string", + regex : '.+' + } + ]}; + +}; + +oop.inherits(YamlHighlightRules, TextHighlightRules); + +exports.YamlHighlightRules = YamlHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; + +var MatchingBraceOutdent = function() {}; + +(function() { + + this.checkOutdent = function(line, input) { + if (! /^\s+$/.test(line)) + return false; + + return /^\s*\}/.test(input); + }; + + this.autoOutdent = function(doc, row) { + var line = doc.getLine(row); + var match = line.match(/^(\s*\})/); + + if (!match) return 0; + + var column = match[1].length; + var openBracePos = doc.findMatchingBracket({row: row, column: column}); + + if (!openBracePos || openBracePos.row == row) return 0; + + var indent = this.$getIndent(doc.getLine(openBracePos.row)); + doc.replace(new Range(row, 0, row, column-1), indent); + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var BaseFoldMode = acequire("./fold_mode").FoldMode; +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.getFoldWidgetRange = function(session, foldStyle, row) { + var range = this.indentationBlock(session, row); + if (range) + return range; + + var re = /\S/; + var line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1 || line[startLevel] != "#") + return; + + var startColumn = line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + line = session.getLine(row); + var level = line.search(re); + + if (level == -1) + continue; + + if (line[level] != "#") + break; + + endRow = row; + } + + if (endRow > startRow) { + var endColumn = session.getLine(endRow).length; + return new Range(startRow, startColumn, endRow, endColumn); + } + }; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + var indent = line.search(/\S/); + var next = session.getLine(row + 1); + var prev = session.getLine(row - 1); + var prevIndent = prev.search(/\S/); + var nextIndent = next.search(/\S/); + + if (indent == -1) { + session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; + return ""; + } + if (prevIndent == -1) { + if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { + session.foldWidgets[row - 1] = ""; + session.foldWidgets[row + 1] = ""; + return "start"; + } + } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { + if (session.getLine(row - 2).search(/\S/) == -1) { + session.foldWidgets[row - 1] = "start"; + session.foldWidgets[row + 1] = ""; + return ""; + } + } + + if (prevIndent!= -1 && prevIndent < indent) + session.foldWidgets[row - 1] = "start"; + else + session.foldWidgets[row - 1] = ""; + + if (indent < nextIndent) + return "start"; + else + return ""; + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/yaml",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/yaml_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/folding/coffee"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var YamlHighlightRules = acequire("./yaml_highlight_rules").YamlHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var FoldMode = acequire("./folding/coffee").FoldMode; + +var Mode = function() { + this.HighlightRules = YamlHighlightRules; + this.$outdent = new MatchingBraceOutdent(); + this.foldingRules = new FoldMode(); + this.$behaviour = this.$defaultBehaviour; +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + + + this.$id = "ace/mode/yaml"; +}).call(Mode.prototype); + +exports.Mode = Mode; + +}); + +},{}],224:[function(require,module,exports){ +ace.define("ace/theme/github",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-github"; +exports.cssText = "\ +.ace-github .ace_gutter {\ +background: #e8e8e8;\ +color: #AAA;\ +}\ +.ace-github {\ +background: #fff;\ +color: #000;\ +}\ +.ace-github .ace_keyword {\ +font-weight: bold;\ +}\ +.ace-github .ace_string {\ +color: #D14;\ +}\ +.ace-github .ace_variable.ace_class {\ +color: teal;\ +}\ +.ace-github .ace_constant.ace_numeric {\ +color: #099;\ +}\ +.ace-github .ace_constant.ace_buildin {\ +color: #0086B3;\ +}\ +.ace-github .ace_support.ace_function {\ +color: #0086B3;\ +}\ +.ace-github .ace_comment {\ +color: #998;\ +font-style: italic;\ +}\ +.ace-github .ace_variable.ace_language {\ +color: #0086B3;\ +}\ +.ace-github .ace_paren {\ +font-weight: bold;\ +}\ +.ace-github .ace_boolean {\ +font-weight: bold;\ +}\ +.ace-github .ace_string.ace_regexp {\ +color: #009926;\ +font-weight: normal;\ +}\ +.ace-github .ace_variable.ace_instance {\ +color: teal;\ +}\ +.ace-github .ace_constant.ace_language {\ +font-weight: bold;\ +}\ +.ace-github .ace_cursor {\ +color: black;\ +}\ +.ace-github.ace_focus .ace_marker-layer .ace_active-line {\ +background: rgb(255, 255, 204);\ +}\ +.ace-github .ace_marker-layer .ace_active-line {\ +background: rgb(245, 245, 245);\ +}\ +.ace-github .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-github.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px white;\ +}\ +.ace-github.ace_nobold .ace_line > span {\ +font-weight: normal !important;\ +}\ +.ace-github .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-github .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-github .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-github .ace_gutter-active-line {\ +background-color : rgba(0, 0, 0, 0.07);\ +}\ +.ace-github .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-github .ace_invisible {\ +color: #BFBFBF\ +}\ +.ace-github .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-github .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}"; + + var dom = acequire("../lib/dom"); + dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],225:[function(require,module,exports){ +ace.define("ace/theme/kuroir",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-kuroir"; +exports.cssText = "\ +.ace-kuroir .ace_gutter {\ +background: #e8e8e8;\ +color: #333;\ +}\ +.ace-kuroir .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-kuroir {\ +background-color: #E8E9E8;\ +color: #363636;\ +}\ +.ace-kuroir .ace_cursor {\ +color: #202020;\ +}\ +.ace-kuroir .ace_marker-layer .ace_selection {\ +background: rgba(245, 170, 0, 0.57);\ +}\ +.ace-kuroir.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #E8E9E8;\ +}\ +.ace-kuroir .ace_marker-layer .ace_step {\ +background: rgb(198, 219, 174);\ +}\ +.ace-kuroir .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(0, 0, 0, 0.29);\ +}\ +.ace-kuroir .ace_marker-layer .ace_active-line {\ +background: rgba(203, 220, 47, 0.22);\ +}\ +.ace-kuroir .ace_gutter-active-line {\ +background-color: rgba(203, 220, 47, 0.22);\ +}\ +.ace-kuroir .ace_marker-layer .ace_selected-word {\ +border: 1px solid rgba(245, 170, 0, 0.57);\ +}\ +.ace-kuroir .ace_invisible {\ +color: #BFBFBF\ +}\ +.ace-kuroir .ace_fold {\ +border-color: #363636;\ +}\ +.ace-kuroir .ace_constant{color:#CD6839;}.ace-kuroir .ace_constant.ace_numeric{color:#9A5925;}.ace-kuroir .ace_support{color:#104E8B;}.ace-kuroir .ace_support.ace_function{color:#005273;}.ace-kuroir .ace_support.ace_constant{color:#CF6A4C;}.ace-kuroir .ace_storage{color:#A52A2A;}.ace-kuroir .ace_invalid.ace_illegal{color:#FD1224;\ +background-color:rgba(255, 6, 0, 0.15);}.ace-kuroir .ace_invalid.ace_deprecated{text-decoration:underline;\ +font-style:italic;\ +color:#FD1732;\ +background-color:#E8E9E8;}.ace-kuroir .ace_string{color:#639300;}.ace-kuroir .ace_string.ace_regexp{color:#417E00;\ +background-color:#C9D4BE;}.ace-kuroir .ace_comment{color:rgba(148, 148, 148, 0.91);\ +background-color:rgba(220, 220, 220, 0.56);}.ace-kuroir .ace_variable{color:#009ACD;}.ace-kuroir .ace_meta.ace_tag{color:#005273;}.ace-kuroir .ace_markup.ace_heading{color:#B8012D;\ +background-color:rgba(191, 97, 51, 0.051);}.ace-kuroir .ace_markup.ace_list{color:#8F5B26;}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],226:[function(require,module,exports){ +ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-monokai"; +exports.cssText = ".ace-monokai .ace_gutter {\ +background: #2F3129;\ +color: #8F908A\ +}\ +.ace-monokai .ace_print-margin {\ +width: 1px;\ +background: #555651\ +}\ +.ace-monokai {\ +background-color: #272822;\ +color: #F8F8F2\ +}\ +.ace-monokai .ace_cursor {\ +color: #F8F8F0\ +}\ +.ace-monokai .ace_marker-layer .ace_selection {\ +background: #49483E\ +}\ +.ace-monokai.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #272822;\ +}\ +.ace-monokai .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0)\ +}\ +.ace-monokai .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #49483E\ +}\ +.ace-monokai .ace_marker-layer .ace_active-line {\ +background: #202020\ +}\ +.ace-monokai .ace_gutter-active-line {\ +background-color: #272727\ +}\ +.ace-monokai .ace_marker-layer .ace_selected-word {\ +border: 1px solid #49483E\ +}\ +.ace-monokai .ace_invisible {\ +color: #52524d\ +}\ +.ace-monokai .ace_entity.ace_name.ace_tag,\ +.ace-monokai .ace_keyword,\ +.ace-monokai .ace_meta.ace_tag,\ +.ace-monokai .ace_storage {\ +color: #F92672\ +}\ +.ace-monokai .ace_punctuation,\ +.ace-monokai .ace_punctuation.ace_tag {\ +color: #fff\ +}\ +.ace-monokai .ace_constant.ace_character,\ +.ace-monokai .ace_constant.ace_language,\ +.ace-monokai .ace_constant.ace_numeric,\ +.ace-monokai .ace_constant.ace_other {\ +color: #AE81FF\ +}\ +.ace-monokai .ace_invalid {\ +color: #F8F8F0;\ +background-color: #F92672\ +}\ +.ace-monokai .ace_invalid.ace_deprecated {\ +color: #F8F8F0;\ +background-color: #AE81FF\ +}\ +.ace-monokai .ace_support.ace_constant,\ +.ace-monokai .ace_support.ace_function {\ +color: #66D9EF\ +}\ +.ace-monokai .ace_fold {\ +background-color: #A6E22E;\ +border-color: #F8F8F2\ +}\ +.ace-monokai .ace_storage.ace_type,\ +.ace-monokai .ace_support.ace_class,\ +.ace-monokai .ace_support.ace_type {\ +font-style: italic;\ +color: #66D9EF\ +}\ +.ace-monokai .ace_entity.ace_name.ace_function,\ +.ace-monokai .ace_entity.ace_other,\ +.ace-monokai .ace_entity.ace_other.ace_attribute-name,\ +.ace-monokai .ace_variable {\ +color: #A6E22E\ +}\ +.ace-monokai .ace_variable.ace_parameter {\ +font-style: italic;\ +color: #FD971F\ +}\ +.ace-monokai .ace_string {\ +color: #E6DB74\ +}\ +.ace-monokai .ace_comment {\ +color: #75715E\ +}\ +.ace-monokai .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],227:[function(require,module,exports){ +ace.define("ace/theme/solarized_dark",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-solarized-dark"; +exports.cssText = ".ace-solarized-dark .ace_gutter {\ +background: #01313f;\ +color: #d0edf7\ +}\ +.ace-solarized-dark .ace_print-margin {\ +width: 1px;\ +background: #33555E\ +}\ +.ace-solarized-dark {\ +background-color: #002B36;\ +color: #93A1A1\ +}\ +.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\ +.ace-solarized-dark .ace_storage {\ +color: #93A1A1\ +}\ +.ace-solarized-dark .ace_cursor,\ +.ace-solarized-dark .ace_string.ace_regexp {\ +color: #D30102\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_active-line,\ +.ace-solarized-dark .ace_marker-layer .ace_selection {\ +background: rgba(255, 255, 255, 0.1)\ +}\ +.ace-solarized-dark.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #002B36;\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0)\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-dark .ace_gutter-active-line {\ +background-color: #0d3440\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_selected-word {\ +border: 1px solid #073642\ +}\ +.ace-solarized-dark .ace_invisible {\ +color: rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-dark .ace_keyword,\ +.ace-solarized-dark .ace_meta,\ +.ace-solarized-dark .ace_support.ace_class,\ +.ace-solarized-dark .ace_support.ace_type {\ +color: #859900\ +}\ +.ace-solarized-dark .ace_constant.ace_character,\ +.ace-solarized-dark .ace_constant.ace_other {\ +color: #CB4B16\ +}\ +.ace-solarized-dark .ace_constant.ace_language {\ +color: #B58900\ +}\ +.ace-solarized-dark .ace_constant.ace_numeric {\ +color: #D33682\ +}\ +.ace-solarized-dark .ace_fold {\ +background-color: #268BD2;\ +border-color: #93A1A1\ +}\ +.ace-solarized-dark .ace_entity.ace_name.ace_function,\ +.ace-solarized-dark .ace_entity.ace_name.ace_tag,\ +.ace-solarized-dark .ace_support.ace_function,\ +.ace-solarized-dark .ace_variable,\ +.ace-solarized-dark .ace_variable.ace_language {\ +color: #268BD2\ +}\ +.ace-solarized-dark .ace_string {\ +color: #2AA198\ +}\ +.ace-solarized-dark .ace_comment {\ +font-style: italic;\ +color: #657B83\ +}\ +.ace-solarized-dark .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db1ZVCxc/sPAAd4AlUHlLenAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],228:[function(require,module,exports){ +ace.define("ace/theme/solarized_light",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-solarized-light"; +exports.cssText = ".ace-solarized-light .ace_gutter {\ +background: #fbf1d3;\ +color: #333\ +}\ +.ace-solarized-light .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8\ +}\ +.ace-solarized-light {\ +background-color: #FDF6E3;\ +color: #586E75\ +}\ +.ace-solarized-light .ace_cursor {\ +color: #000000\ +}\ +.ace-solarized-light .ace_marker-layer .ace_selection {\ +background: rgba(7, 54, 67, 0.09)\ +}\ +.ace-solarized-light.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #FDF6E3;\ +}\ +.ace-solarized-light .ace_marker-layer .ace_step {\ +background: rgb(255, 255, 0)\ +}\ +.ace-solarized-light .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-light .ace_marker-layer .ace_active-line {\ +background: #EEE8D5\ +}\ +.ace-solarized-light .ace_gutter-active-line {\ +background-color : #EDE5C1\ +}\ +.ace-solarized-light .ace_marker-layer .ace_selected-word {\ +border: 1px solid #073642\ +}\ +.ace-solarized-light .ace_invisible {\ +color: rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-light .ace_keyword,\ +.ace-solarized-light .ace_meta,\ +.ace-solarized-light .ace_support.ace_class,\ +.ace-solarized-light .ace_support.ace_type {\ +color: #859900\ +}\ +.ace-solarized-light .ace_constant.ace_character,\ +.ace-solarized-light .ace_constant.ace_other {\ +color: #CB4B16\ +}\ +.ace-solarized-light .ace_constant.ace_language {\ +color: #B58900\ +}\ +.ace-solarized-light .ace_constant.ace_numeric {\ +color: #D33682\ +}\ +.ace-solarized-light .ace_fold {\ +background-color: #268BD2;\ +border-color: #586E75\ +}\ +.ace-solarized-light .ace_entity.ace_name.ace_function,\ +.ace-solarized-light .ace_entity.ace_name.ace_tag,\ +.ace-solarized-light .ace_support.ace_function,\ +.ace-solarized-light .ace_variable,\ +.ace-solarized-light .ace_variable.ace_language {\ +color: #268BD2\ +}\ +.ace-solarized-light .ace_storage {\ +color: #073642\ +}\ +.ace-solarized-light .ace_string {\ +color: #2AA198\ +}\ +.ace-solarized-light .ace_string.ace_regexp {\ +color: #D30102\ +}\ +.ace-solarized-light .ace_comment,\ +.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\ +color: #93A1A1\ +}\ +.ace-solarized-light .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHjy8NJ/AAjgA5fzQUmBAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],229:[function(require,module,exports){ +ace.define("ace/theme/terminal",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-terminal-theme"; +exports.cssText = ".ace-terminal-theme .ace_gutter {\ +background: #1a0005;\ +color: steelblue\ +}\ +.ace-terminal-theme .ace_print-margin {\ +width: 1px;\ +background: #1a1a1a\ +}\ +.ace-terminal-theme {\ +background-color: black;\ +color: #DEDEDE\ +}\ +.ace-terminal-theme .ace_cursor {\ +color: #9F9F9F\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_selection {\ +background: #424242\ +}\ +.ace-terminal-theme.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px black;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_step {\ +background: rgb(0, 0, 0)\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket {\ +background: #090;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket-start {\ +background: #090;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket-unmatched {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #900\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_active-line {\ +background: #2A2A2A\ +}\ +.ace-terminal-theme .ace_gutter-active-line {\ +background-color: #2A112A\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_selected-word {\ +border: 1px solid #424242\ +}\ +.ace-terminal-theme .ace_invisible {\ +color: #343434\ +}\ +.ace-terminal-theme .ace_keyword,\ +.ace-terminal-theme .ace_meta,\ +.ace-terminal-theme .ace_storage,\ +.ace-terminal-theme .ace_storage.ace_type,\ +.ace-terminal-theme .ace_support.ace_type {\ +color: tomato\ +}\ +.ace-terminal-theme .ace_keyword.ace_operator {\ +color: deeppink\ +}\ +.ace-terminal-theme .ace_constant.ace_character,\ +.ace-terminal-theme .ace_constant.ace_language,\ +.ace-terminal-theme .ace_constant.ace_numeric,\ +.ace-terminal-theme .ace_keyword.ace_other.ace_unit,\ +.ace-terminal-theme .ace_support.ace_constant,\ +.ace-terminal-theme .ace_variable.ace_parameter {\ +color: #E78C45\ +}\ +.ace-terminal-theme .ace_constant.ace_other {\ +color: gold\ +}\ +.ace-terminal-theme .ace_invalid {\ +color: yellow;\ +background-color: red\ +}\ +.ace-terminal-theme .ace_invalid.ace_deprecated {\ +color: #CED2CF;\ +background-color: #B798BF\ +}\ +.ace-terminal-theme .ace_fold {\ +background-color: #7AA6DA;\ +border-color: #DEDEDE\ +}\ +.ace-terminal-theme .ace_entity.ace_name.ace_function,\ +.ace-terminal-theme .ace_support.ace_function,\ +.ace-terminal-theme .ace_variable {\ +color: #7AA6DA\ +}\ +.ace-terminal-theme .ace_support.ace_class,\ +.ace-terminal-theme .ace_support.ace_type {\ +color: #E7C547\ +}\ +.ace-terminal-theme .ace_heading,\ +.ace-terminal-theme .ace_string {\ +color: #B9CA4A\ +}\ +.ace-terminal-theme .ace_entity.ace_name.ace_tag,\ +.ace-terminal-theme .ace_entity.ace_other.ace_attribute-name,\ +.ace-terminal-theme .ace_meta.ace_tag,\ +.ace-terminal-theme .ace_string.ace_regexp,\ +.ace-terminal-theme .ace_variable {\ +color: #D54E53\ +}\ +.ace-terminal-theme .ace_comment {\ +color: orangered\ +}\ +.ace-terminal-theme .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLBWV/8PAAK4AYnhiq+xAAAAAElFTkSuQmCC) right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],230:[function(require,module,exports){ +ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +exports.isDark = false; +exports.cssClass = "ace-tm"; +exports.cssText = ".ace-tm .ace_gutter {\ +background: #f0f0f0;\ +color: #333;\ +}\ +.ace-tm .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-tm .ace_fold {\ +background-color: #6B72E6;\ +}\ +.ace-tm {\ +background-color: #FFFFFF;\ +color: black;\ +}\ +.ace-tm .ace_cursor {\ +color: black;\ +}\ +.ace-tm .ace_invisible {\ +color: rgb(191, 191, 191);\ +}\ +.ace-tm .ace_storage,\ +.ace-tm .ace_keyword {\ +color: blue;\ +}\ +.ace-tm .ace_constant {\ +color: rgb(197, 6, 11);\ +}\ +.ace-tm .ace_constant.ace_buildin {\ +color: rgb(88, 72, 246);\ +}\ +.ace-tm .ace_constant.ace_language {\ +color: rgb(88, 92, 246);\ +}\ +.ace-tm .ace_constant.ace_library {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_invalid {\ +background-color: rgba(255, 0, 0, 0.1);\ +color: red;\ +}\ +.ace-tm .ace_support.ace_function {\ +color: rgb(60, 76, 114);\ +}\ +.ace-tm .ace_support.ace_constant {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_support.ace_type,\ +.ace-tm .ace_support.ace_class {\ +color: rgb(109, 121, 222);\ +}\ +.ace-tm .ace_keyword.ace_operator {\ +color: rgb(104, 118, 135);\ +}\ +.ace-tm .ace_string {\ +color: rgb(3, 106, 7);\ +}\ +.ace-tm .ace_comment {\ +color: rgb(76, 136, 107);\ +}\ +.ace-tm .ace_comment.ace_doc {\ +color: rgb(0, 102, 255);\ +}\ +.ace-tm .ace_comment.ace_doc.ace_tag {\ +color: rgb(128, 159, 191);\ +}\ +.ace-tm .ace_constant.ace_numeric {\ +color: rgb(0, 0, 205);\ +}\ +.ace-tm .ace_variable {\ +color: rgb(49, 132, 149);\ +}\ +.ace-tm .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-tm .ace_entity.ace_name.ace_function {\ +color: #0000A2;\ +}\ +.ace-tm .ace_heading {\ +color: rgb(12, 7, 255);\ +}\ +.ace-tm .ace_list {\ +color:rgb(185, 6, 144);\ +}\ +.ace-tm .ace_meta.ace_tag {\ +color:rgb(0, 22, 142);\ +}\ +.ace-tm .ace_string.ace_regex {\ +color: rgb(255, 0, 0)\ +}\ +.ace-tm .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-tm.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px white;\ +}\ +.ace-tm .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-tm .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-tm .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-tm .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.07);\ +}\ +.ace-tm .ace_gutter-active-line {\ +background-color : #dcdcdc;\ +}\ +.ace-tm .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-tm .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],231:[function(require,module,exports){ +ace.define("ace/theme/tomorrow",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-tomorrow"; +exports.cssText = ".ace-tomorrow .ace_gutter {\ +background: #f6f6f6;\ +color: #4D4D4C\ +}\ +.ace-tomorrow .ace_print-margin {\ +width: 1px;\ +background: #f6f6f6\ +}\ +.ace-tomorrow {\ +background-color: #FFFFFF;\ +color: #4D4D4C\ +}\ +.ace-tomorrow .ace_cursor {\ +color: #AEAFAD\ +}\ +.ace-tomorrow .ace_marker-layer .ace_selection {\ +background: #D6D6D6\ +}\ +.ace-tomorrow.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #FFFFFF;\ +}\ +.ace-tomorrow .ace_marker-layer .ace_step {\ +background: rgb(255, 255, 0)\ +}\ +.ace-tomorrow .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #D1D1D1\ +}\ +.ace-tomorrow .ace_marker-layer .ace_active-line {\ +background: #EFEFEF\ +}\ +.ace-tomorrow .ace_gutter-active-line {\ +background-color : #dcdcdc\ +}\ +.ace-tomorrow .ace_marker-layer .ace_selected-word {\ +border: 1px solid #D6D6D6\ +}\ +.ace-tomorrow .ace_invisible {\ +color: #D1D1D1\ +}\ +.ace-tomorrow .ace_keyword,\ +.ace-tomorrow .ace_meta,\ +.ace-tomorrow .ace_storage,\ +.ace-tomorrow .ace_storage.ace_type,\ +.ace-tomorrow .ace_support.ace_type {\ +color: #8959A8\ +}\ +.ace-tomorrow .ace_keyword.ace_operator {\ +color: #3E999F\ +}\ +.ace-tomorrow .ace_constant.ace_character,\ +.ace-tomorrow .ace_constant.ace_language,\ +.ace-tomorrow .ace_constant.ace_numeric,\ +.ace-tomorrow .ace_keyword.ace_other.ace_unit,\ +.ace-tomorrow .ace_support.ace_constant,\ +.ace-tomorrow .ace_variable.ace_parameter {\ +color: #F5871F\ +}\ +.ace-tomorrow .ace_constant.ace_other {\ +color: #666969\ +}\ +.ace-tomorrow .ace_invalid {\ +color: #FFFFFF;\ +background-color: #C82829\ +}\ +.ace-tomorrow .ace_invalid.ace_deprecated {\ +color: #FFFFFF;\ +background-color: #8959A8\ +}\ +.ace-tomorrow .ace_fold {\ +background-color: #4271AE;\ +border-color: #4D4D4C\ +}\ +.ace-tomorrow .ace_entity.ace_name.ace_function,\ +.ace-tomorrow .ace_support.ace_function,\ +.ace-tomorrow .ace_variable {\ +color: #4271AE\ +}\ +.ace-tomorrow .ace_support.ace_class,\ +.ace-tomorrow .ace_support.ace_type {\ +color: #C99E00\ +}\ +.ace-tomorrow .ace_heading,\ +.ace-tomorrow .ace_markup.ace_heading,\ +.ace-tomorrow .ace_string {\ +color: #718C00\ +}\ +.ace-tomorrow .ace_entity.ace_name.ace_tag,\ +.ace-tomorrow .ace_entity.ace_other.ace_attribute-name,\ +.ace-tomorrow .ace_meta.ace_tag,\ +.ace-tomorrow .ace_string.ace_regexp,\ +.ace-tomorrow .ace_variable {\ +color: #C82829\ +}\ +.ace-tomorrow .ace_comment {\ +color: #8E908C\ +}\ +.ace-tomorrow .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bdu3f/BwAlfgctduB85QAAAABJRU5ErkJggg==) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],232:[function(require,module,exports){ +ace.define("ace/theme/twilight",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-twilight"; +exports.cssText = ".ace-twilight .ace_gutter {\ +background: #232323;\ +color: #E2E2E2\ +}\ +.ace-twilight .ace_print-margin {\ +width: 1px;\ +background: #232323\ +}\ +.ace-twilight {\ +background-color: #141414;\ +color: #F8F8F8\ +}\ +.ace-twilight .ace_cursor {\ +color: #A7A7A7\ +}\ +.ace-twilight .ace_marker-layer .ace_selection {\ +background: rgba(221, 240, 255, 0.20)\ +}\ +.ace-twilight.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #141414;\ +}\ +.ace-twilight .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0)\ +}\ +.ace-twilight .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(255, 255, 255, 0.25)\ +}\ +.ace-twilight .ace_marker-layer .ace_active-line {\ +background: rgba(255, 255, 255, 0.031)\ +}\ +.ace-twilight .ace_gutter-active-line {\ +background-color: rgba(255, 255, 255, 0.031)\ +}\ +.ace-twilight .ace_marker-layer .ace_selected-word {\ +border: 1px solid rgba(221, 240, 255, 0.20)\ +}\ +.ace-twilight .ace_invisible {\ +color: rgba(255, 255, 255, 0.25)\ +}\ +.ace-twilight .ace_keyword,\ +.ace-twilight .ace_meta {\ +color: #CDA869\ +}\ +.ace-twilight .ace_constant,\ +.ace-twilight .ace_constant.ace_character,\ +.ace-twilight .ace_constant.ace_character.ace_escape,\ +.ace-twilight .ace_constant.ace_other,\ +.ace-twilight .ace_heading,\ +.ace-twilight .ace_markup.ace_heading,\ +.ace-twilight .ace_support.ace_constant {\ +color: #CF6A4C\ +}\ +.ace-twilight .ace_invalid.ace_illegal {\ +color: #F8F8F8;\ +background-color: rgba(86, 45, 86, 0.75)\ +}\ +.ace-twilight .ace_invalid.ace_deprecated {\ +text-decoration: underline;\ +font-style: italic;\ +color: #D2A8A1\ +}\ +.ace-twilight .ace_support {\ +color: #9B859D\ +}\ +.ace-twilight .ace_fold {\ +background-color: #AC885B;\ +border-color: #F8F8F8\ +}\ +.ace-twilight .ace_support.ace_function {\ +color: #DAD085\ +}\ +.ace-twilight .ace_list,\ +.ace-twilight .ace_markup.ace_list,\ +.ace-twilight .ace_storage {\ +color: #F9EE98\ +}\ +.ace-twilight .ace_entity.ace_name.ace_function,\ +.ace-twilight .ace_meta.ace_tag,\ +.ace-twilight .ace_variable {\ +color: #AC885B\ +}\ +.ace-twilight .ace_string {\ +color: #8F9D6A\ +}\ +.ace-twilight .ace_string.ace_regexp {\ +color: #E9C062\ +}\ +.ace-twilight .ace_comment {\ +font-style: italic;\ +color: #5F5A60\ +}\ +.ace-twilight .ace_variable {\ +color: #7587A6\ +}\ +.ace-twilight .ace_xml-pe {\ +color: #494949\ +}\ +.ace-twilight .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWMQERFpYLC1tf0PAAgOAnPnhxyiAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],233:[function(require,module,exports){ +ace.define("ace/theme/xcode",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-xcode"; +exports.cssText = "\ +.ace-xcode .ace_gutter {\ +background: #e8e8e8;\ +color: #333\ +}\ +.ace-xcode .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8\ +}\ +.ace-xcode {\ +background-color: #FFFFFF;\ +color: #000000\ +}\ +.ace-xcode .ace_cursor {\ +color: #000000\ +}\ +.ace-xcode .ace_marker-layer .ace_selection {\ +background: #B5D5FF\ +}\ +.ace-xcode.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #FFFFFF;\ +}\ +.ace-xcode .ace_marker-layer .ace_step {\ +background: rgb(198, 219, 174)\ +}\ +.ace-xcode .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #BFBFBF\ +}\ +.ace-xcode .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.071)\ +}\ +.ace-xcode .ace_gutter-active-line {\ +background-color: rgba(0, 0, 0, 0.071)\ +}\ +.ace-xcode .ace_marker-layer .ace_selected-word {\ +border: 1px solid #B5D5FF\ +}\ +.ace-xcode .ace_constant.ace_language,\ +.ace-xcode .ace_keyword,\ +.ace-xcode .ace_meta,\ +.ace-xcode .ace_variable.ace_language {\ +color: #C800A4\ +}\ +.ace-xcode .ace_invisible {\ +color: #BFBFBF\ +}\ +.ace-xcode .ace_constant.ace_character,\ +.ace-xcode .ace_constant.ace_other {\ +color: #275A5E\ +}\ +.ace-xcode .ace_constant.ace_numeric {\ +color: #3A00DC\ +}\ +.ace-xcode .ace_entity.ace_other.ace_attribute-name,\ +.ace-xcode .ace_support.ace_constant,\ +.ace-xcode .ace_support.ace_function {\ +color: #450084\ +}\ +.ace-xcode .ace_fold {\ +background-color: #C800A4;\ +border-color: #000000\ +}\ +.ace-xcode .ace_entity.ace_name.ace_tag,\ +.ace-xcode .ace_support.ace_class,\ +.ace-xcode .ace_support.ace_type {\ +color: #790EAD\ +}\ +.ace-xcode .ace_storage {\ +color: #C900A4\ +}\ +.ace-xcode .ace_string {\ +color: #DF0002\ +}\ +.ace-xcode .ace_comment {\ +color: #008E00\ +}\ +.ace-xcode .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +},{}],234:[function(require,module,exports){ +module.exports.id = 'ace/mode/css_worker'; +module.exports.src = "\"no use strict\";(function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}})(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/ [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/worker/mirror\",[\"require\",\"exports\",\"module\",\"ace/range\",\"ace/document\",\"ace/lib/lang\"],function(acequire,exports){\"use strict\";acequire(\"../range\").Range;var Document=acequire(\"../document\").Document,lang=acequire(\"../lib/lang\"),Mirror=exports.Mirror=function(sender){this.sender=sender;var doc=this.doc=new Document(\"\"),deferredUpdate=this.deferredUpdate=lang.delayedCall(this.onUpdate.bind(this)),_self=this;sender.on(\"change\",function(e){var data=e.data;if(data[0].start)doc.applyDeltas(data);else for(var i=0;data.length>i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/css/csslint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){function objectToString(o){return Object.prototype.toString.call(o)}function clone(parent,circular,depth,prototype){function _clone(parent,depth){if(null===parent)return null;if(0==depth)return parent;var child;if(\"object\"!=typeof parent)return parent;if(util.isArray(parent))child=[];else if(util.isRegExp(parent))child=RegExp(parent.source,util.getRegExpFlags(parent)),parent.lastIndex&&(child.lastIndex=parent.lastIndex);else if(util.isDate(parent))child=new Date(parent.getTime());else{if(useBuffer&&Buffer.isBuffer(parent))return child=new Buffer(parent.length),parent.copy(child),child;child=prototype===void 0?Object.create(Object.getPrototypeOf(parent)):Object.create(prototype)}if(circular){var index=allParents.indexOf(parent);if(-1!=index)return allChildren[index];allParents.push(parent),allChildren.push(child)}for(var i in parent)child[i]=_clone(parent[i],depth-1);return child}var allParents=[],allChildren=[],useBuffer=\"undefined\"!=typeof Buffer;return circular===void 0&&(circular=!0),depth===void 0&&(depth=1/0),_clone(parent,depth)}function Reporter(lines,ruleset){this.messages=[],this.stats=[],this.lines=lines,this.ruleset=ruleset}var parserlib={};(function(){function EventTarget(){this._listeners={}}function StringReader(text){this._input=text.replace(/\\n\\r?/g,\"\\n\"),this._line=1,this._col=1,this._cursor=0}function SyntaxError(message,line,col){this.col=col,this.line=line,this.message=message}function SyntaxUnit(text,line,col,type){this.col=col,this.line=line,this.text=text,this.type=type}function TokenStreamBase(input,tokenData){this._reader=input?new StringReader(\"\"+input):null,this._token=null,this._tokenData=tokenData,this._lt=[],this._ltIndex=0,this._ltIndexCache=[]}EventTarget.prototype={constructor:EventTarget,addListener:function(type,listener){this._listeners[type]||(this._listeners[type]=[]),this._listeners[type].push(listener)},fire:function(event){if(\"string\"==typeof event&&(event={type:event}),event.target!==void 0&&(event.target=this),event.type===void 0)throw Error(\"Event object missing 'type' property.\");if(this._listeners[event.type])for(var listeners=this._listeners[event.type].concat(),i=0,len=listeners.length;len>i;i++)listeners[i].call(this,event)},removeListener:function(type,listener){if(this._listeners[type])for(var listeners=this._listeners[type],i=0,len=listeners.length;len>i;i++)if(listeners[i]===listener){listeners.splice(i,1);break}}},StringReader.prototype={constructor:StringReader,getCol:function(){return this._col},getLine:function(){return this._line},eof:function(){return this._cursor==this._input.length},peek:function(count){var c=null;return count=count===void 0?1:count,this._cursori;i++)nameMap.push(tokenData[i].name),tokenData[tokenData[i].name]=i,tokenData[i].text&&(typeMap[tokenData[i].text]=i);return tokenData.name=function(tt){return nameMap[tt]},tokenData.type=function(c){return typeMap[c]},tokenData},TokenStreamBase.prototype={constructor:TokenStreamBase,match:function(tokenTypes,channel){tokenTypes instanceof Array||(tokenTypes=[tokenTypes]);\nfor(var tt=this.get(channel),i=0,len=tokenTypes.length;len>i;)if(tt==tokenTypes[i++])return!0;return this.unget(),!1},mustMatch:function(tokenTypes){var token;if(tokenTypes instanceof Array||(tokenTypes=[tokenTypes]),!this.match.apply(this,arguments))throw token=this.LT(1),new SyntaxError(\"Expected \"+this._tokenData[tokenTypes[0]].name+\" at line \"+token.startLine+\", col \"+token.startCol+\".\",token.startLine,token.startCol)},advance:function(tokenTypes,channel){for(;0!==this.LA(0)&&!this.match(tokenTypes,channel);)this.get();return this.LA(0)},get:function(channel){var token,info,tokenInfo=this._tokenData,i=(this._reader,0);if(tokenInfo.length,this._lt.length&&this._ltIndex>=0&&this._ltIndex-1&&!tokenInfo[token.type].hide&&(token.channel=tokenInfo[token.type].channel,this._token=token,this._lt.push(token),this._ltIndexCache.push(this._lt.length-this._ltIndex+i),this._lt.length>5&&this._lt.shift(),this._ltIndexCache.length>5&&this._ltIndexCache.shift(),this._ltIndex=this._lt.length),info=tokenInfo[token.type],info&&(info.hide||void 0!==info.channel&&channel!==info.channel)?this.get(channel):token.type},LA:function(index){var tt,total=index;if(index>0){if(index>5)throw Error(\"Too much lookahead.\");for(;total;)tt=this.get(),total--;for(;index>total;)this.unget(),total++}else if(0>index){if(!this._lt[this._ltIndex+index])throw Error(\"Too much lookbehind.\");tt=this._lt[this._ltIndex+index].type}else tt=this._token.type;return tt},LT:function(index){return this.LA(index),this._lt[this._ltIndex+index-1]},peek:function(){return this.LA(1)},token:function(){return this._token},tokenName:function(tokenType){return 0>tokenType||tokenType>this._tokenData.length?\"UNKNOWN_TOKEN\":this._tokenData[tokenType].name},tokenType:function(tokenName){return this._tokenData[tokenName]||-1},unget:function(){if(!this._ltIndexCache.length)throw Error(\"Too much lookahead.\");this._ltIndex-=this._ltIndexCache.pop(),this._token=this._lt[this._ltIndex-1]}},parserlib.util={StringReader:StringReader,SyntaxError:SyntaxError,SyntaxUnit:SyntaxUnit,EventTarget:EventTarget,TokenStreamBase:TokenStreamBase}})(),function(){function Combinator(text,line,col){SyntaxUnit.call(this,text,line,col,Parser.COMBINATOR_TYPE),this.type=\"unknown\",/^\\s+$/.test(text)?this.type=\"descendant\":\">\"==text?this.type=\"child\":\"+\"==text?this.type=\"adjacent-sibling\":\"~\"==text&&(this.type=\"sibling\")}function MediaFeature(name,value){SyntaxUnit.call(this,\"(\"+name+(null!==value?\":\"+value:\"\")+\")\",name.startLine,name.startCol,Parser.MEDIA_FEATURE_TYPE),this.name=name,this.value=value}function MediaQuery(modifier,mediaType,features,line,col){SyntaxUnit.call(this,(modifier?modifier+\" \":\"\")+(mediaType?mediaType:\"\")+(mediaType&&features.length>0?\" and \":\"\")+features.join(\" and \"),line,col,Parser.MEDIA_QUERY_TYPE),this.modifier=modifier,this.mediaType=mediaType,this.features=features}function Parser(options){EventTarget.call(this),this.options=options||{},this._tokenStream=null}function PropertyName(text,hack,line,col){SyntaxUnit.call(this,text,line,col,Parser.PROPERTY_NAME_TYPE),this.hack=hack}function PropertyValue(parts,line,col){SyntaxUnit.call(this,parts.join(\" \"),line,col,Parser.PROPERTY_VALUE_TYPE),this.parts=parts}function PropertyValueIterator(value){this._i=0,this._parts=value.parts,this._marks=[],this.value=value}function PropertyValuePart(text,line,col){SyntaxUnit.call(this,text,line,col,Parser.PROPERTY_VALUE_PART_TYPE),this.type=\"unknown\";var temp;if(/^([+\\-]?[\\d\\.]+)([a-z]+)$/i.test(text))switch(this.type=\"dimension\",this.value=+RegExp.$1,this.units=RegExp.$2,this.units.toLowerCase()){case\"em\":case\"rem\":case\"ex\":case\"px\":case\"cm\":case\"mm\":case\"in\":case\"pt\":case\"pc\":case\"ch\":case\"vh\":case\"vw\":case\"vmax\":case\"vmin\":this.type=\"length\";break;case\"deg\":case\"rad\":case\"grad\":this.type=\"angle\";break;case\"ms\":case\"s\":this.type=\"time\";break;case\"hz\":case\"khz\":this.type=\"frequency\";break;case\"dpi\":case\"dpcm\":this.type=\"resolution\"}else/^([+\\-]?[\\d\\.]+)%$/i.test(text)?(this.type=\"percentage\",this.value=+RegExp.$1):/^([+\\-]?\\d+)$/i.test(text)?(this.type=\"integer\",this.value=+RegExp.$1):/^([+\\-]?[\\d\\.]+)$/i.test(text)?(this.type=\"number\",this.value=+RegExp.$1):/^#([a-f0-9]{3,6})/i.test(text)?(this.type=\"color\",temp=RegExp.$1,3==temp.length?(this.red=parseInt(temp.charAt(0)+temp.charAt(0),16),this.green=parseInt(temp.charAt(1)+temp.charAt(1),16),this.blue=parseInt(temp.charAt(2)+temp.charAt(2),16)):(this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16))):/^rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)/i.test(text)?(this.type=\"color\",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3):/^rgb\\(\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*\\)/i.test(text)?(this.type=\"color\",this.red=255*+RegExp.$1/100,this.green=255*+RegExp.$2/100,this.blue=255*+RegExp.$3/100):/^rgba\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*([\\d\\.]+)\\s*\\)/i.test(text)?(this.type=\"color\",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3,this.alpha=+RegExp.$4):/^rgba\\(\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*,\\s*([\\d\\.]+)\\s*\\)/i.test(text)?(this.type=\"color\",this.red=255*+RegExp.$1/100,this.green=255*+RegExp.$2/100,this.blue=255*+RegExp.$3/100,this.alpha=+RegExp.$4):/^hsl\\(\\s*(\\d+)\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*\\)/i.test(text)?(this.type=\"color\",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100):/^hsla\\(\\s*(\\d+)\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*,\\s*([\\d\\.]+)\\s*\\)/i.test(text)?(this.type=\"color\",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100,this.alpha=+RegExp.$4):/^url\\([\"']?([^\\)\"']+)[\"']?\\)/i.test(text)?(this.type=\"uri\",this.uri=RegExp.$1):/^([^\\(]+)\\(/i.test(text)?(this.type=\"function\",this.name=RegExp.$1,this.value=text):/^[\"'][^\"']*[\"']/.test(text)?(this.type=\"string\",this.value=eval(text)):Colors[text.toLowerCase()]?(this.type=\"color\",temp=Colors[text.toLowerCase()].substring(1),this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16)):/^[\\,\\/]$/.test(text)?(this.type=\"operator\",this.value=text):/^[a-z\\-_\\u0080-\\uFFFF][a-z0-9\\-_\\u0080-\\uFFFF]*$/i.test(text)&&(this.type=\"identifier\",this.value=text)}function Selector(parts,line,col){SyntaxUnit.call(this,parts.join(\" \"),line,col,Parser.SELECTOR_TYPE),this.parts=parts,this.specificity=Specificity.calculate(this)}function SelectorPart(elementName,modifiers,text,line,col){SyntaxUnit.call(this,text,line,col,Parser.SELECTOR_PART_TYPE),this.elementName=elementName,this.modifiers=modifiers}function SelectorSubPart(text,type,line,col){SyntaxUnit.call(this,text,line,col,Parser.SELECTOR_SUB_PART_TYPE),this.type=type,this.args=[]}function Specificity(a,b,c,d){this.a=a,this.b=b,this.c=c,this.d=d}function isHexDigit(c){return null!==c&&h.test(c)}function isDigit(c){return null!==c&&/\\d/.test(c)}function isWhitespace(c){return null!==c&&/\\s/.test(c)}function isNewLine(c){return null!==c&&nl.test(c)}function isNameStart(c){return null!==c&&/[a-z_\\u0080-\\uFFFF\\\\]/i.test(c)}function isNameChar(c){return null!==c&&(isNameStart(c)||/[0-9\\-\\\\]/.test(c))}function isIdentStart(c){return null!==c&&(isNameStart(c)||/\\-\\\\/.test(c))}function mix(receiver,supplier){for(var prop in supplier)supplier.hasOwnProperty(prop)&&(receiver[prop]=supplier[prop]);return receiver}function TokenStream(input){TokenStreamBase.call(this,input,Tokens)}function ValidationError(message,line,col){this.col=col,this.line=line,this.message=message}var EventTarget=parserlib.util.EventTarget,TokenStreamBase=parserlib.util.TokenStreamBase,StringReader=parserlib.util.StringReader,SyntaxError=parserlib.util.SyntaxError,SyntaxUnit=parserlib.util.SyntaxUnit,Colors={aliceblue:\"#f0f8ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",azure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brown:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:\"#a9a9a9\",darkgrey:\"#a9a9a9\",darkgreen:\"#006400\",darkkhaki:\"#bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkviolet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff\",gainsboro:\"#dcdcdc\",ghostwhite:\"#f8f8ff\",gold:\"#ffd700\",goldenrod:\"#daa520\",gray:\"#808080\",grey:\"#808080\",green:\"#008000\",greenyellow:\"#adff2f\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianred:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",lavender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lemonchiffon:\"#fffacd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",lightcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3\",lightgrey:\"#d3d3d3\",lightgreen:\"#90ee90\",lightpink:\"#ffb6c1\",lightsalmon:\"#ffa07a\",lightseagreen:\"#20b2aa\",lightskyblue:\"#87cefa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",lightsteelblue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediumaquamarine:\"#66cdaa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",mediumpurple:\"#9370d8\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7b68ee\",mediumspringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediumvioletred:\"#c71585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",mistyrose:\"#ffe4e1\",moccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",navy:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23\",orange:\"#ffa500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegoldenrod:\"#eee8aa\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palevioletred:\"#d87093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",purple:\"#800080\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#4169e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\",seagreen:\"#2e8b57\",seashell:\"#fff5ee\",sienna:\"#a0522d\",silver:\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#708090\",slategrey:\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",steelblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\",tomato:\"#ff6347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yellowgreen:\"#9acd32\",activeBorder:\"Active window border.\",activecaption:\"Active window caption.\",appworkspace:\"Background color of multiple document interface.\",background:\"Desktop background.\",buttonface:\"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.\",buttonhighlight:\"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.\",buttonshadow:\"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.\",buttontext:\"Text on push buttons.\",captiontext:\"Text in caption, size box, and scrollbar arrow box.\",graytext:\"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.\",greytext:\"Greyed (disabled) text. This color is set to #000 if the current display driver does not support a solid grey color.\",highlight:\"Item(s) selected in a control.\",highlighttext:\"Text of item(s) selected in a control.\",inactiveborder:\"Inactive window border.\",inactivecaption:\"Inactive window caption.\",inactivecaptiontext:\"Color of text in an inactive caption.\",infobackground:\"Background color for tooltip controls.\",infotext:\"Text color for tooltip controls.\",menu:\"Menu background.\",menutext:\"Text in menus.\",scrollbar:\"Scroll bar gray area.\",threeddarkshadow:\"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.\",threedface:\"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.\",threedhighlight:\"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.\",threedlightshadow:\"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.\",threedshadow:\"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.\",window:\"Window background.\",windowframe:\"Window frame.\",windowtext:\"Text in windows.\"};Combinator.prototype=new SyntaxUnit,Combinator.prototype.constructor=Combinator,MediaFeature.prototype=new SyntaxUnit,MediaFeature.prototype.constructor=MediaFeature,MediaQuery.prototype=new SyntaxUnit,MediaQuery.prototype.constructor=MediaQuery,Parser.DEFAULT_TYPE=0,Parser.COMBINATOR_TYPE=1,Parser.MEDIA_FEATURE_TYPE=2,Parser.MEDIA_QUERY_TYPE=3,Parser.PROPERTY_NAME_TYPE=4,Parser.PROPERTY_VALUE_TYPE=5,Parser.PROPERTY_VALUE_PART_TYPE=6,Parser.SELECTOR_TYPE=7,Parser.SELECTOR_PART_TYPE=8,Parser.SELECTOR_SUB_PART_TYPE=9,Parser.prototype=function(){var prop,proto=new EventTarget,additions={constructor:Parser,DEFAULT_TYPE:0,COMBINATOR_TYPE:1,MEDIA_FEATURE_TYPE:2,MEDIA_QUERY_TYPE:3,PROPERTY_NAME_TYPE:4,PROPERTY_VALUE_TYPE:5,PROPERTY_VALUE_PART_TYPE:6,SELECTOR_TYPE:7,SELECTOR_PART_TYPE:8,SELECTOR_SUB_PART_TYPE:9,_stylesheet:function(){var count,token,tt,tokenStream=this._tokenStream;for(this.fire(\"startstylesheet\"),this._charset(),this._skipCruft();tokenStream.peek()==Tokens.IMPORT_SYM;)this._import(),this._skipCruft();for(;tokenStream.peek()==Tokens.NAMESPACE_SYM;)this._namespace(),this._skipCruft();for(tt=tokenStream.peek();tt>Tokens.EOF;){try{switch(tt){case Tokens.MEDIA_SYM:this._media(),this._skipCruft();break;case Tokens.PAGE_SYM:this._page(),this._skipCruft();break;case Tokens.FONT_FACE_SYM:this._font_face(),this._skipCruft();break;case Tokens.KEYFRAMES_SYM:this._keyframes(),this._skipCruft();break;case Tokens.VIEWPORT_SYM:this._viewport(),this._skipCruft();break;case Tokens.UNKNOWN_SYM:if(tokenStream.get(),this.options.strict)throw new SyntaxError(\"Unknown @ rule.\",tokenStream.LT(0).startLine,tokenStream.LT(0).startCol);for(this.fire({type:\"error\",error:null,message:\"Unknown @ rule: \"+tokenStream.LT(0).value+\".\",line:tokenStream.LT(0).startLine,col:tokenStream.LT(0).startCol}),count=0;tokenStream.advance([Tokens.LBRACE,Tokens.RBRACE])==Tokens.LBRACE;)count++;for(;count;)tokenStream.advance([Tokens.RBRACE]),count--;break;case Tokens.S:this._readWhitespace();break;default:if(!this._ruleset())switch(tt){case Tokens.CHARSET_SYM:throw token=tokenStream.LT(1),this._charset(!1),new SyntaxError(\"@charset not allowed here.\",token.startLine,token.startCol);case Tokens.IMPORT_SYM:throw token=tokenStream.LT(1),this._import(!1),new SyntaxError(\"@import not allowed here.\",token.startLine,token.startCol);case Tokens.NAMESPACE_SYM:throw token=tokenStream.LT(1),this._namespace(!1),new SyntaxError(\"@namespace not allowed here.\",token.startLine,token.startCol);default:tokenStream.get(),this._unexpectedToken(tokenStream.token())}}}catch(ex){if(!(ex instanceof SyntaxError)||this.options.strict)throw ex;this.fire({type:\"error\",error:ex,message:ex.message,line:ex.line,col:ex.col})}tt=tokenStream.peek()}tt!=Tokens.EOF&&this._unexpectedToken(tokenStream.token()),this.fire(\"endstylesheet\")},_charset:function(emit){var charset,token,line,col,tokenStream=this._tokenStream;tokenStream.match(Tokens.CHARSET_SYM)&&(line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),tokenStream.mustMatch(Tokens.STRING),token=tokenStream.token(),charset=token.value,this._readWhitespace(),tokenStream.mustMatch(Tokens.SEMICOLON),emit!==!1&&this.fire({type:\"charset\",charset:charset,line:line,col:col}))},_import:function(emit){var uri,importToken,tokenStream=this._tokenStream,mediaList=[];tokenStream.mustMatch(Tokens.IMPORT_SYM),importToken=tokenStream.token(),this._readWhitespace(),tokenStream.mustMatch([Tokens.STRING,Tokens.URI]),uri=tokenStream.token().value.replace(/^(?:url\\()?[\"']?([^\"']+?)[\"']?\\)?$/,\"$1\"),this._readWhitespace(),mediaList=this._media_query_list(),tokenStream.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),emit!==!1&&this.fire({type:\"import\",uri:uri,media:mediaList,line:importToken.startLine,col:importToken.startCol})},_namespace:function(emit){var line,col,prefix,uri,tokenStream=this._tokenStream;tokenStream.mustMatch(Tokens.NAMESPACE_SYM),line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),tokenStream.match(Tokens.IDENT)&&(prefix=tokenStream.token().value,this._readWhitespace()),tokenStream.mustMatch([Tokens.STRING,Tokens.URI]),uri=tokenStream.token().value.replace(/(?:url\\()?[\"']([^\"']+)[\"']\\)?/,\"$1\"),this._readWhitespace(),tokenStream.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),emit!==!1&&this.fire({type:\"namespace\",prefix:prefix,uri:uri,line:line,col:col})},_media:function(){var line,col,mediaList,tokenStream=this._tokenStream;for(tokenStream.mustMatch(Tokens.MEDIA_SYM),line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),mediaList=this._media_query_list(),tokenStream.mustMatch(Tokens.LBRACE),this._readWhitespace(),this.fire({type:\"startmedia\",media:mediaList,line:line,col:col});;)if(tokenStream.peek()==Tokens.PAGE_SYM)this._page();else if(tokenStream.peek()==Tokens.FONT_FACE_SYM)this._font_face();else if(tokenStream.peek()==Tokens.VIEWPORT_SYM)this._viewport();else if(!this._ruleset())break;tokenStream.mustMatch(Tokens.RBRACE),this._readWhitespace(),this.fire({type:\"endmedia\",media:mediaList,line:line,col:col})},_media_query_list:function(){var tokenStream=this._tokenStream,mediaList=[];for(this._readWhitespace(),(tokenStream.peek()==Tokens.IDENT||tokenStream.peek()==Tokens.LPAREN)&&mediaList.push(this._media_query());tokenStream.match(Tokens.COMMA);)this._readWhitespace(),mediaList.push(this._media_query());return mediaList},_media_query:function(){var tokenStream=this._tokenStream,type=null,ident=null,token=null,expressions=[];if(tokenStream.match(Tokens.IDENT)&&(ident=tokenStream.token().value.toLowerCase(),\"only\"!=ident&&\"not\"!=ident?(tokenStream.unget(),ident=null):token=tokenStream.token()),this._readWhitespace(),tokenStream.peek()==Tokens.IDENT?(type=this._media_type(),null===token&&(token=tokenStream.token())):tokenStream.peek()==Tokens.LPAREN&&(null===token&&(token=tokenStream.LT(1)),expressions.push(this._media_expression())),null===type&&0===expressions.length)return null;for(this._readWhitespace();tokenStream.match(Tokens.IDENT);)\"and\"!=tokenStream.token().value.toLowerCase()&&this._unexpectedToken(tokenStream.token()),this._readWhitespace(),expressions.push(this._media_expression());return new MediaQuery(ident,type,expressions,token.startLine,token.startCol)},_media_type:function(){return this._media_feature()},_media_expression:function(){var token,tokenStream=this._tokenStream,feature=null,expression=null;return tokenStream.mustMatch(Tokens.LPAREN),feature=this._media_feature(),this._readWhitespace(),tokenStream.match(Tokens.COLON)&&(this._readWhitespace(),token=tokenStream.LT(1),expression=this._expression()),tokenStream.mustMatch(Tokens.RPAREN),this._readWhitespace(),new MediaFeature(feature,expression?new SyntaxUnit(expression,token.startLine,token.startCol):null)},_media_feature:function(){var tokenStream=this._tokenStream;return tokenStream.mustMatch(Tokens.IDENT),SyntaxUnit.fromToken(tokenStream.token())},_page:function(){var line,col,tokenStream=this._tokenStream,identifier=null,pseudoPage=null;tokenStream.mustMatch(Tokens.PAGE_SYM),line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),tokenStream.match(Tokens.IDENT)&&(identifier=tokenStream.token().value,\"auto\"===identifier.toLowerCase()&&this._unexpectedToken(tokenStream.token())),tokenStream.peek()==Tokens.COLON&&(pseudoPage=this._pseudo_page()),this._readWhitespace(),this.fire({type:\"startpage\",id:identifier,pseudo:pseudoPage,line:line,col:col}),this._readDeclarations(!0,!0),this.fire({type:\"endpage\",id:identifier,pseudo:pseudoPage,line:line,col:col})},_margin:function(){var line,col,tokenStream=this._tokenStream,marginSym=this._margin_sym();return marginSym?(line=tokenStream.token().startLine,col=tokenStream.token().startCol,this.fire({type:\"startpagemargin\",margin:marginSym,line:line,col:col}),this._readDeclarations(!0),this.fire({type:\"endpagemargin\",margin:marginSym,line:line,col:col}),!0):!1},_margin_sym:function(){var tokenStream=this._tokenStream;return tokenStream.match([Tokens.TOPLEFTCORNER_SYM,Tokens.TOPLEFT_SYM,Tokens.TOPCENTER_SYM,Tokens.TOPRIGHT_SYM,Tokens.TOPRIGHTCORNER_SYM,Tokens.BOTTOMLEFTCORNER_SYM,Tokens.BOTTOMLEFT_SYM,Tokens.BOTTOMCENTER_SYM,Tokens.BOTTOMRIGHT_SYM,Tokens.BOTTOMRIGHTCORNER_SYM,Tokens.LEFTTOP_SYM,Tokens.LEFTMIDDLE_SYM,Tokens.LEFTBOTTOM_SYM,Tokens.RIGHTTOP_SYM,Tokens.RIGHTMIDDLE_SYM,Tokens.RIGHTBOTTOM_SYM])?SyntaxUnit.fromToken(tokenStream.token()):null},_pseudo_page:function(){var tokenStream=this._tokenStream;return tokenStream.mustMatch(Tokens.COLON),tokenStream.mustMatch(Tokens.IDENT),tokenStream.token().value},_font_face:function(){var line,col,tokenStream=this._tokenStream;tokenStream.mustMatch(Tokens.FONT_FACE_SYM),line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),this.fire({type:\"startfontface\",line:line,col:col}),this._readDeclarations(!0),this.fire({type:\"endfontface\",line:line,col:col})},_viewport:function(){var line,col,tokenStream=this._tokenStream;tokenStream.mustMatch(Tokens.VIEWPORT_SYM),line=tokenStream.token().startLine,col=tokenStream.token().startCol,this._readWhitespace(),this.fire({type:\"startviewport\",line:line,col:col}),this._readDeclarations(!0),this.fire({type:\"endviewport\",line:line,col:col})},_operator:function(inFunction){var tokenStream=this._tokenStream,token=null;return(tokenStream.match([Tokens.SLASH,Tokens.COMMA])||inFunction&&tokenStream.match([Tokens.PLUS,Tokens.STAR,Tokens.MINUS]))&&(token=tokenStream.token(),this._readWhitespace()),token?PropertyValuePart.fromToken(token):null},_combinator:function(){var token,tokenStream=this._tokenStream,value=null;return tokenStream.match([Tokens.PLUS,Tokens.GREATER,Tokens.TILDE])&&(token=tokenStream.token(),value=new Combinator(token.value,token.startLine,token.startCol),this._readWhitespace()),value},_unary_operator:function(){var tokenStream=this._tokenStream;return tokenStream.match([Tokens.MINUS,Tokens.PLUS])?tokenStream.token().value:null},_property:function(){var tokenValue,token,line,col,tokenStream=this._tokenStream,value=null,hack=null;return tokenStream.peek()==Tokens.STAR&&this.options.starHack&&(tokenStream.get(),token=tokenStream.token(),hack=token.value,line=token.startLine,col=token.startCol),tokenStream.match(Tokens.IDENT)&&(token=tokenStream.token(),tokenValue=token.value,\"_\"==tokenValue.charAt(0)&&this.options.underscoreHack&&(hack=\"_\",tokenValue=tokenValue.substring(1)),value=new PropertyName(tokenValue,hack,line||token.startLine,col||token.startCol),this._readWhitespace()),value},_ruleset:function(){var tt,selectors,tokenStream=this._tokenStream;try{selectors=this._selectors_group()}catch(ex){if(!(ex instanceof SyntaxError)||this.options.strict)throw ex;if(this.fire({type:\"error\",error:ex,message:ex.message,line:ex.line,col:ex.col}),tt=tokenStream.advance([Tokens.RBRACE]),tt!=Tokens.RBRACE)throw ex;return!0}return selectors&&(this.fire({type:\"startrule\",selectors:selectors,line:selectors[0].line,col:selectors[0].col}),this._readDeclarations(!0),this.fire({type:\"endrule\",selectors:selectors,line:selectors[0].line,col:selectors[0].col})),selectors},_selectors_group:function(){var selector,tokenStream=this._tokenStream,selectors=[];if(selector=this._selector(),null!==selector)for(selectors.push(selector);tokenStream.match(Tokens.COMMA);)this._readWhitespace(),selector=this._selector(),null!==selector?selectors.push(selector):this._unexpectedToken(tokenStream.LT(1));return selectors.length?selectors:null},_selector:function(){var tokenStream=this._tokenStream,selector=[],nextSelector=null,combinator=null,ws=null;if(nextSelector=this._simple_selector_sequence(),null===nextSelector)return null;for(selector.push(nextSelector);;)if(combinator=this._combinator(),null!==combinator)selector.push(combinator),nextSelector=this._simple_selector_sequence(),null===nextSelector?this._unexpectedToken(tokenStream.LT(1)):selector.push(nextSelector);else{if(!this._readWhitespace())break;ws=new Combinator(tokenStream.token().value,tokenStream.token().startLine,tokenStream.token().startCol),combinator=this._combinator(),nextSelector=this._simple_selector_sequence(),null===nextSelector?null!==combinator&&this._unexpectedToken(tokenStream.LT(1)):(null!==combinator?selector.push(combinator):selector.push(ws),selector.push(nextSelector))}return new Selector(selector,selector[0].line,selector[0].col)},_simple_selector_sequence:function(){var line,col,tokenStream=this._tokenStream,elementName=null,modifiers=[],selectorText=\"\",components=[function(){return tokenStream.match(Tokens.HASH)?new SelectorSubPart(tokenStream.token().value,\"id\",tokenStream.token().startLine,tokenStream.token().startCol):null},this._class,this._attrib,this._pseudo,this._negation],i=0,len=components.length,component=null;for(line=tokenStream.LT(1).startLine,col=tokenStream.LT(1).startCol,elementName=this._type_selector(),elementName||(elementName=this._universal()),null!==elementName&&(selectorText+=elementName);;){if(tokenStream.peek()===Tokens.S)break;for(;len>i&&null===component;)component=components[i++].call(this);if(null===component){if(\"\"===selectorText)return null;break}i=0,modifiers.push(component),selectorText+=\"\"+component,component=null}return\"\"!==selectorText?new SelectorPart(elementName,modifiers,selectorText,line,col):null},_type_selector:function(){var tokenStream=this._tokenStream,ns=this._namespace_prefix(),elementName=this._element_name();return elementName?(ns&&(elementName.text=ns+elementName.text,elementName.col-=ns.length),elementName):(ns&&(tokenStream.unget(),ns.length>1&&tokenStream.unget()),null)},_class:function(){var token,tokenStream=this._tokenStream;return tokenStream.match(Tokens.DOT)?(tokenStream.mustMatch(Tokens.IDENT),token=tokenStream.token(),new SelectorSubPart(\".\"+token.value,\"class\",token.startLine,token.startCol-1)):null},_element_name:function(){var token,tokenStream=this._tokenStream;return tokenStream.match(Tokens.IDENT)?(token=tokenStream.token(),new SelectorSubPart(token.value,\"elementName\",token.startLine,token.startCol)):null},_namespace_prefix:function(){var tokenStream=this._tokenStream,value=\"\";return(tokenStream.LA(1)===Tokens.PIPE||tokenStream.LA(2)===Tokens.PIPE)&&(tokenStream.match([Tokens.IDENT,Tokens.STAR])&&(value+=tokenStream.token().value),tokenStream.mustMatch(Tokens.PIPE),value+=\"|\"),value.length?value:null},_universal:function(){var ns,tokenStream=this._tokenStream,value=\"\";return ns=this._namespace_prefix(),ns&&(value+=ns),tokenStream.match(Tokens.STAR)&&(value+=\"*\"),value.length?value:null},_attrib:function(){var ns,token,tokenStream=this._tokenStream,value=null;return tokenStream.match(Tokens.LBRACKET)?(token=tokenStream.token(),value=token.value,value+=this._readWhitespace(),ns=this._namespace_prefix(),ns&&(value+=ns),tokenStream.mustMatch(Tokens.IDENT),value+=tokenStream.token().value,value+=this._readWhitespace(),tokenStream.match([Tokens.PREFIXMATCH,Tokens.SUFFIXMATCH,Tokens.SUBSTRINGMATCH,Tokens.EQUALS,Tokens.INCLUDES,Tokens.DASHMATCH])&&(value+=tokenStream.token().value,value+=this._readWhitespace(),tokenStream.mustMatch([Tokens.IDENT,Tokens.STRING]),value+=tokenStream.token().value,value+=this._readWhitespace()),tokenStream.mustMatch(Tokens.RBRACKET),new SelectorSubPart(value+\"]\",\"attribute\",token.startLine,token.startCol)):null},_pseudo:function(){var line,col,tokenStream=this._tokenStream,pseudo=null,colons=\":\";return tokenStream.match(Tokens.COLON)&&(tokenStream.match(Tokens.COLON)&&(colons+=\":\"),tokenStream.match(Tokens.IDENT)?(pseudo=tokenStream.token().value,line=tokenStream.token().startLine,col=tokenStream.token().startCol-colons.length):tokenStream.peek()==Tokens.FUNCTION&&(line=tokenStream.LT(1).startLine,col=tokenStream.LT(1).startCol-colons.length,pseudo=this._functional_pseudo()),pseudo&&(pseudo=new SelectorSubPart(colons+pseudo,\"pseudo\",line,col))),pseudo},_functional_pseudo:function(){var tokenStream=this._tokenStream,value=null;return tokenStream.match(Tokens.FUNCTION)&&(value=tokenStream.token().value,value+=this._readWhitespace(),value+=this._expression(),tokenStream.mustMatch(Tokens.RPAREN),value+=\")\"),value},_expression:function(){for(var tokenStream=this._tokenStream,value=\"\";tokenStream.match([Tokens.PLUS,Tokens.MINUS,Tokens.DIMENSION,Tokens.NUMBER,Tokens.STRING,Tokens.IDENT,Tokens.LENGTH,Tokens.FREQ,Tokens.ANGLE,Tokens.TIME,Tokens.RESOLUTION,Tokens.SLASH]);)value+=tokenStream.token().value,value+=this._readWhitespace();return value.length?value:null},_negation:function(){var line,col,arg,tokenStream=this._tokenStream,value=\"\",subpart=null;return tokenStream.match(Tokens.NOT)&&(value=tokenStream.token().value,line=tokenStream.token().startLine,col=tokenStream.token().startCol,value+=this._readWhitespace(),arg=this._negation_arg(),value+=arg,value+=this._readWhitespace(),tokenStream.match(Tokens.RPAREN),value+=tokenStream.token().value,subpart=new SelectorSubPart(value,\"not\",line,col),subpart.args.push(arg)),subpart},_negation_arg:function(){var line,col,part,tokenStream=this._tokenStream,args=[this._type_selector,this._universal,function(){return tokenStream.match(Tokens.HASH)?new SelectorSubPart(tokenStream.token().value,\"id\",tokenStream.token().startLine,tokenStream.token().startCol):null},this._class,this._attrib,this._pseudo],arg=null,i=0,len=args.length;for(line=tokenStream.LT(1).startLine,col=tokenStream.LT(1).startCol;len>i&&null===arg;)arg=args[i].call(this),i++;return null===arg&&this._unexpectedToken(tokenStream.LT(1)),part=\"elementName\"==arg.type?new SelectorPart(arg,[],\"\"+arg,line,col):new SelectorPart(null,[arg],\"\"+arg,line,col)},_declaration:function(){var tokenStream=this._tokenStream,property=null,expr=null,prio=null,invalid=null,propertyName=\"\";if(property=this._property(),null!==property){tokenStream.mustMatch(Tokens.COLON),this._readWhitespace(),expr=this._expr(),expr&&0!==expr.length||this._unexpectedToken(tokenStream.LT(1)),prio=this._prio(),propertyName=\"\"+property,(this.options.starHack&&\"*\"==property.hack||this.options.underscoreHack&&\"_\"==property.hack)&&(propertyName=property.text);try{this._validateProperty(propertyName,expr)}catch(ex){invalid=ex}return this.fire({type:\"property\",property:property,value:expr,important:prio,line:property.line,col:property.col,invalid:invalid}),!0}return!1},_prio:function(){var tokenStream=this._tokenStream,result=tokenStream.match(Tokens.IMPORTANT_SYM);return this._readWhitespace(),result},_expr:function(inFunction){var values=(this._tokenStream,[]),value=null,operator=null;if(value=this._term(inFunction),null!==value)for(values.push(value);;){if(operator=this._operator(inFunction),operator&&values.push(operator),value=this._term(inFunction),null===value)break;\nvalues.push(value)}return values.length>0?new PropertyValue(values,values[0].line,values[0].col):null},_term:function(inFunction){var token,line,col,tokenStream=this._tokenStream,unary=null,value=null,endChar=null;return unary=this._unary_operator(),null!==unary&&(line=tokenStream.token().startLine,col=tokenStream.token().startCol),tokenStream.peek()==Tokens.IE_FUNCTION&&this.options.ieFilters?(value=this._ie_function(),null===unary&&(line=tokenStream.token().startLine,col=tokenStream.token().startCol)):inFunction&&tokenStream.match([Tokens.LPAREN,Tokens.LBRACE,Tokens.LBRACKET])?(token=tokenStream.token(),endChar=token.endChar,value=token.value+this._expr(inFunction).text,null===unary&&(line=tokenStream.token().startLine,col=tokenStream.token().startCol),tokenStream.mustMatch(Tokens.type(endChar)),value+=endChar,this._readWhitespace()):tokenStream.match([Tokens.NUMBER,Tokens.PERCENTAGE,Tokens.LENGTH,Tokens.ANGLE,Tokens.TIME,Tokens.FREQ,Tokens.STRING,Tokens.IDENT,Tokens.URI,Tokens.UNICODE_RANGE])?(value=tokenStream.token().value,null===unary&&(line=tokenStream.token().startLine,col=tokenStream.token().startCol),this._readWhitespace()):(token=this._hexcolor(),null===token?(null===unary&&(line=tokenStream.LT(1).startLine,col=tokenStream.LT(1).startCol),null===value&&(value=tokenStream.LA(3)==Tokens.EQUALS&&this.options.ieFilters?this._ie_function():this._function())):(value=token.value,null===unary&&(line=token.startLine,col=token.startCol))),null!==value?new PropertyValuePart(null!==unary?unary+value:value,line,col):null},_function:function(){var lt,tokenStream=this._tokenStream,functionText=null,expr=null;if(tokenStream.match(Tokens.FUNCTION)){if(functionText=tokenStream.token().value,this._readWhitespace(),expr=this._expr(!0),functionText+=expr,this.options.ieFilters&&tokenStream.peek()==Tokens.EQUALS)do for(this._readWhitespace()&&(functionText+=tokenStream.token().value),tokenStream.LA(0)==Tokens.COMMA&&(functionText+=tokenStream.token().value),tokenStream.match(Tokens.IDENT),functionText+=tokenStream.token().value,tokenStream.match(Tokens.EQUALS),functionText+=tokenStream.token().value,lt=tokenStream.peek();lt!=Tokens.COMMA&<!=Tokens.S&<!=Tokens.RPAREN;)tokenStream.get(),functionText+=tokenStream.token().value,lt=tokenStream.peek();while(tokenStream.match([Tokens.COMMA,Tokens.S]));tokenStream.match(Tokens.RPAREN),functionText+=\")\",this._readWhitespace()}return functionText},_ie_function:function(){var lt,tokenStream=this._tokenStream,functionText=null;if(tokenStream.match([Tokens.IE_FUNCTION,Tokens.FUNCTION])){functionText=tokenStream.token().value;do for(this._readWhitespace()&&(functionText+=tokenStream.token().value),tokenStream.LA(0)==Tokens.COMMA&&(functionText+=tokenStream.token().value),tokenStream.match(Tokens.IDENT),functionText+=tokenStream.token().value,tokenStream.match(Tokens.EQUALS),functionText+=tokenStream.token().value,lt=tokenStream.peek();lt!=Tokens.COMMA&<!=Tokens.S&<!=Tokens.RPAREN;)tokenStream.get(),functionText+=tokenStream.token().value,lt=tokenStream.peek();while(tokenStream.match([Tokens.COMMA,Tokens.S]));tokenStream.match(Tokens.RPAREN),functionText+=\")\",this._readWhitespace()}return functionText},_hexcolor:function(){var color,tokenStream=this._tokenStream,token=null;if(tokenStream.match(Tokens.HASH)){if(token=tokenStream.token(),color=token.value,!/#[a-f0-9]{3,6}/i.test(color))throw new SyntaxError(\"Expected a hex color but found '\"+color+\"' at line \"+token.startLine+\", col \"+token.startCol+\".\",token.startLine,token.startCol);this._readWhitespace()}return token},_keyframes:function(){var token,tt,name,tokenStream=this._tokenStream,prefix=\"\";for(tokenStream.mustMatch(Tokens.KEYFRAMES_SYM),token=tokenStream.token(),/^@\\-([^\\-]+)\\-/.test(token.value)&&(prefix=RegExp.$1),this._readWhitespace(),name=this._keyframe_name(),this._readWhitespace(),tokenStream.mustMatch(Tokens.LBRACE),this.fire({type:\"startkeyframes\",name:name,prefix:prefix,line:token.startLine,col:token.startCol}),this._readWhitespace(),tt=tokenStream.peek();tt==Tokens.IDENT||tt==Tokens.PERCENTAGE;)this._keyframe_rule(),this._readWhitespace(),tt=tokenStream.peek();this.fire({type:\"endkeyframes\",name:name,prefix:prefix,line:token.startLine,col:token.startCol}),this._readWhitespace(),tokenStream.mustMatch(Tokens.RBRACE)},_keyframe_name:function(){var tokenStream=this._tokenStream;return tokenStream.mustMatch([Tokens.IDENT,Tokens.STRING]),SyntaxUnit.fromToken(tokenStream.token())},_keyframe_rule:function(){var keyList=(this._tokenStream,this._key_list());this.fire({type:\"startkeyframerule\",keys:keyList,line:keyList[0].line,col:keyList[0].col}),this._readDeclarations(!0),this.fire({type:\"endkeyframerule\",keys:keyList,line:keyList[0].line,col:keyList[0].col})},_key_list:function(){var tokenStream=this._tokenStream,keyList=[];for(keyList.push(this._key()),this._readWhitespace();tokenStream.match(Tokens.COMMA);)this._readWhitespace(),keyList.push(this._key()),this._readWhitespace();return keyList},_key:function(){var token,tokenStream=this._tokenStream;if(tokenStream.match(Tokens.PERCENTAGE))return SyntaxUnit.fromToken(tokenStream.token());if(tokenStream.match(Tokens.IDENT)){if(token=tokenStream.token(),/from|to/i.test(token.value))return SyntaxUnit.fromToken(token);tokenStream.unget()}this._unexpectedToken(tokenStream.LT(1))},_skipCruft:function(){for(;this._tokenStream.match([Tokens.S,Tokens.CDO,Tokens.CDC]););},_readDeclarations:function(checkStart,readMargins){var tt,tokenStream=this._tokenStream;this._readWhitespace(),checkStart&&tokenStream.mustMatch(Tokens.LBRACE),this._readWhitespace();try{for(;;){if(tokenStream.match(Tokens.SEMICOLON)||readMargins&&this._margin());else{if(!this._declaration())break;if(!tokenStream.match(Tokens.SEMICOLON))break}this._readWhitespace()}tokenStream.mustMatch(Tokens.RBRACE),this._readWhitespace()}catch(ex){if(!(ex instanceof SyntaxError)||this.options.strict)throw ex;if(this.fire({type:\"error\",error:ex,message:ex.message,line:ex.line,col:ex.col}),tt=tokenStream.advance([Tokens.SEMICOLON,Tokens.RBRACE]),tt==Tokens.SEMICOLON)this._readDeclarations(!1,readMargins);else if(tt!=Tokens.RBRACE)throw ex}},_readWhitespace:function(){for(var tokenStream=this._tokenStream,ws=\"\";tokenStream.match(Tokens.S);)ws+=tokenStream.token().value;return ws},_unexpectedToken:function(token){throw new SyntaxError(\"Unexpected token '\"+token.value+\"' at line \"+token.startLine+\", col \"+token.startCol+\".\",token.startLine,token.startCol)},_verifyEnd:function(){this._tokenStream.LA(1)!=Tokens.EOF&&this._unexpectedToken(this._tokenStream.LT(1))},_validateProperty:function(property,value){Validation.validate(property,value)},parse:function(input){this._tokenStream=new TokenStream(input,Tokens),this._stylesheet()},parseStyleSheet:function(input){return this.parse(input)},parseMediaQuery:function(input){this._tokenStream=new TokenStream(input,Tokens);var result=this._media_query();return this._verifyEnd(),result},parsePropertyValue:function(input){this._tokenStream=new TokenStream(input,Tokens),this._readWhitespace();var result=this._expr();return this._readWhitespace(),this._verifyEnd(),result},parseRule:function(input){this._tokenStream=new TokenStream(input,Tokens),this._readWhitespace();var result=this._ruleset();return this._readWhitespace(),this._verifyEnd(),result},parseSelector:function(input){this._tokenStream=new TokenStream(input,Tokens),this._readWhitespace();var result=this._selector();return this._readWhitespace(),this._verifyEnd(),result},parseStyleAttribute:function(input){input+=\"}\",this._tokenStream=new TokenStream(input,Tokens),this._readDeclarations()}};for(prop in additions)additions.hasOwnProperty(prop)&&(proto[prop]=additions[prop]);return proto}();var Properties={\"align-items\":\"flex-start | flex-end | center | baseline | stretch\",\"align-content\":\"flex-start | flex-end | center | space-between | space-around | stretch\",\"align-self\":\"auto | flex-start | flex-end | center | baseline | stretch\",\"-webkit-align-items\":\"flex-start | flex-end | center | baseline | stretch\",\"-webkit-align-content\":\"flex-start | flex-end | center | space-between | space-around | stretch\",\"-webkit-align-self\":\"auto | flex-start | flex-end | center | baseline | stretch\",\"alignment-adjust\":\"auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | | \",\"alignment-baseline\":\"baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical\",animation:1,\"animation-delay\":{multi:\"
; + * } + * }); + * + * 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
Hello, {name}!
; + * } + * + * @return {ReactComponent} + * @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 ("production" !== 'production') { + validateTypeDef(Constructor, childContextTypes, 'childContext'); + } + Constructor.childContextTypes = _assign( + {}, + Constructor.childContextTypes, + childContextTypes + ); + }, + contextTypes: function(Constructor, contextTypes) { + if ("production" !== '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 ("production" !== '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__ + if ("production" !== '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 + ); + } + } + } + } + + 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)) { + _invariant( + specPolicy === 'OVERRIDE_BASE', + 'ReactClassInterface: You are attempting to override ' + + '`%s` from your class specification. Ensure that your method names ' + + 'do not overlap with React methods.', + name + ); + } + + // Disallow defining methods more than once unless explicitly allowed. + if (isAlreadyDefined) { + _invariant( + specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', + 'ReactClassInterface: You are attempting to define ' + + '`%s` on your component more than once. This conflict may be due ' + + 'to a mixin.', + name + ); + } + } + + /** + * Mixin helper which handles policy validation and reserved + * specification keys when building React classes. + */ + function mixSpecIntoComponent(Constructor, spec) { + if (!spec) { + if ("production" !== 'production') { + var typeofSpec = typeof spec; + var isMixinValid = typeofSpec === 'object' && spec !== null; + + if ("production" !== '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 + ); + } + } + + return; + } + + _invariant( + typeof spec !== 'function', + "ReactClass: You're attempting to " + + 'use a component class or function as a mixin. Instead, just use a ' + + 'regular object.' + ); + _invariant( + !isValidElement(spec), + "ReactClass: You're attempting to " + + 'use a component as a mixin. Instead, just use a regular object.' + ); + + 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. + _invariant( + isReactClassMethod && + (specPolicy === 'DEFINE_MANY_MERGED' || + specPolicy === 'DEFINE_MANY'), + 'ReactClass: Unexpected spec policy %s for key %s ' + + 'when mixing in component specs.', + specPolicy, + name + ); + + // 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 ("production" !== '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; + _invariant( + !isReserved, + '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 + ); + + var isInherited = name in Constructor; + _invariant( + !isInherited, + 'ReactClass: You are attempting to define ' + + '`%s` on your component more than once. This conflict may be ' + + 'due to a mixin.', + name + ); + 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) { + _invariant( + one && two && typeof one === 'object' && typeof two === 'object', + 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' + ); + + for (var key in two) { + if (two.hasOwnProperty(key)) { + _invariant( + one[key] === undefined, + '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 + ); + 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 ("production" !== '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) { + if ("production" !== 'production') { + warning( + false, + 'bind(): React component methods may only be bound to the ' + + 'component instance. See %s', + componentName + ); + } + } else if (!args.length) { + if ("production" !== '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 + ); + } + 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); + } + } + + var IsMountedPreMixin = { + componentDidMount: function() { + this.__isMounted = true; + } + }; + + var IsMountedPostMixin = { + componentWillUnmount: function() { + this.__isMounted = false; + } + }; + + /** + * 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, callback); + }, + + /** + * Checks whether or not this composite component is mounted. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function() { + if ("production" !== 'production') { + warning( + this.__didWarnIsMounted, + '%s: isMounted is deprecated. Instead, make sure to clean up ' + + 'subscriptions and pending requests in componentWillUnmount to ' + + 'prevent memory leaks.', + (this.constructor && this.constructor.displayName) || + this.name || + 'Component' + ); + this.__didWarnIsMounted = true; + } + return !!this.__isMounted; + } + }; + + var ReactClassComponent = function() {}; + _assign( + ReactClassComponent.prototype, + ReactComponent.prototype, + ReactClassMixin + ); + + /** + * 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 + */ + function createClass(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 ("production" !== 'production') { + warning( + this instanceof Constructor, + 'Something is calling a React component directly. Use a factory or ' + + 'JSX instead. See: https://fb.me/react-legacyfactory' + ); + } + + // 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 ("production" !== '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; + } + } + _invariant( + typeof initialState === 'object' && !Array.isArray(initialState), + '%s.getInitialState(): must return an object or null', + Constructor.displayName || 'ReactCompositeComponent' + ); + + this.state = initialState; + }); + Constructor.prototype = new ReactClassComponent(); + Constructor.prototype.constructor = Constructor; + Constructor.prototype.__reactAutoBindPairs = []; + + injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); + + mixSpecIntoComponent(Constructor, IsMountedPreMixin); + mixSpecIntoComponent(Constructor, spec); + mixSpecIntoComponent(Constructor, IsMountedPostMixin); + + // Initialize the defaultProps property after all mixins have been merged. + if (Constructor.getDefaultProps) { + Constructor.defaultProps = Constructor.getDefaultProps(); + } + + if ("production" !== '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 = {}; + } + } + + _invariant( + Constructor.prototype.render, + 'createClass(...): Class specification must implement a `render` method.' + ); + + if ("production" !== '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' + ); + warning( + !Constructor.prototype.componentWillRecieveProps, + '%s has a method called ' + + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', + spec.displayName || 'A component' + ); + } + + // 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; + } + + return createClass; +} + +module.exports = factory; + +},{"fbjs/lib/emptyObject":309,"fbjs/lib/invariant":316,"fbjs/lib/warning":323,"object-assign":504}],242:[function(require,module,exports){ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +'use strict'; + +var React = require('react'); +var factory = require('./factory'); + +if (typeof React === 'undefined') { + throw Error( + 'create-react-class could not find the React object. If you are using script tags, ' + + 'make sure that React is being loaded before create-react-class.' + ); +} + +// Hack to grab NoopUpdateQueue from isomorphic React +var ReactNoopUpdateQueue = new React.Component().updater; + +module.exports = factory( + React.Component, + React.isValidElement, + ReactNoopUpdateQueue +); + +},{"./factory":241,"react":983}],243:[function(require,module,exports){ +'use strict'; + +var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; + +exports.__esModule = true; + +var _isDisposable = require('./isDisposable'); + +var _isDisposable2 = _interopRequireWildcard(_isDisposable); + +/** + * Represents a group of disposable resources that are disposed together. + */ + +var CompositeDisposable = (function () { + function CompositeDisposable() { + for (var _len = arguments.length, disposables = Array(_len), _key = 0; _key < _len; _key++) { + disposables[_key] = arguments[_key]; + } + + _classCallCheck(this, CompositeDisposable); + + if (Array.isArray(disposables[0]) && disposables.length === 1) { + disposables = disposables[0]; + } + + for (var i = 0; i < disposables.length; i++) { + if (!_isDisposable2['default'](disposables[i])) { + throw new Error('Expected a disposable'); + } + } + + this.disposables = disposables; + this.isDisposed = false; + } + + /** + * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + * @param {Disposable} item Disposable to add. + */ + + CompositeDisposable.prototype.add = function add(item) { + if (this.isDisposed) { + item.dispose(); + } else { + this.disposables.push(item); + } + }; + + /** + * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. + * @param {Disposable} item Disposable to remove. + * @returns {Boolean} true if found; false otherwise. + */ + + CompositeDisposable.prototype.remove = function remove(item) { + if (this.isDisposed) { + return false; + } + + var index = this.disposables.indexOf(item); + if (index === -1) { + return false; + } + + this.disposables.splice(index, 1); + item.dispose(); + return true; + }; + + /** + * Disposes all disposables in the group and removes them from the group. + */ + + CompositeDisposable.prototype.dispose = function dispose() { + if (this.isDisposed) { + return; + } + + var len = this.disposables.length; + var currentDisposables = new Array(len); + for (var i = 0; i < len; i++) { + currentDisposables[i] = this.disposables[i]; + } + + this.isDisposed = true; + this.disposables = []; + this.length = 0; + + for (var i = 0; i < len; i++) { + currentDisposables[i].dispose(); + } + }; + + return CompositeDisposable; +})(); + +exports['default'] = CompositeDisposable; +module.exports = exports['default']; +},{"./isDisposable":247}],244:[function(require,module,exports){ +"use strict"; + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +exports.__esModule = true; +var noop = function noop() {}; + +/** + * The basic disposable. + */ + +var Disposable = (function () { + function Disposable(action) { + _classCallCheck(this, Disposable); + + this.isDisposed = false; + this.action = action || noop; + } + + Disposable.prototype.dispose = function dispose() { + if (!this.isDisposed) { + this.action.call(null); + this.isDisposed = true; + } + }; + + _createClass(Disposable, null, [{ + key: "empty", + enumerable: true, + value: { dispose: noop } + }]); + + return Disposable; +})(); + +exports["default"] = Disposable; +module.exports = exports["default"]; +},{}],245:[function(require,module,exports){ +'use strict'; + +var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; + +exports.__esModule = true; + +var _isDisposable = require('./isDisposable'); + +var _isDisposable2 = _interopRequireWildcard(_isDisposable); + +var SerialDisposable = (function () { + function SerialDisposable() { + _classCallCheck(this, SerialDisposable); + + this.isDisposed = false; + this.current = null; + } + + /** + * Gets the underlying disposable. + * @return The underlying disposable. + */ + + SerialDisposable.prototype.getDisposable = function getDisposable() { + return this.current; + }; + + /** + * Sets the underlying disposable. + * @param {Disposable} value The new underlying disposable. + */ + + SerialDisposable.prototype.setDisposable = function setDisposable() { + var value = arguments[0] === undefined ? null : arguments[0]; + + if (value != null && !_isDisposable2['default'](value)) { + throw new Error('Expected either an empty value or a valid disposable'); + } + + var isDisposed = this.isDisposed; + var previous = undefined; + + if (!isDisposed) { + previous = this.current; + this.current = value; + } + + if (previous) { + previous.dispose(); + } + + if (isDisposed && value) { + value.dispose(); + } + }; + + /** + * Disposes the underlying disposable as well as all future replacements. + */ + + SerialDisposable.prototype.dispose = function dispose() { + if (this.isDisposed) { + return; + } + + this.isDisposed = true; + var previous = this.current; + this.current = null; + + if (previous) { + previous.dispose(); + } + }; + + return SerialDisposable; +})(); + +exports['default'] = SerialDisposable; +module.exports = exports['default']; +},{"./isDisposable":247}],246:[function(require,module,exports){ +'use strict'; + +var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; + +exports.__esModule = true; + +var _isDisposable2 = require('./isDisposable'); + +var _isDisposable3 = _interopRequireWildcard(_isDisposable2); + +exports.isDisposable = _isDisposable3['default']; + +var _Disposable2 = require('./Disposable'); + +var _Disposable3 = _interopRequireWildcard(_Disposable2); + +exports.Disposable = _Disposable3['default']; + +var _CompositeDisposable2 = require('./CompositeDisposable'); + +var _CompositeDisposable3 = _interopRequireWildcard(_CompositeDisposable2); + +exports.CompositeDisposable = _CompositeDisposable3['default']; + +var _SerialDisposable2 = require('./SerialDisposable'); + +var _SerialDisposable3 = _interopRequireWildcard(_SerialDisposable2); + +exports.SerialDisposable = _SerialDisposable3['default']; +},{"./CompositeDisposable":243,"./Disposable":244,"./SerialDisposable":245,"./isDisposable":247}],247:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports['default'] = isDisposable; + +function isDisposable(obj) { + return Boolean(obj && typeof obj.dispose === 'function'); +} + +module.exports = exports['default']; +},{}],248:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _createStore = require('redux/lib/createStore'); + +var _createStore2 = _interopRequireDefault(_createStore); + +var _reducers = require('./reducers'); + +var _reducers2 = _interopRequireDefault(_reducers); + +var _dragDrop = require('./actions/dragDrop'); + +var dragDropActions = _interopRequireWildcard(_dragDrop); + +var _DragDropMonitor = require('./DragDropMonitor'); + +var _DragDropMonitor2 = _interopRequireDefault(_DragDropMonitor); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DragDropManager = function () { + function DragDropManager(createBackend) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, DragDropManager); + + var store = (0, _createStore2.default)(_reducers2.default); + this.context = context; + this.store = store; + this.monitor = new _DragDropMonitor2.default(store); + this.registry = this.monitor.registry; + this.backend = createBackend(this); + + store.subscribe(this.handleRefCountChange.bind(this)); + } + + _createClass(DragDropManager, [{ + key: 'handleRefCountChange', + value: function handleRefCountChange() { + var shouldSetUp = this.store.getState().refCount > 0; + if (shouldSetUp && !this.isSetUp) { + this.backend.setup(); + this.isSetUp = true; + } else if (!shouldSetUp && this.isSetUp) { + this.backend.teardown(); + this.isSetUp = false; + } + } + }, { + key: 'getContext', + value: function getContext() { + return this.context; + } + }, { + key: 'getMonitor', + value: function getMonitor() { + return this.monitor; + } + }, { + key: 'getBackend', + value: function getBackend() { + return this.backend; + } + }, { + key: 'getRegistry', + value: function getRegistry() { + return this.registry; + } + }, { + key: 'getActions', + value: function getActions() { + var manager = this; + var dispatch = this.store.dispatch; + + + function bindActionCreator(actionCreator) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var action = actionCreator.apply(manager, args); + if (typeof action !== 'undefined') { + dispatch(action); + } + }; + } + + return Object.keys(dragDropActions).filter(function (key) { + return typeof dragDropActions[key] === 'function'; + }).reduce(function (boundActions, key) { + var action = dragDropActions[key]; + boundActions[key] = bindActionCreator(action); // eslint-disable-line no-param-reassign + return boundActions; + }, {}); + } + }]); + + return DragDropManager; +}(); + +exports.default = DragDropManager; +},{"./DragDropMonitor":249,"./actions/dragDrop":253,"./reducers":260,"redux/lib/createStore":984}],249:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _invariant = require('invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _matchesType = require('./utils/matchesType'); + +var _matchesType2 = _interopRequireDefault(_matchesType); + +var _HandlerRegistry = require('./HandlerRegistry'); + +var _HandlerRegistry2 = _interopRequireDefault(_HandlerRegistry); + +var _dragOffset = require('./reducers/dragOffset'); + +var _dirtyHandlerIds = require('./reducers/dirtyHandlerIds'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DragDropMonitor = function () { + function DragDropMonitor(store) { + _classCallCheck(this, DragDropMonitor); + + this.store = store; + this.registry = new _HandlerRegistry2.default(store); + } + + _createClass(DragDropMonitor, [{ + key: 'subscribeToStateChange', + value: function subscribeToStateChange(listener) { + var _this = this; + + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var handlerIds = options.handlerIds; + + (0, _invariant2.default)(typeof listener === 'function', 'listener must be a function.'); + (0, _invariant2.default)(typeof handlerIds === 'undefined' || (0, _isArray2.default)(handlerIds), 'handlerIds, when specified, must be an array of strings.'); + + var prevStateId = this.store.getState().stateId; + var handleChange = function handleChange() { + var state = _this.store.getState(); + var currentStateId = state.stateId; + try { + var canSkipListener = currentStateId === prevStateId || currentStateId === prevStateId + 1 && !(0, _dirtyHandlerIds.areDirty)(state.dirtyHandlerIds, handlerIds); + + if (!canSkipListener) { + listener(); + } + } finally { + prevStateId = currentStateId; + } + }; + + return this.store.subscribe(handleChange); + } + }, { + key: 'subscribeToOffsetChange', + value: function subscribeToOffsetChange(listener) { + var _this2 = this; + + (0, _invariant2.default)(typeof listener === 'function', 'listener must be a function.'); + + var previousState = this.store.getState().dragOffset; + var handleChange = function handleChange() { + var nextState = _this2.store.getState().dragOffset; + if (nextState === previousState) { + return; + } + + previousState = nextState; + listener(); + }; + + return this.store.subscribe(handleChange); + } + }, { + key: 'canDragSource', + value: function canDragSource(sourceId) { + var source = this.registry.getSource(sourceId); + (0, _invariant2.default)(source, 'Expected to find a valid source.'); + + if (this.isDragging()) { + return false; + } + + return source.canDrag(this, sourceId); + } + }, { + key: 'canDropOnTarget', + value: function canDropOnTarget(targetId) { + var target = this.registry.getTarget(targetId); + (0, _invariant2.default)(target, 'Expected to find a valid target.'); + + if (!this.isDragging() || this.didDrop()) { + return false; + } + + var targetType = this.registry.getTargetType(targetId); + var draggedItemType = this.getItemType(); + return (0, _matchesType2.default)(targetType, draggedItemType) && target.canDrop(this, targetId); + } + }, { + key: 'isDragging', + value: function isDragging() { + return Boolean(this.getItemType()); + } + }, { + key: 'isDraggingSource', + value: function isDraggingSource(sourceId) { + var source = this.registry.getSource(sourceId, true); + (0, _invariant2.default)(source, 'Expected to find a valid source.'); + + if (!this.isDragging() || !this.isSourcePublic()) { + return false; + } + + var sourceType = this.registry.getSourceType(sourceId); + var draggedItemType = this.getItemType(); + if (sourceType !== draggedItemType) { + return false; + } + + return source.isDragging(this, sourceId); + } + }, { + key: 'isOverTarget', + value: function isOverTarget(targetId) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { shallow: false }; + var shallow = options.shallow; + + if (!this.isDragging()) { + return false; + } + + var targetType = this.registry.getTargetType(targetId); + var draggedItemType = this.getItemType(); + if (!(0, _matchesType2.default)(targetType, draggedItemType)) { + return false; + } + + var targetIds = this.getTargetIds(); + if (!targetIds.length) { + return false; + } + + var index = targetIds.indexOf(targetId); + if (shallow) { + return index === targetIds.length - 1; + } else { + return index > -1; + } + } + }, { + key: 'getItemType', + value: function getItemType() { + return this.store.getState().dragOperation.itemType; + } + }, { + key: 'getItem', + value: function getItem() { + return this.store.getState().dragOperation.item; + } + }, { + key: 'getSourceId', + value: function getSourceId() { + return this.store.getState().dragOperation.sourceId; + } + }, { + key: 'getTargetIds', + value: function getTargetIds() { + return this.store.getState().dragOperation.targetIds; + } + }, { + key: 'getDropResult', + value: function getDropResult() { + return this.store.getState().dragOperation.dropResult; + } + }, { + key: 'didDrop', + value: function didDrop() { + return this.store.getState().dragOperation.didDrop; + } + }, { + key: 'isSourcePublic', + value: function isSourcePublic() { + return this.store.getState().dragOperation.isSourcePublic; + } + }, { + key: 'getInitialClientOffset', + value: function getInitialClientOffset() { + return this.store.getState().dragOffset.initialClientOffset; + } + }, { + key: 'getInitialSourceClientOffset', + value: function getInitialSourceClientOffset() { + return this.store.getState().dragOffset.initialSourceClientOffset; + } + }, { + key: 'getClientOffset', + value: function getClientOffset() { + return this.store.getState().dragOffset.clientOffset; + } + }, { + key: 'getSourceClientOffset', + value: function getSourceClientOffset() { + return (0, _dragOffset.getSourceClientOffset)(this.store.getState().dragOffset); + } + }, { + key: 'getDifferenceFromInitialOffset', + value: function getDifferenceFromInitialOffset() { + return (0, _dragOffset.getDifferenceFromInitialOffset)(this.store.getState().dragOffset); + } + }]); + + return DragDropMonitor; +}(); + +exports.default = DragDropMonitor; +},{"./HandlerRegistry":252,"./reducers/dirtyHandlerIds":257,"./reducers/dragOffset":258,"./utils/matchesType":264,"invariant":336,"lodash/isArray":481}],250:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DragSource = function () { + function DragSource() { + _classCallCheck(this, DragSource); + } + + _createClass(DragSource, [{ + key: "canDrag", + value: function canDrag() { + return true; + } + }, { + key: "isDragging", + value: function isDragging(monitor, handle) { + return handle === monitor.getSourceId(); + } + }, { + key: "endDrag", + value: function endDrag() {} + }]); + + return DragSource; +}(); + +exports.default = DragSource; +},{}],251:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DropTarget = function () { + function DropTarget() { + _classCallCheck(this, DropTarget); + } + + _createClass(DropTarget, [{ + key: "canDrop", + value: function canDrop() { + return true; + } + }, { + key: "hover", + value: function hover() {} + }, { + key: "drop", + value: function drop() {} + }]); + + return DropTarget; +}(); + +exports.default = DropTarget; +},{}],252:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _invariant = require('invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _asap = require('asap'); + +var _asap2 = _interopRequireDefault(_asap); + +var _registry = require('./actions/registry'); + +var _getNextUniqueId = require('./utils/getNextUniqueId'); + +var _getNextUniqueId2 = _interopRequireDefault(_getNextUniqueId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var HandlerRoles = { + SOURCE: 'SOURCE', + TARGET: 'TARGET' +}; + +function validateSourceContract(source) { + (0, _invariant2.default)(typeof source.canDrag === 'function', 'Expected canDrag to be a function.'); + (0, _invariant2.default)(typeof source.beginDrag === 'function', 'Expected beginDrag to be a function.'); + (0, _invariant2.default)(typeof source.endDrag === 'function', 'Expected endDrag to be a function.'); +} + +function validateTargetContract(target) { + (0, _invariant2.default)(typeof target.canDrop === 'function', 'Expected canDrop to be a function.'); + (0, _invariant2.default)(typeof target.hover === 'function', 'Expected hover to be a function.'); + (0, _invariant2.default)(typeof target.drop === 'function', 'Expected beginDrag to be a function.'); +} + +function validateType(type, allowArray) { + if (allowArray && (0, _isArray2.default)(type)) { + type.forEach(function (t) { + return validateType(t, false); + }); + return; + } + + (0, _invariant2.default)(typeof type === 'string' || (typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'symbol', allowArray ? 'Type can only be a string, a symbol, or an array of either.' : 'Type can only be a string or a symbol.'); +} + +function getNextHandlerId(role) { + var id = (0, _getNextUniqueId2.default)().toString(); + switch (role) { + case HandlerRoles.SOURCE: + return 'S' + id; + case HandlerRoles.TARGET: + return 'T' + id; + default: + (0, _invariant2.default)(false, 'Unknown role: ' + role); + } +} + +function parseRoleFromHandlerId(handlerId) { + switch (handlerId[0]) { + case 'S': + return HandlerRoles.SOURCE; + case 'T': + return HandlerRoles.TARGET; + default: + (0, _invariant2.default)(false, 'Cannot parse handler ID: ' + handlerId); + } +} + +var HandlerRegistry = function () { + function HandlerRegistry(store) { + _classCallCheck(this, HandlerRegistry); + + this.store = store; + + this.types = {}; + this.handlers = {}; + + this.pinnedSourceId = null; + this.pinnedSource = null; + } + + _createClass(HandlerRegistry, [{ + key: 'addSource', + value: function addSource(type, source) { + validateType(type); + validateSourceContract(source); + + var sourceId = this.addHandler(HandlerRoles.SOURCE, type, source); + this.store.dispatch((0, _registry.addSource)(sourceId)); + return sourceId; + } + }, { + key: 'addTarget', + value: function addTarget(type, target) { + validateType(type, true); + validateTargetContract(target); + + var targetId = this.addHandler(HandlerRoles.TARGET, type, target); + this.store.dispatch((0, _registry.addTarget)(targetId)); + return targetId; + } + }, { + key: 'addHandler', + value: function addHandler(role, type, handler) { + var id = getNextHandlerId(role); + this.types[id] = type; + this.handlers[id] = handler; + + return id; + } + }, { + key: 'containsHandler', + value: function containsHandler(handler) { + var _this = this; + + return Object.keys(this.handlers).some(function (key) { + return _this.handlers[key] === handler; + }); + } + }, { + key: 'getSource', + value: function getSource(sourceId, includePinned) { + (0, _invariant2.default)(this.isSourceId(sourceId), 'Expected a valid source ID.'); + + var isPinned = includePinned && sourceId === this.pinnedSourceId; + var source = isPinned ? this.pinnedSource : this.handlers[sourceId]; + + return source; + } + }, { + key: 'getTarget', + value: function getTarget(targetId) { + (0, _invariant2.default)(this.isTargetId(targetId), 'Expected a valid target ID.'); + return this.handlers[targetId]; + } + }, { + key: 'getSourceType', + value: function getSourceType(sourceId) { + (0, _invariant2.default)(this.isSourceId(sourceId), 'Expected a valid source ID.'); + return this.types[sourceId]; + } + }, { + key: 'getTargetType', + value: function getTargetType(targetId) { + (0, _invariant2.default)(this.isTargetId(targetId), 'Expected a valid target ID.'); + return this.types[targetId]; + } + }, { + key: 'isSourceId', + value: function isSourceId(handlerId) { + var role = parseRoleFromHandlerId(handlerId); + return role === HandlerRoles.SOURCE; + } + }, { + key: 'isTargetId', + value: function isTargetId(handlerId) { + var role = parseRoleFromHandlerId(handlerId); + return role === HandlerRoles.TARGET; + } + }, { + key: 'removeSource', + value: function removeSource(sourceId) { + var _this2 = this; + + (0, _invariant2.default)(this.getSource(sourceId), 'Expected an existing source.'); + this.store.dispatch((0, _registry.removeSource)(sourceId)); + + (0, _asap2.default)(function () { + delete _this2.handlers[sourceId]; + delete _this2.types[sourceId]; + }); + } + }, { + key: 'removeTarget', + value: function removeTarget(targetId) { + var _this3 = this; + + (0, _invariant2.default)(this.getTarget(targetId), 'Expected an existing target.'); + this.store.dispatch((0, _registry.removeTarget)(targetId)); + + (0, _asap2.default)(function () { + delete _this3.handlers[targetId]; + delete _this3.types[targetId]; + }); + } + }, { + key: 'pinSource', + value: function pinSource(sourceId) { + var source = this.getSource(sourceId); + (0, _invariant2.default)(source, 'Expected an existing source.'); + + this.pinnedSourceId = sourceId; + this.pinnedSource = source; + } + }, { + key: 'unpinSource', + value: function unpinSource() { + (0, _invariant2.default)(this.pinnedSource, 'No source is pinned at the time.'); + + this.pinnedSourceId = null; + this.pinnedSource = null; + } + }]); + + return HandlerRegistry; +}(); + +exports.default = HandlerRegistry; +},{"./actions/registry":254,"./utils/getNextUniqueId":263,"asap":89,"invariant":336,"lodash/isArray":481}],253:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.END_DRAG = exports.DROP = exports.HOVER = exports.PUBLISH_DRAG_SOURCE = exports.BEGIN_DRAG = undefined; + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +exports.beginDrag = beginDrag; +exports.publishDragSource = publishDragSource; +exports.hover = hover; +exports.drop = drop; +exports.endDrag = endDrag; + +var _invariant = require('invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _isObject = require('lodash/isObject'); + +var _isObject2 = _interopRequireDefault(_isObject); + +var _matchesType = require('../utils/matchesType'); + +var _matchesType2 = _interopRequireDefault(_matchesType); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var BEGIN_DRAG = exports.BEGIN_DRAG = 'dnd-core/BEGIN_DRAG'; +var PUBLISH_DRAG_SOURCE = exports.PUBLISH_DRAG_SOURCE = 'dnd-core/PUBLISH_DRAG_SOURCE'; +var HOVER = exports.HOVER = 'dnd-core/HOVER'; +var DROP = exports.DROP = 'dnd-core/DROP'; +var END_DRAG = exports.END_DRAG = 'dnd-core/END_DRAG'; + +function beginDrag(sourceIds) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { publishSource: true, clientOffset: null }; + var publishSource = options.publishSource, + clientOffset = options.clientOffset, + getSourceClientOffset = options.getSourceClientOffset; + + (0, _invariant2.default)((0, _isArray2.default)(sourceIds), 'Expected sourceIds to be an array.'); + + var monitor = this.getMonitor(); + var registry = this.getRegistry(); + (0, _invariant2.default)(!monitor.isDragging(), 'Cannot call beginDrag while dragging.'); + + for (var i = 0; i < sourceIds.length; i++) { + (0, _invariant2.default)(registry.getSource(sourceIds[i]), 'Expected sourceIds to be registered.'); + } + + var sourceId = null; + for (var _i = sourceIds.length - 1; _i >= 0; _i--) { + if (monitor.canDragSource(sourceIds[_i])) { + sourceId = sourceIds[_i]; + break; + } + } + if (sourceId === null) { + return; + } + + var sourceClientOffset = null; + if (clientOffset) { + (0, _invariant2.default)(typeof getSourceClientOffset === 'function', 'When clientOffset is provided, getSourceClientOffset must be a function.'); + sourceClientOffset = getSourceClientOffset(sourceId); + } + + var source = registry.getSource(sourceId); + var item = source.beginDrag(monitor, sourceId); + (0, _invariant2.default)((0, _isObject2.default)(item), 'Item must be an object.'); + + registry.pinSource(sourceId); + + var itemType = registry.getSourceType(sourceId); + return { + type: BEGIN_DRAG, + itemType: itemType, + item: item, + sourceId: sourceId, + clientOffset: clientOffset, + sourceClientOffset: sourceClientOffset, + isSourcePublic: publishSource + }; +} + +function publishDragSource() { + var monitor = this.getMonitor(); + if (!monitor.isDragging()) { + return; + } + + return { type: PUBLISH_DRAG_SOURCE }; +} + +function hover(targetIdsArg) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$clientOffset = _ref.clientOffset, + clientOffset = _ref$clientOffset === undefined ? null : _ref$clientOffset; + + (0, _invariant2.default)((0, _isArray2.default)(targetIdsArg), 'Expected targetIds to be an array.'); + var targetIds = targetIdsArg.slice(0); + + var monitor = this.getMonitor(); + var registry = this.getRegistry(); + (0, _invariant2.default)(monitor.isDragging(), 'Cannot call hover while not dragging.'); + (0, _invariant2.default)(!monitor.didDrop(), 'Cannot call hover after drop.'); + + // First check invariants. + for (var i = 0; i < targetIds.length; i++) { + var targetId = targetIds[i]; + (0, _invariant2.default)(targetIds.lastIndexOf(targetId) === i, 'Expected targetIds to be unique in the passed array.'); + + var target = registry.getTarget(targetId); + (0, _invariant2.default)(target, 'Expected targetIds to be registered.'); + } + + var draggedItemType = monitor.getItemType(); + + // Remove those targetIds that don't match the targetType. This + // fixes shallow isOver which would only be non-shallow because of + // non-matching targets. + for (var _i2 = targetIds.length - 1; _i2 >= 0; _i2--) { + var _targetId = targetIds[_i2]; + var targetType = registry.getTargetType(_targetId); + if (!(0, _matchesType2.default)(targetType, draggedItemType)) { + targetIds.splice(_i2, 1); + } + } + + // Finally call hover on all matching targets. + for (var _i3 = 0; _i3 < targetIds.length; _i3++) { + var _targetId2 = targetIds[_i3]; + var _target = registry.getTarget(_targetId2); + _target.hover(monitor, _targetId2); + } + + return { + type: HOVER, + targetIds: targetIds, + clientOffset: clientOffset + }; +} + +function drop() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + var monitor = this.getMonitor(); + var registry = this.getRegistry(); + (0, _invariant2.default)(monitor.isDragging(), 'Cannot call drop while not dragging.'); + (0, _invariant2.default)(!monitor.didDrop(), 'Cannot call drop twice during one drag operation.'); + + var targetIds = monitor.getTargetIds().filter(monitor.canDropOnTarget, monitor); + + targetIds.reverse(); + targetIds.forEach(function (targetId, index) { + var target = registry.getTarget(targetId); + + var dropResult = target.drop(monitor, targetId); + (0, _invariant2.default)(typeof dropResult === 'undefined' || (0, _isObject2.default)(dropResult), 'Drop result must either be an object or undefined.'); + if (typeof dropResult === 'undefined') { + dropResult = index === 0 ? {} : monitor.getDropResult(); + } + + _this.store.dispatch({ + type: DROP, + dropResult: _extends({}, options, dropResult) + }); + }); +} + +function endDrag() { + var monitor = this.getMonitor(); + var registry = this.getRegistry(); + (0, _invariant2.default)(monitor.isDragging(), 'Cannot call endDrag while not dragging.'); + + var sourceId = monitor.getSourceId(); + var source = registry.getSource(sourceId, true); + source.endDrag(monitor, sourceId); + + registry.unpinSource(); + + return { type: END_DRAG }; +} +},{"../utils/matchesType":264,"invariant":336,"lodash/isArray":481,"lodash/isObject":488}],254:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.addSource = addSource; +exports.addTarget = addTarget; +exports.removeSource = removeSource; +exports.removeTarget = removeTarget; +var ADD_SOURCE = exports.ADD_SOURCE = 'dnd-core/ADD_SOURCE'; +var ADD_TARGET = exports.ADD_TARGET = 'dnd-core/ADD_TARGET'; +var REMOVE_SOURCE = exports.REMOVE_SOURCE = 'dnd-core/REMOVE_SOURCE'; +var REMOVE_TARGET = exports.REMOVE_TARGET = 'dnd-core/REMOVE_TARGET'; + +function addSource(sourceId) { + return { + type: ADD_SOURCE, + sourceId: sourceId + }; +} + +function addTarget(targetId) { + return { + type: ADD_TARGET, + targetId: targetId + }; +} + +function removeSource(sourceId) { + return { + type: REMOVE_SOURCE, + sourceId: sourceId + }; +} + +function removeTarget(targetId) { + return { + type: REMOVE_TARGET, + targetId: targetId + }; +} +},{}],255:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +exports.default = createBackend; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TestBackend = function () { + function TestBackend(manager) { + _classCallCheck(this, TestBackend); + + this.actions = manager.getActions(); + } + + _createClass(TestBackend, [{ + key: 'setup', + value: function setup() { + this.didCallSetup = true; + } + }, { + key: 'teardown', + value: function teardown() { + this.didCallTeardown = true; + } + }, { + key: 'connectDragSource', + value: function connectDragSource() { + return _noop2.default; + } + }, { + key: 'connectDragPreview', + value: function connectDragPreview() { + return _noop2.default; + } + }, { + key: 'connectDropTarget', + value: function connectDropTarget() { + return _noop2.default; + } + }, { + key: 'simulateBeginDrag', + value: function simulateBeginDrag(sourceIds, options) { + this.actions.beginDrag(sourceIds, options); + } + }, { + key: 'simulatePublishDragSource', + value: function simulatePublishDragSource() { + this.actions.publishDragSource(); + } + }, { + key: 'simulateHover', + value: function simulateHover(targetIds, options) { + this.actions.hover(targetIds, options); + } + }, { + key: 'simulateDrop', + value: function simulateDrop() { + this.actions.drop(); + } + }, { + key: 'simulateEndDrag', + value: function simulateEndDrag() { + this.actions.endDrag(); + } + }]); + + return TestBackend; +}(); + +function createBackend(manager) { + return new TestBackend(manager); +} +},{"lodash/noop":495}],256:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _DragDropManager = require('./DragDropManager'); + +Object.defineProperty(exports, 'DragDropManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DragDropManager).default; + } +}); + +var _DragSource = require('./DragSource'); + +Object.defineProperty(exports, 'DragSource', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DragSource).default; + } +}); + +var _DropTarget = require('./DropTarget'); + +Object.defineProperty(exports, 'DropTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DropTarget).default; + } +}); + +var _createTestBackend = require('./backends/createTestBackend'); + +Object.defineProperty(exports, 'createTestBackend', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_createTestBackend).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./DragDropManager":248,"./DragSource":250,"./DropTarget":251,"./backends/createTestBackend":255}],257:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = dirtyHandlerIds; +exports.areDirty = areDirty; + +var _xor = require('lodash/xor'); + +var _xor2 = _interopRequireDefault(_xor); + +var _intersection = require('lodash/intersection'); + +var _intersection2 = _interopRequireDefault(_intersection); + +var _dragDrop = require('../actions/dragDrop'); + +var _registry = require('../actions/registry'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var NONE = []; +var ALL = []; + +function dirtyHandlerIds() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : NONE; + var action = arguments[1]; + var dragOperation = arguments[2]; + + switch (action.type) { + case _dragDrop.HOVER: + break; + case _registry.ADD_SOURCE: + case _registry.ADD_TARGET: + case _registry.REMOVE_TARGET: + case _registry.REMOVE_SOURCE: + return NONE; + case _dragDrop.BEGIN_DRAG: + case _dragDrop.PUBLISH_DRAG_SOURCE: + case _dragDrop.END_DRAG: + case _dragDrop.DROP: + default: + return ALL; + } + + var targetIds = action.targetIds; + var prevTargetIds = dragOperation.targetIds; + + var result = (0, _xor2.default)(targetIds, prevTargetIds); + + var didChange = false; + if (result.length === 0) { + for (var i = 0; i < targetIds.length; i++) { + if (targetIds[i] !== prevTargetIds[i]) { + didChange = true; + break; + } + } + } else { + didChange = true; + } + + if (!didChange) { + return NONE; + } + + var prevInnermostTargetId = prevTargetIds[prevTargetIds.length - 1]; + var innermostTargetId = targetIds[targetIds.length - 1]; + + if (prevInnermostTargetId !== innermostTargetId) { + if (prevInnermostTargetId) { + result.push(prevInnermostTargetId); + } + if (innermostTargetId) { + result.push(innermostTargetId); + } + } + + return result; +} + +function areDirty(state, handlerIds) { + if (state === NONE) { + return false; + } + + if (state === ALL || typeof handlerIds === 'undefined') { + return true; + } + + return (0, _intersection2.default)(handlerIds, state).length > 0; +} +},{"../actions/dragDrop":253,"../actions/registry":254,"lodash/intersection":479,"lodash/xor":501}],258:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +exports.default = dragOffset; +exports.getSourceClientOffset = getSourceClientOffset; +exports.getDifferenceFromInitialOffset = getDifferenceFromInitialOffset; + +var _dragDrop = require('../actions/dragDrop'); + +var initialState = { + initialSourceClientOffset: null, + initialClientOffset: null, + clientOffset: null +}; + +function areOffsetsEqual(offsetA, offsetB) { + if (offsetA === offsetB) { + return true; + } + return offsetA && offsetB && offsetA.x === offsetB.x && offsetA.y === offsetB.y; +} + +function dragOffset() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; + var action = arguments[1]; + + switch (action.type) { + case _dragDrop.BEGIN_DRAG: + return { + initialSourceClientOffset: action.sourceClientOffset, + initialClientOffset: action.clientOffset, + clientOffset: action.clientOffset + }; + case _dragDrop.HOVER: + if (areOffsetsEqual(state.clientOffset, action.clientOffset)) { + return state; + } + return _extends({}, state, { + clientOffset: action.clientOffset + }); + case _dragDrop.END_DRAG: + case _dragDrop.DROP: + return initialState; + default: + return state; + } +} + +function getSourceClientOffset(state) { + var clientOffset = state.clientOffset, + initialClientOffset = state.initialClientOffset, + initialSourceClientOffset = state.initialSourceClientOffset; + + if (!clientOffset || !initialClientOffset || !initialSourceClientOffset) { + return null; + } + return { + x: clientOffset.x + initialSourceClientOffset.x - initialClientOffset.x, + y: clientOffset.y + initialSourceClientOffset.y - initialClientOffset.y + }; +} + +function getDifferenceFromInitialOffset(state) { + var clientOffset = state.clientOffset, + initialClientOffset = state.initialClientOffset; + + if (!clientOffset || !initialClientOffset) { + return null; + } + return { + x: clientOffset.x - initialClientOffset.x, + y: clientOffset.y - initialClientOffset.y + }; +} +},{"../actions/dragDrop":253}],259:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +exports.default = dragOperation; + +var _without = require('lodash/without'); + +var _without2 = _interopRequireDefault(_without); + +var _dragDrop = require('../actions/dragDrop'); + +var _registry = require('../actions/registry'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var initialState = { + itemType: null, + item: null, + sourceId: null, + targetIds: [], + dropResult: null, + didDrop: false, + isSourcePublic: null +}; + +function dragOperation() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; + var action = arguments[1]; + + switch (action.type) { + case _dragDrop.BEGIN_DRAG: + return _extends({}, state, { + itemType: action.itemType, + item: action.item, + sourceId: action.sourceId, + isSourcePublic: action.isSourcePublic, + dropResult: null, + didDrop: false + }); + case _dragDrop.PUBLISH_DRAG_SOURCE: + return _extends({}, state, { + isSourcePublic: true + }); + case _dragDrop.HOVER: + return _extends({}, state, { + targetIds: action.targetIds + }); + case _registry.REMOVE_TARGET: + if (state.targetIds.indexOf(action.targetId) === -1) { + return state; + } + return _extends({}, state, { + targetIds: (0, _without2.default)(state.targetIds, action.targetId) + }); + case _dragDrop.DROP: + return _extends({}, state, { + dropResult: action.dropResult, + didDrop: true, + targetIds: [] + }); + case _dragDrop.END_DRAG: + return _extends({}, state, { + itemType: null, + item: null, + sourceId: null, + dropResult: null, + didDrop: false, + isSourcePublic: null, + targetIds: [] + }); + default: + return state; + } +} +},{"../actions/dragDrop":253,"../actions/registry":254,"lodash/without":499}],260:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduce; + +var _dragOffset = require('./dragOffset'); + +var _dragOffset2 = _interopRequireDefault(_dragOffset); + +var _dragOperation = require('./dragOperation'); + +var _dragOperation2 = _interopRequireDefault(_dragOperation); + +var _refCount = require('./refCount'); + +var _refCount2 = _interopRequireDefault(_refCount); + +var _dirtyHandlerIds = require('./dirtyHandlerIds'); + +var _dirtyHandlerIds2 = _interopRequireDefault(_dirtyHandlerIds); + +var _stateId = require('./stateId'); + +var _stateId2 = _interopRequireDefault(_stateId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reduce() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var action = arguments[1]; + + return { + dirtyHandlerIds: (0, _dirtyHandlerIds2.default)(state.dirtyHandlerIds, action, state.dragOperation), + dragOffset: (0, _dragOffset2.default)(state.dragOffset, action), + refCount: (0, _refCount2.default)(state.refCount, action), + dragOperation: (0, _dragOperation2.default)(state.dragOperation, action), + stateId: (0, _stateId2.default)(state.stateId) + }; +} +},{"./dirtyHandlerIds":257,"./dragOffset":258,"./dragOperation":259,"./refCount":261,"./stateId":262}],261:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = refCount; + +var _registry = require('../actions/registry'); + +function refCount() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var action = arguments[1]; + + switch (action.type) { + case _registry.ADD_SOURCE: + case _registry.ADD_TARGET: + return state + 1; + case _registry.REMOVE_SOURCE: + case _registry.REMOVE_TARGET: + return state - 1; + default: + return state; + } +} +},{"../actions/registry":254}],262:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = stateId; +function stateId() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + + return state + 1; +} +},{}],263:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getNextUniqueId; +var nextUniqueId = 0; + +function getNextUniqueId() { + return nextUniqueId++; +} +},{}],264:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = matchesType; + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function matchesType(targetType, draggedItemType) { + if ((0, _isArray2.default)(targetType)) { + return targetType.some(function (t) { + return t === draggedItemType; + }); + } else { + return targetType === draggedItemType; + } +} +},{"lodash/isArray":481}],265:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = activeElement; + +var _ownerDocument = require('./ownerDocument'); + +var _ownerDocument2 = _interopRequireDefault(_ownerDocument); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function activeElement() { + var doc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _ownerDocument2.default)(); + + try { + return doc.activeElement; + } catch (e) {/* ie throws if no active element */} +} +module.exports = exports['default']; +},{"./ownerDocument":275}],266:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = addClass; + +var _hasClass = require('./hasClass'); + +var _hasClass2 = _interopRequireDefault(_hasClass); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function addClass(element, className) { + if (element.classList) element.classList.add(className);else if (!(0, _hasClass2.default)(element)) element.className = element.className + ' ' + className; +} +module.exports = exports['default']; +},{"./hasClass":267}],267:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = hasClass; +function hasClass(element, className) { + if (element.classList) return !!className && element.classList.contains(className);else return (" " + element.className + " ").indexOf(" " + className + " ") !== -1; +} +module.exports = exports["default"]; +},{}],268:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasClass = exports.removeClass = exports.addClass = undefined; + +var _addClass = require('./addClass'); + +var _addClass2 = _interopRequireDefault(_addClass); + +var _removeClass = require('./removeClass'); + +var _removeClass2 = _interopRequireDefault(_removeClass); + +var _hasClass = require('./hasClass'); + +var _hasClass2 = _interopRequireDefault(_hasClass); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.addClass = _addClass2.default; +exports.removeClass = _removeClass2.default; +exports.hasClass = _hasClass2.default; +exports.default = { addClass: _addClass2.default, removeClass: _removeClass2.default, hasClass: _hasClass2.default }; +},{"./addClass":266,"./hasClass":267,"./removeClass":269}],269:[function(require,module,exports){ +'use strict'; + +module.exports = function removeClass(element, className) { + if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); +}; +},{}],270:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = filterEvents; + +var _contains = require('../query/contains'); + +var _contains2 = _interopRequireDefault(_contains); + +var _querySelectorAll = require('../query/querySelectorAll'); + +var _querySelectorAll2 = _interopRequireDefault(_querySelectorAll); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterEvents(selector, handler) { + return function filterHandler(e) { + var top = e.currentTarget, + target = e.target, + matches = (0, _querySelectorAll2.default)(top, selector); + + if (matches.some(function (match) { + return (0, _contains2.default)(match, target); + })) handler.call(this, e); + }; +} +module.exports = exports['default']; +},{"../query/contains":276,"../query/querySelectorAll":281}],271:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.listen = exports.filter = exports.off = exports.on = undefined; + +var _on = require('./on'); + +var _on2 = _interopRequireDefault(_on); + +var _off = require('./off'); + +var _off2 = _interopRequireDefault(_off); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _listen = require('./listen'); + +var _listen2 = _interopRequireDefault(_listen); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.on = _on2.default; +exports.off = _off2.default; +exports.filter = _filter2.default; +exports.listen = _listen2.default; +exports.default = { on: _on2.default, off: _off2.default, filter: _filter2.default, listen: _listen2.default }; +},{"./filter":270,"./listen":272,"./off":273,"./on":274}],272:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _inDOM = require('../util/inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +var _on = require('./on'); + +var _on2 = _interopRequireDefault(_on); + +var _off = require('./off'); + +var _off2 = _interopRequireDefault(_off); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var listen = function listen() {}; + +if (_inDOM2.default) { + listen = function listen(node, eventName, handler, capture) { + (0, _on2.default)(node, eventName, handler, capture); + return function () { + (0, _off2.default)(node, eventName, handler, capture); + }; + }; +} + +exports.default = listen; +module.exports = exports['default']; +},{"../util/inDOM":293,"./off":273,"./on":274}],273:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _inDOM = require('../util/inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var off = function off() {}; +if (_inDOM2.default) { + off = function () { + if (document.addEventListener) return function (node, eventName, handler, capture) { + return node.removeEventListener(eventName, handler, capture || false); + };else if (document.attachEvent) return function (node, eventName, handler) { + return node.detachEvent('on' + eventName, handler); + }; + }(); +} + +exports.default = off; +module.exports = exports['default']; +},{"../util/inDOM":293}],274:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _inDOM = require('../util/inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var on = function on() {}; +if (_inDOM2.default) { + on = function () { + + if (document.addEventListener) return function (node, eventName, handler, capture) { + return node.addEventListener(eventName, handler, capture || false); + };else if (document.attachEvent) return function (node, eventName, handler) { + return node.attachEvent('on' + eventName, function (e) { + e = e || window.event; + e.target = e.target || e.srcElement; + e.currentTarget = node; + handler.call(node, e); + }); + }; + }(); +} + +exports.default = on; +module.exports = exports['default']; +},{"../util/inDOM":293}],275:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ownerDocument; +function ownerDocument(node) { + return node && node.ownerDocument || document; +} +module.exports = exports["default"]; +},{}],276:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _inDOM = require('../util/inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function () { + // HTML DOM and SVG DOM may have different support levels, + // so we need to check on context instead of a document root element. + return _inDOM2.default ? function (context, node) { + if (context.contains) { + return context.contains(node); + } else if (context.compareDocumentPosition) { + return context === node || !!(context.compareDocumentPosition(node) & 16); + } else { + return fallback(context, node); + } + } : fallback; +}(); + +function fallback(context, node) { + if (node) do { + if (node === context) return true; + } while (node = node.parentNode); + + return false; +} +module.exports = exports['default']; +},{"../util/inDOM":293}],277:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getWindow; +function getWindow(node) { + return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; +} +module.exports = exports["default"]; +},{}],278:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = offset; + +var _contains = require('./contains'); + +var _contains2 = _interopRequireDefault(_contains); + +var _isWindow = require('./isWindow'); + +var _isWindow2 = _interopRequireDefault(_isWindow); + +var _ownerDocument = require('../ownerDocument'); + +var _ownerDocument2 = _interopRequireDefault(_ownerDocument); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function offset(node) { + var doc = (0, _ownerDocument2.default)(node), + win = (0, _isWindow2.default)(doc), + docElem = doc && doc.documentElement, + box = { top: 0, left: 0, height: 0, width: 0 }; + + if (!doc) return; + + // Make sure it's not a disconnected DOM node + if (!(0, _contains2.default)(docElem, node)) return box; + + if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect(); + + // IE8 getBoundingClientRect doesn't support width & height + box = { + top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), + left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0), + width: (box.width == null ? node.offsetWidth : box.width) || 0, + height: (box.height == null ? node.offsetHeight : box.height) || 0 + }; + + return box; +} +module.exports = exports['default']; +},{"../ownerDocument":275,"./contains":276,"./isWindow":277}],279:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = offsetParent; + +var _ownerDocument = require('../ownerDocument'); + +var _ownerDocument2 = _interopRequireDefault(_ownerDocument); + +var _style = require('../style'); + +var _style2 = _interopRequireDefault(_style); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function nodeName(node) { + return node.nodeName && node.nodeName.toLowerCase(); +} + +function offsetParent(node) { + var doc = (0, _ownerDocument2.default)(node), + offsetParent = node && node.offsetParent; + + while (offsetParent && nodeName(node) !== 'html' && (0, _style2.default)(offsetParent, 'position') === 'static') { + offsetParent = offsetParent.offsetParent; + } + + return offsetParent || doc.documentElement; +} +module.exports = exports['default']; +},{"../ownerDocument":275,"../style":285}],280:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + +exports.default = position; + +var _offset = require('./offset'); + +var _offset2 = _interopRequireDefault(_offset); + +var _offsetParent = require('./offsetParent'); + +var _offsetParent2 = _interopRequireDefault(_offsetParent); + +var _scrollTop = require('./scrollTop'); + +var _scrollTop2 = _interopRequireDefault(_scrollTop); + +var _scrollLeft = require('./scrollLeft'); + +var _scrollLeft2 = _interopRequireDefault(_scrollLeft); + +var _style = require('../style'); + +var _style2 = _interopRequireDefault(_style); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function nodeName(node) { + return node.nodeName && node.nodeName.toLowerCase(); +} + +function position(node, offsetParent) { + var parentOffset = { top: 0, left: 0 }, + offset; + + // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, + // because it is its only offset parent + if ((0, _style2.default)(node, 'position') === 'fixed') { + offset = node.getBoundingClientRect(); + } else { + offsetParent = offsetParent || (0, _offsetParent2.default)(node); + offset = (0, _offset2.default)(node); + + if (nodeName(offsetParent) !== 'html') parentOffset = (0, _offset2.default)(offsetParent); + + parentOffset.top += parseInt((0, _style2.default)(offsetParent, 'borderTopWidth'), 10) - (0, _scrollTop2.default)(offsetParent) || 0; + parentOffset.left += parseInt((0, _style2.default)(offsetParent, 'borderLeftWidth'), 10) - (0, _scrollLeft2.default)(offsetParent) || 0; + } + + // Subtract parent offsets and node margins + return _extends({}, offset, { + top: offset.top - parentOffset.top - (parseInt((0, _style2.default)(node, 'marginTop'), 10) || 0), + left: offset.left - parentOffset.left - (parseInt((0, _style2.default)(node, 'marginLeft'), 10) || 0) + }); +} +module.exports = exports['default']; +},{"../style":285,"./offset":278,"./offsetParent":279,"./scrollLeft":282,"./scrollTop":283}],281:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = qsa; +// Zepto.js +// (c) 2010-2015 Thomas Fuchs +// Zepto.js may be freely distributed under the MIT license. +var simpleSelectorRE = /^[\w-]*$/; +var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice); + +function qsa(element, selector) { + var maybeID = selector[0] === '#', + maybeClass = selector[0] === '.', + nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, + isSimple = simpleSelectorRE.test(nameOnly), + found; + + if (isSimple) { + if (maybeID) { + element = element.getElementById ? element : document; + return (found = element.getElementById(nameOnly)) ? [found] : []; + } + + if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly)); + + return toArray(element.getElementsByTagName(selector)); + } + + return toArray(element.querySelectorAll(selector)); +} +module.exports = exports['default']; +},{}],282:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = scrollTop; + +var _isWindow = require('./isWindow'); + +var _isWindow2 = _interopRequireDefault(_isWindow); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function scrollTop(node, val) { + var win = (0, _isWindow2.default)(node); + + if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft; + + if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val; +} +module.exports = exports['default']; +},{"./isWindow":277}],283:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = scrollTop; + +var _isWindow = require('./isWindow'); + +var _isWindow2 = _interopRequireDefault(_isWindow); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function scrollTop(node, val) { + var win = (0, _isWindow2.default)(node); + + if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop; + + if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val; +} +module.exports = exports['default']; +},{"./isWindow":277}],284:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _getComputedStyle; + +var _camelizeStyle = require('../util/camelizeStyle'); + +var _camelizeStyle2 = _interopRequireDefault(_camelizeStyle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var rposition = /^(top|right|bottom|left)$/; +var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; + +function _getComputedStyle(node) { + if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); + var doc = node.ownerDocument; + + return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { + //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 + getPropertyValue: function getPropertyValue(prop) { + var style = node.style; + + prop = (0, _camelizeStyle2.default)(prop); + + if (prop == 'float') prop = 'styleFloat'; + + var current = node.currentStyle[prop] || null; + + if (current == null && style && style[prop]) current = style[prop]; + + if (rnumnonpx.test(current) && !rposition.test(prop)) { + // Remember the original values + var left = style.left; + var runStyle = node.runtimeStyle; + var rsLeft = runStyle && runStyle.left; + + // Put in the new values to get a computed value out + if (rsLeft) runStyle.left = node.currentStyle.left; + + style.left = prop === 'fontSize' ? '1em' : current; + current = style.pixelLeft + 'px'; + + // Revert the changed values + style.left = left; + if (rsLeft) runStyle.left = rsLeft; + } + + return current; + } + }; +} +module.exports = exports['default']; +},{"../util/camelizeStyle":290}],285:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = style; + +var _camelizeStyle = require('../util/camelizeStyle'); + +var _camelizeStyle2 = _interopRequireDefault(_camelizeStyle); + +var _hyphenateStyle = require('../util/hyphenateStyle'); + +var _hyphenateStyle2 = _interopRequireDefault(_hyphenateStyle); + +var _getComputedStyle2 = require('./getComputedStyle'); + +var _getComputedStyle3 = _interopRequireDefault(_getComputedStyle2); + +var _removeStyle = require('./removeStyle'); + +var _removeStyle2 = _interopRequireDefault(_removeStyle); + +var _properties = require('../transition/properties'); + +var _isTransform = require('../transition/isTransform'); + +var _isTransform2 = _interopRequireDefault(_isTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function style(node, property, value) { + var css = ''; + var transforms = ''; + var props = property; + + if (typeof property === 'string') { + if (value === undefined) { + return node.style[(0, _camelizeStyle2.default)(property)] || (0, _getComputedStyle3.default)(node).getPropertyValue((0, _hyphenateStyle2.default)(property)); + } else { + (props = {})[property] = value; + } + } + + Object.keys(props).forEach(function (key) { + var value = props[key]; + if (!value && value !== 0) { + (0, _removeStyle2.default)(node, (0, _hyphenateStyle2.default)(key)); + } else if ((0, _isTransform2.default)(key)) { + transforms += key + '(' + value + ') '; + } else { + css += (0, _hyphenateStyle2.default)(key) + ': ' + value + ';'; + } + }); + + if (transforms) { + css += _properties.transform + ': ' + transforms + ';'; + } + + node.style.cssText += ';' + css; +} +module.exports = exports['default']; +},{"../transition/isTransform":287,"../transition/properties":288,"../util/camelizeStyle":290,"../util/hyphenateStyle":292,"./getComputedStyle":284,"./removeStyle":286}],286:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = removeStyle; +function removeStyle(node, key) { + return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); +} +module.exports = exports['default']; +},{}],287:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isTransform; +var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i; + +function isTransform(property) { + return !!(property && supportedTransforms.test(property)); +} +module.exports = exports["default"]; +},{}],288:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.animationEnd = exports.animationDelay = exports.animationTiming = exports.animationDuration = exports.animationName = exports.transitionEnd = exports.transitionDuration = exports.transitionDelay = exports.transitionTiming = exports.transitionProperty = exports.transform = undefined; + +var _inDOM = require('../util/inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var transform = 'transform'; +var prefix = void 0, + transitionEnd = void 0, + animationEnd = void 0; +var transitionProperty = void 0, + transitionDuration = void 0, + transitionTiming = void 0, + transitionDelay = void 0; +var animationName = void 0, + animationDuration = void 0, + animationTiming = void 0, + animationDelay = void 0; + +if (_inDOM2.default) { + var _getTransitionPropert = getTransitionProperties(); + + prefix = _getTransitionPropert.prefix; + exports.transitionEnd = transitionEnd = _getTransitionPropert.transitionEnd; + exports.animationEnd = animationEnd = _getTransitionPropert.animationEnd; + + + exports.transform = transform = prefix + '-' + transform; + exports.transitionProperty = transitionProperty = prefix + '-transition-property'; + exports.transitionDuration = transitionDuration = prefix + '-transition-duration'; + exports.transitionDelay = transitionDelay = prefix + '-transition-delay'; + exports.transitionTiming = transitionTiming = prefix + '-transition-timing-function'; + + exports.animationName = animationName = prefix + '-animation-name'; + exports.animationDuration = animationDuration = prefix + '-animation-duration'; + exports.animationTiming = animationTiming = prefix + '-animation-delay'; + exports.animationDelay = animationDelay = prefix + '-animation-timing-function'; +} + +exports.transform = transform; +exports.transitionProperty = transitionProperty; +exports.transitionTiming = transitionTiming; +exports.transitionDelay = transitionDelay; +exports.transitionDuration = transitionDuration; +exports.transitionEnd = transitionEnd; +exports.animationName = animationName; +exports.animationDuration = animationDuration; +exports.animationTiming = animationTiming; +exports.animationDelay = animationDelay; +exports.animationEnd = animationEnd; +exports.default = { + transform: transform, + end: transitionEnd, + property: transitionProperty, + timing: transitionTiming, + delay: transitionDelay, + duration: transitionDuration +}; + + +function getTransitionProperties() { + var style = document.createElement('div').style; + + var vendorMap = { + O: function O(e) { + return 'o' + e.toLowerCase(); + }, + Moz: function Moz(e) { + return e.toLowerCase(); + }, + Webkit: function Webkit(e) { + return 'webkit' + e; + }, + ms: function ms(e) { + return 'MS' + e; + } + }; + + var vendors = Object.keys(vendorMap); + + var transitionEnd = void 0, + animationEnd = void 0; + var prefix = ''; + + for (var i = 0; i < vendors.length; i++) { + var vendor = vendors[i]; + + if (vendor + 'TransitionProperty' in style) { + prefix = '-' + vendor.toLowerCase(); + transitionEnd = vendorMap[vendor]('TransitionEnd'); + animationEnd = vendorMap[vendor]('AnimationEnd'); + break; + } + } + + if (!transitionEnd && 'transitionProperty' in style) transitionEnd = 'transitionend'; + + if (!animationEnd && 'animationName' in style) animationEnd = 'animationend'; + + style = null; + + return { animationEnd: animationEnd, transitionEnd: transitionEnd, prefix: prefix }; +} +},{"../util/inDOM":293}],289:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = camelize; +var rHyphen = /-(.)/g; + +function camelize(string) { + return string.replace(rHyphen, function (_, chr) { + return chr.toUpperCase(); + }); +} +module.exports = exports["default"]; +},{}],290:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = camelizeStyleName; + +var _camelize = require('./camelize'); + +var _camelize2 = _interopRequireDefault(_camelize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var msPattern = /^-ms-/; /** + * Copyright 2014-2015, Facebook, Inc. + * All rights reserved. + * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js + */ +function camelizeStyleName(string) { + return (0, _camelize2.default)(string.replace(msPattern, 'ms-')); +} +module.exports = exports['default']; +},{"./camelize":289}],291:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = hyphenate; + +var rUpper = /([A-Z])/g; + +function hyphenate(string) { + return string.replace(rUpper, '-$1').toLowerCase(); +} +module.exports = exports['default']; +},{}],292:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = hyphenateStyleName; + +var _hyphenate = require('./hyphenate'); + +var _hyphenate2 = _interopRequireDefault(_hyphenate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var msPattern = /^ms-/; /** + * Copyright 2013-2014, Facebook, Inc. + * All rights reserved. + * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js + */ + +function hyphenateStyleName(string) { + return (0, _hyphenate2.default)(string).replace(msPattern, '-ms-'); +} +module.exports = exports['default']; +},{"./hyphenate":291}],293:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = !!(typeof window !== 'undefined' && window.document && window.document.createElement); +module.exports = exports['default']; +},{}],294:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (recalc) { + if (!size || recalc) { + if (_inDOM2.default) { + var scrollDiv = document.createElement('div'); + + scrollDiv.style.position = 'absolute'; + scrollDiv.style.top = '-9999px'; + scrollDiv.style.width = '50px'; + scrollDiv.style.height = '50px'; + scrollDiv.style.overflow = 'scroll'; + + document.body.appendChild(scrollDiv); + size = scrollDiv.offsetWidth - scrollDiv.clientWidth; + document.body.removeChild(scrollDiv); + } + } + + return size; +}; + +var _inDOM = require('./inDOM'); + +var _inDOM2 = _interopRequireDefault(_inDOM); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var size = void 0; + +module.exports = exports['default']; +},{"./inDOM":293}],295:[function(require,module,exports){ +module.exports = require('./lib/dom-scroll-into-view'); + +},{"./lib/dom-scroll-into-view":296}],296:[function(require,module,exports){ +var util = require('./util'); + +function scrollIntoView(elem, container, config) { + config = config || {}; + // document 归一化到 window + if (container.nodeType === 9) { + container = util.getWindow(container); + } + + var allowHorizontalScroll = config.allowHorizontalScroll; + var onlyScrollIfNeeded = config.onlyScrollIfNeeded; + var alignWithTop = config.alignWithTop; + var alignWithLeft = config.alignWithLeft; + + allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll; + + var isWin = util.isWindow(container); + var elemOffset = util.offset(elem); + var eh = util.outerHeight(elem); + var ew = util.outerWidth(elem); + var containerOffset, ch, cw, containerScroll, + diffTop, diffBottom, win, + winScroll, ww, wh; + + if (isWin) { + win = container; + wh = util.height(win); + ww = util.width(win); + winScroll = { + left: util.scrollLeft(win), + top: util.scrollTop(win) + }; + // elem 相对 container 可视视窗的距离 + diffTop = { + left: elemOffset.left - winScroll.left, + top: elemOffset.top - winScroll.top + }; + diffBottom = { + left: elemOffset.left + ew - (winScroll.left + ww), + top: elemOffset.top + eh - (winScroll.top + wh) + }; + containerScroll = winScroll; + } else { + containerOffset = util.offset(container); + ch = container.clientHeight; + cw = container.clientWidth; + containerScroll = { + left: container.scrollLeft, + top: container.scrollTop + }; + // elem 相对 container 可视视窗的距离 + // 注意边框, offset 是边框到根节点 + diffTop = { + left: elemOffset.left - (containerOffset.left + + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)), + top: elemOffset.top - (containerOffset.top + + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) + }; + diffBottom = { + left: elemOffset.left + ew - + (containerOffset.left + cw + + (parseFloat(util.css(container, 'borderRightWidth')) || 0)), + top: elemOffset.top + eh - + (containerOffset.top + ch + + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + }; + } + + if (diffTop.top < 0 || diffBottom.top > 0) { + // 强制向上 + if (alignWithTop === true) { + util.scrollTop(container, containerScroll.top + diffTop.top); + } else if (alignWithTop === false) { + util.scrollTop(container, containerScroll.top + diffBottom.top); + } else { + // 自动调整 + if (diffTop.top < 0) { + util.scrollTop(container, containerScroll.top + diffTop.top); + } else { + util.scrollTop(container, containerScroll.top + diffBottom.top); + } + } + } else { + if (!onlyScrollIfNeeded) { + alignWithTop = alignWithTop === undefined ? true : !!alignWithTop; + if (alignWithTop) { + util.scrollTop(container, containerScroll.top + diffTop.top); + } else { + util.scrollTop(container, containerScroll.top + diffBottom.top); + } + } + } + + if (allowHorizontalScroll) { + if (diffTop.left < 0 || diffBottom.left > 0) { + // 强制向上 + if (alignWithLeft === true) { + util.scrollLeft(container, containerScroll.left + diffTop.left); + } else if (alignWithLeft === false) { + util.scrollLeft(container, containerScroll.left + diffBottom.left); + } else { + // 自动调整 + if (diffTop.left < 0) { + util.scrollLeft(container, containerScroll.left + diffTop.left); + } else { + util.scrollLeft(container, containerScroll.left + diffBottom.left); + } + } + } else { + if (!onlyScrollIfNeeded) { + alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft; + if (alignWithLeft) { + util.scrollLeft(container, containerScroll.left + diffTop.left); + } else { + util.scrollLeft(container, containerScroll.left + diffBottom.left); + } + } + } + } +} + +module.exports = scrollIntoView; + +},{"./util":297}],297:[function(require,module,exports){ +var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source; + +function getClientPosition(elem) { + var box, x, y; + var doc = elem.ownerDocument; + var body = doc.body; + var docElem = doc && doc.documentElement; + // 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式 + box = elem.getBoundingClientRect(); + + // 注:jQuery 还考虑减去 docElem.clientLeft/clientTop + // 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确 + // 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin + + x = box.left; + y = box.top; + + // In IE, most of the time, 2 extra pixels are added to the top and left + // due to the implicit 2-pixel inset border. In IE6/7 quirks mode and + // IE6 standards mode, this border can be overridden by setting the + // document element's border to zero -- thus, we cannot rely on the + // offset always being 2 pixels. + + // In quirks mode, the offset can be determined by querying the body's + // clientLeft/clientTop, but in standards mode, it is found by querying + // the document element's clientLeft/clientTop. Since we already called + // getClientBoundingRect we have already forced a reflow, so it is not + // too expensive just to query them all. + + // ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的 + // 窗口边框标准是设 documentElement ,quirks 时设置 body + // 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去 + // 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置 + // 标准 ie 下 docElem.clientTop 就是 border-top + // ie7 html 即窗口边框改变不了。永远为 2 + // 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0 + + x -= docElem.clientLeft || body.clientLeft || 0; + y -= docElem.clientTop || body.clientTop || 0; + + return {left: x, top: y}; +} + +function getScroll(w, top) { + var ret = w['page' + (top ? 'Y' : 'X') + 'Offset']; + var method = 'scroll' + (top ? 'Top' : 'Left'); + if (typeof ret !== 'number') { + var d = w.document; + //ie6,7,8 standard mode + ret = d.documentElement[method]; + if (typeof ret !== 'number') { + //quirks mode + ret = d.body[method]; + } + } + return ret; +} + +function getScrollLeft(w) { + return getScroll(w); +} + +function getScrollTop(w) { + return getScroll(w, true); +} + +function getOffset(el) { + var pos = getClientPosition(el); + var doc = el.ownerDocument; + var w = doc.defaultView || doc.parentWindow; + pos.left += getScrollLeft(w); + pos.top += getScrollTop(w); + return pos; +} +function _getComputedStyle(elem, name, computedStyle) { + var val = ''; + var d = elem.ownerDocument; + + // https://github.com/kissyteam/kissy/issues/61 + if ((computedStyle = (computedStyle || d.defaultView.getComputedStyle(elem, null)))) { + val = computedStyle.getPropertyValue(name) || computedStyle[name]; + } + + return val; +} + +var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i'); +var RE_POS = /^(top|right|bottom|left)$/, + CURRENT_STYLE = 'currentStyle', + RUNTIME_STYLE = 'runtimeStyle', + LEFT = 'left', + PX = 'px'; + +function _getComputedStyleIE(elem, name) { + // currentStyle maybe null + // http://msdn.microsoft.com/en-us/library/ms535231.aspx + var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name]; + + // 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值 + // 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19 + // 在 ie 下不对,需要直接用 offset 方式 + // borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了 + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // exclude left right for relativity + if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) { + // Remember the original values + var style = elem.style, + left = style[LEFT], + rsLeft = elem[RUNTIME_STYLE][LEFT]; + + // prevent flashing of content + elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT]; + + // Put in the new values to get a computed value out + style[LEFT] = name === 'fontSize' ? '1em' : (ret || 0); + ret = style.pixelLeft + PX; + + // Revert the changed values + style[LEFT] = left; + + elem[RUNTIME_STYLE][LEFT] = rsLeft; + } + return ret === '' ? 'auto' : ret; +} + +var getComputedStyleX; +if (typeof window !== 'undefined') { + getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE; +} + +// 设置 elem 相对 elem.ownerDocument 的坐标 +function setOffset(elem, offset) { + // set position first, in-case top/left are set even on static elem + if (css(elem, 'position') === 'static') { + elem.style.position = 'relative'; + } + + var old = getOffset(elem), + ret = {}, + current, key; + + for (key in offset) { + current = parseFloat(css(elem, key)) || 0; + ret[key] = current + offset[key] - old[key]; + } + css(elem, ret); +} + +function each(arr, fn) { + for (var i = 0; i < arr.length; i++) { + fn(arr[i]); + } +} + +function isBorderBoxFn(elem) { + return getComputedStyleX(elem, 'boxSizing') === 'border-box'; +} + +var BOX_MODELS = ['margin', 'border', 'padding'], + CONTENT_INDEX = -1, + PADDING_INDEX = 2, + BORDER_INDEX = 1, + MARGIN_INDEX = 0; + +function swap(elem, options, callback) { + var old = {}, + style = elem.style, + name; + + // Remember the old values, and insert the new ones + for (name in options) { + old[name] = style[name]; + style[name] = options[name]; + } + + callback.call(elem); + + // Revert the old values + for (name in options) { + style[name] = old[name]; + } +} + +function getPBMWidth(elem, props, which) { + var value = 0, prop, j, i; + for (j = 0; j < props.length; j++) { + prop = props[j]; + if (prop) { + for (i = 0; i < which.length; i++) { + var cssProp; + if (prop === 'border') { + cssProp = prop + which[i] + 'Width'; + } else { + cssProp = prop + which[i]; + } + value += parseFloat(getComputedStyleX(elem, cssProp)) || 0; + } + } + } + return value; +} + +/** + * A crude way of determining if an object is a window + * @member util + */ +function isWindow(obj) { + // must use == for ie8 + /*jshint eqeqeq:false*/ + return obj != null && obj == obj.window; +} + +var domUtils = {}; + +each(['Width', 'Height'], function (name) { + domUtils['doc' + name] = function (refWin) { + var d = refWin.document; + return Math.max( + //firefox chrome documentElement.scrollHeight< body.scrollHeight + //ie standard mode : documentElement.scrollHeight> body.scrollHeight + d.documentElement['scroll' + name], + //quirks : documentElement.scrollHeight 最大等于可视窗口多一点? + d.body['scroll' + name], + domUtils['viewport' + name](d)); + }; + + domUtils['viewport' + name] = function (win) { + // pc browser includes scrollbar in window.innerWidth + var prop = 'client' + name, + doc = win.document, + body = doc.body, + documentElement = doc.documentElement, + documentElementProp = documentElement[prop]; + // 标准模式取 documentElement + // backcompat 取 body + return doc.compatMode === 'CSS1Compat' && documentElementProp || + body && body[prop] || documentElementProp; + }; +}); + +/* + 得到元素的大小信息 + @param elem + @param name + @param {String} [extra] 'padding' : (css width) + padding + 'border' : (css width) + padding + border + 'margin' : (css width) + padding + border + margin + */ +function getWH(elem, name, extra) { + if (isWindow(elem)) { + return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem); + } else if (elem.nodeType === 9) { + return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem); + } + var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'], + borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight; + var computedStyle = getComputedStyleX(elem); + var isBorderBox = isBorderBoxFn(elem, computedStyle); + var cssBoxValue = 0; + if (borderBoxValue == null || borderBoxValue <= 0) { + borderBoxValue = undefined; + // Fall back to computed then un computed css if necessary + cssBoxValue = getComputedStyleX(elem, name); + if (cssBoxValue == null || (Number(cssBoxValue)) < 0) { + cssBoxValue = elem.style[name] || 0; + } + // Normalize '', auto, and prepare for extra + cssBoxValue = parseFloat(cssBoxValue) || 0; + } + if (extra === undefined) { + extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX; + } + var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox; + var val = borderBoxValue || cssBoxValue; + if (extra === CONTENT_INDEX) { + if (borderBoxValueOrIsBorderBox) { + return val - getPBMWidth(elem, ['border', 'padding'], + which, computedStyle); + } else { + return cssBoxValue; + } + } else if (borderBoxValueOrIsBorderBox) { + return val + (extra === BORDER_INDEX ? 0 : + (extra === PADDING_INDEX ? + -getPBMWidth(elem, ['border'], which, computedStyle) : + getPBMWidth(elem, ['margin'], which, computedStyle))); + } else { + return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), + which, computedStyle); + } +} + +var cssShow = {position: 'absolute', visibility: 'hidden', display: 'block'}; + +// fix #119 : https://github.com/kissyteam/kissy/issues/119 +function getWHIgnoreDisplay(elem) { + var val, args = arguments; + // in case elem is window + // elem.offsetWidth === undefined + if (elem.offsetWidth !== 0) { + val = getWH.apply(undefined, args); + } else { + swap(elem, cssShow, function () { + val = getWH.apply(undefined, args); + }); + } + return val; +} + +each(['width', 'height'], function (name) { + var first = name.charAt(0).toUpperCase() + name.slice(1); + domUtils['outer' + first] = function (el, includeMargin) { + return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX); + }; + var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom']; + + domUtils[name] = function (elem, val) { + if (val !== undefined) { + if (elem) { + var computedStyle = getComputedStyleX(elem); + var isBorderBox = isBorderBoxFn(elem); + if (isBorderBox) { + val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle); + } + return css(elem, name, val); + } + return; + } + return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX); + }; +}); + +function css(el, name, value) { + if (typeof name === 'object') { + for (var i in name) { + css(el, i, name[i]); + } + return; + } + if (typeof value !== 'undefined') { + if (typeof value === 'number') { + value = value + 'px'; + } + el.style[name] = value; + } else { + return getComputedStyleX(el, name); + } +} + +function mix(to, from) { + for (var i in from) { + to[i] = from[i]; + } + return to; +} + +var utils = module.exports = { + getWindow: function (node) { + var doc = node.ownerDocument || node; + return doc.defaultView || doc.parentWindow; + }, + offset: function (el, value) { + if (typeof value !== 'undefined') { + setOffset(el, value); + } else { + return getOffset(el); + } + }, + isWindow: isWindow, + each: each, + css: css, + clone: function (obj) { + var ret = {}; + for (var i in obj) { + ret[i] = obj[i]; + } + var overflow = obj.overflow; + if (overflow) { + for (i in obj) { + ret.overflow[i] = obj.overflow[i]; + } + } + return ret; + }, + mix: mix, + scrollLeft: function (w, v) { + if (isWindow(w)) { + if (v === undefined) { + return getScrollLeft(w); + } else { + window.scrollTo(v, getScrollTop(w)); + } + } else { + if (v === undefined) { + return w.scrollLeft; + } else { + w.scrollLeft = v; + } + } + }, + scrollTop: function (w, v) { + if (isWindow(w)) { + if (v === undefined) { + return getScrollTop(w); + } else { + window.scrollTo(getScrollLeft(w), v); + } + } else { + if (v === undefined) { + return w.scrollTop; + } else { + w.scrollTop = v; + } + } + }, + merge: function () { + var ret = {}; + for (var i = 0; i < arguments.length; i++) { + utils.mix(ret, arguments[i]); + } + return ret; + }, + viewportWidth: 0, + viewportHeight: 0 +}; + +mix(utils, domUtils); + +},{}],298:[function(require,module,exports){ +module.exports = function(opts) { + return new ElementClass(opts) +} + +function indexOf(arr, prop) { + if (arr.indexOf) return arr.indexOf(prop) + for (var i = 0, len = arr.length; i < len; i++) + if (arr[i] === prop) return i + return -1 +} + +function ElementClass(opts) { + if (!(this instanceof ElementClass)) return new ElementClass(opts) + var self = this + if (!opts) opts = {} + + // similar doing instanceof HTMLElement but works in IE8 + if (opts.nodeType) opts = {el: opts} + + this.opts = opts + this.el = opts.el || document.body + if (typeof this.el !== 'object') this.el = document.querySelector(this.el) +} + +ElementClass.prototype.add = function(className) { + var el = this.el + if (!el) return + if (el.className === "") return el.className = className + var classes = el.className.split(' ') + if (indexOf(classes, className) > -1) return classes + classes.push(className) + el.className = classes.join(' ') + return classes +} + +ElementClass.prototype.remove = function(className) { + var el = this.el + if (!el) return + if (el.className === "") return + var classes = el.className.split(' ') + var idx = indexOf(classes, className) + if (idx > -1) classes.splice(idx, 1) + el.className = classes.join(' ') + return classes +} + +ElementClass.prototype.has = function(className) { + var el = this.el + if (!el) return + var classes = el.className.split(' ') + return indexOf(classes, className) > -1 +} + +ElementClass.prototype.toggle = function(className) { + var el = this.el + if (!el) return + if (this.has(className)) this.remove(className) + else this.add(className) +} + +},{}],299:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],300:[function(require,module,exports){ +/*! + Copyright (c) 2015 Jed Watson. + Based on code that is Copyright 2013-2015, Facebook, Inc. + All rights reserved. +*/ + +(function () { + 'use strict'; + + var canUseDOM = !!( + typeof window !== 'undefined' && + window.document && + window.document.createElement + ); + + var ExecutionEnvironment = { + + canUseDOM: canUseDOM, + + canUseWorkers: typeof Worker !== 'undefined', + + canUseEventListeners: + canUseDOM && !!(window.addEventListener || window.attachEvent), + + canUseViewport: canUseDOM && !!window.screen + + }; + + if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { + define(function () { + return ExecutionEnvironment; + }); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = ExecutionEnvironment; + } else { + window.ExecutionEnvironment = ExecutionEnvironment; + } + +}()); + +},{}],301:[function(require,module,exports){ +'use strict'; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var emptyFunction = require('./emptyFunction'); + +/** + * 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 ("production" !== '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; +},{"./emptyFunction":308}],302:[function(require,module,exports){ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +'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; +},{}],303:[function(require,module,exports){ +"use strict"; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @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; +},{}],304:[function(require,module,exports){ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +'use strict'; + +var camelize = require('./camelize'); + +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; +},{"./camelize":303}],305:[function(require,module,exports){ +'use strict'; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + +var isTextNode = require('./isTextNode'); + +/*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; +},{"./isTextNode":318}],306:[function(require,module,exports){ +'use strict'; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +var invariant = require('./invariant'); + +/** + * 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')) ? "production" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; + + !(typeof length === 'number') ? "production" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; + + !(length === 0 || length - 1 in obj) ? "production" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; + + !(typeof obj.callee !== 'function') ? "production" !== '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; +},{"./invariant":316}],307:[function(require,module,exports){ +'use strict'; + +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @typechecks + */ + +/*eslint-disable fb-www/unsafe-html*/ + +var ExecutionEnvironment = require('./ExecutionEnvironment'); + +var createArrayFromMixed = require('./createArrayFromMixed'); +var getMarkupWrap = require('./getMarkupWrap'); +var invariant = require('./invariant'); + +/** + * 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 + *