language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class RaceCheckpoint {
constructor(type, position, nextPosition, size) {
this.type_ = type;
this.position_ = position;
this.nextPosition_ = nextPosition || new Vector(0, 0, 0);
this.size_ = size;
}
// Returns the type of the checkpoint.
get type() { return this.type_; }
// Returns the position of the checkpoint.
get position() { return this.position_; }
// Returns the position of the checkpoint that follows this one.
get nextPosition() { return this.nextPosition_; }
// Returns the size of the checkpoint, i.e. the diameter in game units.
get size() { return this.size_; }
// Displays the checkpoint for |player|. Returns a promise that will be resolved when the player
// enters the checkpoint, or rejected when the player disconnects from the server.
displayForPlayer(player) {
return server.raceCheckpointManager.displayForPlayer(player, this);
}
// Hides the checkpoint for |player|. The promise resolved by the displayForPlayer() method will
// be rejected, as the player has not entered the checkpoint.
hideForPlayer(player) {
server.raceCheckpointManager.hideForPlayer(player, this);
}
} |
JavaScript | @connect()
class DatasetLoader extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.dispatch(loadJSONs()); // choose via URL
this.props.dispatch({type: PAGE_CHANGE, displayComponent: "main"});
}
render() {
return null;
}
} |
JavaScript | class Trustline extends Component {
constructor(props) {
super(props);
this.deleteTrustline = this.deleteTrustline.bind(this);
this.copyToClipboard = this.copyToClipboard.bind(this);
}
deleteTrustline() {
this.props.deleteAction(this.props.trustline.issuer);
}
copyToClipboard() {
var el = document.createElement('textarea');
el.value = this.props.trustline.issuer;
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
M.toast({ html: 'Copied to clipboard' });
}
render() {
return (
<div className="trustline" id={ this.props.trustline.issuer }>
<div className="issuer">
<b>Account ID: </b><div onClick={ this.copyToClipboard } className="selectable" style={{ height: '16px' }}>{ this.props.trustline.issuer.slice(0, 17) }...
{ this.props.trustline.issuer.slice(this.props.trustline.issuer.length - 17, this.props.trustline.issuer.length) }</div>
<div className="button-box">
<a onClick={ this.deleteTrustline } style={{color: 'red'}}><i className="tiny material-icons">close</i></a>
</div>
</div>
<div className="balance">${ this.props.trustline.balance.slice(0, this.props.trustline.balance.length - 5) }</div>
</div>
);
}
} |
JavaScript | class AoflPicture extends AoflElement {
/**
* Creates an instance of AoflPicture.
*/
constructor() {
super();
this.img = null;
this.defaultSrc = null;
this.sources = [];
this.updateImageSrc = () => {
const matchedSource = AoflPicture.findMatchingSource(this.sources);
this.setMediaSrc(matchedSource);
};
}
/**
*
* @readonly
* @type {String}
*/
static get is() {
return 'aofl-picture';
}
/**
*
* @readonly
* @type {Object}
*/
static get properties() {
return {
'disable-sources': {type: Boolean}
};
}
/**
*
* @return {Object}
*/
render() {
return super.render((ctx, html) => html`<slot></slot>`, [style]);
}
/**
* setImg should be invoked by a slotted <aofl-img> and sets the aofl-img element as the main img element of aofl-picture.
*
* @param {HTMLElement} img
*/
setImg(img) {
/* istanbul ignore next */
if (this.img !== null) { return; }
this.img = img;
this.defaultSrc = {
src: this.img.src,
height: this.img.height,
width: this.img.width
};
this.updateImageSrc();
}
/**
* addSource should be invoked by a slotted <aofl-source> element and adds aofl-source elements as alternative
* sources for image besed on media attribute of aofl-source
*
* @param {String} source
*/
addSource(source) {
if (this['disable-sources']) return;
const mediaQuery = window.matchMedia(source.getAttribute('media'));
const sourceAttributes = {
src: source.getAttribute('srcset'),
height: source.getAttribute('height'),
width: source.getAttribute('width'),
mediaQuery
};
this.sources.push(sourceAttributes);
mediaQuery.addListener(this.updateImageSrc);
this.updateImageSrc();
}
/**
* Set's aofl-picture's image source to the matching aofl-source media query.
*
* @param {String} [source=this.defaultSrc]
*/
setMediaSrc(source = this.defaultSrc) {
if (!this.img) { return; }
const imgSrc = this.img.src;
if (imgSrc !== source.src) {
this.img.setAttribute('src', source.src);
/* istanbul ignore else */
if (source.width) {
this.img.setAttribute('width', source.width);
}
/* istanbul ignore else */
if (source.height) {
this.img.setAttribute('height', source.height);
}
}
}
/**
* Iterates through an array of sources and returns the first matching source.
*
* @param {Array} [sources=[]]
* @return {Object}
*/
static findMatchingSource(/* istanbul ignore next */sources = []) {
for (let i = 0; i < sources.length; i++) {
if (sources[i].mediaQuery.matches === true) {
return sources[i];
}
}
}
/**
*
*/
disconnectedCallback() {
for (let i = 0; i < this.sources.length; i++) {
this.sources[i].mediaQuery.removeListener(this.updateImageSrc);
}
super.disconnectedCallback();
}
} |
JavaScript | class FormCsrfHandler extends Plugin {
static options = {
formSelector: ''
};
init() {
if(!this.checkHandlerShouldBeActive()) {
return;
}
if (this.options.formSelector) {
this._form = DomAccess.querySelector(this.el, this.options.formSelector);
} else {
this._form = this.el;
}
// check if validation plugin is active for this form
this._validationPluginActive = !!window.PluginManager.getPluginInstanceFromElement(this._form, 'FormValidation');
this.client = new HttpClient(window.accessKey, window.contextToken);
this.registerEvents();
}
checkHandlerShouldBeActive() {
// Deactivate if form method is not post
return this.el.getAttribute('method').toUpperCase() === 'POST';
}
registerEvents() {
this.el.addEventListener('submit', this.onSubmit.bind(this));
}
onSubmit(event) {
// Abort when form.validation.plugin is active and form is not valid.
// The validation plugin handles the submit itself in this case
if(this._validationPluginActive) {
if (this.el.checkValidity() === false) {
return;
}
}
event.preventDefault();
this.$emitter.publish('beforeFetchCsrfToken');
this.client.fetchCsrfToken(this.onTokenFetched.bind(this));
}
onTokenFetched(token) {
this._form.appendChild(this.createCsrfInput(token));
this.$emitter.publish('beforeSubmit');
this.el.submit();
}
createCsrfInput(token) {
const elem = document.createElement('input');
elem.name = '_csrf_token';
elem.value = token;
elem.type = 'hidden';
return elem;
}
} |
JavaScript | class ProxyView extends AD3View {
constructor(context, selection, parent, options = {}) {
super(context, selection, parent);
this.options = {
/**
* proxy key - will be redirected through a local server proxy
*/
proxy: null,
/**
* direct loading of an iframe site
*/
site: null,
/**
* within the url {argument} will be replaced with the current selected id
*/
argument: 'gene',
/**
* idtype of the argument
*/
idtype: null,
extra: {},
openExternally: false
};
this.naturalSize = [1280, 800];
BaseUtils.mixin(this.options, context.desc, options);
this.$node.classed('proxy_view', true);
this.openExternally = parent.ownerDocument.createElement('p');
}
async init(params, onParameterChange) {
const initResult = await super.init(params, onParameterChange);
// inject stats
const base = params.querySelector('form') || params;
base.insertAdjacentHTML('beforeend', `<div class="col"></div>`);
base.lastElementChild.appendChild(this.openExternally);
return initResult;
}
initImpl() {
super.initImpl();
// update the selection first, then update the proxy view
return this.updateSelectedItemSelect()
.then(() => {
this.updateProxyView();
});
}
createUrl(args) {
//use internal proxy
if (this.options.proxy) {
return RestBaseUtils.getProxyUrl(this.options.proxy, args);
}
if (this.options.site) {
return this.options.site.replace(/{([^}]+)}/gi, (match, variable) => args[variable]);
}
return null;
}
getParameterFormDescs() {
return super.getParameterFormDescs().concat([{
type: FormElementType.SELECT,
label: 'Show',
id: ProxyView.FORM_ID_SELECTED_ITEM,
options: {
optionsData: [],
},
useSession: true
}]);
}
parameterChanged(name) {
super.parameterChanged(name);
this.updateProxyView();
}
selectionChanged() {
super.selectionChanged();
// update the selection first, then update the proxy view
this.updateSelectedItemSelect(true) // true = force use last selection
.then(() => {
this.updateProxyView();
});
}
updateSelectedItemSelect(forceUseLastSelection = false) {
return this.resolveSelection()
.then((names) => Promise.all([names, this.getSelectionSelectData(names)]))
.then((args) => {
const names = args[0]; // use names to get the last selected element
const data = args[1];
const selectedItemSelect = this.getParameterElement(ProxyView.FORM_ID_SELECTED_ITEM);
// backup entry and restore the selectedIndex by value afterwards again,
// because the position of the selected element might change
const bak = selectedItemSelect.value || data[selectedItemSelect.getSelectedIndex()];
selectedItemSelect.updateOptionElements(data);
// select last item from incoming `selection.range`
if (forceUseLastSelection) {
selectedItemSelect.value = data.filter((d) => d.value === names[names.length - 1])[0];
// otherwise try to restore the backup
}
else if (bak !== null) {
selectedItemSelect.value = bak;
}
// just show if there is more than one
selectedItemSelect.setVisible(data.length > 1);
});
}
getSelectionSelectData(names) {
if (names === null) {
return Promise.resolve([]);
}
// hook
return Promise.resolve(names.map((d) => ({ value: d, name: d, data: d })));
}
updateProxyView() {
this.loadProxyPage(this.getParameter(ProxyView.FORM_ID_SELECTED_ITEM).value);
}
loadProxyPage(selectedItemId) {
if (selectedItemId === null) {
this.showErrorMessage(selectedItemId);
return;
}
//remove old mapping error notice if any exists
this.openExternally.innerHTML = '';
this.$node.selectAll('p').remove();
this.$node.selectAll('iframe').remove();
this.setBusy(true);
const args = BaseUtils.mixin(this.options.extra, { [this.options.argument]: selectedItemId });
const url = this.createUrl(args);
if (ProxyView.isNoNSecurePage(url)) {
this.showNoHttpsMessage(url);
return;
}
if (this.options.openExternally) {
this.setBusy(false);
this.node.innerHTML = `<div class="alert alert-info mx-auto" role="alert">${I18nextManager.getInstance().i18n.t('tdp:core.views.proxyPageCannotBeShownHere')}
<a href="${url}" target="_blank" rel="noopener" class="alert-link">${url}</a>
</div>`;
return;
}
this.openExternally.innerHTML = `${I18nextManager.getInstance().i18n.t('tdp:core.views.isLoaded')} <a href="${url}" target="_blank" rel="noopener"><i class="fas fa-external-link-alt"></i>${url.startsWith('http') ? url : `${location.protocol}${url}`}</a>`;
//console.log('start loading', this.$node.select('iframe').node().getBoundingClientRect());
this.$node.append('iframe')
.attr('src', url)
.on('load', () => {
this.setBusy(false);
//console.log('finished loading', this.$node.select('iframe').node().getBoundingClientRect());
this.fire(ProxyView.EVENT_LOADING_FINISHED);
});
}
showErrorMessage(selectedItemId) {
this.setBusy(false);
const to = this.options.idtype ? IDTypeManager.getInstance().resolveIdType(this.options.idtype).name : I18nextManager.getInstance().i18n.t('tdp:core.views.unknown');
this.$node.html(`<p>${I18nextManager.getInstance().i18n.t('tdp:core.views.cannotMap', { name: this.selection.idtype.name, selectedItemId, to })}</p>`);
this.openExternally.innerHTML = ``;
this.fire(ProxyView.EVENT_LOADING_FINISHED);
}
static isNoNSecurePage(url) {
const self = location.protocol.toLowerCase();
if (!self.startsWith('https')) {
return false; // if I'm not secure doesn't matter
}
return url.startsWith('http://');
}
showNoHttpsMessage(url) {
this.setBusy(false);
this.$node.html(`
<div class="alert alert-info mx-auto" role="alert">${I18nextManager.getInstance().i18n.t('tdp:core.views.proxyPageCannotBeShownHere')}
<a href="${url}" target="_blank" rel="noopener" class="alert-link">${url}</a>
</div>`);
this.openExternally.innerHTML = ``;
this.fire(ProxyView.EVENT_LOADING_FINISHED);
}
static create(context, selection, parent, options = {}) {
return new ProxyView(context, selection, parent, options);
}
} |
JavaScript | class AvaPwarSimple extends AvaPwar {
static get is() { return 'ava-pwar-simple'; }
set manifest(val) {
super.manifest = val;
this.render();
}
render() {
const input = this._manifest;
const $ = this.$;
if (!input.icons)
return;
let oneNineTwoIcon = input.icons.find(icon => (icon.sizes.indexOf('192') > -1));
if (!oneNineTwoIcon)
oneNineTwoIcon = input.icons[input.icons.length - 1];
let imagePath = oneNineTwoIcon.src;
if (imagePath.startsWith('/'))
imagePath = imagePath.substring(1);
const imgURL = imagePath.startsWith('http') ? imagePath : input.url + imagePath;
const inverseColor = this.invertColor(input.background_color);
this.innerHTML = /* html */ `
<div class="simple" style="background-color:${input.background_color};color:${inverseColor}">
<div class="iconLabel">Icon:</div>
<div class="icon"><img height="192" width="192" src="${imgURL}"/></div>
<div class="nameLabel">Name:</div>
<div class="name">${$(input.name)}</div>
<div class="shortNameLabel">Short Name:</div>
<div class="shortName">${$(input.short_name)}</div>
<a class="url" target="_blank" href="${input.url}">${$(input.url)}</a>
</div>
`;
}
$(str) {
return str.replace(/(<([^>]+)>)/ig, '');
}
invertColor(hex) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
// invert color components
var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16), g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16), b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
// pad each with zeros and return
return '#' + this.padZero(r) + this.padZero(g) + this.padZero(b);
}
padZero(str, len) {
len = len || 2;
var zeros = new Array(len).join('0');
return (zeros + str).slice(-len);
}
} |
JavaScript | class Question
{
/**
* Constructor
* @param qStart the beginning offset of the quiz question
* @param qEnd the ending offset of the quiz question
*/
constructor( question, correctAnswer=-1, answers=[] )
{
this.question = question;
this.correctAnswer=correctAnswer;
this.answers = answers;
}
/**
* @return the beginning offset of the quiz question
*/
getQuestion()
{
return this.question;
}
/**
* @return the beginning offset of the quiz question
*/
setQuestion(question)
{
this.question = question;
}
/**
* @return A Vector containing the offsets for the answer choices to the quiz question. The first
* element is the correct answer.
*/
getAnswers()
{
return this.answers;
}
/**
* Adds the offset to an answer choice to the quiz question.
* @param answerOffset an offset to an answer choice to the quiz question
*/
addAnswer( answer )
{
this.answers.push( answer );
}
/**
* Adds the offset to an answer choice to the quiz question.
* @param answerOffset an offset to an answer choice to the quiz question
*/
setCorrect( correct )
{
this.correctAnswer = correct;
}
/**
* Adds the offset to an answer choice to the quiz question.
* @param answerOffset an offset to an answer choice to the quiz question
*/
getCorrect( )
{
return this.correctAnswer;
}
} |
JavaScript | class MiddlewareRegistry {
/**
* Creates a MiddlewareRegistry instance.
*/
constructor() {
/**
* The set of registered middleware.
*
* @private
* @type {Middleware[]}
*/
this._elements = [];
}
/**
* Applies all registered middleware into a store enhancer.
* (@link http://redux.js.org/docs/api/applyMiddleware.html).
*
* @param {Middleware[]} additional - Any additional middleware that need to
* be included (such as middleware from third-party modules).
* @returns {Middleware}
*/
applyMiddleware(...additional) {
return applyMiddleware(...this._elements, ...additional);
}
/**
* Adds a middleware to the registry.
*
* The method is to be invoked only before {@link #applyMiddleware()}.
*
* @param {Middleware} middleware - A Redux middleware.
* @returns {void}
*/
register(middleware) {
this._elements.push(middleware);
}
} |
JavaScript | class HtmlImage extends PureComponent {
static propTypes = {
...RNImage.propTypes,
lightbox: PropTypes.bool,
allowUpscale: PropTypes.bool,
};
static defaultProps = {
lightbox: true,
allowUpscale: false,
};
constructor(props) {
super(props);
autoBindReact(this);
this.state = {
width: null,
height: null,
};
RNImage.getSize(
props.source.uri,
this.imageSizeLoaded,
this.imageSizeLoadFailed,
);
}
imageSizeLoaded(width, height) {
this.setState({ width, height });
}
imageSizeLoadFailed() {
// TODO - handle properly
// eslint-disable-next-line no-console
console.warn(
'Could not load image size for image: ',
this.props.source.uri,
);
}
render() {
const { children, style, allowUpscale } = this.props;
const { width, height } = this.state;
if (!style) {
// eslint-disable-next-line no-console
console.warn(
'Invalid Html image style. Html image requires style.width.',
);
return null;
}
// Image can not be rendered without width and height.
if (!height || !width) {
return null;
}
// Do not enlarge image.
// If image is smaller then image style width,
// width that fits the screen best, use actual image width.
const imageWidth =
allowUpscale && style.width ? style.width : _.min([width, style.width]);
const imageHeight = style.height || (imageWidth / width) * height;
const { source, lightbox } = this.props;
if (_.isEmpty(children) && lightbox) {
// Showing image as part of the content, can be opened (zoomed).
// Not background image (if it has any children)
return (
<Lightbox
activeProps={{ styleName: 'preview wrapper' }}
styleName="wrapper"
>
<Image
{...this.props}
source={{ width: imageWidth, height: imageHeight, ...source }}
/>
</Lightbox>
);
}
// Showing image as background, can't be opened (zoomed).
return (
<ImageBackground
{...this.props}
source={{ width: imageWidth, height: imageHeight, ...source }}
>
{children}
</ImageBackground>
);
}
} |
JavaScript | class AngeError extends Error {
constructor(message) {
super(message);
}
} |
JavaScript | class ConnectorConfiguration {
/**
* @param {string} connectorConfigurationPath path to the json or yaml file defining the configuration
*/
constructor(connectorConfigurationPath) {
CaliperUtils.assertDefined(connectorConfigurationPath, '[ConnectorConfiguration.constructor] Parameter \'connectorConfigurationPath\' is undefined or null');
const configPath = CaliperUtils.resolvePath(connectorConfigurationPath);
this.adapterConfiguration = CaliperUtils.parseYaml(configPath);
}
/**
* return whether mutual TLS is required or not
* @returns {boolean} true if mutual TLS required, false otherwise
*/
isMutualTLS() {
return (this.adapterConfiguration.caliper.sutOptions &&
this.adapterConfiguration.caliper.sutOptions.mutualTls) ? true : false;
}
/**
* Returns a list of all the channels defined in the configuration
* @returns {string[]} A list of all channels in the configuration
*/
getAllChannelNames() {
const channelList = this.adapterConfiguration.channels;
if (channelList &&
Array.isArray(channelList)) {
return channelList.map(channelDefinition => channelDefinition.channelName);
}
return [];
}
/**
* Returns a list of all the channels which are marked for creation
* @returns {string[]} A list of all channels which are marked for creation
*/
getChannelNamesForCreation() {
const channelList = this.adapterConfiguration.channels;
if (channelList &&
Array.isArray(channelList)) {
return channelList.filter(channelDefinition => channelDefinition.create).map(channelDefinition => channelDefinition.channelName);
}
return [];
}
/**
*
* @param {string} channelName the name of the channel
* @returns {*} returns the channel definition or null if no channel definition for that name
*/
getDefinitionForChannelName(channelName) {
const channelList = this.adapterConfiguration.channels;
if (channelList &&
Array.isArray(channelList)) {
const filteredChannelDefinitionList = channelList.filter(channelDefinition => channelDefinition.channelName === channelName);
return filteredChannelDefinitionList.length > 0 ? filteredChannelDefinitionList[0].definition : null;
}
return null;
}
} |
JavaScript | class InlineAutoformatEditing {
/**
* Enables autoformatting mechanism for a given {@link module:core/editor/editor~Editor}.
*
* It formats the matched text by applying the given model attribute or by running the provided formatting callback.
* On every change applied to the model the autoformatting engine checks the text on the left of the selection
* and executes the provided action if the text matches given criteria (regular expression or callback).
*
* @param {module:core/editor/editor~Editor} editor The editor instance.
* @param {Function|RegExp} testRegexpOrCallback The regular expression or callback to execute on text.
* Provided regular expression *must* have three capture groups. The first and the third capture group
* should match opening and closing delimiters. The second capture group should match the text to format.
*
* // Matches the `**bold text**` pattern.
* // There are three capturing groups:
* // - The first to match the starting `**` delimiter.
* // - The second to match the text to format.
* // - The third to match the ending `**` delimiter.
* new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, 'bold' );
*
* When a function is provided instead of the regular expression, it will be executed with the text to match as a parameter.
* The function should return proper "ranges" to delete and format.
*
* {
* remove: [
* [ 0, 1 ], // Remove the first letter from the given text.
* [ 5, 6 ] // Remove the 6th letter from the given text.
* ],
* format: [
* [ 1, 5 ] // Format all letters from 2nd to 5th.
* ]
* }
*
* @param {Function|String} attributeOrCallback The name of attribute to apply on matching text or a callback for manual
* formatting. If callback is passed it should return `false` if changes should not be applied (e.g. if a command is disabled).
*
* // Use attribute name:
* new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, 'bold' );
*
* // Use formatting callback:
* new InlineAutoformatEditing( editor, /(\*\*)([^\*]+?)(\*\*)$/g, ( writer, rangesToFormat ) => {
* const command = editor.commands.get( 'bold' );
*
* if ( !command.isEnabled ) {
* return false;
* }
*
* const validRanges = editor.model.schema.getValidRanges( rangesToFormat, 'bold' );
*
* for ( let range of validRanges ) {
* writer.setAttribute( 'bold', true, range );
* }
* } );
*/
constructor(editor, testRegexpOrCallback, attributeOrCallback) {
let regExp;
let attributeKey;
let testCallback;
let formatCallback;
if (testRegexpOrCallback instanceof RegExp) {
regExp = testRegexpOrCallback;
} else {
testCallback = testRegexpOrCallback;
}
if (typeof attributeOrCallback == 'string') {
attributeKey = attributeOrCallback;
} else {
formatCallback = attributeOrCallback;
}
// A test callback run on changed text.
testCallback =
testCallback ||
(text => {
let result;
const remove = [];
const format = [];
while ((result = regExp.exec(text)) !== null) {
// There should be full match and 3 capture groups.
if (result && result.length < 4) {
break;
}
let { index, '1': leftDel, '2': content, '3': rightDel } = result;
// Real matched string - there might be some non-capturing groups so we need to recalculate starting index.
const found = leftDel + content + rightDel;
index += result[0].length - found.length;
// Start and End offsets of delimiters to remove.
const delStart = [index, index + leftDel.length];
const delEnd = [
index + leftDel.length + content.length,
index + leftDel.length + content.length + rightDel.length,
];
remove.push(delStart);
remove.push(delEnd);
format.push([index + leftDel.length, index + leftDel.length + content.length]);
}
return {
remove,
format,
};
});
// A format callback run on matched text.
formatCallback =
formatCallback ||
((writer, rangesToFormat) => {
const validRanges = editor.model.schema.getValidRanges(rangesToFormat, attributeKey);
for (const range of validRanges) {
writer.setAttribute(attributeKey, true, range);
}
// After applying attribute to the text, remove given attribute from the selection.
// This way user is able to type a text without attribute used by auto formatter.
writer.removeSelectionAttribute(attributeKey);
});
editor.model.document.on('change', (evt, batch) => {
if (batch.type == 'transparent') {
return;
}
const selection = editor.model.document.selection;
// Do nothing if selection is not collapsed.
if (!selection.isCollapsed) {
return;
}
const changes = Array.from(editor.model.document.differ.getChanges());
const entry = changes[0];
// Typing is represented by only a single change.
if (changes.length != 1 || entry.type !== 'insert' || entry.name != '$text' || entry.length != 1) {
return;
}
const block = selection.focus.parent;
const text = getText(block).slice(0, selection.focus.offset);
const testOutput = testCallback(text);
const rangesToFormat = testOutputToRanges(block, testOutput.format, editor.model);
const rangesToRemove = testOutputToRanges(block, testOutput.remove, editor.model);
if (!(rangesToFormat.length && rangesToRemove.length)) {
return;
}
// Use enqueueChange to create new batch to separate typing batch from the auto-format changes.
editor.model.enqueueChange(writer => {
// Apply format.
const hasChanged = formatCallback(writer, rangesToFormat);
// Strict check on `false` to have backward compatibility (when callbacks were returning `undefined`).
if (hasChanged === false) {
return;
}
// Remove delimiters - use reversed order to not mix the offsets while removing.
for (const range of rangesToRemove.reverse()) {
writer.remove(range);
}
});
});
}
} |
JavaScript | class TableResizer {
constructor(tableId, options = {}) {
this.tableSelector = tableId;
this.tableEl = document.querySelector(tableId);
this.sticky = options.sticky;
this.observeTableChange = options.observeTableChange;
this.dontSaveStorage = options.dontSaveStorage;
this.drag = {};
this.init();
}
init() {
if (!this.tableEl) return;
const prepared = this.prepareTable();
if (!prepared) return;
this.loadSavedColumns();
if (this.sticky) {
this.calculateStickyColumns();
}
}
prepareTable() {
this.tableEl.classList.add("table-resizer");
const heads = this.tableEl.querySelectorAll("th[data-resizable-column-id]");
if (heads.length === 0) return false;
heads.forEach(thead => {
const handle = this.createHandle();
thead.style.boxSizing = "border-box";
thead.style.minWidth = "0";
/*
affix is cloned header for "sticky" purposes, if there is no sticky cloned column, then add handle to normal
head otherwise we need to put it in "sticky" cloned affix element
*/
const theadAffix = thead.querySelector(".affix-cell-wrap");
if (theadAffix) {
theadAffix.appendChild(handle);
} else {
thead.appendChild(handle);
}
// set listener for every handle
handle.addEventListener("mousedown", this.dragStart.bind(this));
});
this.setTableListeners();
return true;
}
loadSavedColumns() {
if (this.dontSaveStorage) return;
const storage = JSON.parse(window.localStorage.getItem("table_resizer"));
if (!storage) return;
for (let tableKeyId in storage) {
if (!storage.hasOwnProperty(tableKeyId)) continue;
if (tableKeyId !== this.tableSelector) continue;
const table = storage[tableKeyId];
for (let columnId in table) {
if (!table.hasOwnProperty(columnId)) continue;
const columnWidth = table[columnId];
const selector = document.querySelector(
`${this.tableSelector} th[data-resizable-column-id=${columnId}]`
);
if (selector) {
selector.style.width = columnWidth + "px";
}
}
}
}
saveColumns() {
if (this.dontSaveStorage) return;
let nxtColWidth, nxtColDataId;
const curColDataId = this.drag.curCol.dataset.resizableColumnId;
const curColWidth = this.drag.curCol.offsetWidth;
if (this.drag.nxtCol) {
nxtColDataId = this.drag.nxtCol.dataset.resizableColumnId;
nxtColWidth = this.drag.nxtCol.offsetWidth;
}
let storage = JSON.parse(window.localStorage.getItem("table_resizer"));
let tablesJson = {};
let newCols = {};
if (nxtColDataId) {
newCols[curColDataId] = curColWidth;
newCols[nxtColDataId] = nxtColWidth;
} else {
newCols[curColDataId] = curColWidth;
}
tablesJson[this.tableSelector] = newCols;
if (!storage) {
window.localStorage.setItem("table_resizer", JSON.stringify(tablesJson));
return;
}
const isTableInStorage = window.EASY.utils.isStorageItem(
"table_resizer",
this.tableSelector
);
if (!isTableInStorage) {
storage[this.tableSelector] = {};
}
storage[this.tableSelector][curColDataId] = curColWidth;
if (nxtColDataId) {
storage[this.tableSelector][nxtColDataId] = nxtColWidth;
}
window.localStorage.setItem("table_resizer", JSON.stringify(storage));
}
calculateStickyColumns() {
// calculating sticky positions
const tableRows = this.tableEl.querySelectorAll("tr");
tableRows.forEach(row => {
let sumLeft = 0;
const stickyColumns = row.querySelectorAll(
"th[data-resizable-sticky], td[data-resizable-sticky]"
);
if (!stickyColumns) return;
stickyColumns.forEach((column, index) => {
column.style.position = "sticky";
if (index === 0) {
column.style.left = "0";
return;
}
const prevColWidth = stickyColumns[index - 1].offsetWidth;
sumLeft += prevColWidth;
column.style.left = sumLeft + "px";
});
});
}
setTableListeners() {
this.tableEl.addEventListener("mousemove", this.dragMove.bind(this));
document.addEventListener("mouseup", this.dragEnd.bind(this));
// Set mutation observer for tables that dynamically add some content
// i.e. recalculate all sticky positions after adding rows or columns to table
if (this.observeTableChange) {
const config = {
attributes: false,
childList: true,
subtree: true
};
const observer = new MutationObserver(this.recalculateTable.bind(this));
observer.observe(this.tableEl, config);
}
}
dragStart(e) {
// disable selecting text when dragging
this.tableEl.style.userSelect = "none";
this.drag.pageX = e.pageX;
this.drag.curCol = e.target.closest("th");
this.drag.nxtCol = this.drag.curCol.nextElementSibling;
this.drag.curColResizable = this.drag.curCol.dataset.resizableColumnId;
this.drag.curColWidth = this.drag.curCol.offsetWidth;
this.drag.prevStateCurColWidth = this.drag.curColWidth;
if (this.drag.nxtCol) {
this.drag.nxtColResizable = this.drag.nxtCol.dataset.resizableColumnId;
this.drag.nxtColWidth = this.drag.nxtCol.offsetWidth;
}
}
dragMove(e) {
if (this.drag.curCol) {
let diffX = e.pageX - this.drag.pageX;
if (this.drag.nxtCol) {
this.drag.curCol.style.width = this.drag.curColWidth + diffX + "px";
// test if column is not resizing and if so, dont allow it to change other columns
if (this.drag.prevStateCurColWidth === this.drag.curColWidth) {
diffX = 0;
} else {
this.drag.prevStateCurColWidth = this.drag.curColWidth;
}
if (this.drag.nxtColResizable) {
this.drag.nxtCol.style.width = this.drag.nxtColWidth - diffX + "px";
}
}
if (this.sticky) {
this.calculateStickyColumns();
}
}
}
dragEnd() {
// enable text selecting on dragEnd
this.tableEl.style.userSelect = "auto";
if (this.drag.curCol && this.drag.curColResizable) {
this.saveColumns();
this.clearDrag();
}
}
clearDrag() {
// set all drag attributes to null
Object.keys(this.drag).forEach(key => (this.drag[key] = null));
}
recalculateTable() {
if (this.sticky) this.calculateStickyColumns();
}
createHandle() {
const handle = document.createElement("div");
handle.classList.add("column__handle");
handle.style.right = "-5px";
handle.style.top = "0";
handle.style.position = "absolute";
handle.style.height = "100%";
handle.style.width = "10px";
handle.style.display = "block";
handle.style.zIndex = "10000000";
return handle;
}
} |
JavaScript | class LocalStorage {
/**
* Whether support Local Storage
*
* @return {boolean} Whether support ls
*/
_isCachePage () {
return fn.isCacheUrl(href)
}
/**
* Whether support Local Storage
*
* @return {boolean} Whether support ls
*/
_supportLs () {
let support = false
try {
window.localStorage.setItem('lsExisted', '1')
window.localStorage.removeItem('lsExisted')
support = true
} catch (e) {
support = false
}
return support
}
/**
* Get local storage
*
* @return {Object} value of local storage
*/
_getLocalStorage () {
let ls = this._supportLs() ? localStorage.getItem(HOST) : lsCache[HOST]
ls = ls ? parseJson(ls) : {}
updateTime(ls)
return ls
}
/**
* Delete local storage
*
* @param {string} key the key of local storage
*/
_rmLocalStorage (key) {
if (!key) {
key = HOST
}
this._supportLs() ? localStorage.removeItem(key) : fn.del(lsCache, key)
}
/**
* Set current site data in local storage
*
* @param {string} name name of storage
* @param {string} value value of storage
* @param {string} expire optional
* @param {string} callback if error callback to publisher
*/
set (name, value, expire, callback) {
if (!name || !value) {
return
}
callback = typeof expire === 'function' ? expire : callback
if (this._isCachePage()) {
let ls = this._getLocalStorage()
ls[name] = value
expire = parseInt(expire, 10)
if (!isNaN(expire) && expire > 0) {
ls.e = new Date().getTime() + expire
} else {
fn.del(ls, 'e')
}
ls = JSON.stringify(ls)
if (ls.length > STORAGESIZE) {
callback && callback(getError(eCode.siteExceed, getErrorMess(eCode.siteExceed)))
throw getErrorMess(eCode.siteExceed)
}
this._setLocalStorage(HOST, ls, expire, callback)
} else {
this._setLocalStorage(name, value, expire, callback)
}
}
/**
* Set local storage
*
* @param {string} key the key of local storage
* @param {string} value the key of local storage
* @param {string} expire the expire of local storage
* @param {string} callback if error callback to publisher
*/
_setLocalStorage (key, value, expire, callback) {
let mess = getErrorMess(eCode.lsExceed, key)
callback = typeof expire === 'function' ? expire : callback
if (this._supportLs()) {
try {
localStorage.setItem(key, value)
} catch (e) {
if (this._isExceed(e) && this._isCachePage()) {
this._exceedHandler(key, value, expire)
} else if (this._isExceed(e) && !this._isCachePage()) {
callback && callback(getError(eCode.lsExceed, mess))
throw mess
}
}
} else {
let size = value.length / 1024.0 / 1024.0
for (let k in lsCache) {
if (lsCache[k]) {
size += lsCache[k].length / 1024.0 / 1024.0
}
}
if (size > 5.0) {
callback && callback(eCode.lsExceed, mess)
throw mess
}
lsCache[key] = value
}
}
/**
* Get current site data in local storage
*
* @param {string} name name of storage
* @return {string} get data with key
*/
get (name) {
if (!fn.isString(name)) {
return
}
let result
if (this._isCachePage()) {
let ls = this._getLocalStorage()
if (ls && ls[name]) {
result = ls[name]
}
} else {
result = this._supportLs() ? localStorage.getItem(name) : lsCache[name]
}
return result
}
/**
* Delete current site data in local storage with key
*
* @param {string} name name of storage
*/
rm (name) {
if (!fn.isString(name)) {
return
}
if (this._isCachePage()) {
let ls = this._getLocalStorage()
if (ls && ls[name]) {
fn.del(ls, name)
this._setLocalStorage(HOST, JSON.stringify(ls))
}
} else {
this._supportLs() ? localStorage.removeItem(name) : fn.del(lsCache, name)
}
}
/**
* Clear current site local storage
*
*/
clear () {
if (this._isCachePage()) {
this._rmLocalStorage()
} else {
this._supportLs() ? localStorage.clear() : lsCache = {}
}
}
/**
* Delete all expire storage, scope is all sites
*
* @return {boolean} whether storage has expired
*/
rmExpires () {
let hasExpires = false
if (this._isCachePage()) {
let ls = this._supportLs() ? localStorage : lsCache
for (let k in ls) {
if (ls[k]) {
let val
if (typeof ls[k] === 'string') {
val = parseJson(ls[k])
}
if (val && val.e) {
let expire = parseInt(parseJson(ls[k]).e, 10)
if (expire && new Date().getTime() >= expire) {
hasExpires = true
this._rmLocalStorage(k)
}
}
}
}
}
return hasExpires
}
/**
* Whether local storage is exceed, http://crocodillon.com/blog/always-catch-localstorage-security-and-quota-exceeded-errors
*
* @param {Object} e set local storage error
* @return {boolean} whether storage exceed
*/
_isExceed (e) {
let quotaExceeded = false
if (e && e.code) {
switch (e.code) {
case 22: {
quotaExceeded = true
break
}
case 1014: { // Firefox
quotaExceeded = e.name === 'NS_ERROR_DOM_QUOTA_REACHED'
break
}
}
} else if (e && e.number === -2147024882) { // Internet Explorer 8
quotaExceeded = true
}
return quotaExceeded
}
/**
* Handle when storage exceed
*
* @param {string} name the key of local storage
* @param {string} value the key of local storage
* @param {string} expire the expire of local storage
*/
_exceedHandler (name, value, expire) {
let minTimeStamp
let key
if (!this.rmExpires()) {
let ls = localStorage
for (let k in ls) {
if (ls[k]) {
let item = parseJson(ls[k]).u
if (!key || parseInt(item, 10) < minTimeStamp) {
key = k
minTimeStamp = parseInt(item, 10)
}
}
}
this._rmLocalStorage(key)
}
this.set(name, value, expire)
}
} |
JavaScript | class AsyncStorage {
/**
* Send request to server with params
*
* @param {Object} opt request params
*/
request (opt) {
if (!opt || !opt.url) {
return
}
let myInit = {}
myInit.mode = opt.mode ? opt.mode : null
myInit.method = opt.method ? opt.method : 'GET'
myInit.credentials = opt.credentials ? opt.credentials : 'omit'
myInit.cache = opt.cache ? opt.cache : 'default'
if (opt.headers) {
myInit.headers = opt.headers
}
if (opt.body) {
myInit.body = opt.body
}
fetch(opt.url, myInit)
.then(res => {
if (res.ok) {
res.text().then(data => opt.success && opt.success(parseJson(data)))
} else {
opt.error && opt.error(res)
}
})
.catch(err => opt.error && opt.error(err))
}
} |
JavaScript | class CookieStorage {
/**
* Delete exceed cookie storage
*
* @param {Object} opt request params
*/
delExceedCookie () {
// don't execute in origin page
if (this._notIframed()) {
return
}
let domain = window.location.hostname
let cks = document.cookie
let MINSIZE = 3 * 1024
let MAXSIZE = 5 * 1024
if (document.cookie.length < MAXSIZE) {
return
}
let items = cks.split(';')
for (let i = 0; i < items.length; i++) {
let item = items[i].split('=')
if (item && item.length > 1) {
let expires = new Date()
let key = item[0].trim()
let value = item[1].trim()
expires.setMilliseconds(expires.getMilliseconds() - 1 * 864e+5)
this._set({
key,
value,
expires,
domain
})
if (this._get(key)) {
this._set({
key,
value,
expires,
domain: domain.split('.').slice(-2).join('.')
})
}
}
if (document.cookie.length <= MINSIZE) {
break
}
}
}
/**
* Whether iframed or not
*
* @return {string} Whether iframed
*/
_notIframed () {
return window === top
}
/**
* Get cookie
*
* @param {string} name cookie name
* @return {string} cookie value
*/
_get (name) {
name = name.trim()
let cks = document.cookie
let cookies = cks ? cks.split(';') : []
for (let i = 0, len = cookies.length; i < len; i++) {
let cookie = cookies[i]
let items = cookie.split('=')
if (items[0].trim() === name) {
return items[1]
}
}
}
/**
* Set cookie
*
* @param {Object} options cookie option
*/
_set (options) {
document.cookie = [
options.key,
'=',
'; expires=' + options.expires.toGMTString(),
'; path=/',
'; domain=' + options.domain
].join('')
}
} |
JavaScript | class DaggerInputPin extends DaggerBasePin {
/**
* DaggerInputPin ctor
*/
constructor() {
super();
this._connectedTo = null;
}
/**
* Get the pin's direction
* @returns {DaggerBasePin.PinDirection.Input}
*/
get direction() {
return DaggerBasePin.PinDirection.Input;
}
/**
* Get the DaggerOutputPin this pin is connected to
* @returns {DaggerOutputPin}
*/
get connectedTo() {
return this._connectedTo;
}
/**
* Get the instance ID of the DaggerOutputPin this pin is connected to.
* @returns {string}
*/
get connectedToUUID() {
if(this.isConnected) {
return this._connectedTo.instanceUUID;
}
// the 'null' uuid
return "00000000-0000-0000-0000-000000000000";
}
/**
* Get if this pin is connected
* @returns {boolean}
*/
get isConnected() {
return (this._connectedTo !== null) ? true : false;
}
/**
* Returns true if this pin can connect to the given DaggerOutputPin
* @param {DaggerOutputPin} pin
*/
canConnectToPin(pin) {
let tsystem = this.topologySystem;
if(tsystem != pin.topologySystem) {
// pins must belong to the same topology system
this.emitError("pins must belong to the same topology system");
return false;
}
if(!this.parentNode) {
// this is an exported or non-node pin, so it can connect to any DaggerOutputPin
return super.canConnectToPin(pin);
}
if(this.parentNode == pin.parentNode) {
// big NO-NO!
this.emitError("pins belong to the same parent node");
return false;
}
let retv = false;
if(this._parentNode.parentGraph.enableTopology) {
if(!this.parentNode.descendents(tsystem).includes(pin.parentNode)) {
retv = super.canConnectToPin(pin);
} else if(pin.parentNode.ordinal(tsystem) <= this.parentNode.ordinal(tsystem)) {
retv = super.canConnectToPin(pin);
}
} else {
retv = true;
}
return retv;
}
/**
* Disconnects this pin.
* @param {boolean} forceDisconnect - when true, the pin will disconnect regardless if the topology says it shouldn't
*/
disconnectPin(forceDisconnect = false) {
if (this._parentNode === null)
return false;
// is it even connected?
if (this.isConnected) {
// call the OutputPin's Disconnect method
return this.connectedTo.disconnectPin(this, forceDisconnect);
}
// since we were never connected to this pin, they are technically disconnected
return true;
}
/**
* Clean up when object hierarchy is unraveled. Subclasses should always super.
*/
purgeAll() {
super.purgeAll();
this._connectedTo = null;
}
} |
JavaScript | class Session {
constructor() {
this.key = 'session';
}
/**
* @description select cookie by name
* @param {BOLEAN} name
*/
isValid(key=null) {
key = key || this.key;
const session = db.get(key);
return session && session.access_token ? true : false;
}
/**
* @description get session
* @param {OBJECT}
*/
get(key=null) {
key = key || this.key;
return db.get(key);
}
/**
* @description clean session
*/
del(key=null) {
key = key || this.key;
db.del(key);
return this;
}
/**
* @description update session
*/
set(payload, key=null) {
key = key || this.key;
db.set(payload, this.key);
}
} |
JavaScript | class KW18 {
constructor(data = [], types = [], meta = {}) {
this.data = data;
this.types = types;
this.meta = meta;
this.postProcess();
}
postProcess() {
const typeMap = {};
this.types.forEach((t) => {
typeMap[t[TYPE_TRACK_i]] = {
id: t[TYPE_TRACK_i],
type: t[TYPE_TYPE_i],
};
});
this.types = typeMap;
const trackMap = {};
this.data.forEach((d) => {
const trackId = d[TRACK_ID_i];
const detection = {
frame: parseInt(d[FRAME_i], 10),
box: d.slice(BBOX_i0, BBOX_i0 + 4).map(c => parseInt(c, 10)),
meta: {},
};
if (!(trackId in trackMap)) {
trackMap[trackId] = {
begin: parseInt(d[FRAME_i], 10),
end: parseInt(d[FRAME_i], 10) + parseInt(d[TRACK_LENGTH_i], 10) - 1,
key: trackId,
meta: {
type: this.types[trackId],
},
detections: [],
};
}
trackMap[trackId].detections.push(detection);
});
this.tracks_ = trackMap;
}
/**
* return a list of the tracks
* @returns {Array.<track>}
*/
get tracks() {
return Object.keys(this.tracks_)
.map(key => this.tracks_[key]);
}
/**
* Create KPF object from YAML text strings.
* @param {String} activityText
* @param {String} geometryText
*/
static fromText(dataText, typeText) {
const dataLines = dataText.split('\n');
const data = dataLines
.map(line => line.replace('\r', ''))
.map(line => line.split(' '))
.filter(line => line[0].indexOf('#') !== 0)
.filter(line => line.length > 1);
const typeLines = typeText.split('\n');
const types = typeLines
.map(line => line.replace('\r', ''))
.map(line => line.split(' '))
.filter(line => line.length > 1);
return new KW18(data, types);
}
} |
JavaScript | class LoggerFactory {
constructor(config) {
this.config = config;
}
build(){
var self = this;
var logLevelsConfig = {
levels: {
silly: 6,
verbose: 5,
info: 4,
data: 3,
warn: 2,
debug: 1,
error: 0
},
colors: {
silly: 'magenta',
verbose: 'cyan',
info: 'green',
data: 'grey',
warn: 'yellow',
debug: 'blue',
error: 'red'
}
};
winston.setLevels(logLevelsConfig.levels);
winston.addColors(logLevelsConfig.colors);
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {colorize: true, timestamp: true, level: 'silly'});
winston.add(winston.transports.File, { filename: 'log/debug.log', json: false, level:'info' });
/*
if (self.config && self.config.get("mongo-log-connection-string")) {
winston.add(winston.transports.MongoDB, {collection: "log", db: self.config.get("mongo-log-connection-string"), level:'info'});
}
*/
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ level: 'silly' }),
new (winston.transports.File)({
filename: 'log/debug.log',
level: 'info'
})
]
});
return logger;
}
} |
JavaScript | class SwapService extends BaseService {
static Events = {
CREATED: "swap.created",
RECEIVED: "swap.received",
SHIPMENT_CREATED: "swap.shipment_created",
PAYMENT_COMPLETED: "swap.payment_completed",
PAYMENT_CAPTURED: "swap.payment_captured",
PAYMENT_CAPTURE_FAILED: "swap.payment_capture_failed",
PROCESS_REFUND_FAILED: "swap.process_refund_failed",
REFUND_PROCESSED: "swap.refund_processed",
FULFILLMENT_CREATED: "swap.fulfillment_created",
}
constructor({
manager,
swapRepository,
eventBusService,
cartService,
totalsService,
returnService,
lineItemService,
paymentProviderService,
shippingOptionService,
fulfillmentService,
orderService,
inventoryService,
}) {
super()
/** @private @const {EntityManager} */
this.manager_ = manager
/** @private @const {SwapModel} */
this.swapRepository_ = swapRepository
/** @private @const {TotalsService} */
this.totalsService_ = totalsService
/** @private @const {LineItemService} */
this.lineItemService_ = lineItemService
/** @private @const {ReturnService} */
this.returnService_ = returnService
/** @private @const {PaymentProviderService} */
this.paymentProviderService_ = paymentProviderService
/** @private @const {CartService} */
this.cartService_ = cartService
/** @private @const {FulfillmentService} */
this.fulfillmentService_ = fulfillmentService
/** @private @const {OrderService} */
this.orderService_ = orderService
/** @private @const {ShippingOptionService} */
this.shippingOptionService_ = shippingOptionService
/** @private @const {InventoryService} */
this.inventoryService_ = inventoryService
/** @private @const {EventBusService} */
this.eventBus_ = eventBusService
}
withTransaction(transactionManager) {
if (!transactionManager) {
return this
}
const cloned = new SwapService({
manager: transactionManager,
swapRepository: this.swapRepository_,
eventBusService: this.eventBus_,
cartService: this.cartService_,
totalsService: this.totalsService_,
returnService: this.returnService_,
lineItemService: this.lineItemService_,
paymentProviderService: this.paymentProviderService_,
shippingOptionService: this.shippingOptionService_,
orderService: this.orderService_,
inventoryService: this.inventoryService_,
fulfillmentService: this.fulfillmentService_,
})
cloned.transactionManager_ = transactionManager
return cloned
}
transformQueryForTotals_(config) {
let { select, relations } = config
if (!select) {
return {
...config,
totalsToSelect: [],
}
}
const totalFields = [
"cart.subtotal",
"cart.tax_total",
"cart.shipping_total",
"cart.discount_total",
"cart.gift_card_total",
"cart.total",
]
const totalsToSelect = select.filter(v => totalFields.includes(v))
if (totalsToSelect.length > 0) {
const relationSet = new Set(relations)
relationSet.add("cart")
relationSet.add("cart.items")
relationSet.add("cart.gift_cards")
relationSet.add("cart.discounts")
relationSet.add("cart.shipping_methods")
relationSet.add("cart.region")
relations = [...relationSet]
select = select.filter(v => !totalFields.includes(v))
}
return {
...config,
relations,
select,
totalsToSelect,
}
}
async decorateTotals_(cart, totalsFields = []) {
if (totalsFields.includes("cart.shipping_total")) {
cart.shipping_total = await this.totalsService_.getShippingTotal(cart)
}
if (totalsFields.includes("cart.discount_total")) {
cart.discount_total = await this.totalsService_.getDiscountTotal(cart)
}
if (totalsFields.includes("cart.tax_total")) {
cart.tax_total = await this.totalsService_.getTaxTotal(cart)
}
if (totalsFields.includes("cart.gift_card_total")) {
cart.gift_card_total = await this.totalsService_.getGiftCardTotal(cart)
}
if (totalsFields.includes("cart.subtotal")) {
cart.subtotal = await this.totalsService_.getSubtotal(cart)
}
if (totalsFields.includes("cart.total")) {
cart.total = await this.totalsService_.getTotal(cart)
}
return cart
}
/**
* Retrieves a swap with the given id.
* @param {string} id - the id of the swap to retrieve
* @return {Promise<Swap>} the swap
*/
async retrieve(id, config = {}) {
const swapRepo = this.manager_.getCustomRepository(this.swapRepository_)
const validatedId = this.validateId_(id)
const { totalsToSelect, ...newConfig } = this.transformQueryForTotals_(
config
)
const query = this.buildQuery_({ id: validatedId }, newConfig)
const rels = query.relations
delete query.relations
const swap = await swapRepo.findOneWithRelations(rels, query)
if (!swap) {
throw new MedusaError(MedusaError.Types.NOT_FOUND, "Swap was not found")
}
if (rels && rels.includes("cart")) {
const cart = await this.decorateTotals_(swap.cart, totalsToSelect)
swap.cart = cart
}
return swap
}
/**
* Retrieves a swap based on its associated cart id
* @param {string} cartId - the cart id that the swap's cart has
* @return {Promise<Swap>} the swap
*/
async retrieveByCartId(cartId, relations = []) {
const swapRepo = this.manager_.getCustomRepository(this.swapRepository_)
const swap = await swapRepo.findOne({
where: {
cart_id: cartId,
},
relations,
})
if (!swap) {
throw new MedusaError(MedusaError.Types.NOT_FOUND, "Swap was not found")
}
return swap
}
/**
* @param {Object} selector - the query object for find
* @return {Promise} the result of the find operation
*/
list(
selector,
config = { skip: 0, take: 50, order: { created_at: "DESC" } }
) {
const swapRepo = this.manager_.getCustomRepository(this.swapRepository_)
const query = this.buildQuery_(selector, config)
let rels = query.relations
delete query.relations
return swapRepo.findWithRelations(rels, query)
}
/**
* @typedef OrderLike
* @property {Array<LineItem>} items - the items on the order
*/
/**
* @typedef ReturnItem
* @property {string} item_id - the id of the item in the order to return from.
* @property {number} quantity - the amount of the item to return.
*/
/**
* Goes through a list of return items to ensure that they exist on the
* original order. If the item exists it is verified that the quantity to
* return is not higher than the original quantity ordered.
* @param {OrderLike} order - the order to return from
* @param {Array<ReturnItem>} returnItems - the items to return
* @return {Array<ReturnItems>} the validated returnItems
*/
validateReturnItems_(order, returnItems) {
return returnItems.map(({ item_id, quantity }) => {
const item = order.items.find(i => i.id === item_id)
// The item must exist in the order
if (!item) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Item does not exist on order"
)
}
// Item's cannot be returned multiple times
if (item.quantity < item.returned_quantity + quantity) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Cannot return more items than have been ordered"
)
}
return { item_id, quantity }
})
}
/**
* @typedef PreliminaryLineItem
* @property {string} variant_id - the id of the variant to create an item from
* @property {number} quantity - the amount of the variant to add to the line item
*/
/**
* Creates a swap from an order, with given return items, additional items
* and an optional return shipping method.
* @param {Order} order - the order to base the swap off.
* @param {Array<ReturnItem>} returnItems - the items to return in the swap.
* @param {Array<PreliminaryLineItem>} additionalItems - the items to send to
* the customer.
* @param {ReturnShipping?} returnShipping - an optional shipping method for
* returning the returnItems.
* @param {Object} custom - contains relevant custom information. This object may
* include no_notification which will disable sending notification when creating
* swap. If set, it overrules the attribute inherited from the order.
* @returns {Promise<Swap>} the newly created swap.
*/
async create(
order,
returnItems,
additionalItems,
returnShipping,
custom = {
no_notification: undefined,
}
) {
const { no_notification, ...rest } = custom
return this.atomicPhase_(async manager => {
if (
order.fulfillment_status === "not_fulfilled" ||
order.payment_status !== "captured"
) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Order cannot be swapped"
)
}
for (const item of returnItems) {
const line = await this.lineItemService_.retrieve(item.item_id, {
relations: ["order", "swap", "claim_order"],
})
console.log(line)
if (
line.order?.canceled_at ||
line.swap?.canceled_at ||
line.claim_order?.canceled_at
) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Cannot create a swap on a canceled item.`
)
}
}
const newItems = await Promise.all(
additionalItems.map(({ variant_id, quantity }) => {
return this.lineItemService_.generate(
variant_id,
order.region_id,
quantity
)
})
)
const evaluatedNoNotification =
no_notification !== undefined ? no_notification : order.no_notification
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const created = swapRepo.create({
...rest,
fulfillment_status: "not_fulfilled",
payment_status: "not_paid",
order_id: order.id,
additional_items: newItems,
no_notification: evaluatedNoNotification,
})
const result = await swapRepo.save(created)
await this.returnService_.withTransaction(manager).create({
swap_id: result.id,
order_id: order.id,
items: returnItems,
shipping_method: returnShipping,
no_notification: evaluatedNoNotification,
})
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.CREATED, {
id: result.id,
no_notification: evaluatedNoNotification,
})
return result
})
}
async processDifference(swapId) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: ["payment", "order", "order.payments"],
})
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be processed"
)
}
if (!swap.confirmed_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Cannot process a swap that hasn't been confirmed by the customer"
)
}
const swapRepo = manager.getCustomRepository(this.swapRepository_)
if (swap.difference_due < 0) {
if (swap.payment_status === "difference_refunded") {
return swap
}
try {
await this.paymentProviderService_
.withTransaction(manager)
.refundPayment(
swap.order.payments,
-1 * swap.difference_due,
"swap"
)
} catch (err) {
swap.payment_status = "requires_action"
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.PROCESS_REFUND_FAILED, {
id: result.id,
no_notification: swap.no_notification,
})
return result
}
swap.payment_status = "difference_refunded"
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.REFUND_PROCESSED, {
id: result.id,
no_notification: swap.no_notification,
})
return result
} else if (swap.difference_due === 0) {
if (swap.payment_status === "difference_refunded") {
return swap
}
swap.payment_status = "difference_refunded"
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.REFUND_PROCESSED, {
id: result.id,
no_notification: swap.no_notification,
})
return result
}
try {
if (swap.payment_status === "captured") {
return swap
}
await this.paymentProviderService_
.withTransaction(manager)
.capturePayment(swap.payment)
} catch (err) {
swap.payment_status = "requires_action"
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.PAYMENT_CAPTURE_FAILED, {
id: swap.id,
no_notification: swap.no_notification,
})
return result
}
swap.payment_status = "captured"
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.PAYMENT_CAPTURED, {
id: result.id,
no_notification: swap.no_notification,
})
return result
})
}
async update(swapId, update) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId)
if ("metadata" in update) {
swap.metadata = this.setMetadata_(swap, update.metadata)
}
if ("no_notification" in update) {
swap.no_notification = update.no_notification
}
if ("shipping_address" in update) {
await this.updateShippingAddress_(swap, update.shipping_address)
}
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
return result
})
}
/**
* Creates a cart from the given swap and order. The cart can be used to pay
* for differences associated with the swap. The swap represented by the
* swapId must belong to the order. Fails if there is already a cart on the
* swap.
* @param {Order} order - the order to create the cart from
* @param {string} swapId - the id of the swap to create the cart from
* @returns {Promise<Swap>} the swap with its cart_id prop set to the id of
* the new cart.
*/
async createCart(swapId) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: [
"order",
"order.items",
"order.swaps",
"order.swaps.additional_items",
"order.discounts",
"additional_items",
"return_order",
"return_order.items",
"return_order.shipping_method",
],
})
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be used to create a cart"
)
}
if (swap.cart_id) {
throw new MedusaError(
MedusaError.Types.DUPLICATE_ERROR,
"A cart has already been created for the swap"
)
}
const order = swap.order
// filter out free shipping discounts
const discounts =
order?.discounts?.filter(({ rule }) => rule.type !== "free_shipping") ||
undefined
const cart = await this.cartService_.withTransaction(manager).create({
discounts,
email: order.email,
billing_address_id: order.billing_address_id,
shipping_address_id: order.shipping_address_id,
region_id: order.region_id,
customer_id: order.customer_id,
type: "swap",
metadata: {
swap_id: swap.id,
parent_order_id: order.id,
},
})
for (const item of swap.additional_items) {
await this.lineItemService_.withTransaction(manager).update(item.id, {
cart_id: cart.id,
})
}
// If the swap has a return shipping method the price has to be added to the
// cart.
if (swap.return_order && swap.return_order.shipping_method) {
await this.lineItemService_.withTransaction(manager).create({
cart_id: cart.id,
title: "Return shipping",
quantity: 1,
has_shipping: true,
allow_discounts: false,
unit_price: swap.return_order.shipping_method.price,
metadata: {
is_return_line: true,
},
})
}
for (const r of swap.return_order.items) {
let allItems = [...order.items]
if (order.swaps && order.swaps.length) {
for (const s of order.swaps) {
allItems = [...allItems, ...s.additional_items]
}
}
const lineItem = allItems.find(i => i.id === r.item_id)
const toCreate = {
cart_id: cart.id,
thumbnail: lineItem.thumbnail,
title: lineItem.title,
variant_id: lineItem.variant_id,
unit_price: -1 * lineItem.unit_price,
quantity: r.quantity,
allow_discounts: lineItem.allow_discounts,
metadata: {
...lineItem.metadata,
is_return_line: true,
},
}
await this.lineItemService_.withTransaction(manager).create(toCreate)
}
swap.cart_id = cart.id
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
return result
})
}
/**
*
*/
async registerCartCompletion(swapId) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: [
"cart",
"cart.region",
"cart.shipping_methods",
"cart.shipping_address",
"cart.items",
"cart.discounts",
"cart.discounts.rule",
"cart.payment",
"cart.gift_cards",
],
})
// If we already registered the cart completion we just return
if (swap.confirmed_at) {
return swap
}
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Cart related to canceled swap cannot be completed"
)
}
const cart = swap.cart
const items = swap.cart.items
for (const item of items) {
await this.inventoryService_
.withTransaction(manager)
.confirmInventory(item.variant_id, item.quantity)
}
const total = await this.totalsService_.getTotal(cart)
if (total > 0) {
const { payment } = cart
if (!payment) {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Cart does not contain a payment"
)
}
const paymentStatus = await this.paymentProviderService_
.withTransaction(manager)
.getStatus(payment)
// If payment status is not authorized, we throw
if (paymentStatus !== "authorized" && paymentStatus !== "succeeded") {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Payment method is not authorized"
)
}
await this.paymentProviderService_
.withTransaction(manager)
.updatePayment(payment.id, {
swap_id: swapId,
order_id: swap.order_id,
})
for (const item of items) {
await this.inventoryService_
.withTransaction(manager)
.adjustInventory(item.variant_id, -item.quantity)
}
}
const now = new Date()
swap.difference_due = total
swap.shipping_address_id = cart.shipping_address_id
swap.shipping_methods = cart.shipping_methods
swap.confirmed_at = now.toISOString()
swap.payment_status = total === 0 ? "difference_refunded" : "awaiting"
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
for (const method of cart.shipping_methods) {
await this.shippingOptionService_
.withTransaction(manager)
.updateShippingMethod(method.id, {
swap_id: result.id,
})
}
this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.PAYMENT_COMPLETED, {
id: swap.id,
no_notification: swap.no_notification,
})
return result
})
}
/**
* Registers the return associated with a swap as received. If the return
* is received with mismatching return items the swap's status will be updated
* to requires_action.
* @param {Order} order - the order to receive the return based off
* @param {string} swapId - the id of the swap to receive.
* @param {Array<ReturnItem>} - the items that have been returned
* @returns {Promise<Swap>} the resulting swap, with an updated return and
* status.
*/
async receiveReturn(swapId, returnItems) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, { relations: ["return_order"] })
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be registered as received"
)
}
const returnId = swap.return_order && swap.return_order.id
if (!returnId) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Swap has no return request"
)
}
const updatedRet = await this.returnService_
.withTransaction(manager)
.receiveReturn(returnId, returnItems, undefined, false)
if (updatedRet.status === "requires_action") {
const swapRepo = manager.getCustomRepository(this.swapRepository_)
swap.fulfillment_status = "requires_action"
const result = await swapRepo.save(swap)
return result
}
return this.retrieve(swapId)
})
}
/**
* Cancels a given swap if possible. A swap can only be canceled if all
* related returns, fulfillments, and payments have been canceled. If a swap
* is associated with a refund, it cannot be canceled.
* @param {string} swapId - the id of the swap to cancel.
* @returns {Promise<Swap>} the canceled swap.
*/
async cancel(swapId) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: ["payment", "fulfillments", "return_order"],
})
if (
swap.payment_status === "difference_refunded" ||
swap.payment_status === "partially_refunded" ||
swap.payment_status === "refunded"
) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Swap with a refund cannot be canceled"
)
}
if (swap.fulfillments) {
for (const f of swap.fulfillments) {
if (!f.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"All fulfillments must be canceled before the swap can be canceled"
)
}
}
}
if (swap.return_order && swap.return_order.status !== "canceled") {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Return must be canceled before the swap can be canceled"
)
}
swap.payment_status = "canceled"
swap.fulfillment_status = "canceled"
swap.canceled_at = new Date()
if (swap.payment) {
await this.paymentProviderService_
.withTransaction(manager)
.cancelPayment(swap.payment)
}
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
return result
})
}
/**
* Fulfills the addtional items associated with the swap. Will call the
* fulfillment providers associated with the shipping methods.
* @param {string} swapId - the id of the swap to fulfill,
* @param {object} config - optional configurations, includes optional metadata to attach to the shipment, and a no_notification flag.
* @returns {Promise<Swap>} the updated swap with new status and fulfillments.
*/
async createFulfillment(
swapId,
config = {
metadata: {},
no_notification: undefined,
}
) {
const { metadata, no_notification } = config
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: [
"payment",
"shipping_address",
"additional_items",
"shipping_methods",
"order",
"order.billing_address",
"order.discounts",
"order.payments",
],
})
const order = swap.order
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be fulfilled"
)
}
if (
swap.fulfillment_status !== "not_fulfilled" &&
swap.fulfillment_status !== "canceled"
) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"The swap was already fulfilled"
)
}
if (!swap.shipping_methods?.length) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Cannot fulfill an swap that doesn't have shipping methods"
)
}
const evaluatedNoNotification =
no_notification !== undefined ? no_notification : swap.no_notification
swap.fulfillments = await this.fulfillmentService_
.withTransaction(manager)
.createFulfillment(
{
...swap,
payments: swap.payment ? [swap.payment] : order.payments,
email: order.email,
discounts: order.discounts,
currency_code: order.currency_code,
tax_rate: order.tax_rate,
region_id: order.region_id,
display_id: order.display_id,
billing_address: order.billing_address,
items: swap.additional_items,
shipping_methods: swap.shipping_methods,
is_swap: true,
no_notification: evaluatedNoNotification,
},
swap.additional_items.map(i => ({
item_id: i.id,
quantity: i.quantity,
})),
{ swap_id: swapId, metadata }
)
let successfullyFulfilled = []
for (const f of swap.fulfillments) {
successfullyFulfilled = successfullyFulfilled.concat(f.items)
}
swap.fulfillment_status = "fulfilled"
// Update all line items to reflect fulfillment
for (const item of swap.additional_items) {
const fulfillmentItem = successfullyFulfilled.find(
f => item.id === f.item_id
)
if (fulfillmentItem) {
const fulfilledQuantity =
(item.fulfilled_quantity || 0) + fulfillmentItem.quantity
// Update the fulfilled quantity
await this.lineItemService_.withTransaction(manager).update(item.id, {
fulfilled_quantity: fulfilledQuantity,
})
if (item.quantity !== fulfilledQuantity) {
swap.fulfillment_status = "requires_action"
}
} else {
if (item.quantity !== item.fulfilled_quantity) {
swap.fulfillment_status = "requires_action"
}
}
}
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
await this.eventBus_.withTransaction(manager).emit(
SwapService.Events.FULFILLMENT_CREATED,
{
id: swapId,
fulfillment_id: result.id,
no_notification: evaluatedNoNotification,
}
)
return result
})
}
/**
* Cancels a fulfillment (if related to a swap)
* @param {string} fulfillmentId - the ID of the fulfillment to cancel
* @returns updated swap
*/
async cancelFulfillment(fulfillmentId) {
return this.atomicPhase_(async manager => {
const canceled = await this.fulfillmentService_
.withTransaction(manager)
.cancelFulfillment(fulfillmentId)
if (!canceled.swap_id) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
`Fufillment not related to a swap`
)
}
const swap = await this.retrieve(canceled.swap_id)
swap.fulfillment_status = "canceled"
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const updated = await swapRepo.save(swap)
return updated
})
}
/**
* Marks a fulfillment as shipped and attaches tracking numbers.
* @param {string} swapId - the id of the swap that has been shipped.
* @param {string} fulfillmentId - the id of the specific fulfillment that
* has been shipped
* @param {TrackingLink[]} trackingLinks - the tracking numbers associated
* with the shipment
* @param {object} config - optional configurations, includes optional metadata to attach to the shipment, and a noNotification flag.
* @returns {Promise<Swap>} the updated swap with new fulfillments and status.
*/
async createShipment(
swapId,
fulfillmentId,
trackingLinks,
config = {
metadata: {},
no_notification: undefined,
}
) {
const { metadata, no_notification } = config
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(swapId, {
relations: ["additional_items"],
})
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be fulfilled as shipped"
)
}
const evaluatedNoNotification =
no_notification !== undefined ? no_notification : swap.no_notification
// Update the fulfillment to register
const shipment = await this.fulfillmentService_
.withTransaction(manager)
.createShipment(fulfillmentId, trackingLinks, {
metadata,
no_notification: evaluatedNoNotification,
})
swap.fulfillment_status = "shipped"
// Go through all the additional items in the swap
for (const i of swap.additional_items) {
const shipped = shipment.items.find(si => si.item_id === i.id)
if (shipped) {
const shippedQty = (i.shipped_quantity || 0) + shipped.quantity
await this.lineItemService_.withTransaction(manager).update(i.id, {
shipped_quantity: shippedQty,
})
if (shippedQty !== i.quantity) {
swap.fulfillment_status = "partially_shipped"
}
} else {
if (i.shipped_quantity !== i.quantity) {
swap.fulfillment_status = "partially_shipped"
}
}
}
const swapRepo = manager.getCustomRepository(this.swapRepository_)
const result = await swapRepo.save(swap)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.SHIPMENT_CREATED, {
id: swapId,
fulfillment_id: shipment.id,
no_notification: swap.no_notification,
})
return result
})
}
/**
* Dedicated method to delete metadata for a swap.
* @param {string} swapId - the order to delete metadata from.
* @param {string} key - key for metadata field
* @return {Promise} resolves to the updated result.
*/
async deleteMetadata(swapId, key) {
const validatedId = this.validateId_(swapId)
if (typeof key !== "string") {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Key type is invalid. Metadata keys must be strings"
)
}
const keyPath = `metadata.${key}`
return this.swapModel_
.updateOne({ _id: validatedId }, { $unset: { [keyPath]: "" } })
.catch(err => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
/**
* Registers the swap return items as received so that they cannot be used
* as a part of other swaps/returns.
* @param {string} id - the id of the order with the swap.
* @param {string} swapId - the id of the swap that has been received.
* @returns {Promise<Order>} the resulting order
*/
async registerReceived(id) {
return this.atomicPhase_(async manager => {
const swap = await this.retrieve(id, {
relations: ["return_order", "return_order.items"],
})
if (swap.canceled_at) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Canceled swap cannot be registered as received"
)
}
if (swap.return_order.status !== "received") {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Swap is not received"
)
}
const result = await this.retrieve(id)
await this.eventBus_
.withTransaction(manager)
.emit(SwapService.Events.RECEIVED, {
id: id,
order_id: result.order_id,
no_notification: swap.no_notification,
})
return result
})
}
} |
JavaScript | class Server {
//saves {room: [id1, id2, .....]}
_games = {};
_users = {};
_messageConfig = {
'getAllBundles': data => this.getAllBundles(data),
'messageToGameChat': data => this.messageToGameChat(data),
'newGameLobby': data => this.createNewGame(data),
'returnAllGames': data => this.returnAllGames(data),
'joinGame': data => this.joinGame(data),
'broadcastInRoom': data => this.broadcastInRoom(data),
'saveBundleToDB': data => this.saveBundleToDB(data),
'leaveGame': data => this.leaveGame(data),
'newGameMaster': data => this.newGameMaster(data),
'sendName': data => this.sendName(data),
'removeUserFromServer': data => this.removeUserFromServer(data),
'updateGameStatus': data => this.updateGameStatus(data),
'getBundleNames': data => this.getBundleNames(data),
'getBundleByName': data => this.getBundleByName(data),
};
constructor(port) {
if (!Server._instance) {
Server._instance = this;
this.server = http.createServer();
this.server.listen(port, () => console.log('Listening on port ' + port));
this.server.on('request', this.handleRequest);
const server = this.server;
this.ws = new WebSocket.Server({ server });
this.ws.on('connection', (connection, req) => {
this.connectionOpen(connection, req);
connection.on('message', m => this.connectionMessage(connection, m));
connection.on('close', () => this.connectionClose(connection));
});
}
return Server._instance;
}
updateGameStatus(data) {
const roomId = data.data.roomID;
this._games[roomId].settings.running = true;
const gamesSend = this.prepareGamesForClient();
this.sendToAll({mType: 'returnAllGames', data: gamesSend});
}
//handles request to server
async handleRequest(req, res) {
let name = req.url;
if (routing[name]) name = routing[name];
let extention = name.split('.')[1];
const typeAns = mime[extention];
let data = null;
data = await fileManager.readFile('.' + name);
if (data) {
res.writeHead(200, { 'Content-Type': `${typeAns}; charset=utf-8` });
res.write(data);
}
res.end();
}
//on new user connected
connectionOpen(connection, req) {
const id = idGenerator.getID();
this._users[id] = {connection: connection, name: ''};
}
//write into this._users name
sendName(data) {
if (!this._users.hasOwnProperty(data.id)) {
console.log('(sendName) no such id property in this._users: ', data.id);
return;
}
if (!data.data.hasOwnProperty('name')) {
console.log('(sendName) no name property in data.data: ', data);
return;
}
this._users[data.id].name = data.data.name;
const users = {names: []};
for (let i in this._users) {
users.names.push(this._users[i].name);
}
this.sendToAll({mType: 'usersOnline', data: users});
}
//send message to everyone
sendToAll(message) {
this.ws.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
}
//send to specific user
sendToUser(id, message) {
if (!this._users.hasOwnProperty(id) || !this._users[id].hasOwnProperty('connection')) {
console.log(('(sendToUser) user with id: ' + id + ' probably left before answer arrived'));
return;
}
const user = this._users[id].connection;
if (user.readyState === WebSocket.OPEN) {
user.send(JSON.stringify(message));
}
}
//executes specific function on new message from client
async connectionMessage(connection, message) {
const request = JSON.parse(message);
console.log('request ', request);
if (!this._messageConfig.hasOwnProperty(request.mType)) {
console.log('(connectionMessage) should exist mType, wrong input: ', request);
return;
}
const messageHandler = this._messageConfig[request.mType];
if (!messageHandler) {
console.log('(connectionMessage) no handle exists for mType: ' + request.mType);
return;
}
await messageHandler({
'id': this.getIdByConnection(connection),
'data': request.data,
});
}
//gets all bundles from database
getAllBundles(message) {
const database = new Database(databaseConfig);
const connection = database.returnConnection();
connection.connect( async err => {
if (err) throw err;
console.log('Connected!');
let bundles = null;
try {
bundles = await database.getAllBundles();
} catch (err) {
console.log(('(getAllBundles) error when awaiting bundles from db occured ', err));
}
this.sendToUser(message.id, {mType: 'allBundles', data: bundles});
connection.destroy();
});
}
//sends message to everyone in game chat
messageToGameChat(message) {
const data = message.data;
const id = message.id;
data.name = this._users[id].name;
for (let userId in this._games[data.room].players) {
this.sendToUser(userId, {mType: 'messageToGameChat', data: data });
}
}
//games to send to client
prepareGamesForClient() {
const getCircularReplacer = () => {
const seen = new WeakSet();
return (k, val) => {
if (typeof val === 'object' && val !== null) {
if (seen.has(val)) {
return;
}
seen.add(val);
}
return val;
};
}
const gamesSend = JSON.parse(JSON.stringify(this._games, getCircularReplacer()));
for (const gameID in gamesSend) {
const players = gamesSend[gameID].players;
gamesSend[gameID].players = [];
for (const playerID in players) {
const plName = players[playerID].name;
gamesSend[gameID].players.push(plName);
}
}
return gamesSend;
}
//creates new game and puts it to games
createNewGame(data) {
const message = data.data;
const id = idGenerator.getID();
this._games[id] = {
players: {},
};
this._games[id].players[data.id] = this._users[data.id];
this._games[id].bundle = message.bundle;
this._games[id].settings = message.settings;
this._games[id].settings.running = false;
this.sendToUser(data.id, {mType: 'newLobbyId', data: {id: id}});
for (let id of Object.keys(this._users)) {
this.returnAllGames({id: id});
}
}
//returns all games
returnAllGames(data) {
const id = data.id;
const gamesSend = this.prepareGamesForClient();
this.sendToUser(id, {mType: 'returnAllGames', data: gamesSend});
}
//remove all info about user from server
removeUserFromServer(data) {
const id = data.id;
const roomID = data.data.roomID;
if (roomID) this.leaveGame({id: id, roomID: roomID});
console.log('this._users[id] ', this._users[id]);
delete this._users[id];
idGenerator.removeID(roomID);
}
//on user leaves game
leaveGame(data) {
const id = data.id;
const roomID = data.data.roomID;
if (!this._games.hasOwnProperty(roomID)) {
console.log('(leaveGame) no such game with id ' + roomID);
return;
}
const players = this._games[roomID].players;
delete players[id];
//remove comments on production
if (Object.keys(this._games[roomID].players).length === 0) {
delete this._games[roomID];
idGenerator.removeID(roomID);
}
const gamesSend = this.prepareGamesForClient();
this.sendToAll({mType: 'returnAllGames', data: gamesSend});
console.log(this._games);
}
//broadcast for all people in room
broadcastInRoom(data) {
const roomID = data.data.roomID;
if (!this._games.hasOwnProperty(roomID)) {
console.log('(broadcast in room) no such game with id ' + roomID);
return;
}
const players = this._games[roomID].players;
for (let player in players) {
this.sendToUser(player, {mType: 'broadcastedEvent', data: data});
}
}
joinGame(data) {
const id = data.id;
const message = data.data;
this._games[message.id].players[id] = this._users[id];
const gamesSend = this.prepareGamesForClient();
this.sendToAll({mType: 'returnAllGames', data: gamesSend});
const gameData = this._games[message.id];
for (let player in gameData.players) {
this.sendToUser(player, {mType: 'newJoin', data: {id: id, name: gameData.players[player].name}});
}
this.sendToUser(id, {mType: 'joinGame', data: {id: message.id}});
}
//saves bundle to db
saveBundleToDB(data) {
const database = new Database(databaseConfig);
const connection = database.returnConnection();
connection.connect( async err => {
if (err) throw err;
console.log('Connected!');
console.log('from saveBundle to db' , data.data);
await database.insertBundle(data.data);
connection.end(err => {
if(err) console.log('error when connection ends: ' + err);
else console.log('closed');
});
});
}
//on new game master
newGameMaster(data) {
const game = this._games[data.data.roomID];
if (!game) return;
game.settings.master = data.data.newGM;
const gamesSend = this.prepareGamesForClient();
this.sendToAll({mType: 'returnAllGames', data: gamesSend});
}
//executes on user quitting
connectionClose(connection) {
const id = this.getIdByConnection(connection);
for (let idGame in this._games) {
const game = this._games[idGame];
const players = game.players;
if (players.hasOwnProperty(id)) this.leaveGame({id: id, data: {roomID: idGame}});
}
delete this._users[id];
idGenerator.removeID(id);
const users = {names: []};
for (let i in this._users) {
users.names.push(this._users[i].name);
}
this.sendToAll({mType: 'usersOnline', data: users});
}
// gets users id by connection
getIdByConnection(connection) {
for (let [id, info] of Object.entries(this._users)) {
if (info.connection === connection) return id;
}
}
//get all bundle names
getBundleNames(data) {
const database = new Database(databaseConfig);
const connection = database.returnConnection();
connection.on('error', e => console.log('on error: ' + e));
connection.connect( async err => {
if (err) console.error('Issues with connection to Database \n' + err);
console.log('Connected!');
let bundleNames = null;
try {
bundleNames = await database.getBundleNames();
} catch (err) {
console.log(err);
}
this.sendToUser(data.id, {mType: 'bundleNames', data: bundleNames});
connection.end(err => {
if(err) console.log('error when connection ends: ' + err);
else console.log('closed');
});
});
}
//get bundle by name
getBundleByName(data) {
const name = data.data.name;
const database = new Database(databaseConfig);
const connection = database.returnConnection();
connection.on('error', e => console.log('on error: ' + e));
connection.connect( async err => {
if (err) console.error('Issues with connection to Database \n' + err);
console.log('Connected!');
let bundleRows = null;
try {
bundleRows = await database.getBundleByName(name);
} catch (err) {
console.log(err);
}
this.sendToUser(data.id, {mType: 'bundleRows', data: bundleRows});
connection.end(err => {
if (err) console.log('error when connection ends: ' + err);
else console.log('closed');
});
});
}
} |
JavaScript | class Game {
/**
* @param {MyLoader} loader - custom loader object
* @param {PIXI.Application} app - pixi application
**/
constructor(loader, app){
// disable pixi's default linear interpolation
PIXI.SCALE_MODES.DEFAULT = PIXI.SCALE_MODES.NEAREST;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
// Pixi application object
this.app = app;
// physics Engine
this.engine = Engine.create();
this.world = this.engine.world;
this.updateLag = 0;
// display object containers
this.worldContainer = new PIXI.Container(); // every display object in the game world
this.animationContainer = new PIXI.Container(); // every animated sprite in the game
this.foregroundContainer = new PIXI.Container(); // objects with no parallax scroll
this.backgroundContainer = new PIXI.Container(); // objects affected by parallax
this.dynamicLightContainer = new PIXI.Container(); // torch that follows the player around
this.staticLights = new PIXI.Container();
this.scale = 0.5; // zoom level of map
this.app.stage.scale.set(this.scale);
this.initFilters(loader);
let resources = {
world: this.world,
loader: loader,
screen: this.app.screen,
filterCache: this.filterCache
}
// static dungeon map for debugging
this.tileMap = MapManager(resources, "wang");
// draw the static light
this.tileMap.lights.forEach( (light) => {
light.update(this.app.ticker.speed);
});
// Contains player animations, physics bodies, flags, behavior functions
this.player = new Player(this.tileMap.playerSpawn, loader.catAnimations, this.filterCache, this.app.screen);
this.camera = new MyCamera(this.player.position);
// controls all catnip powerups/filters
this.catnipTrip = new CatnipTrip(this.player, this.tileMap.powerups);
// detect input hardware, init event handlers & UI elements
this.initInput(loader);
// add objects to physics world, setup collision events
this.initPhysics();
// resize canvas on window resize
window.addEventListener( 'resize', this.onWindowResize.bind(this), false );
this.app.stage.position.set(this.app.screen.width/2, this.app.screen.height/2);
// Add objects to pixi stage
this.initLayers();
// Start the game loop
this.app.ticker.add(delta => this.loop(delta));
}
/**
* main game loop, does not update at a constant rate */
loop(delta){
let prevPosition = Vector.create(this.camera.position.x, this.camera.position.y);
// update physics bodies at 60 hz constant
this.FixedUpdate();
let frameMovement = Vector.sub(this.camera.position, prevPosition);
this.updateUniforms(frameMovement);
this.GamepadInput.update();
if ( this.catnipTrip.ticker.started)
this.worldContainer.rotation = this.catnipTrip.cameraRotation;
this.pauseMenu.moveButtons(this.camera.position);
// adjust stage for camera movement
this.app.stage.pivot.copyFrom(this.camera.position);
this.app.stage.angle = this.camera.angleOffset;
this.tileMap.parallaxScroll(this.app.stage.pivot);
this.catnipTrip.update(delta);
this.updateShadows();
this.tileMap.update();
}
FixedUpdate(){
this.updateLag += this.app.ticker.deltaMS;
while ( this.updateLag >= 16.666 ) {
// move forward one time step
this.updateLag -= 16.666
// apply player input to physics bodies
this.player.update(this.app.ticker.speed);
this.tileMap.FixedUpdate();
Engine.update(this.engine);
if ( this.player.cameraSnapped)
this.camera.update(this.player.position, this.player.flip, this.app.ticker.speed);
else {
this.camera.update(this.player.climbTranslation, this.player.flip, this.app.ticker.speed);
}
// increase gravity if player is falling
if (!this.player.isGrounded && !this.player.inSlide && !this.player.isHanging && this.player.body.velocity.y > 0){
if ( this.world.gravity.y < 3.5 )
this.world.gravity.y += 0.015;
}
else {
this.world.gravity.y = 1;
}
this.tileMap.lights.forEach( (light) => {
//light.visionSource.mesh.shader.uniforms.time += 0.00003;
light.visionSource.mesh.shader.uniforms.time += 0.003;
});
// update displacement filter for the catnip trip effect
this.catnipTrip.FixedUpdate(this.player,
this.foregroundContainer.filters,
this.backgroundContainer.filters);
}
}
/**
* - create post processing filters
* - create necessary textures, sprites
* @param {MyLoader} loader - custom file loader
*/
initFilters(loader){
// Filter manager for effects that use previous frame data
this.filterCache = new FilterCache();
this.filterTicker = new PIXI.Ticker();
this.filterTicker.add(this.filterCache.update.bind(this.filterCache));
this.filterTicker.start();
// render texture/sprite for shadows
this.lightRenderTexture = PIXI.RenderTexture.create(this.app.screen.width, this.app.screen.height);
console.log("screen dimensions ", this.app.screen.width, this.app.screen.height)
this.shadowFilter;
this.dynamicLight = new PIXI.Sprite();
this.dynamicLight.scale.set(1/this.scale);
this.filterOffset = new PIXI.Point(0,0);
// palette swap filter
this.paletteIndex = 2;
this.paletteSwap = new PaletteSwapFilter( loader.paletteTextures[this.paletteIndex] );
// dissolve filter noise texture
this.dissolveSprite = new PIXI.Sprite.from('https://res.cloudinary.com/dvxikybyi/image/upload/v1486634113/2yYayZk_vqsyzx.png');
this.dissolveSprite.texture.baseTexture.wrapMode = PIXI.WRAP_MODES.REPEAT;
this.dissolveSprite.scale.set(0.2);
this.worldContainer.addChild(this.dissolveSprite);
}
/**
* Add pixi objects to global renderer,
* - Works like a stack, last element added = top graphics layer */
initLayers() {
// fill the animation container
this.tileMap.torchSprites.forEach( (animation) => {
this.animationContainer.addChild(animation); // add torches
});
this.animationContainer.addChild(this.player.animationContainer);
// background / uninteractable tiles
this.backgroundContainer.addChild(this.tileMap.backgroundContainer);
this.worldContainer.addChild(this.backgroundContainer);
this.dynamicLightContainer.addChild(this.dynamicLight);
this.foregroundContainer.addChild(this.dynamicLightContainer)
// add animations
this.foregroundContainer.addChild(this.animationContainer);
// add terrain tiles
this.foregroundContainer.addChild(this.tileMap.tileContainer);
this.foregroundContainer.addChild(this.tileMap.powerupContainer);
this.tileMap.lights.forEach( (light) => {
this.staticLights.addChild(light.visionSource.mesh);
});
this.foregroundContainer.addChild(this.staticLights);
this.shadowFilter = new ShadowFilter(this.dynamicLight, 2);
this.worldContainer.addChild(this.foregroundContainer);
this.app.stage.addChild(this.worldContainer);
// add ui buttons to the top layer
this.app.stage.addChild(this.pauseMenu.buttonContainer);
this.foregroundContainer.addChild(this.catnipTrip.foregroundNoise);
this.foregroundContainer.addChild(this.catnipTrip.badFilterSolution);
this.tileMap.backgroundContainer.addChild(this.catnipTrip.backgroundNoise);
// apply filters to containers
this.worldContainer.filterArea = this.app.screen;
this.worldContainer.filters = [this.shadowFilter,new PixelateFilter(2.5) ];
}
/**
* - Creates a new WebGL mesh for the dynamic light
* - Draws all the lights to a texture for the shadow filter */
updateShadows(){
this.filterOffset.set( -this.camera.position.x + this.app.screen.width,
-this.camera.position.y + this.app.screen.height);
this.dynamicLight.position.set(-this.filterOffset.x, -this.filterOffset.y);
// camera offset
let viewTransform = new PIXI.Matrix();
viewTransform.tx = this.filterOffset.x*this.scale;
viewTransform.ty = this.filterOffset.y*this.scale;
viewTransform.a = this.scale;
viewTransform.d = this.scale;
// draw to shadow mask texture
this.app.renderer.render(this.staticLights, this.lightRenderTexture, true, viewTransform );
this.app.renderer.render(this.tileMap.lightContainer, this.lightRenderTexture, false, viewTransform );
this.dynamicLight.texture = this.lightRenderTexture;
this.shadowFilter.uniforms.lightSampler = this.lightRenderTexture;
}
updateUniforms(frameMovement){
this.tileMap.filter.uniforms.movement = [frameMovement.x*this.scale, frameMovement.y*this.scale];
this.player.tintedTrail.uniforms.movement = this.tileMap.filter.uniforms.movement;
this.player.tintedTrail.uniforms.alpha = this.catnipTrip.bezierY*0.6;
}
initPhysics(){
// Add player's rigidbody to matterjs world
World.add(this.world, this.player.body);
// Add tile colliders to matterjs engine
this.tileMap.terrain.forEach((element) => {
World.add(this.world, element.Collider);
if ( element.walkBox)
World.add(this.world, element.walkBox);
World.add(this.world, element.edgeBoxes)
});
// add catnip trigger colliders
this.tileMap.powerups.forEach( (powerup) => {
World.add(this.world, powerup.collider);
});
// define collision event callbacks
this.collisionEventSetup();
}
/** NSFW Spaghetti code */
collisionEventSetup() {
Events.on(this.engine, 'collisionActive', (event) => {
var inWalkBox = false;
var catCollision = false;
var pairs = event.pairs;
var physicsCollisions = 0;
let otherBody;
let terrainBodies = [];
// Iterate through collision pairs
for (var i = 0; i < pairs.length; i++) {
let pair = pairs[i];
// check if the collision involves the cat
if ( pair.bodyA.id == this.player.body.id )
otherBody = pair.bodyB;
else if ( pair.bodyB.id == this.player.body.id )
otherBody = pair.bodyA;
// ignore collision if player not involved
else continue;
// check if collision with sensors
if ( otherBody.isSensor ) {
// if collding with a ledge climb trigger collider
if ( otherBody.isEdgeBox ) {
if ((this.player.lastInput == "right" && !otherBody.isRight) || this.player.lastInput == "left" && otherBody.isRight){
this.world.gravity.y = 1;
const impactVel = this.player.prevVel;
if (impactVel > this.player.fallDamageVel && this.pauseMenu.cameraShake)
this.camera.addTrauma(impactVel / (this.player.fallDamageVel * 2));
this.player.startLedgeClimb(otherBody.position, otherBody.isRight)
return; // skip the rest of the collision checks for this frame; the player will be locked in place
}
else {
inWalkBox = false;
this.player.isGrounded = false;
this.player.inSlide = true;
}
}
// if colliding with a ground trigger collider
else if (!this.player.isHanging)
inWalkBox = true;
if ( otherBody.isCatnip ){
this.foregroundContainer.filters = [this.catnipTrip.foregroundFilter];
this.tileMap.backgroundContainer.filters = [this.catnipTrip.backgroundFilter];
// this.player.tintedTrail.uniforms.alpha = 0.9;
this.catnipTrip.start();
World.remove(this.world, otherBody);
otherBody.spriteReference.filters = [new DissolveFilter(this.dissolveSprite, 1)];
}
}
else if (otherBody.isParticle){
let vel = Vector.create( 25 - Math.random() * 50, -10);
Body.setVelocity(otherBody, vel);
otherBody.collisionFilter.mask = 0x0002 | 0x0001;
otherBody.ticks = 0;
}
else {// if physics collision
catCollision = true;
physicsCollisions++;
terrainBodies.push(otherBody);
}
}
this.player.physicsCollisions = physicsCollisions;
// Handle collision cases
// cat is sliding on a wall
if ( catCollision && !inWalkBox && !this.player.isGrounded){
this.player.wallJumpTimer.stop();
this.player.inSlide = true;
let slideAnimation = this.player.animations.get("slide");
if ( this.player.xVel > 0){
this.player.setFlip("right");
slideAnimation.scale.x = -this.player.scale;
slideAnimation.angle = -90;
this.player.animations.set("slide", slideAnimation);
}
else if ( this.player.xVel < 0 ){
this.player.setFlip("left");
slideAnimation.scale.x = -this.player.scale;
slideAnimation.angle = 90;
this.player.animations.set("slide", slideAnimation);
}
else if ( this.player.flip == "right") {
slideAnimation.scale.x = -this.player.scale;
slideAnimation.angle = -90;
this.player.animations.set("slide", slideAnimation);
}
else if ( this.player.flip == "left"){
slideAnimation.scale.x = -this.player.scale;
slideAnimation.angle = 90;
this.player.animations.set("slide", slideAnimation);
}
this.player.xVel = 0;
this.player.setAnimation("slide");
}
// if landing
else if ( !this.player.isGrounded &&
( (inWalkBox && catCollision && !this.player.inSlide) || (physicsCollisions >= 2 && inWalkBox ) ) ) {
this.world.gravity.y = 1;
const impactVel = this.player.prevVel;
if (impactVel > this.player.fallDamageVel && this.pauseMenu.cameraShake)
this.camera.addTrauma(impactVel / (this.player.fallDamageVel * 2));
this.player.prevVel = 0.0;
this.player.isGrounded = true;
this.player.inSlide = false;
if ( this.player.xVel == 0 || this.player.inSlowDown )
this.player.setAnimation("stop");
else if ( !this.player.inSlowDown )
this.player.setAnimation("walk");
}
this.player.inWalkBox = inWalkBox;
});
// start a timer if the player ends a collision with a physics collider
Events.on(this.engine, 'collisionEnd', (event) => {
let pairs = event.pairs;
let otherBody;
// Iterate through collision pairs
for (var i = 0; i < pairs.length; i++) {
let pair = pairs[i];
// check if the collision involves the cat
if ( pair.bodyA.id == this.player.body.id )
otherBody = pair.bodyB;
else if ( pair.bodyB.id == this.player.body.id )
otherBody = pair.bodyA;
if (otherBody && !otherBody.isSensor && this.player.physicsCollisions == 0) {
this.player.collisionTimer.start();
// if the player jumps or slides upwards off a wall
if (this.player.body.velocity.y < 0 ){
this.player.setAnimation("jump", 5);
this.player.collisionTimer.stop();
this.player.isGrounded = false;
this.player.inSlide = false;
this.player.jumpInput = false;
}
// if the player falls
else if (this.player.body.velocity.y > 0 ){
// apply velocity from input when the player slides off a wall
if (this.buttonController){
if ( this.buttonController.buttons.get("right").pressed)
this.player.xVel = this.player.maxVel;
else if ( this.buttonController.buttons.get("left").pressed)
this.player.xVel = -this.player.maxVel;
}
else {
if ( this.player.lastInput == "right")
this.player.xVel = this.player.maxVel;
else if ( this.player.lastInput == "left")
this.player.xVel = -this.player.maxVel;
}
}
}
}
});
}
initInput(loader){
// pause menu ui elements
this.pauseMenu = new PauseMenu( loader.menuButtons,
loader.paletteTextures,
this.player.position,
this.animationContainer,
this.paletteSwap.filter,
this.player.animationContainer,
this.app.ticker,
this.catnipTrip.ticker);
this.buttonController = null;
// touch controller
if ( "ontouchstart" in document.documentElement ){
this.buttonController = new ButtonController(loader.buttonFrames,
this.player.position,
this.player.handleEvent.bind(this.player),
this.pauseMenu.handleEvent.bind(this.pauseMenu),
this.app.renderer.view
);
this.pauseMenu.attachController(this.buttonController);
}
// gamepad controller
this.GamepadInput = new GamepadController(this.player.handleEvent.bind(this.player),
this.pauseMenu.handleEvent.bind(this.pauseMenu),
this.pauseMenu,
this.app.ticker);
// keyboard
this.KBInput = new KBController(this.player, this.player.body, this.app.ticker, this.camera, this.pauseMenu);
}
/** resize and center canvas */
onWindowResize() {
// Get canvas parent node
const parent = this.app.view.parentNode;
// Resize the renderer
this.app.renderer.resize(parent.clientWidth, parent.clientHeight);
// Lock the camera to the cat's position
this.app.stage.position.set(this.app.screen.width/2, this.app.screen.height/2);
// resize shadow render texture
this.lightRenderTexture.resize(parent.clientWidth, parent.clientHeight)
// update static lights
this.tileMap.lights.forEach( ( light ) => {
light.update(this.app.ticker.speed);
this.staticLights.addChild(light.visionSource.mesh);
});
// resize old frames in the filtercache
this.filterCache.entries.forEach( entry => {
entry.texture.resize(parent.clientWidth, parent.clientHeight);
entry.texture.filterFrame = this.app.screen;
})
// move ui elements
this.pauseMenu.onResize();
}
} |
JavaScript | class SColor {
/**
* @name constructor
* @type Function
*
* Constructor
*
* @param {object} color The color description like (#ff0000 | rgba(...) | hsl(...) | hsv(...) | {r:255,r:140,b:23,a:40})
* @param {Object} [settings={}] The settings to configure the SColor instance. Here's the available settings:
* - returnNewInstance (false) {Boolean}: Specify if you want by default a new instance back when calling methods like "saturate", "desaturate", etc...
* - defaultFormat (hex) {String}: Specify the default format for this instance. This is used in the "toString" method for example...
* @return {object} The color instance
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
constructor(color, settings = {}) {
/**
* @name _originalSColor
* @type Object
* @private
*
* Original color value
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._originalSColor = null;
/**
* @name _r
* @type Number
* @private
*
* Internal red value
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._r = null;
/**
* @name _g
* @type Number
* @private
*
* Internal green value
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._g = null;
/**
* @name _b
* @type Number
* @private
*
* Internal blue value
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._b = null;
/**
* @name _a
* @type Number
* @private
*
* Internal alpha value
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._a = 1;
/**
* @name _settings
* @type Object
* @private
*
* Store the settings passed to the constructor. Here's the list of available settings:
* - returnNewInstance (false) {Boolean}: Specify if you want by default a new instance back when calling methods like "saturate", "desaturate", etc...
* - defaultFormat (hex) {String}: Specify the default format for this instance. This is used in the "toString" method for example...
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
this._settings = {};
// save the instance settings
this._settings = __deepMerge({
returnNewInstance: false,
defaultFormat: 'hex'
}, settings);
// get the actual real color
color = this.getColor(color);
// save the original color
this._originalSColor = color;
// parse the input color to
// split into rgba values
this._parse(color);
}
/**
* @name getColor
* @type Function
*
* This method take as parameter the passed color to the constructor and has to return the
* actual real color like color from the static colors listed in the SColor class or maybe
* from the Sugar configured colors
*/
getColor(color) {
// try to get the color from the map
if (typeof color == 'string' && SColor.colors[color.toLowerCase()]) {
return SColor.colors[color.toLowerCase()];
}
// return the passed color
return color;
}
/**
* @name _parse
* @type Function
* @private
*
* Parse
*
* @param {object} color The color to parse like (#ff0000 | rgba(...) | hsl(...) | hsv(...) | {r:255,r:140,b:23,a:40})
* @return {object} The rgba representation of the passed color
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
_parse(color) {
// parse the color
color = __convert(color, 'rgba');
// assign new color values
this.r = color.r;
this.g = color.g;
this.b = color.b;
this.a = color.a;
// return the parsed color
return color;
}
/**
* @name convert2
* @type Function
* @private
*
* Concert color
*
* @param {string} format The format wanted as output like (rgba,hsl,hsv and hex)
* @values rgba, hsl, hsv, hex
* @return {object} The color in wanted object format
*
* @example js
* myColor._convert2('rgba');
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
_convert2(format) {
switch (format) {
case 'rgba':
return {
r: this.r,
g: this.g,
b: this.b,
a: this.a
};
break;
case 'hsl':
return __rgba2hsl(this.r, this.g, this.b, this.a);
break;
case 'hsv':
return __rgba2hsv(this.r, this.g, this.b, this.a);
break;
case 'hex':
return __rgba2hex(this.r, this.g, this.b, this.a);
break;
}
}
/**
* @name toHex
* @type Function
*
* To hex
*
* @return {string} The hex string representation
*
* @example js
* myColor.toHex();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHex() {
return this._convert2('hex');
}
/**
* @name toHsl
* @type Function
*
* To hsl
*
* @return {object} The hsl object representation
*
* @example js
* myColor.toHsl();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHsl() {
return this._convert2('hsl');
}
/**
* @name toHsv
* @type Function
*
* To hsv
*
* @return {object} The hsv object representation
*
* @example js
* myColor.toHsv();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHsv() {
return this._convert2('hsv');
}
/**
* @name toRgba
* @type Function
*
* To rgba
*
* @return {object} The rgba object representation
*
* @example js
* myColor.toRgba();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toRgba() {
return this._convert2('rgba');
}
/**
* @name r
* @type Number
*
* Get/set the red value
*
* @example js
* myColor.r;
* myColor.r = 128;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get r() {
return this._r;
}
set r(value) {
value = parseInt(value);
value = value > 255 ? 255 : value;
this._r = value;
}
/**
* @name g
* @type Number
*
* Get/set the green value
*
* @example js
* myColor.g;
* myColor.g = 20;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get g() {
return this._g;
}
set g(value) {
value = parseInt(value);
value = value > 255 ? 255 : value;
this._g = value;
}
/**
* @name b
* @type Number
*
* Get/set the blue value
*
* @example js
* myColor.b;
* myColor.b = 30;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get b() {
return this._b;
}
set b(value) {
value = parseInt(value);
value = value > 255 ? 255 : value;
this._b = value;
}
/**
* @name a
* @type Number
*
* Get/set the alpha value
*
* @example js
* myColor.a;
* myColor.a = 20;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get a() {
return this._a;
}
set a(value) {
value = parseFloat(value);
value = value > 1 ? (1 / 100) * value : value;
value = value > 1 ? 1 : value;
this._a = value;
}
/**
* @name l
* @type Number
*
* The luminence value
*
* @example js
* myColor.l;
* myColor.l = 10;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get l() {
return this._convert2('hsl').l;
}
set l(value) {
const hsl = this._convert2('hsl');
value = parseInt(value);
value = value > 100 ? 100 : value;
hsl.l = value;
const rgba = __hsl2rgba(hsl.h, hsl.s, hsl.l);
this.r = rgba.r;
this.g = rgba.g;
this.b = rgba.b;
}
/**
* @name s
* @type Number
*
* The saturation value
*
* @example js
* myColor.s;
* myColor.s = 20;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get s() {
return this._convert2('hsl').s;
}
set s(value) {
const hsl = this._convert2('hsl');
value = parseInt(value);
value = value > 100 ? 100 : value;
hsl.s = value;
const rgba = __hsl2rgba(hsl.h, hsl.s, hsl.l);
this.r = rgba.r;
this.g = rgba.g;
this.b = rgba.b;
}
/**
* @name v
* @type Number
*
* The value of the HSV format
*
* @example js
* myColor.v;
* myColor.v = 20;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get v() {
return this._convert2('hsv').v;
}
set v(value) {
const hsv = this._convert2('hsv');
value = parseInt(value);
value = value > 100 ? 100 : value;
hsv.v = value;
const rgba = __hsv2rgba(hsv.h, hsv.s, hsv.v);
this.r = rgba.r;
this.g = rgba.g;
this.b = rgba.b;
}
/**
* @name h
* @type Number
*
* Get/set the hue
*
* @example js
* myColor.h;
* myColor.h = 30;
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
get h() {
return this._convert2('hsl').h;
}
set h(value) {
const hsl = this._convert2('hsl');
value = parseInt(value);
value = value > 360 ? 360 : value;
hsl.h = value;
const rgba = __hsl2rgba(hsl.h, hsl.s, hsl.l);
this.r = rgba.r;
this.g = rgba.g;
this.b = rgba.b;
}
/**
* @name reset
* @type Function
*
* Reset to the original color
*
* @example js
* myColor.reset();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
reset() {
// parse again the color
this._parse(this._originalSColor);
}
/**
* @name desaturate
* @type Function
*
* Desaturate
*
* @param {Number} amount The amount of desaturation wanted between 0-100
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.desaturate(20);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
desaturate(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseInt(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.s -= amount;
return n;
}
this.s -= amount;
return this;
}
/**
* @name saturate
* @type Function
*
* Saturate
*
* @param {Number} amount The amount of saturation wanted between 0-100
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.saturate(20);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
saturate(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseInt(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.s += amount;
return n;
}
this.s += amount;
return this;
}
/**
* @name grayscale
* @type Function
*
* Return a new SColor instance of the color to grayscale
*
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.grayscale();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
grayscale(returnNewInstance = this._settings.returnNewInstance) {
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.s = 0;
return n;
}
this.s = 0;
return this;
}
/**
* @name spin
* @type Function
*
* Spin the hue on the passed value (max 360)
*
* @param {Number} amount The amount of hue spin wanted between 0-360
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.spin(230);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
spin(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseInt(amount);
const hue = this.h;
let newHue = hue + amount;
if (newHue > 360) {
newHue -= 360;
}
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.h = newHue;
return n;
}
this.h = newHue;
return this;
}
/**
* @name transparentize
* @type Function
*
* Transparentize
*
* @param {Number} amount The amount of transparence to apply between 0-100|0-1
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.transparenize(30);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
transparentize(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseFloat(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.a -= amount;
return n;
}
this.a -= amount;
return this;
}
/**
* @name alpha
* @type Function
*
* Set the alpha
*
* @param {Number} alpha The new alpha value to apply between 0-100|0-1
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.alpha(10);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
alpha(alpha, returnNewInstance = this._settings.returnNewInstance) {
alpha = parseFloat(alpha);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.a = alpha;
return n;
}
this.a = alpha;
return this;
}
/**
* @name opacity
* @type Function
*
* Set the opacity (alias for alpha)
*
* @param {Number} opacity The new opacity value to apply between 0-100|0-1
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.opacity(20);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
opacity(opacity, returnNewInstance = this._settings.returnNewInstance) {
return this.alpha(opacity, returnNewInstance);
}
/**
* @name opacify
* @type Function
*
* Opacify
*
* @param {Number} amount The amount of transparence to remove between 0-100|0-1
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.opacify(18);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
opacify(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseFloat(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.a += amount;
return n;
}
this.a += amount;
return this;
}
/**
* @name darken
* @type Function
*
* Darken
*
* @param {Number} amount The amount of darkness (of the nightmare of the shadow) to apply between 0-100
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.darken(20);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
darken(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseInt(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.l -= amount;
return n;
}
this.l -= amount;
return this;
}
/**
* @name lighten
* @type Function
*
* Lighten
*
* @param {Number} amount The amount of lightness (of the sky of the angels) to apply between 0-100
* @param {Boolean} [returnNewInstance=this._settings.returnNewInstance] Specify if you want back a new SColor instance of the actual one
* @return {SColor} A new SColor instance or the actual one
*
* @example js
* myColor.lighten(20);
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
lighten(amount, returnNewInstance = this._settings.returnNewInstance) {
amount = parseInt(amount);
if (returnNewInstance) {
const n = new SColor(this.toHex());
n.l += amount;
return n;
}
this.l += amount;
return this;
}
/**
* @name toHexString
* @type Function
*
* To hex string
*
* @return {string} The hex string representation of the color
*
* @example js
* myColor.toHexString();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHexString() {
return this._convert2('hex');
}
/**
* @name toRgbaString
* @type Function
*
* To rgba string
*
* @return {string} The rgba string representation of the color
*
* @example js
* myColor.toRgbaString();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toRgbaString() {
return `rgba(${this._r},${this._g},${this._b},${this._a})`;
}
/**
* @name toHslString
* @type Function
*
* To hsl string
*
* @return {string} The hsl string representation of the color
*
* @example js
* myColor.toHslString();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHslString() {
const hsl = this._convert2('hsl');
return `hsl(${hsl.h},${hsl.s},${hsl.l})`;
}
/**
* @name toHsvString
* @type Function
*
* To hsv string
*
* @return {string} The hsv string representation of the color
*
* @example js
* myColor.toHsvString();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toHsvString() {
const hsv = this._convert2('hsv');
return `hsv(${hsv.h},${hsv.s},${hsv.v})`;
}
/**
* @name toString
* @type Function
*
* To string
*
* @param {String} [format=this._settings.defaultFormat] The format you want back
* @values hex,hsl,hsv,rgba
* @return {string} The rgba string representation of the color
*
* @example js
* myColor.toString();
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
toString(format = this._settings.defaultFormat) {
switch (format) {
case 'hex':
return this.toHexString();
break;
case 'hsl':
return this.toHslString();
break;
case 'hsv':
return this.toHsvString();
break;
case 'rgba':
default:
return this.toRgbaString();
break;
}
}
} |
JavaScript | class PagerDutyImplementer {
/**
* Constructor to PagerDuty incidents
*
* @param {Object} params
*
* @constructor
*/
constructor(params, infraAlert) {
const oThis = this;
oThis.highSeverityApiKey = params.highSeverityApiKey;
oThis.mediumSeverityApiKey = params.mediumSeverityApiKey;
oThis.highSeverityInfraApiKey = params.highSeverityInfraApiKey;
oThis.mediumSeverityInfraApiKey = params.mediumSeverityInfraApiKey;
oThis.infraAlert = infraAlert;
}
/**
* Call pagerDuty create for high severity errors.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async createHighSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
let key = (oThis.infraAlert ? oThis.highSeverityInfraApiKey : oThis.highSeverityApiKey);
const pager = new PagerDuty(key);
return new Promise(function (resolve, reject) {
pager
.trigger(incidentKey, description, null)
.then((data) => {
console.log(FgGreen, 'Incident creation triggered!', defColor);
resolve(data);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
reject(err);
});
});
// return pager
// .trigger(incidentKey, description, null)
// .then(() => {
// console.log(FgGreen, 'Incident creation triggered!', defColor);
// })
// .catch((err) => {
// console.log(FgRed, 'Error:', err, defColor);
// });
}
/**
* Call pagerDuty create for medium severity errors.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async createMediumSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
let key = (oThis.infraAlert ? oThis.mediumSeverityInfraApiKey : oThis.mediumSeverityApiKey);
const pager = new PagerDuty(key);
return pager
.trigger(incidentKey, description, null)
.then(() => {
console.log(FgGreen, 'Incident creation triggered!', defColor);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
});
}
/**
* Call pagerDuty acknowledge for high severity.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async acknowledgeHighSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
const pager = new PagerDuty(oThis.highSeverityApiKey);
return pager
.acknowledge(incidentKey, description, null)
.then((data) => {
console.log(FgGreen, 'Incident creation acknowledged!', defColor);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
});
}
/**
* Call pagerDuty acknowledge for medium severity.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async acknowledgeMediumSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
const pager = new PagerDuty(oThis.mediumSeverityApiKey);
return pager
.acknowledge(incidentKey, description, null)
.then((data) => {
console.log(FgGreen, 'Incident creation acknowledged!', defColor);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
});
}
/**
* Call pagerDuty resolve for high severity errors.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async resolveHighSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
const pager = new PagerDuty(oThis.highSeverityApiKey);
return pager
.resolve(incidentKey, description, null)
.then(() => {
console.log(FgGreen, 'Incident resolve triggered!', defColor);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
});
}
/**
* Call pagerDuty resolve for medium severity errors.
*
* @param {String} incidentKey
* @param {String} description
*
* @return {Promise<*>}
*/
async resolveMediumSeverityPagerDutyIncident(incidentKey, description) {
const oThis = this;
const pager = new PagerDuty(oThis.mediumSeverityApiKey);
return pager
.resolve(incidentKey, description, null)
.then(() => {
console.log(FgGreen, 'Incident resolve triggered!', defColor);
})
.catch((err) => {
console.log(FgRed, 'Error:', err, defColor);
});
}
} |
JavaScript | class Typeahead extends Component {
static propTypes = {
customClasses: PropTypes.object,
maxVisible: PropTypes.number,
options: PropTypes.array,
header: PropTypes.string,
searchIcon: PropTypes.object,
datatype: PropTypes.string,
defaultValue: PropTypes.string,
placeholder: PropTypes.string,
onOptionSelected: PropTypes.func,
onSubmit: PropTypes.func,
onKeyDown: PropTypes.func,
fetchLazyOption: PropTypes.func,
updateHeader: PropTypes.func,
className: PropTypes.string,
typeHeadSelectorLeft: PropTypes.number,
typeHeadTokenCollectionSelectorLeft: PropTypes.object,
typeHeadJustCheckSelectorLeft: PropTypes.object,
typeaheadRef: PropTypes.number,
setStaticWidth: PropTypes.bool,
}
static defaultProps = {
options: [],
header: 'Category',
datatype: 'text',
customClasses: {},
defaultValue: '',
placeholder: '',
onKeyDown() { return; },
onOptionSelected() { },
onSubmit() { },
}
constructor(...args) {
super(...args);
this._onTextEntryUpdated = this._onTextEntryUpdated.bind(this);
this._onKeyDown = this._onKeyDown.bind(this);
this._onBlur = this._onBlur.bind(this);
this._onFocus = this._onFocus.bind(this);
this._onOptionSelected = this._onOptionSelected.bind(this);
this._onSearchOptionSelected = this._onSearchOptionSelected.bind(this);
this._handleDateChange = this._handleDateChange.bind(this);
this._onEnter = this._onEnter.bind(this);
this._onEscape = this._onEscape.bind(this);
this._onTab = this._onTab.bind(this);
// this._addTokenForValue = this._addTokenForValue.bind( this );
}
state = {
// The set of all options... Does this need to be state? I guess for lazy load...
options: this.props.options,
header: this.props.header,
datatype: this.props.datatype,
typeHeadSelectorLeft: this.props.typeHeadSelectorLeft,
typeHeadTokenCollectionSelectorLeft: this.props.typeHeadTokenCollectionSelectorLeft,
typeHeadJustCheckSelectorLeft: this.props.typeHeadJustCheckSelectorLeft,
focused: false,
// The currently visible set of options
visible: this.getOptionsForValue(this.props.defaultValue, this.props.options),
// This should be called something else, "entryValue"
entryValue: this.props.defaultValue,
// A valid typeahead value
selection: null,
displayColorPicker: false
}
componentWillReceiveProps(nextProps) {
this.setState({
options: nextProps.options,
header: nextProps.header,
datatype: nextProps.datatype,
typeHeadSelectorLeft: nextProps.typeHeadSelectorLeft,
typeHeadTokenCollectionSelectorLeft: nextProps.typeHeadTokenCollectionSelectorLeft,
typeHeadJustCheckSelectorLeft: nextProps.typeHeadJustCheckSelectorLeft,
visible: this.getOptionsForValue(this.state.entryValue, nextProps.options),
});
}
componentDidUpdate(prevProps) {
if (prevProps.typeaheadRef !== this.props.typeaheadRef) {
this.forceUpdate();
}
}
getOptionsForValue(value, options) {
// let result = fuzzy
// .filter( value, options )
// .map( res => res.string );
let result = options;
if (this.state && this.state.header === 'Category' && value) {
const valueSearch = (value && typeof value === 'string') ? value.toLowerCase() : value;
result = options.filter(itm => {
return (itm.text.toLowerCase().indexOf(valueSearch) !== -1)
});
}
if (this.props.maxVisible) {
result = result.slice(0, this.props.maxVisible);
}
result = result.map(itm => ({ value: itm.value, text: itm.text, image: itm.image, icon: itm.icon, username: itm.username }));
return result;
}
setEntryText(value) {
if (this.refs.entry != null) {
ReactDOM.findDOMNode(this.refs.entry).value = value;
}
this._onTextEntryUpdated();
}
_renderIncrementalSearchResults() {
if (!this.state.focused) {
return '';
}
// Something was just selected
if (this.state.selection) {
return '';
}
// There are no typeahead / autocomplete suggestions
/* if (!this.state.visible.length) {
return '';
} */
return (
<TypeaheadSelector
ref="sel"
options={this.state.visible}
typeHeadSelectorLeft={this.state.typeHeadSelectorLeft}
typeHeadTokenCollectionSelectorLeft={this.state.typeHeadTokenCollectionSelectorLeft}
typeHeadJustCheckSelectorLeft={this.state.typeHeadJustCheckSelectorLeft}
typeHeadInputSelectorLeft={(this.refs.input) ? this.refs.input.offsetLeft : this.refs.input.offsetLeft}
header={this.state.header}
onOptionSelected={this._onOptionSelected}
onSearchOptionSelected={this._onSearchOptionSelected}
customClasses={this.props.customClasses}
/>
);
}
_onOptionSelected(option) {
const nEntry = ReactDOM.findDOMNode(this.inputRef());
nEntry.focus();
nEntry.value = typeof option === 'string' ? option : option.value;
this.setState({
visible: this.getOptionsForValue(option, this.state.options),
selection: option,
entryValue: option,
typeHeadSelectorLeft: this.props.typeHeadSelectorLeft,
typeHeadTokenCollectionSelectorLeft: this.props.typeHeadTokenCollectionSelectorLeft,
typeHeadJustCheckSelectorLeft: this.props.typeHeadJustCheckSelectorLeft
});
this.props.onOptionSelected(option);
if (this.refs.sel && this.refs.sel.setSelectionIndex) {
this.refs.sel.setSelectionIndex(null);
}
this._onFocus();
}
_onSearchOptionSelected(option) {
const nEntry = ReactDOM.findDOMNode(this.inputRef());
const SearchOption = option;
nEntry.focus();
nEntry.value = "";
SearchOption.value = this.state.entryValue;
if(SearchOption && SearchOption.text === "Search for this text"){
if(SearchOption.value.trim() === ""){
return;
}
}
this.props.onOptionSelected(SearchOption);
if (this.refs.sel && this.refs.sel.setSelectionIndex) {
this.refs.sel.setSelectionIndex(null);
}
this._onFocus();
}
_onTextEntryUpdated() {
let value = '';
if (this.refs.entry != null) {
value = ReactDOM.findDOMNode(this.refs.entry).value;
}
if (this.state.header === 'Value' && this.props.fetchLazyOption) {
this.props.fetchLazyOption(value);
}
this.setState({
visible: this.getOptionsForValue(value, this.state.options),
selection: null,
entryValue: value,
});
}
_onEnter(event) {
if (!this.refs.sel.state.selection && this.refs.sel.state.selectionIndex === null) {
if (this.state.entryValue && this.state.entryValue !== "" && this.state.header === "Category" && this.state.entryValue.trim() !== "") {
this._onOptionSelected({ text: "Search for this text", value: this.state.entryValue, image: undefined, icon: undefined, username: undefined });
return this.props.onKeyDown(event);
}
if (this.props.onSubmit && this.state.header === "Category") {
this.props.onSubmit();
}
return this.props.onKeyDown(event);
} else if (!this.refs.sel.state.selection && this.refs.sel.state.selectionIndex !== null && this.state.header === "Category") {
if(this.state.entryValue && this.state.entryValue !== "" && this.state.entryValue.trim() !== ""){
this._onOptionSelected({ text: "Search for this text", value: this.state.entryValue, image: undefined, icon: undefined, username: undefined });
}
return this.props.onKeyDown(event);
}
this._onOptionSelected(this.refs.sel.state.selection);
}
_onEscape() {
this.refs.sel.setSelectionIndex(null);
}
_onTab() {
const option = this.refs.sel.state.selection ?
this.refs.sel.state.selection : this.state.visible[0];
this._onOptionSelected(option);
}
eventMap() {
const events = {};
events[KeyEvent.DOM_VK_UP] = this.refs.sel.navUp;
events[KeyEvent.DOM_VK_DOWN] = this.refs.sel.navDown;
events[KeyEvent.DOM_VK_RETURN] = events[KeyEvent.DOM_VK_ENTER] = this._onEnter;
events[KeyEvent.DOM_VK_ESCAPE] = this._onEscape;
events[KeyEvent.DOM_VK_TAB] = this._onTab;
return events;
}
_onKeyDown(event) {
// If Enter pressed
if (event.keyCode === KeyEvent.DOM_VK_RETURN || event.keyCode === KeyEvent.DOM_VK_ENTER) {
// If no options were provided so we can match on anything
if (this.props.options.length === 0 && (this.props.datatype !== 'textoptions' && this.props.datatype !== 'textcompareoptions') && this.state.entryValue) {
this._onOptionSelected(this.state.entryValue);
}
// If what has been typed in is an exact match of one of the options
if (this.props.options.indexOf(this.state.entryValue) > -1) {
this._onOptionSelected(this.state.entryValue);
}
}
// If there are no visible elements, don't perform selector navigation.
// Just pass this up to the upstream onKeydown handler
if (!this.refs.sel) {
return this.props.onKeyDown(event);
}
const handler = this.eventMap()[event.keyCode];
if (handler) {
handler(event);
} else {
return this.props.onKeyDown(event);
}
// Don't propagate the keystroke back to the DOM/browser
event.preventDefault();
}
_onBlur(event) {
// If Enter pressed
// If no options were provided so we can match on anything
if (this.props.options.length === 0 && (this.props.datatype !== 'textoptions' && this.props.datatype !== 'textcompareoptions') && this.state.entryValue) {
this._onOptionSelected(this.state.entryValue);
}
// If what has been typed in is an exact match of one of the options
if (this.props.options.indexOf(this.state.entryValue) > -1) {
this._onOptionSelected(this.state.entryValue);
}
// If there are no visible elements, don't perform selector navigation.
// Just pass this up to the upstream onKeydown handler
if (!this.refs.sel) {
return this.props.onKeyDown(event);
}
const handler = this.eventMap()[event.keyCode];
if (handler) {
handler(event);
} else {
return this.props.onKeyDown(event);
}
// Don't propagate the keystroke back to the DOM/browser
event.preventDefault();
}
_onFocus() {
this.setState({ focused: true });
this.props.updateHeader();
}
handleClickOutside() {
this.setState({ focused: false });
}
isDescendant(parent, child) {
let node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
_handleDateChange(date) {
let newDate = moment(date, 'YYYY-MM-DD');
if (!newDate.isValid()) newDate = moment();
this.props.onOptionSelected(newDate.format('YYYY-MM-DD'));
}
_showDatePicker() {
if (this.state.datatype === 'date') {
return true;
}
return false;
}
_showColorPicker() {
if (this.state.datatype === 'color') {
return true;
}
return false;
}
inputRef() {
if (this._showDatePicker()) {
return this.refs.datepicker.input;
}
return this.refs.entry;
}
handleChangeColor = (color) => {
this.props.onOptionSelected(color.hex);
this.props.updateHeader();
const nEntry = ReactDOM.findDOMNode(this.inputRef());
nEntry.focus();
// this._onFocus();
};
render() {
const inputClasses = {};
inputClasses[this.props.customClasses.input] = !!this.props.customClasses.input;
let inputClassList = classNames(inputClasses);
let dateClassName = '';
if (this.state.focused || this.props.setStaticWidth) {
inputClassList += ' filter-tokenizer-text-input-width';
dateClassName = 'filter-tokenizer-text-input-width';
}
const classes = {
typeahead: true,
};
classes[this.props.className] = !!this.props.className;
const classList = classNames(classes);
if (this._showDatePicker()) {
/* let left = 0;
if (this.refs.datepicker && this.refs.datepicker.offsetLeft) {
left = this.refs.datepicker.offsetLeft;
}
console.log(this.refs.input);
console.log(this.refs.input.offsetLeft);
if (left > this.state.typeHeadTokenCollectionSelectorLeft.current.clientWidth) {
// hardcoded xpos input
this.state.typeHeadTokenCollectionSelectorLeft.current.scrollTo(50000, 0);
left = this.state.typeHeadJustCheckSelectorLeft.current.clientWidth + this.state.typeHeadJustCheckSelectorLeft.current.getBoundingClientRect().left + 8;
} */
let defaultDate = moment(this.state.entryValue, 'YYYY-MM-DD');
if (!defaultDate.isValid()) defaultDate = moment();
return (
<span
ref="input"
className={classList}
onFocus={this._onFocus}
>
<DatePicker
ref="datepicker"
selected={this.state.startDate}
onChange={this.handleChange}
defaultValue={defaultDate}
dateFormat={"YYYY-MM-DD"}
onChange={this._handleDateChange}
open={this.state.focused}
onKeyDown={this._onKeyDown}
/>
{/* <div style={{ left }}>
<Datetime
style={{ left }}
ref="datepicker"
dateFormat={"YYYY-MM-DD"}
timeFormat={false}
inputProps={{ className: inputClassList }}
defaultValue={defaultDate}
onChange={this._handleDateChange}
open={this.state.focused}
/>
</div> */}
</span>
);
}
let left = 0;
let styles = {};
if (this._showColorPicker()) {
if (this.refs.input && this.refs.input.offsetLeft) {
left = this.refs.input.offsetLeft;
}
if (this.state.typeHeadTokenCollectionSelectorLeft && this.state.typeHeadTokenCollectionSelectorLeft.current) {
if (left > this.state.typeHeadTokenCollectionSelectorLeft.current.clientWidth) {
// dummy x calculation
this.state.typeHeadTokenCollectionSelectorLeft.current.scrollTo(50000, 0);
left = this.state.typeHeadJustCheckSelectorLeft.current.clientWidth + this.state.typeHeadJustCheckSelectorLeft.current.getBoundingClientRect().left + 8;
}
}
styles = {
popover: {
position: 'absolute',
zIndex: '2',
left: left
}
}
}
const colors = ['#ff8080', '#ff8097', '#ff80ae', '#ff80c6', '#ff80dd', '#ff80f4', '#f280ff', '#db80ff', '#c480ff', '#ac80ff', '#9580ff', '#8082ff', '#8099ff', '#80b0ff', '#80c8ff', '#80dfff', '#80f7ff', '#80fff0', '#80ffd9', '#80ffc1', '#80ffaa', '#80ff93', '#84ff80', '#9bff80', '#b3ff80', '#caff80', '#e1ff80', '#f9ff80', '#ffee80', '#ffd780', '#ffbf80', '#bfbfbf']
return (
<span
ref="input"
className={classList}
onFocus={this._onFocus}
>
<input
ref="entry"
type="text"
autoFocus={this.state.focused}
placeholder={this.props.placeholder}
className={inputClassList}
defaultValue={this.state.entryValue}
onChange={this._onTextEntryUpdated}
onKeyDown={this._onKeyDown}
onBlur={this._onBlur}
/>
{this._showColorPicker() ? <div style={styles.popover}>
<div />
<BlockPicker color={this.state.entryValue || 'transparent'} colors={colors} onChange={this.handleChangeColor} width={268} />
</div> : null}
{this.props.searchIcon && (
<div className="input-group-append">
<span className="input-group-text"> {this.props.searchIcon}</span>
</div>
)}
{this._renderIncrementalSearchResults()}
</span>
);
}
} |
JavaScript | class DecryptionResult {
constructor(event, senderCurve25519Key, claimedKeys) {
this.event = event;
this.senderCurve25519Key = senderCurve25519Key;
this.claimedEd25519Key = claimedKeys.ed25519;
this._device = null;
this._roomTracked = true;
}
setDevice(device) {
this._device = device;
}
setRoomNotTrackedYet() {
this._roomTracked = false;
}
get isVerified() {
if (this._device) {
const comesFromDevice = this._device.ed25519Key === this.claimedEd25519Key;
return comesFromDevice;
}
return false;
}
get isUnverified() {
if (this._device) {
return !this.isVerified;
} else if (this.isVerificationUnknown) {
return false;
} else {
return true;
}
}
get isVerificationUnknown() {
// verification is unknown if we haven't yet fetched the devices for the room
return !this._device && !this._roomTracked;
}
} |
JavaScript | class HistoryScene extends IMPComponent {
constructor(props) {
super(props)
this.state = {
loaded: false,
historyData: [],
month: moment(new Date()).month() + 1,
year: moment(new Date()).year()
}
}
componentDidMount() {
super.componentDidMount()
this._fetchData(this.state.month, this.state.year)
}
_goBack() {
if(!Config.debug)
Sentry.addNavigationBreadcrumb(this._className, 'HistoryScene', 'MainScene')
this.navigator.pop()
}
_hardwareBackHandler() {
this._goBack()
return true
}
/**
* Fetch server data needed to render the page
* @memberof
* @returns {undefined}
*/
_fetchData() {
this.setState({
loaded: false
})
const sessionState = Session.getState()
Api.fetchHistory(
sessionState.userData.user.centre_id,
this.state.year,
this.state.month,
sessionState.userData._token
)
.then((data) => {
setTimeout(() => {
this.setState({
historyData: data,
loaded: true
})
},Config.sceneTransitionMinumumTime)
})
.catch((error) => {
if(Config.debug) {
IMPLog.error(error.toString(),this._fileName)
}
Alert.alert(
Config.errorMessage.network.title,
Config.errorMessage.network.message,
[{text: "Okay"}]
)
})
}
nextMonth () {
// get current month/year
const currentMoment = moment(new Date(this.state.year, this.state.month - 1))
// add one month
const nextMonthMoment = currentMoment.add(1,'M')
// set state to these new values
this.setState({
month: nextMonthMoment.month() + 1,
year: nextMonthMoment.year()
})
this._fetchData()
}
previousMonth () {
// get current month/year
const currentMoment = moment(new Date(this.state.year, this.state.month - 1))
// subtract one month
const nextMonthMoment = currentMoment.subtract(1,'M')
// set state to these new values
this.setState({
month: nextMonthMoment.month() + 1,
year: nextMonthMoment.year()
})
this._fetchData()
}
/**
* Convert the api data to a more appropriate form
*/
reformatHistory (z) {
let days = []
// First create an object for each day
z.forEach( (x, i) => {
const dayOfMonth = moment(x.attendance_date).date()
days[dayOfMonth] = {
day: dayOfMonth,
absent: [],
present: []
}
})
// Populate by sorting between absent and present
z.forEach((x, i) => {
const entry = {class_name: x.class_name, given_name: x.given_name, family_name: x.family_name}
const dayOfMonth = moment(x.attendance_date).date()
if(x.attended === 1) {
days[dayOfMonth].present.push(entry)
} else {
days[dayOfMonth].absent.push(entry)
}
})
return days
}
/**
* @returns {Component} MonthNavButtons
*/
MonthNavButtons = () =>
(<View style={{flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', margin: 10}}>
<View style={{flex: 1, marginLeft: 5, marginRight: 5, marginTop: 10, marginBottom: 10}}>
<Button text="Previous Month" style={{fontSize: FontSizes.xSmall}} onPress={ () => this.previousMonth()}/>
</View>
{ // What is one month in the future in relation to the current page view ?
moment(new Date()).add(1,'M').diff(moment(new Date(this.state.year, this.state.month + 1))) >= 0 ?
(<View style={{flex: 1, marginLeft: 5, marginRight: 5, marginTop: 10, marginBottom: 10}}>
<Button text="Next Month" style={{fontSize: FontSizes.xSmall}} onPress={ () => this.nextMonth()}/>
</View>)
:
null }
</View>)
/**
* Make an array of HistoryDayItem components based on
* z (data), month and year.
* @param {Array} z - data
* @param {number} month - The month
* @param {number} year - The year
* @returns {Array} components - An array containing the resulting components
*/
makeHistoryDayItems = (z, month, year) =>
z.map((x) =>
(<HistoryDayItem
key={x.day}
day={x.day}
month={month}
absentChildren={x.absent}
totalChildren={(x.absent.length + x.present.length)}
/>)
)
/**
* Create either an array of HistoryDayItem components or a
* text component informing the user that there was no data.
*/
makeMainView = () => {
const items = this.makeHistoryDayItems(this.reformatHistory(this.state.historyData), this.state.month, this.state.year)
if(items.length > 0) {
return items
} else {
return (
<Text>No attendance data was recorded for this month</Text>
)
}
}
render() {
super.render()
return (
<View style={{flex: 1}}>
<AndroidBackButton onPress={ () => this._hardwareBackHandler()}/>
<NavBar
navigator={ this.props.navigator }
leftButtonAction={ () => this._goBack() }
/>
<ScrollableWaitableView loaded={this.state.loaded}>
<SceneHeading text="Attendance History"/>
<FormHeading text={moment().year(this.state.year).month(this.state.month - 1).format("MMMM YYYY")}/>
<View style={{flex: 1, marginLeft: 15}}>
{this.makeMainView()}
</View>
<this.MonthNavButtons/>
</ScrollableWaitableView>
</View>
)
}
} |
JavaScript | class RegistryClientConnection {
/**
* Create entity
* @param {string} name
*/
constructor(name) {
this._name = name;
this._server = null; // boolean flag
this._connected = 0; // peers connected
}
/**
* Service name is 'entities.registryClientConnection'
* @type {string}
*/
static get provides() {
return 'entities.registryClientConnection';
}
/**
* Dependencies as constructor arguments
* @type {string[]}
*/
static get requires() {
return [];
}
/**
* Name getter
* @type {string}
*/
get name() {
return this._name;
}
/**
* Server setter
* @param {boolean} server
*/
set server(server) {
this._server = server;
}
/**
* Server getter
* @type {boolean}
*/
get server() {
return this._server;
}
/**
* Connected setter
* @param {number} connected
*/
set connected(connected) {
this._connected = connected;
}
/**
* Connected getter
* @type {number}
*/
get connected() {
return this._connected;
}
} |
JavaScript | class Source {
constructor(index) {
// Web UI info
this.index = index;
this.rgbValueString = rgbValueStrings[index];
this.selected = true;
// Source info
this.id = null;
this.active = false;
this.x = null;
this.y = null;
this.z = null;
}
} |
JavaScript | class PotentialSource {
constructor() {
this.e = null;
this.x = null;
this.y = null;
this.z = null;
}
} |
JavaScript | class DataFrame {
constructor() {
this.timestamp = null;
this.ptimestamp = null;
this.sources = [];
rgbValueStrings.forEach(function (color,i) {
this.sources.push(new Source(i));
}.bind(this));
this.potentialSources = [];
}
} |
JavaScript | class ChipsInputExample {
constructor() {
this.visible = true;
this.selectable = true;
this.removable = true;
this.addOnBlur = true;
this.separatorKeysCodes = [ENTER, COMMA];
this.fruits = [
{ name: 'Lemon' },
{ name: 'Lime' },
{ name: 'Apple' },
];
}
add(event) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push({ name: value.trim() });
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(fruit) {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
} |
JavaScript | class FileSystem {
/**
* Generate a random cryptographic filename with
* @method generateRandomFilename
*/
static generateRandomFilename(extension) {
// create pseudo random bytes
const bytes = crypto.pseudoRandomBytes(32);
// create the md5 hash of the random bytes
const checksum = crypto.createHash("MD5").update(bytes).digest("hex");
// return as filename the hash with the output extension
return checksum;
}
static getBase64Extension(data){
if(data.search("data:image/png;base64,") > -1){
return "png";
}else if(data.search("data:image/jpeg;base64,") > -1){
return "jpeg";
}
}
} |
JavaScript | class Luckt {
/**
*
* @param {StoreProperties} props
*/
constructor(props) {
this.state = props.state;
this.getters = {};
const acts = props.acts;
const futures = props.futures;
const watchers = {};
for (const key in props.getters)
Object.defineProperty(this.getters, key, { get: () => props.getters[key](this.state, this.getters) });
/**
*
* @param {string} act
* @param {...any} args
*/
this.commit = function (act, ...args) {
acts[act](this.state, ...args);
// Dispatch the watchers
if (watchers[act])
for (let i = 0; i < watchers[act].length; ++i)
watchers[act][i]();
}
/**
*
* @param {string} future
* @param {...any} args
*/
this.promise = function (future, ...args) {
futures[future](this.commit.bind(this), ...args);
}
/**
*
* @param {string} act
* @param {() => void} callback
* @param {boolean} prepend
* @returns
*/
this.watch = (act, callback, prepend) => {
if (!watchers[act]) watchers[act] = [];
if (prepend) watchers[act].unshift(callback);
else watchers[act].push(callback);
return () => {
const index = watchers[act].indexOf(callback);
if (index !== -1) watchers[act].splice(index, 1);
}
}
}
} |
JavaScript | class Icons {
/**
* Return the svg icons list
*
* @returns {object} Svg icons object
*/
static iconsSvg() {
return icons;
}
/**
* Return the svg icons list
*
* @returns {object} Svg icons object
*/
static icons() {
const r = {};
Object.keys(icons).forEach((key) => {
r[key] = key;
});
return r;
}
/**
* Return a list of icons (key / value)
*
* @returns {object} The icons under Key / Value format
*/
static list() {
return this.icons();
}
} |
JavaScript | class CharacterReputations {
constructor(blizzardApi) {
this.blizzardApi = blizzardApi;
}
/**
* Returns a summary of a character's reputations.
*
* @param {object} obj Options object
* @param {string} obj.realm Realm name
* @param {string} obj.name Character name
* @param {function} getUser Function that returns the logged-in user's data
*/
async getCharacterReputations(realm, name, getUser) {
const user = getUser();
const response = await this.blizzardApi.get(
encodeURI(
`/profile/wow/character/${realm.toLowerCase()}/${name.toLowerCase()}/reputations`
),
"profile",
user.token
);
return response.status == 200 ? response.data : [];
}
} |
JavaScript | class UserActivatingScreen extends Component {
static navigationOptions = ({ navigation, navigationOptions }) => {
return {
header: null,
headerBackTitle: null
};
};
onCreatePin() {
this.props.navigation.navigate('SetPinScreen');
}
getAirDropPepoAmount(){
const pepoAmountInWei = ReduxGetters.getPepoAmtInWei();
return Pricer.getFromDecimal(pepoAmountInWei);
}
getAirDropUSDAmount(){
const pepoAmtInUSD = ReduxGetters.getPepoAmtInUSD();
return pepoAmtInUSD ;
}
render() {
return (
<View style={styles.container}>
<SafeAreaView forceInset={{ top: 'never' }}>
<ScrollView
contentContainerStyle=
{{
flexGrow: 1,
justifyContent: 'center'
}}
showsVerticalScrollIndicator={false}>
<View style={styles.contentContainer}>
<Image source={air_drop} style={{width: 137.5, height: 192}} />
<Text style={styles.heading}>Welcome Gift!</Text>
<View style={styles.valueContainer}>
<Text style={styles.desc}>You’ve received <Text style={[styles.desc, {color: '#ff5566', fontWeight: '700'}]}> {this.getAirDropPepoAmount()} </Text>Pepo!</Text>
<Text style={styles.desc}>${this.getAirDropUSDAmount()} Value!</Text>
</View>
</View>
<View style={{paddingBottom: 30}}>
<LinearGradient
colors={['#ff7499', '#ff5566']}
locations={[0, 1]}
style={{ marginHorizontal: 30, borderRadius: 3}}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
>
<TouchableButton
TouchableStyles={[{ minWidth: '100%', borderColor: 'none', borderWidth: 0}]}
TextStyles={[Theme.Button.btnPinkText]}
text="Add to Wallet"
onPress={() => {
this.onCreatePin();
}}
/>
</LinearGradient>
</View>
</ScrollView>
</SafeAreaView>
</View>
);
}
} |
JavaScript | class Events {
/**
* Create a Events.
* @param {ApplicationInsightsDataClient} client Reference to the service client.
*/
constructor(client) {
this.client = client;
this._getByType = _getByType;
this._get = _get;
}
/**
* @summary Execute OData query
*
* Executes an OData query for events
*
* @param {string} appId ID of the application. This is Application ID from the
* API Access settings blade in the Azure portal.
*
* @param {string} eventType The type of events to query; either a standard
* event type (`traces`, `customEvents`, `pageViews`, `requests`,
* `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
* across all event types. Possible values include: '$all', 'traces',
* 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
* 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.timespan] Optional. The timespan over which to
* retrieve events. This is an ISO8601 time period value. This timespan is
* applied in addition to any that are specified in the Odata expression.
*
* @param {string} [options.filter] An expression used to filter the returned
* events
*
* @param {string} [options.search] A free-text search expression to match for
* whether a particular event should be returned
*
* @param {string} [options.orderby] A comma-separated list of properties with
* \"asc\" (the default) or \"desc\" to control the order of returned events
*
* @param {string} [options.select] Limits the properties to just those
* requested on each returned event
*
* @param {number} [options.skip] The number of items to skip over before
* returning events
*
* @param {number} [options.top] The number of events to return
*
* @param {string} [options.format] Format for the returned events
*
* @param {boolean} [options.count] Request a count of matching items included
* with the returned events
*
* @param {string} [options.apply] An expression used for aggregation over
* returned events
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventsResults>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getByTypeWithHttpOperationResponse(appId, eventType, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getByType(appId, eventType, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Execute OData query
*
* Executes an OData query for events
*
* @param {string} appId ID of the application. This is Application ID from the
* API Access settings blade in the Azure portal.
*
* @param {string} eventType The type of events to query; either a standard
* event type (`traces`, `customEvents`, `pageViews`, `requests`,
* `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
* across all event types. Possible values include: '$all', 'traces',
* 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
* 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.timespan] Optional. The timespan over which to
* retrieve events. This is an ISO8601 time period value. This timespan is
* applied in addition to any that are specified in the Odata expression.
*
* @param {string} [options.filter] An expression used to filter the returned
* events
*
* @param {string} [options.search] A free-text search expression to match for
* whether a particular event should be returned
*
* @param {string} [options.orderby] A comma-separated list of properties with
* \"asc\" (the default) or \"desc\" to control the order of returned events
*
* @param {string} [options.select] Limits the properties to just those
* requested on each returned event
*
* @param {number} [options.skip] The number of items to skip over before
* returning events
*
* @param {number} [options.top] The number of events to return
*
* @param {string} [options.format] Format for the returned events
*
* @param {boolean} [options.count] Request a count of matching items included
* with the returned events
*
* @param {string} [options.apply] An expression used for aggregation over
* returned events
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {EventsResults} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link EventsResults} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getByType(appId, eventType, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getByType(appId, eventType, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getByType(appId, eventType, options, optionalCallback);
}
}
/**
* @summary Get an event
*
* Gets the data for a single event
*
* @param {string} appId ID of the application. This is Application ID from the
* API Access settings blade in the Azure portal.
*
* @param {string} eventType The type of events to query; either a standard
* event type (`traces`, `customEvents`, `pageViews`, `requests`,
* `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
* across all event types. Possible values include: '$all', 'traces',
* 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
* 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
*
* @param {string} eventId ID of event.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.timespan] Optional. The timespan over which to
* retrieve events. This is an ISO8601 time period value. This timespan is
* applied in addition to any that are specified in the Odata expression.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventsResults>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getWithHttpOperationResponse(appId, eventType, eventId, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._get(appId, eventType, eventId, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Get an event
*
* Gets the data for a single event
*
* @param {string} appId ID of the application. This is Application ID from the
* API Access settings blade in the Azure portal.
*
* @param {string} eventType The type of events to query; either a standard
* event type (`traces`, `customEvents`, `pageViews`, `requests`,
* `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
* across all event types. Possible values include: '$all', 'traces',
* 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
* 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
*
* @param {string} eventId ID of event.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.timespan] Optional. The timespan over which to
* retrieve events. This is an ISO8601 time period value. This timespan is
* applied in addition to any that are specified in the Odata expression.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {EventsResults} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link EventsResults} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
get(appId, eventType, eventId, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._get(appId, eventType, eventId, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._get(appId, eventType, eventId, options, optionalCallback);
}
}
} |
JavaScript | class Model extends Ormur {
constructor () {
super(...arguments);
this.knex = knexConnection;
}
} |
JavaScript | class Production {
/**
* Receives a raw production in a view of:
*
* LHS -> RHS or a short alternative
* | RHS if the LHS is the same.
*/
constructor(LHS, RHS, number, semanticAction, isShort, grammar, precedence) {
this._rawLHS = LHS;
this._rawRHS = RHS;
this._number = number;
this._isAugmented = number === 0;
this._isShort = !!isShort;
this._grammar = grammar;
this._normalize();
if (semanticAction == null) {
semanticAction = this._createDefaultSemanticAction();
}
this._orginialSemanticAction = semanticAction;
this._rawSemanticAction = this._rewriteNamedArg(semanticAction);
this._semanticAction = this._buildSemanticAction(this._rawSemanticAction);
this._precedence = precedence || this._calculatePrecedence();
}
/**
* Creates default semantic action for simple productions.
*/
_createDefaultSemanticAction() {
if (this.getRHS().length !== 1 || this.isEpsilon()) {
return null;
}
return '$$ = $1';
}
/**
* Whether the production propagating.
*/
isPropagating() {
if (this._isPropagating == null) {
this._isPropagating =
this.getRHS().length === 1 &&
/\$\$\s+=\s+\$1/.test(this._rawSemanticAction);
}
return this._isPropagating;
}
/**
* Whther this production derives token.
*/
derivesPropagatingToken() {
if (this._derivesPropagatingToken == null) {
if (!this.isPropagating()) {
return (this._derivesPropagatingToken = false);
}
const symbol = this.getRHS()[0].getSymbol();
if (this._grammar.isTokenSymbol(symbol)) {
return (this._derivesPropagatingToken = true);
}
const productionsForSymbol = this._grammar.getProductionsForSymbol(
symbol
);
for (const production of productionsForSymbol) {
if (production.derivesPropagatingToken(production)) {
return (this._derivesPropagatingToken = true);
}
}
return (this._derivesPropagatingToken = false);
}
return this._derivesPropagatingToken;
}
/**
* Rewrites named arguments to positioned ones.
* $foo -> $1, ...
*/
_rewriteNamedArg(semanticAction) {
if (!semanticAction) {
return null;
}
const RHS = this.getRHS();
const idRe = /[a-zA-Z][a-zA-Z0-9]*/;
for (let i = 0; i < RHS.length; i++) {
const symbol = RHS[i].getSymbol();
if (!idRe.test(symbol)) {
continue;
}
const index = i + 1;
const symbolRe = new RegExp(`(\\$|@)${symbol}\\b`, 'g');
semanticAction = semanticAction.replace(symbolRe, `$1${index}`);
}
return semanticAction;
}
/**
* Returns number of the production
* in the grammar.
*/
getNumber() {
return this._number;
}
/**
* Whether this production is augmented.
*/
isAugmented() {
return this._isAugmented;
}
/**
* Returns LHS symbol.
*/
getLHS() {
return this._LHS;
}
/**
* Returns an array of symbols on RHS (aka "handle").
*/
getRHS() {
return this._RHS;
}
/**
* Same as `getRHS`, but returns raw symbols.
*/
getRHSSymbols() {
if (!this._rhsSymbols) {
this._rhsSymbols = this._RHS.map(symbol => symbol.getSymbol());
}
return this._rhsSymbols;
}
/**
* A map for faster searches whether a symbol is used on RHS.
*/
getRHSSymbolsMap() {
if (!this._rhsSymbolsMap) {
this._rhsSymbolsMap = {};
this._RHS.forEach(
symbol => (this._rhsSymbolsMap[symbol.getSymbol()] = true)
);
}
return this._rhsSymbolsMap;
}
/**
* Returns precedence of this production.
*/
getPrecedence() {
return this._precedence;
}
/**
* Returns original semantic action.
*/
getOriginalSemanticAction() {
return this._orginialSemanticAction;
}
/**
* Returns semantic action string.
*/
getRawSemanticAction() {
return this._rawSemanticAction;
}
/**
* Returns semantic action function.
*/
getSemanticAction() {
return this._semanticAction;
}
/**
* Whether this production has semantic action.
*/
hasSemanticAction() {
return this._semanticAction !== null;
}
/**
* Executes semantic action.
*/
runSemanticAction(args) {
if (!this._semanticAction) {
return;
}
return this._semanticAction(...args);
}
/**
* Whether this production is epsilon.
*/
isEpsilon() {
let RHS = this.getRHS();
return RHS.length === 1 && RHS[0].isEpsilon();
}
/**
* String representation.
*/
toString() {
return this._toKey(this._isShort);
}
/**
* String representation in full notation.
*/
toFullString() {
return this._toKey(false);
}
_toKey(isShort = false) {
let LHS = this._LHS.getSymbol();
let RHS = this._RHS.map(symbol => symbol.getSymbol()).join(' ');
let pad = Array(LHS.length + '->'.length).join(' ');
return isShort ? `${pad} | ${RHS}` : `${LHS} -> ${RHS}`;
}
/**
* Constructs semantic action based on the RHS length,
* each stack entry which corresponds to a symbol is available
* as $1, $2, $3, etc. arguments. The result is $$.
*/
_buildSemanticAction(semanticAction) {
if (!semanticAction) {
return null;
}
// Generate the function handler only for JS language.
try {
const handler = CodeUnit.createProductionHandler({
production: this,
captureLocations: this._grammar.shouldCaptureLocations(),
});
return (...args) => {
// Executing a handler mutates $$ variable, return it.
try {
handler(...args);
} catch (e) {
this._logProductionError();
throw e;
}
return CodeUnit.getSandbox().__;
};
} catch (e) {
if (global.globalOptions.output == null) {
this._logProductionError();
throw e;
}
/* And skip for other languages, which use raw handler in generator */
}
}
_logProductionError() {
console.error(
colors.red(`\nError in handler for production `) +
colors.bold(this.toFullString()) +
`:\n\n` +
this.getOriginalSemanticAction() +
'\n'
);
}
_normalize() {
let LHS = GrammarSymbol.get(this._rawLHS);
let RHS = [];
// If no RHS provided, assume it's ε. We support
// both formats, explicit: F -> ε, and implicit: F ->
if (!this._rawRHS) {
RHS.push(GrammarSymbol.get(EPSILON));
} else {
let rhsProd = this._rawRHS.split(/\s+/);
for (let i = 0; i < rhsProd.length; i++) {
if (rhsProd[i] === '"' && rhsProd[i + 1] === '"') {
RHS.push(GrammarSymbol.get('" "'));
i++;
} else {
RHS.push(GrammarSymbol.get(rhsProd[i]));
}
}
}
this._LHS = LHS;
this._RHS = RHS;
}
_calculatePrecedence() {
let operators = this._grammar.getOperators();
for (let grammarSymbol of this.getRHS()) {
let symbol = grammarSymbol.getSymbol();
if (symbol in operators) {
return operators[symbol].precedence;
}
}
return 0;
}
} |
JavaScript | class Reset extends React.Component {
render() {
return <GlobalReset />
}
} |
JavaScript | class DegRadHelper {
constructor(obj, prop) {
this.obj = obj;
this.prop = prop;
}
get value() {
return THREE.Math.radToDeg(this.obj[this.prop]);
}
set value(v) {
this.obj[this.prop] = THREE.Math.degToRad(v);
}
} |
JavaScript | class TraversalStrategy {
/**
* Not instantiable.
*/
__construct() {
throw new Error('Not instantiable.');
}
} |
JavaScript | class CollectionResource extends Resource {
/**
* Fetches all collections on the shop, not including products.
* To fetch collections with products use [fetchAllsWithProducts]{@link Client#fetchAllsWithProducts}.
*
* @example
* client.collection.fetchAll().then((collections) => {
* // Do something with the collections
* });
*
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/
fetchAll(first = 20) {
return this.graphQLClient
.send(collectionConnectionQuery, {first})
.then(defaultResolver('collections'));
}
/**
* Fetches all collections on the shop, including products.
*
* @example
* client.collection.fetchAllWithProducts().then((collections) => {
* // Do something with the collections
* });
*
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/
fetchAllWithProducts({first = 20, productsFirst = 20} = {}) {
return this.graphQLClient
.send(collectionConnectionWithProductsQuery, {first, productsFirst})
.then(defaultResolver('collections'))
.then(paginateCollectionsProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a single collection by ID on the shop, not including products.
* To fetch the collection with products use [fetchWithProducts]{@link Client#fetchWithProducts}.
*
* @example
* client.collection.fetch('Xk9lM2JkNzFmNzIQ4NTIY4ZDFiZTUyZTUwNTE2MDNhZjg==').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} id The id of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/
fetch(id) {
return this.graphQLClient
.send(collectionNodeQuery, {id})
.then(defaultResolver('node'));
}
/**
* Fetches a single collection by ID on the shop, including products.
*
* @example
* client.collection.fetchWithProducts('Xk9lM2JkNzFmNzIQ4NTIY4ZDFiZTUyZTUwNTE2MDNhZjg==').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} id The id of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/
fetchWithProducts(id) {
return this.graphQLClient
.send(collectionNodeWithProductsQuery, {id})
.then(defaultResolver('node'))
.then(paginateCollectionsProductConnectionsAndResolve(this.graphQLClient));
}
/**
* Fetches a collection by handle on the shop.
*
* @example
* client.collection.fetchByHandle('my-collection').then((collection) => {
* // Do something with the collection
* });
*
* @param {String} handle The handle of the collection to fetch.
* @return {Promise|GraphModel} A promise resolving with a `GraphModel` of the collection.
*/
fetchByHandle(handle) {
return this.graphQLClient
.send(collectionByHandleQuery, {handle})
.then(defaultResolver('collectionByHandle'));
}
/**
* Fetches all collections on the shop that match the query.
*
* @example
* client.collection.fetchQuery({first: 20, sortKey: 'CREATED_AT', reverse: true}).then((collections) => {
* // Do something with the first 10 collections sorted by title in ascending order
* });
*
* @param {Object} [args] An object specifying the query data containing zero or more of:
* @param {Int} [args.first=20] The relay `first` param. This specifies page size.
* @param {String} [args.sortKey=ID] The key to sort results by. Available values are
* documented as {@link https://help.shopify.com/api/storefront-api/reference/enum/collectionsortkeys|Collection Sort Keys}.
* @param {String} [args.query] A query string. See full documentation {@link https://help.shopify.com/api/storefront-api/reference/object/shop#collections|here}
* @param {Boolean} [args.reverse] Whether or not to reverse the sort order of the results
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the collections.
*/
fetchQuery({first = 20, sortKey = 'ID', query, reverse} = {}) {
return this.graphQLClient.send(collectionConnectionQuery, {
first,
sortKey,
query,
reverse
}).then(defaultResolver('collections'));
}
} |
JavaScript | class Fms {
/**
* @constructor
* @param aircraftInitProps {object}
* @param initialRunwayAssignment {RunwayModel}
* @param typeDefinitionModel {AircraftTypeDefinitionModel}
* @param navigationLibrary {NavigationLibrary}
*/
constructor(aircraftInitProps, initialRunwayAssignment, typeDefinitionModel, navigationLibrary) {
if (!_isObject(aircraftInitProps) || _isEmpty(aircraftInitProps)) {
throw new TypeError('Invalid aircraftInitProps passed to Fms');
}
/**
* Instance of the `NavigationLibrary`
*
* provides access to the aiport SIDs, STARs and Fixes via collection objects and fascade methods.
* used for route building
*
* @property _navigationLibrary
* @type {NavigationLibrary}
* @private
*/
this._navigationLibrary = navigationLibrary;
/**
* routeSegments of legs that have been completed
*
* Used to generate #flightPlanRoute
*
* @property _previousRouteSegments
* @type {array<string>}
* @default []
* @private
*/
this._previousRouteSegments = [];
/**
* Name of runway used at arrival airport
*
* @for Fms
* @property arrivalRunwayModel
* @type {RunwayModel}
*/
this.arrivalRunwayModel = null;
/**
* Current flight phase of an aircraft
*
* @property currentPhase
* @type {string}
* @default ''
*/
this.currentPhase = '';
/**
* Name of runway used at departure airport
*
* @for Fms
* @property departureRunwayModel
* @type {RunwayModel}
*/
this.departureRunwayModel = null;
/**
* @property _flightPhaseHistory
* @type {array<string>}
* @default []
* @private
*/
this._flightPhaseHistory = [];
/**
* Altitude expected for this flight. Will change as ATC amends it.
*
* @property flightPlanAltitude
* @type {Object}
* @default ''
*/
this.flightPlanAltitude = -1;
/**
* Collection of `LegModel` objects
*
* @property legCollection
* @type {array}
* @default []
*/
this.legCollection = [];
this.init(aircraftInitProps, initialRunwayAssignment);
}
/**
* Provides access to the `RunwayModel` currently associated with the Fms
*
* It is assumed only an arrival or departure runway will
* exist at any one time
*
* @property currentRunway
* @return {RunwayModel}
*/
get currentRunway() {
return this.arrivalRunwayModel || this.departureRunwayModel;
}
/**
* The name of the currently assigned runway
*
* // TODO: this may need to be moved to a function in the event
* both departure and arrival runways are supported for
* a single aircraft
*
* @property currentRunwayName
* @type {string}
*/
get currentRunwayName() {
return this.currentRunway.name;
}
/**
* The active waypoint an aircraft is flying towards
*
* Assumed to ALWAYS be the first `WaypointModel` in the `currentLeg`
*
* @property currentWaypoint
* @type {WaypointModel}
*/
get currentWaypoint() {
return this.currentLeg.currentWaypoint;
}
/**
* The active Leg in the `legCollection`
*
* Assumed to ALWAYS be the first `LegModel` in the `legCollection`
*
* @property currentLeg
* @type {LegModel}
*/
get currentLeg() {
return this.legCollection[0];
}
/**
* Builds a routeString from the current legs in the `legCollection` and joins
* each section with `..`
*
* A `routeString` might look like one of the following:
* - `cowby..bikkr..dag.kepec3.klas`
* - `cowby`
* - `dag.kepec3.klas`
*
* @property currentRoute
* @type {string}
*/
get currentRoute() {
const routeSegments = _map(this.legCollection, (legModel) => legModel.routeString);
return routeSegments.join(DIRECT_ROUTE_SEGMENT_SEPARATOR);
}
/**
* Flight plan as filed
*
* @method flightPlan
* @type {object}
*/
get flightPlan() {
return {
altitude: this.flightPlanAltitude,
route: this.flightPlanRoute
};
}
/**
* Route expected for this flight. Will change as ATC amends it.
*
* @property flightPlanRoute
* @type {string}
*/
get flightPlanRoute() {
const previousAndCurrentRouteStrings = this._previousRouteSegments.concat(this.currentRoute);
return previousAndCurrentRouteStrings.join(DIRECT_ROUTE_SEGMENT_SEPARATOR);
}
// TODO: this should move to a class method
/**
* Returns a flattened array of each `WaypointModel` in the flightPlan
*
* This is used only in the `CanvasController` when drawing the projected
* aircraft path.
*
* Using a getter here to stay in line with the previous api.
*
* @property waypoints
* @type {array<WaypointModel>}
*/
get waypoints() {
const waypointList = _map(this.legCollection, (legModel) => {
return [
...legModel.waypointCollection
];
});
return _flatten(waypointList);
}
/**
* Initialize the instance and setup initial properties
*
* @for Fms
* @method init
* @param aircraftInitProps {object}
*/
init({ category, model, route }, initialRunwayAssignment) {
this._setCurrentPhaseFromCategory(category);
this._setInitialRunwayAssignmentFromCategory(category, initialRunwayAssignment);
this.flightPlanAltitude = model.ceiling;
this.legCollection = this._buildLegCollection(route);
}
/**
* Destroy the instance and reset properties
*
* @for LegModel
* @method destroy
*/
destroy() {
this._navigationLibrary = null;
this._previousRouteSegments = [];
this.currentPhase = '';
this.departureRunwayModel = null;
this.arrivalRunwayModel = null;
this.flightPlanAltitude = -1;
this.legCollection = [];
}
/**
* Return the name of the current procedure, if following a procedure
*
* @for fms
* @method getProcedureName
* @return {string}
*/
getProcedureName() {
if (!this.isFollowingProcedure()) {
return null;
}
return this.currentLeg.procedureName;
}
/**
* Return the name and exit point of the current procedure, if following a procedure
*
* @for fms
* @method getProcedureAndExitName
* @return {string}
*/
getProcedureAndExitName() {
if (!this.isFollowingProcedure()) {
return null;
}
return this.currentLeg.procedureAndExitName;
}
/**
* Return the name of the airport and the assigned runway, if following an arrival procedure
* or just the assigned runway when not on a procedure
*
* @for Fms
* @method getDestinationAndRunwayName
* @return {string}
*/
getDestinationAndRunwayName() {
if (!this.isFollowingStar()) {
return `${this.currentRunwayName}`;
}
return `${this.currentLeg.exitName} ${this.currentRunwayName}`;
}
/**
* Return the name of the airport, if following an arrival procedure
*
* @for Fms
* @method getDestinationName
* @return {string}
*/
getDestinationName() {
// TODO: this method should use the `RouteModel` to get the various pieces below
// TODO: determine if this method is even needed after `AircraftStrip` enhancements
// coming in https://github.com/openscope/openscope/issues/285
if (this.isFollowingStar()) {
const routeString = this.currentLeg.routeString;
const routeStringElements = routeString.split('.');
// TODO: This would actually be better as [0,1] than [1,2]
// eg `THHMP.CAVLR3.KIAD` --> `THHMP.CAVLR3` instead of `CAVLR3.KIAD`
return `${routeStringElements[1]}.${routeStringElements[2]}`;
}
if (this.isFollowingSid()) {
const routeString = this.currentLeg.routeString;
const routeStringElements = routeString.split('.');
return `${routeStringElements[1]}.${routeStringElements[2]}`;
}
const lastPointOnRoute = _last(this.flightPlanRoute.split('.'));
return lastPointOnRoute;
}
/**
* Collects the `.getProcedureTopAltitude()` value from each `LegModel`
* in the `#legCollection`, then finds and returns the highest value
*
* @for LegModel
* @method getTopAltitude
* @return {number}
*/
getTopAltitude() {
const maxAltitudeFromLegs = _map(this.legCollection, (leg) => leg.getProcedureTopAltitude());
return Math.max(...maxAltitudeFromLegs);
}
/**
* Collects the `.getProcedureBottomAltitude()` value from each `LegModel`
* in the `#legCollection`, then finds and returns the lowest value
*
* @for LegModel
* @method getBottomAltitude
* @return {number}
*/
getBottomAltitude() {
const valueToExclude = -1;
const minAltitudeFromLegs = _without(
_map(this.legCollection, (leg) => leg.getProcedureBottomAltitude()),
valueToExclude
);
return Math.min(...minAltitudeFromLegs);
}
/**
* Encapsulates setting `#departureRunwayModel`
*
* @for fms
* @method setDepartureRunway
* @param runwayModel {RunwayModel}
*/
setDepartureRunway(runwayModel) {
// TODO: this should be an `instanceof` check and should be implemented as part of (or after)
// https://github.com/openscope/openscope/issues/93
if (!_isObject(runwayModel)) {
throw new TypeError(`Expected instance of RunwayModel, but received ${runwayModel}`);
}
this.departureRunwayModel = runwayModel;
}
/**
* Encapsulates setting of `#arrivalRunwayModel`
*
* @for fms
* @method setArrivalRunway
* @param runwayModel {RunwayModel}
*/
setArrivalRunway(runwayModel) {
// TODO: this should be an `instanceof` check and should be implemented as part of (or after)
// https://github.com/openscope/openscope/issues/93
if (!_isObject(runwayModel)) {
throw new TypeError(`Expected instance of RunwayModel, but received ${runwayModel}`);
}
this.arrivalRunwayModel = runwayModel;
}
/**
* Set the `#currentPhase`
*
* this value is used to determine how to calculate and aircraft's next
* altitude, heading and speed.
*
* @for Fms
* @method setFlightPhase
* @param phase {string}
*/
setFlightPhase(phase) {
if (!_has(FLIGHT_PHASE, phase)) {
return new TypeError(`Expected known flight phase, but received '${phase}'`);
}
if (this.currentPhase === phase) {
return;
}
this._addPhaseToFlightHistory(phase);
this.currentPhase = phase;
}
/**
* Add a new `LegModel` to the left side of the `#legCollection`
*
* @for Fms
* @method prependLeg
* @param legModel {LegModel}
*/
prependLeg(legModel) {
this.legCollection.unshift(legModel);
}
/**
* Add a new `LegModel` to the right side of the `#legCollection`
*
* @for Fms
* @method appendLeg
* @param legModel {LegModel}
*/
appendLeg(legModel) {
this.legCollection.push(legModel);
}
// TODO: this method should be simplified
/**
* Create a new `LegModel` for a holding pattern at a Fix or a position
*
* @for Fms
* @method createLegWithHoldingPattern
* @param inboundHeading {number}
* @param turnDirection {string}
* @param legLength {number}
* @param holdRouteSegment {string}
* @param holdPosition {StaticPositionModel}
*/
createLegWithHoldingPattern(inboundHeading, turnDirection, legLength, holdRouteSegment, holdPosition) {
// TODO: replace with constant
const isPositionHold = holdRouteSegment === 'GPS';
const waypointProps = {
turnDirection,
legLength,
isHold: true,
inboundHeading,
name: holdRouteSegment,
positionModel: holdPosition,
altitudeRestriction: INVALID_VALUE,
speedRestriction: INVALID_VALUE
};
if (isPositionHold) {
const legModel = this._createLegWithHoldWaypoint(waypointProps);
this.prependLeg(legModel);
return;
}
const waypointNameToFind = extractFixnameFromHoldSegment(holdRouteSegment);
const { waypointIndex } = this._findLegAndWaypointIndexForWaypointName(waypointNameToFind);
if (waypointIndex !== INVALID_VALUE) {
this.skipToWaypoint(waypointNameToFind);
this.currentWaypoint.updateWaypointWithHoldProps(inboundHeading, turnDirection, legLength);
return;
}
const legModel = this._createLegWithHoldWaypoint(waypointProps);
this.prependLeg(legModel);
return;
}
/**
* Move to the next possible waypoint
*
* This could be the next waypoint in the current leg,
* or the first waypoint in the next leg.
*
* @for LegModel
* @method nextWaypoint
*/
nextWaypoint() {
if (!this.currentLeg.hasNextWaypoint()) {
this._updatePreviousRouteSegments(this.currentLeg.routeString);
this._moveToNextLeg();
return;
}
this._moveToNextWaypointInLeg();
}
/**
* Replace the current flightPlan with an entire new one
*
* Used when an aircraft has been re-routed
*
* @for Fms
* @method replaceCurrentFlightPlan
* @param routeString {string}
*/
replaceCurrentFlightPlan(routeString) {
this._destroyLegCollection();
this.legCollection = this._buildLegCollection(routeString);
}
/**
* Given a `waypointName`, find the index of that waypoint within
* the `legsColelction`. Then make that Leg active and `waypointName`
* the active waypoint for that Leg.
*
* @for Fms
* @method skipToWaypoint
* @param waypointName {string}
*/
skipToWaypoint(waypointName) {
const { legIndex, waypointIndex } = this._findLegAndWaypointIndexForWaypointName(waypointName);
// TODO: this may be deprectaed
this._collectRouteStringsForLegsToBeDropped(legIndex);
this.legCollection = _drop(this.legCollection, legIndex);
this.currentLeg.skipToWaypointAtIndex(waypointIndex);
}
/**
* Get the position of the next waypoint in the flightPlan.
*
* Currently only Used in `calculateTurnInitiaionDistance()` helper function
*
* @for Fms
* @method getNextWaypointPositionModel
* @return waypointPosition {StaticPositionModel}
*/
getNextWaypointPositionModel() {
if (!this.hasNextWaypoint()) {
console.log('has no next waypoint');
return null;
}
let waypointPosition = this.currentLeg.nextWaypoint;
if (!this.currentLeg.hasNextWaypoint()) {
waypointPosition = this.legCollection[1].currentWaypoint;
}
return waypointPosition.positionModel;
}
/**
* Find the departure procedure (if it exists) within the `#legCollection` and
* reset it with a new departure procedure.
*
* This method does not remove any `LegModel`s. It instead finds and updates a
* `LegModel` with a new routeString. If a `LegModel` with a departure
* procedure cannot be found, then we create a new `LegModel` and place it
* at the beginning of the `#legCollection`.
*
* @for Fms
* @method replaceDepartureProcedure
* @param routeString {string}
* @param runwayModel {RunwayModel}
*/
replaceDepartureProcedure(routeString, runwayModel) {
// this is the same procedure that is already set, no need to continue
if (this.hasLegWithRouteString(routeString)) {
return;
}
if (this.departureRunwayModel.name !== runwayModel.name) {
this.setDepartureRunway(runwayModel);
}
const procedureLegIndex = this._findLegIndexForProcedureType(PROCEDURE_TYPE.SID);
// a procedure does not exist in the flight plan, so we must create a new one
if (procedureLegIndex === INVALID_VALUE) {
const legModel = this._buildLegModelFromRouteSegment(routeString);
this.prependLeg(legModel);
return;
}
this._replaceLegAtIndexWithRouteString(procedureLegIndex, routeString);
}
/**
* Find the arrival procedure (if it exists) within the `#legCollection` and
* reset it with a new arrival procedure.
*
* This method does not remove any `LegModel`s. It instead finds and updates a
* `LegModel` with a new routeString. If a `LegModel` without a arrival
* procedure cannot be found, then we create a new `LegModel` and place it
* at the end of the `#legCollection`.
*
* @for Fms
* @method replaceArrivalProcedure
* @param routeString {string}
* @param runwayModel {RunwayModel}
*/
replaceArrivalProcedure(routeString, runwayModel) {
// this is the same procedure that is already set, no need to continue
if (this.hasLegWithRouteString(routeString)) {
return;
}
if (this.arrivalRunwayModel.name !== runwayModel.name) {
this.setArrivalRunway(runwayModel);
}
const procedureLegIndex = this._findLegIndexForProcedureType(PROCEDURE_TYPE.STAR);
// a procedure does not exist in the flight plan, so we must create a new one
if (procedureLegIndex === INVALID_VALUE) {
const legModel = this._buildLegModelFromRouteSegment(routeString);
this.appendLeg(legModel);
return;
}
this._replaceLegAtIndexWithRouteString(procedureLegIndex, routeString);
}
/**
* Removes an existing flightPlan and replaces it with a
* brand new route.
*
* This is a destructive operation.
*
* @for Fms
* @method replaceFlightPlanWithNewRoute
* @param routeString {string}
* @param runway {string}
*/
replaceFlightPlanWithNewRoute(routeString, runway) {
// TODO: we may need to update the runway in this method
this._destroyLegCollection();
this.legCollection = this._buildLegCollection(routeString);
}
/**
* Replace a portion of the existing flightPlan with a new route,
* up to a shared routeSegment.
*
* It is assumed that any `routeString` passed to this method has
* already been verified to contain a shared segment with the existing
* route. This method is not designed to handle errors for cases where
* there are not shared routeSegments.
*
* @for Fms
* @metho replaceRouteUpToSharedRouteSegment
* @param routeString {routeString}
*/
replaceRouteUpToSharedRouteSegment(routeString) {
let legIndex = INVALID_VALUE;
let amendmentRouteString = '';
const routeSegments = routeStringFormatHelper(routeString.toLowerCase());
for (let i = 0; i < routeSegments.length; i++) {
const segment = routeSegments[i];
// with the current routeSegment, find if this same routeSegment exists already within the #legCollection
if (this.hasLegWithRouteString(segment)) {
legIndex = this._findLegIndexByRouteString(segment);
// build a new routeString with only the pieces we need to create new `LegModels` for
amendmentRouteString = routeSegments.slice(0, i);
break;
}
}
this._trimLegCollectionAtIndex(legIndex);
this._prependLegCollectionWithRouteAmendment(amendmentRouteString);
}
/**
* Unset `HOLD` as the `#currentPhase` only if `HOLD` is the `#currentPhase`
*
* @Fms
* @method exitHoldIfHolding
*/
exitHoldIfHolding() {
if (this.currentPhase !== FLIGHT_PHASE.HOLD) {
return;
}
this._exitHoldToPreviousFlightPhase();
}
/**
* Sets `#currentPhase` to its previous value
*
* This method should only be called from `.exitHoldIfHolding()`, which performs
* the requisit checks for correct `#flightPhase`
*
* @for Fms
* @method _exitHoldToPreviousFlightPhase
*/
_exitHoldToPreviousFlightPhase() {
this.currentPhase = _last(this._flightPhaseHistory);
}
/**
* Validate and entire route.
*
* This can be:
* - a directRouteString,
* - a procedureRouteString,
* - or combination of both directRouteStrings and procedureRouteString
*
* @for fms
* @method isValidRoute
* @param routeString {string}
* @param runway {string}
* @return {boolean}
*/
isValidRoute(routeString, runway = '') {
const routeSegments = routeStringFormatHelper(routeString);
if (!routeSegments) {
return false;
}
for (let i = 0; i < routeSegments.length; i++) {
let isValid = false;
const segment = routeSegments[i];
if (RouteModel.isProcedureRouteString(segment)) {
isValid = this.isValidProcedureRoute(segment, runway);
} else if (RouteModel.isHoldRouteString(segment)) {
const fixName = extractFixnameFromHoldSegment(segment);
isValid = this._navigationLibrary.hasFix(fixName);
} else if (RouteModel.isVectorRouteString(segment)) {
const heading = extractHeadingFromVectorSegment(segment);
const isValidNumber = !isNaN(heading);
const isThreeDigits = heading.length === 3;
isValid = isValidNumber && isThreeDigits;
} else {
isValid = this._navigationLibrary.hasFix(segment);
}
if (!isValid) {
return false;
}
}
return true;
}
/**
* Determinines if the passed `routeString` is a valid procedure route.
*
* This can be either a SID or a STAR.
* A valid `procedureRouteString` is expected to be in the shape of:
* `ENTRY.PROCEDURE_NAME.EXIT`
*
* @for Fms
* @method isValidProcedureRoute
* @param routeString {string}
* @param runway {string}
* @param flightPhase {string}
* @return {boolean}
*/
isValidProcedureRoute(routeString, runway, flightPhase = '') {
let routeStringModel;
// RouteModel will throw when presented with an invalid procedureRouteString,
// we only want to capture that here and continue on our way.
try {
routeStringModel = new RouteModel(routeString);
} catch (error) {
console.error(error);
return false;
}
// flightPhase is unknown or unavailable so it must be extrapolated based on the `procedureId`.
if (flightPhase === '') {
flightPhase = this._translateProcedureNameToFlightPhase(routeStringModel.procedure);
}
// a `LegModel` already exists with this routeString
if (this.hasLegWithRouteString(routeStringModel.routeCode)) {
return true;
}
// TODO: abstract this to a method or combine with if/returns below
// find the prcedure model from the correct collection based on flightPhase
const procedureModel = flightPhase === FLIGHT_CATEGORY.ARRIVAL
? this.findStarByProcedureId(routeStringModel.procedure)
: this.findSidByProcedureId(routeStringModel.procedure);
if (!procedureModel) {
return false;
}
if (flightPhase === FLIGHT_CATEGORY.ARRIVAL) {
// TODO: this is too aggressive at the moment because of inconsistencies in airport files. this should be
// reimplemented as soon as possible.
return procedureModel.hasFixName(routeStringModel.entry); // && procedureModel.hasFixName(runway);
}
// TODO: this is too aggressive at the moment because of inconsistencies in airport files. this should be
// reimplemented as soon as possible.
return procedureModel.hasFixName(routeStringModel.exit); // && procedureModel.hasFixName(runway);
}
/**
* Given a `routeString`, find if any `routeSegments` match an existing
* `LegModel#routeString`.
*
* This method will return true on only the first match.
*
* This method should be used before using `applyPartialRouteAmendment()`
* to verify a `routeAmmendment` has some shared `routeSegment`.
*
* @for Fms
* @method isValidRouteAmendment
* @param routeString {string} any `routeString` representing a future routeAmmendment
* @return isValid {boolean}
*/
isValidRouteAmendment(routeString) {
let isValid = false;
const routeSegments = routeStringFormatHelper(routeString);
for (let i = 0; i < routeSegments.length; i++) {
const segment = routeSegments[i];
if (this.hasLegWithRouteString(segment)) {
isValid = true;
break;
}
}
return isValid;
}
/**
* Find if a Waypoint exists within `#legCollection`
*
* This will call a `.hasWaypoint` method on each `LegModel`
*
* @for Fms
* @method hasWaypoint
* @param waypointName {string}
* @return {boolean}
*/
hasWaypoint(waypointName) {
// using a for loop here instead of `_find()` because this operation could happen a lot and
// a for loop is going to be faster than `_find()` in most cases.
for (let i = 0; i < this.legCollection.length; i++) {
const leg = this.legCollection[i];
if (leg.hasWaypoint(waypointName)) {
return true;
}
}
return false;
}
/**
* Encapsulation of boolean logic used to determine if there is a
* WaypointModel available after the current one has been flown over.
*
* @for fms
* @method hasNextWaypoint
* @return {boolean}
*/
hasNextWaypoint() {
return this.currentLeg.hasNextWaypoint() || !_isNil(this.legCollection[1]);
}
/**
* Determiens is any `LegModel` with the `#legCollection` contains
* a specific `routeString`.
*
* It is assumed that if a leg matches the `routeString` provided,
* the route is the same.
*
* @for Fms
* @method hasLegWithRouteString
* @param routeString {string}
* @return {boolean}
*/
hasLegWithRouteString(routeString) {
const previousProcedureLeg = this._findLegByRouteString(routeString);
return typeof previousProcedureLeg !== 'undefined';
}
/**
* Returns true if the `#currentLeg` is a procedure (sid/star)
*
* @for Fms
* @method isFollowingProcedure
* @return {boolean}
*/
isFollowingProcedure() {
return this.currentLeg.isProcedure;
}
/**
* Returns true if the `#currentLeg` is a SID procedure
*
* @for Fms
* @method
* @return {boolean}
*/
isFollowingSid() {
return this.isFollowingProcedure() && this.currentLeg.procedureType === PROCEDURE_TYPE.SID;
}
/**
* Returns true if the `#currentLeg` is a STAR procedure
*
* @for Fms
* @method
* @return {boolean}
*/
isFollowingStar() {
return this.isFollowingProcedure() && this.currentLeg.procedureType === PROCEDURE_TYPE.STAR;
}
/**
* Fascade method for `sidCollection.findRouteByIcao`
*
* Allows classes that have access to the `Aircraft`, but not the
* navigation library, to do standardRoute building and logic.
*
* @for Fms
* @method findSidByProcedureId
* @param procedureId {string}
* @return {array<StandardRouteWaypointModel>}
*/
findSidByProcedureId(procedureId) {
return this._navigationLibrary.sidCollection.findRouteByIcao(procedureId);
}
/**
* Fascade method for `starCollection.findRouteByIcao`
*
* Allows classes that have access to the `Aircraft`, but not the
* navigation library, to do standardRoute building and logic.
*
* @for Fms
* @method findStarByProcedureId
* @param procedureId {string}
* @return {array<StandardRouteWaypointModel>}
*/
findStarByProcedureId(procedureId) {
return this._navigationLibrary.starCollection.findRouteByIcao(procedureId);
}
/**
* Fascade method for `sidCollection.findRandomExitPointForSIDIcao`
*
* Allows classes that have access to the `Aircraft`, but not the
* navigation library, to do standardRoute building and logic.
*
* @Fms
* @method findRandomExitPointForSidProcedureId
* @param procedureId {string}
* @return {array<StandardRouteWaypointModel>}
*/
findRandomExitPointForSidProcedureId(procedureId) {
return this._navigationLibrary.sidCollection.findRandomExitPointForSIDIcao(procedureId);
}
/**
* From a routeString, find each routeString segment and create
* new `LegModels` for each segment then retun that list.
*
* Used on instantiation to build the initial `legCollection`.
*
* @for LegModel
* @method _buildLegCollection
* @param routeString {string}
* @return {array<LegModel>}
* @private
*/
_buildLegCollection(routeString) {
const routeStringSegments = routeStringFormatHelper(routeString);
const legsForRoute = _map(routeStringSegments,
(routeSegment) => this._buildLegModelFromRouteSegment(routeSegment)
);
return legsForRoute;
}
/**
* Build a `LegModel` instance
*
* This is abstracted to centralize the creation of `LegModels` so the same,
* consistent operation can be performed from within a loop or one at a time.
*
* @for Fms
* @method _buildLegModelFromRouteSegment
* @param routeSegment {string} a segment of a `routeString`
* @private
*/
_buildLegModelFromRouteSegment(routeSegment) {
return new LegModel(routeSegment, this.currentRunwayName, this.currentPhase, this._navigationLibrary);
}
/**
* Build a `LegModel` instance that contains a `WaypointModel` with hold properties
*
* @for Fms
* @method _createLegWithHoldWaypoint
* @param waypointProps {object}
* @return legModel {LegModel}
*/
_createLegWithHoldWaypoint(waypointProps) {
const legModel = new LegModel(
waypointProps.name,
this.currentRunwayName,
this.currentPhase,
this._navigationLibrary,
waypointProps
);
return legModel;
}
/**
* Make the next `WaypointModel` in the currentLeg the currentWaypoint
*
* @for Fms
* @method _moveToNextWaypointInLeg
* @private
*/
_moveToNextWaypointInLeg() {
this.currentLeg.moveToNextWaypoint();
}
/**
* Make the next `LegModel` in the `legCollection` the currentWaypoint
*
* @for Fms
* @method _moveToNextLeg
* @private
*/
_moveToNextLeg() {
this.currentLeg.destroy();
// this is mutable
this.legCollection.shift();
}
/**
* Loop through the `LegModel`s in the `#legCollection` untill
* the `waypointName` is found, then return the location indicies
* for the Leg and Waypoint.
*
* Used to adjust `currentLeg` and `currentWaypoint` values by
* dropping items to the left of these indicies.
*
* @for Fms
* @method _findLegAndWaypointIndexForWaypointName
* @param waypointName {string}
* @return {object}
* @private
*/
_findLegAndWaypointIndexForWaypointName(waypointName) {
let legIndex;
let waypointIndex = INVALID_VALUE;
for (legIndex = 0; legIndex < this.legCollection.length; legIndex++) {
const legModel = this.legCollection[legIndex];
// TODO: this should be made into a class method for the WaypointModel
waypointIndex = _findIndex(legModel.waypointCollection, { name: waypointName.toLowerCase() });
if (waypointIndex !== INVALID_VALUE) {
break;
}
}
// TODO: what happens here if a waypoint isn't found within the collection?
return {
legIndex,
waypointIndex
};
}
/**
* Given a `procedureType` this locates the array index of a leg with that `#procedureType`.
*
* @for Fms
* @method _findLegIndexForProcedureType
* @param procedureType {PROCEDURE_TYPE|string} either `SID` or `STAR`, but can be extended to anything in the
* `PROCEDURE_TYPE` enum
* @return {number} array index of a `procedureType` from the `#legCollection`
* @private
*/
_findLegIndexForProcedureType(procedureType) {
return _findIndex(this.legCollection, { isProcedure: true, procedureType: procedureType });
}
/**
* Locate a `LegModel` in the collection by it's `#routeString` property
*
* @for Fms
* @method _findLegIndexByRouteString
* @param routeString {string}
* @return {number|undefined} array index of the found `LegModel` or undefined
*/
_findLegIndexByRouteString(routeString) {
return _findIndex(this.legCollection, { routeString: routeString });
}
/**
* Loop through the `#legCollection` up to the `legIndex` and add each
* `routeString` to `#_previousRouteSegments`.
*
* Called from `.skipToWaypoint()` before the `currentLeg` is updated to the
* `LegModel` at `legIndex`.
*
* @for Fms
* @method _collectRouteStringsForLegsToBeDropped
* @param legIndex {number} index number of the next currentLeg
* @private
*/
_collectRouteStringsForLegsToBeDropped(legIndex) {
for (let i = 0; i < legIndex; i++) {
this._previousRouteSegments.push(this.legCollection[i].routeString);
}
}
/**
* Loop through each `LegModel` and call `.destroy()`
*
* This clears destroys each `WaypointModel` contained within each
* `LegModel` in the collection.
*
* TODO: implement object pooling with `LegModel` and `WaypointModel`,
* this is the method where the `LegModel` is be returned to the pool
*
* @for Fms
* @method _destroyLegCollection
* @private
*/
_destroyLegCollection() {
for (let i = 0; i < this.legCollection.length; i++) {
const legModel = this.legCollection[i];
legModel.destroy();
}
this.legCollection = [];
}
/**
* Find a LegModel within the collection by its route string
*
* @for Fms
* @method _findLegByRouteString
* @param routeString {string}
* @return {LegModel|undefined}
* @private
*/
_findLegByRouteString(routeString) {
return _find(this.legCollection, { routeString: routeString.toLowerCase() });
}
/**
* This method will find an leg at `legIndex` in the `#legCollection` and
* replace it with a new `routeString`.
*
* It is important to note that this doesn't create a new `LegModel` instance.
* Instead, this locates the leg at `legIndex`, destroys it's properties, then
* runs `init()` with the new `routeString`.
*
* @for Fms
* @method _replaceLegAtIndexWithRouteString
* @param legIndex {number} array index of the leg to replace
* @param routeString {string} routeString to use for the replacement leg
* @private
*/
_replaceLegAtIndexWithRouteString(legIndex, routeString) {
const legModel = this.legCollection[legIndex];
legModel.destroy();
legModel.init(routeString, this.currentRunwayName, this.currentPhase);
}
/**
* Set the currentPhase with the appropriate value, based on the spawn category
*
* @for Fms
* @method _setCurrentPhaseFromCategory
* @param category {string}
* @private
*/
_setCurrentPhaseFromCategory(category) {
switch (category) {
case FLIGHT_CATEGORY.ARRIVAL:
this.setFlightPhase(FLIGHT_PHASE.CRUISE);
break;
case FLIGHT_CATEGORY.DEPARTURE:
this.setFlightPhase(FLIGHT_PHASE.APRON);
break;
default:
break;
}
}
/**
* Set the appropriate runway property with the passed `RunwayModel`
*
* @for Fms
* @method _setInitialRunwayAssignmentFromCategory
* @param category {string}
* @param runway {RunwayModel}
* @private
*/
_setInitialRunwayAssignmentFromCategory(category, runway) {
// TODO: change to switch with a default throw
if (category === FLIGHT_CATEGORY.ARRIVAL) {
this.setArrivalRunway(runway);
} else if (category === FLIGHT_CATEGORY.DEPARTURE) {
this.setDepartureRunway(runway);
}
}
/**
* Given a `procedureId` find the `#collectionName` that
* procedure belongs to, then translate that `#collectionName`
* to a `flightPhase`.
*
* @for Fms
* @method _translateProcedureNameToFlightPhase
* @param procedureId {string}
* @return {string}
* @private
*/
_translateProcedureNameToFlightPhase(procedureId) {
const collectionToFlightPhaseDictionary = {
sidCollection: FLIGHT_CATEGORY.DEPARTURE,
starCollection: FLIGHT_CATEGORY.ARRIVAL
};
const collectionName = this._navigationLibrary.findCollectionNameForProcedureId(procedureId);
return collectionToFlightPhaseDictionary[collectionName];
}
/**
* Removes `LegModel`s from index `0` to `#legIndex`.
*
* This method is useful for removing a specific number of `LegModel`s
* from the left of the collection.
*
* @for Fms
* @method _trimLegCollectionAtIndex
* @param legIndex {number}
* @private
*/
_trimLegCollectionAtIndex(legIndex) {
this.legCollection = this.legCollection.slice(legIndex);
}
// TODO: simplify this and abstract it away from `.prependLeg()`
/**
* Given an array of `routeSegments`, prepend each to the left of the `#legCollection`
*
* @for Fms
* @method _prependLegCollectionWithRouteAmendment
* @param routeSegments {array<string>} direct or procedure routeStrings
* @private
*/
_prependLegCollectionWithRouteAmendment(routeSegments) {
// reversing order here because we're leveraging `.prependLeg()`, which adds a single
// leg to the left of the `#legCollection`. by reversing the array, we can ensure the
// correct order of legs.
const routeSegmentList = routeSegments.slice().reverse();
for (let i = 0; i < routeSegmentList.length; i++) {
const routeSegment = routeSegmentList[i];
const legModel = this._buildLegModelFromRouteSegment(routeSegment);
this.prependLeg(legModel);
}
}
/**
* Add the `#currentPhase` to `#_flightPhaseHistory`
*
* @for Fms
* @method _addPhaseToFlightHistory
* @private
*/
_addPhaseToFlightHistory() {
if (this.currentPhase === '') {
return;
}
this._flightPhaseHistory.push(this.currentPhase);
}
/**
* Adds a `routeString` to `#_previousRouteSegments` only when it is not
* already present in the list
*
* @for Fms
* @method _updatePreviousRouteSegments
* @param routeString {string} a valid routeString
*/
_updatePreviousRouteSegments(routeString) {
if (this._previousRouteSegments.indexOf(routeString) !== -1) {
return;
}
this._previousRouteSegments.push(routeString);
}
} |
JavaScript | class GetLog extends ClientCommand {
performAction(actionCallback) {
this.api.sessionLog(this.typeString, actionCallback);
}
command(typeString = 'browser', callback) {
if (arguments.length === 1 && typeof arguments[0] == 'function') {
callback = arguments[0];
typeString = 'browser';
}
this.typeString = typeString;
return super.command(callback);
}
} |
JavaScript | class HingeConstraint extends PointToPointConstraint {
constructor(bodyA, bodyB, options = {}) {
const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6
const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3()
const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3()
super(bodyA, pivotA, bodyB, pivotB, maxForce)
/**
* Rotation axis, defined locally in bodyA.
* @property {Vec3} axisA
*/
const axisA = (this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0))
axisA.normalize()
/**
* Rotation axis, defined locally in bodyB.
* @property {Vec3} axisB
*/
const axisB = (this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0))
axisB.normalize()
/**
* @property {RotationalEquation} rotationalEquation1
*/
const r1 = (this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options))
/**
* @property {RotationalEquation} rotationalEquation2
*/
const r2 = (this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options))
/**
* @property {RotationalMotorEquation} motorEquation
*/
const motor = (this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce))
motor.enabled = false // Not enabled by default
// Equations to be fed to the solver
this.equations.push(
r1, // rotational1
r2, // rotational2
motor
)
}
/**
* @method enableMotor
*/
enableMotor() {
this.motorEquation.enabled = true
}
/**
* @method disableMotor
*/
disableMotor() {
this.motorEquation.enabled = false
}
/**
* @method setMotorSpeed
* @param {number} speed
*/
setMotorSpeed(speed) {
this.motorEquation.targetVelocity = speed
}
/**
* @method setMotorMaxForce
* @param {number} maxForce
*/
setMotorMaxForce(maxForce) {
this.motorEquation.maxForce = maxForce
this.motorEquation.minForce = -maxForce
}
update() {
const bodyA = this.bodyA
const bodyB = this.bodyB
const motor = this.motorEquation
const r1 = this.rotationalEquation1
const r2 = this.rotationalEquation2
const worldAxisA = HingeConstraint_update_tmpVec1
const worldAxisB = HingeConstraint_update_tmpVec2
const axisA = this.axisA
const axisB = this.axisB
super.update()
// Get world axes
bodyA.quaternion.vmult(axisA, worldAxisA)
bodyB.quaternion.vmult(axisB, worldAxisB)
worldAxisA.tangents(r1.axisA, r2.axisA)
r1.axisB.copy(worldAxisB)
r2.axisB.copy(worldAxisB)
if (this.motorEquation.enabled) {
bodyA.quaternion.vmult(this.axisA, motor.axisA)
bodyB.quaternion.vmult(this.axisB, motor.axisB)
}
}
} |
JavaScript | class MediaQueryManager extends PaginatedQueryManager {
static QueryKey = MediaQueryKey;
static DefaultQuery = DEFAULT_MEDIA_QUERY;
/**
* Returns true if the media item matches the given query, or false
* otherwise.
*
* @param {Object} query Query object
* @param {Object} media Item to consider
* @return {Boolean} Whether media item matches query
*/
static matches( query, media ) {
return every( { ...this.DefaultQuery, ...query }, ( value, key ) => {
switch ( key ) {
case 'search':
if ( ! value ) {
return true;
}
return media.title && includes( media.title.toLowerCase(), value.toLowerCase() );
case 'mime_type':
if ( ! value ) {
return true;
}
// See: https://developer.wordpress.org/reference/functions/wp_post_mime_type_where/
return new RegExp(
`^${ value
// Replace wildcard-only, wildcard group, and empty
// group with wildcard pattern matching
.replace( /(^%|(\/)%?)$/, '$2.+' )
// Split subgroup and group to filter
.split( '/' )
// Remove invalid characters
.map( group => group.replace( /[^-*.+a-zA-Z0-9]/g, '' ) )
// If no group, append wildcard match
.concat( '.+' )
// Take only subgroup and group
.slice( 0, 2 )
// Finally, merge back into string
.join( '/' ) }$`
).test( media.mime_type );
case 'post_ID':
// Note that documentation specifies that query value of 0
// will match only media not attached to posts, but since
// those media items assign post_ID of 0, we can still
// match by equality
return value === media.post_ID;
case 'after':
case 'before':
const queryDate = moment( value, moment.ISO_8601 );
const comparison = /after$/.test( key ) ? 'isAfter' : 'isBefore';
return queryDate.isValid() && moment( media.date )[ comparison ]( queryDate );
}
return true;
} );
}
/**
* A sort comparison function that defines the sort order of media items
* under consideration of the specified query.
*
* @param {Object} query Query object
* @param {Object} mediaA First media item
* @param {Object} mediaB Second media item
* @return {Number} 0 if equal, less than 0 if mediaA is first,
* greater than 0 if mediaB is first.
*/
static compare( query, mediaA, mediaB ) {
let order;
switch ( query.order_by ) {
case 'id':
order = mediaA.id - mediaB.id;
break;
case 'title':
order = mediaA.title.localeCompare( mediaB.title );
break;
case 'date':
default:
order = moment( mediaA.date ).diff( mediaB.date );
}
// Default to descending order, opposite sign of ordered result
if ( ! query.order || /^desc$/i.test( query.order ) ) {
order *= -1;
}
return order || 0;
}
} |
JavaScript | class Schema {
constructor(options) {
this.options = options;
}
validate(field, value) {
// TODO: validate agaisnt json schema
}
} |
JavaScript | class EveSpriteLineSetBatch
{
spriteLineSet = null;
/**
* Commits the batch for rendering
* @param {String} technique
*/
Commit(technique)
{
this.spriteLineSet.Render(technique);
}
} |
JavaScript | class EveSpriteLineSetItem extends EveObjectSetItem
{
// ccp
blinkPhase = 0;
blinkPhaseShift = 0;
blinkRate = 0;
boneIndex = 0;
colorType = 0;
falloff = 0;
intensity = 0;
isCircle = false;
maxScale = 0;
minScale = 0;
position = vec3.create();
rotation = quat.create();
scaling = vec3.fromValues(1, 1, 1);
spacing = 0;
// ccpwgl
display = true;
transform = mat4.create();
_dirty = true;
/**
* Fires on value changes
*/
OnValueChanged()
{
mat4.fromRotationTranslationScale(this.transform, this.rotation, this.position, this.scaling);
this._dirty = true;
}
} |
JavaScript | class EveSpriteLineSet extends EveObjectSet
{
/**
* Unloads the sprite line set's buffers
*/
Unload()
{
// TODO: Unload
}
/**
* Rebuilds the sprite line set's buffers
*/
Rebuild()
{
// TODO: Rebuild
}
/**
* Gets the sprite line set's render batches
* @param {Number} mode
* @param {Tw2BatchAccumulator} accumulator
* @param {Tw2PerObjectData} perObjectData
*/
GetBatches(mode, accumulator, perObjectData)
{
// TODO: GetBatches
}
/**
* Renders the sprite line set
* @param {String} technique - technique name
* @returns {Boolean} - true if rendered
*/
Render(technique)
{
// TODO: Render
}
} |
JavaScript | class ContinuousDialog extends BaseConfig {
/**
* get intent map
* @returns {object} - intent map
*/
getIntentMap () {
return {
pickupswitch: this.applyPickupSwitch.bind(this)
}
}
/**
* get url map
* @returns {object} - url map
*/
getUrlMap () {
return {
continuousDialog: this.onPickupSwitchStatusChanged.bind(this)
}
}
/**
* handler of skill url
* @param {object} queryObj
*/
onPickupSwitchStatusChanged (queryObj) {
if (queryObj) {
this.applyPickupSwitch(queryObj.action, queryObj.isFirstLoad)
}
}
/**
* handler of intent
* @param action
* @param isFirstLoad
*/
applyPickupSwitch (action, isFirstLoad) {
if (action) {
property.set('sys.pickupswitch', action, 'persist')
if (!isFirstLoad) {
if (action === SWITCH_OPEN) {
this.activity.tts.speak(PICKUP_SWITCH_OPEN).then(() => this.activity.exit())
} else if (action === SWITCH_CLOSE) {
this.activity.tts.speak(PICKUP_SWITCH_CLOSE).then(() => this.activity.exit())
} else {
this.activity.tts.speak(CONFIG_FAILED).then(() => this.activity.exit())
}
}
}
}
} |
JavaScript | class EventManager {
/**
* Constructor
* @param {boolean} enabled - if true (default), the events emitting is enabled, if false, they won't be fired.
*/
constructor(enabled=true) {
this._events = {}
this._enabled = enabled
// by event hash, stores the even name and the callback, in order to remove it
// efficiently
this._eventIndex = {}
}
/**
* Tells how many events are registered under this event name
* @return {number}
*/
countEvents(eventName){
if(eventName in this._events){
return this._events[eventName].length
}else{
return 0
}
}
/**
* This way, the events are not emitted
*/
disableEvents() {
this._enabled = false
}
/**
* This way, the events are properly emitted
*/
enableEvents() {
this._enabled = true
}
/**
* Define an event, with a name associated with a function
* @param {String} eventName - Name to give to the event
* @param {Function} callback - function associated to the even
* @return {string|null} the eventId (useful to remove it) or null if the event couldnt be added
*/
on(eventName, callback) {
if (typeof callback === 'function') {
if (!(eventName in this._events)) {
this._events[eventName] = []
}
let eventId = uuidv4()
this._eventIndex[eventId] = {
eventName: eventName,
callback: callback
}
this._events[eventName].push(eventId)
return eventId
} else {
console.warn('The callback must be of type Function')
}
return null
}
/**
* Emit the event, run the functions attached to it
* @param {string} eventName - the name of the event to run
* @param {Array} args - array of arguments the event callbacks are going to be called with (with destructuring operator)
*/
emit(eventName, args = []) {
if(!this._enabled){
return
}
// the event must exist and be non null
if ((eventName in this._events) && (this._events[eventName].length > 0)) {
const events = this._events[eventName]
for (let i = 0; i < events.length; i += 1) {
this._eventIndex[events[i]].callback(...args)
}
} else {
//console.warn(`No function associated to the event ${eventName}`)
}
}
/**
* Emit the event, run the functions attached to it in a async fashion
* @param {string} eventName - the name of the event to run
* @param {Array} args - array of arguments the event callbacks are going to be called with (with destructuring operator)
*/
async emitAsync(eventName, args = []) {
if(!this._enabled){
return
}
// the event must exist and be non null
if ((eventName in this._events) && (this._events[eventName].length > 0)) {
const events = this._events[eventName]
for (let i = 0; i < events.length; i += 1) {
await this._eventIndex[events[i]].callback(...args)
}
} else {
//console.warn(`No function associated to the event ${eventName}`)
}
}
/**
* Delete an event using its id
* @param {string} id - id of the event (returned by the `.on()` method)
*/
delete(eventId) {
if(!(eventId in this._eventIndex)){
console.log(`No event of id ${eventId}.`)
return
}
// array of events of the same name as eventId
let eventOfSameName = this._events[this._eventIndex[eventId].eventName]
let index = eventOfSameName.indexOf(eventId)
delete this._eventIndex[eventId]
if(index !== -1) {
eventOfSameName.splice(index, 1)
}
if(eventOfSameName.length === 0){
delete this._events[this._eventIndex[eventId].eventName]
}
}
} |
JavaScript | class Controller {
constructor(canvas, {initialZoom = 2, onDrop = (file) => {}} = {}) {
this.mouse = {
lastX: 0,
lastY: 0
};
this.translate = initialZoom;
this.rotation = [0, 0];
this.rotationStart = [0, 0];
this.rotationAnimation = true;
this.onDrop = onDrop;
this._initializeEventHandling(canvas);
}
animate(time) {
if (this.rotationAnimation) {
this.rotation[1] = time / 3600;
}
}
getMatrices() {
const [pitch, roll] = this.rotation;
const cameraPosition = [
-this.translate * Math.sin(roll) * Math.cos(-pitch),
-this.translate * Math.sin(-pitch),
this.translate * Math.cos(roll) * Math.cos(-pitch)
];
const viewMatrix = new Matrix4()
.translate([0, 0, -this.translate])
.rotateX(pitch)
.rotateY(roll);
return {
cameraPosition,
viewMatrix
};
}
// PRIVATE
_initializeEventHandling(canvas) {
canvas.onwheel = (e) => {
this.translate += e.deltaY / 10;
if (this.translate < 0.1) {
this.translate = 0.1;
}
e.preventDefault();
};
canvas.onpointerdown = (e) => {
this.mouse.lastX = e.clientX;
this.mouse.lastY = e.clientY;
this.rotationStart[0] = this.rotation[0];
this.rotationStart[1] = this.rotation[1];
canvas.setPointerCapture(e.pointerId);
e.preventDefault();
this.rotationAnimation = false;
};
canvas.onpointermove = (e) => {
if (e.buttons) {
const dX = e.clientX - this.mouse.lastX;
const dY = e.clientY - this.mouse.lastY;
this.rotation[0] = this.rotationStart[0] + dY / 100;
this.rotation[1] = this.rotationStart[1] + dX / 100;
}
};
canvas.ondragover = (e) => {
e.dataTransfer.dropEffect = 'link';
e.preventDefault();
};
canvas.ondrop = async (event) => {
event.preventDefault();
if (event.dataTransfer.files && event.dataTransfer.files.length === 1) {
const file = event.dataTransfer.files[0];
this.onDrop(file);
}
};
}
} |
JavaScript | class BarElement extends PluginElement {
/**
* @param {BarView} view
* @param opts
* @constructor
*/
constructor(view, opts) {
super('BarElement', view);
this._config(view, opts, window.$(this.getTemplate())).build(opts);
}
/**
* Define template
* @memberOf BarElement
* @returns {string}
*/
getTemplate() {
return `<ul class="nav" />`;
}
} |
JavaScript | class CallProperties {
/**
* A URI that uniquely identifies the call's handler.
* @type {String}
* @const
*/
endpoint;
/**
* The HTTP method used for the call.
* @type {String}
* @const
*/
method;
/**
* A short description of the call's purpose.
* @type {String}
* @const
*/
label;
/**
* The descriptors (keys) of the call arguments.
* @type {Array<String>}
* @const
*/
argKeys;
/**
* The passed value for each call argument.
* @type {Array<String>}
* @const
*/
argVals;
/**
* A concatenation of all code snippets contained in the call.
* @type {String}
* @const
*/
code;
/**
* Create a new CallProperties instance.
* @param {String} endpoint A URI that uniquely identifies the call's
* handler.
* @param {String} method The HTTP method used for the call.
* @param {String} label The arguments of the call
* @param {Array<String>} argKeys The descriptors (keys) of the call
* arguments.
* @param {Array<String>} argVals The passed value for each call argument.
* @param {String} code A concatenation of all code snippets contained in the
* call.
*/
constructor(
endpoint,
method,
label,
argKeys,
argVals,
code,
) {
this.endpoint = endpoint;
this.method = method;
this.label = label;
this.argKeys = argKeys;
this.argVals = argVals;
this.code = code;
}
/** @return {Boolean} */
hasArgs() {
return this.argKeys != null && this.argKeys.length > 0;
}
/** @return {Boolean} */
hasCode() {
return this.code != null;
}
/** @return {Boolean} */
hasLabel() {
return this.label != null;
}
/** @return {Boolean} */
hasMethod() {
return this.method != null;
}
} |
JavaScript | class BaseTransport extends events_1.EventEmitter {
constructor({ address, port, id, serverPort, protocol }) {
super();
this.onconnect = () => { };
this.onclose = () => { };
this.onerror = (error) => { };
this.onrpcRequest = (rpcRequests) => { };
this.onnotmatch = (rpcRequest) => { };
this._onconnect = () => __awaiter(this, void 0, void 0, function* () { yield this.onconnect(); });
this._onclose = () => __awaiter(this, void 0, void 0, function* () { yield this.onclose(); });
this._onerror = (error) => __awaiter(this, void 0, void 0, function* () { yield this.onerror(error); });
this.on("connect", this._onconnect);
this.on("close", this._onclose);
this.on("error", this._onerror);
this._transport = TransportCreator_1.TransportCreator.create({ address, port, id, serverPort, protocol });
this._transport.onconnect = this._onconnect;
this._transport.onclose = this._onclose;
this._transport.onerror = this._onerror;
}
connect({ timeout } = {}) {
return __awaiter(this, void 0, void 0, function* () { return yield this._transport.connect({ timeout }); });
}
request(message) {
return __awaiter(this, void 0, void 0, function* () { return yield this._transport.request(message); });
}
send(message) {
return __awaiter(this, void 0, void 0, function* () { return yield this._transport.send(message); });
}
close() {
return __awaiter(this, void 0, void 0, function* () { yield this._transport.close(); });
}
isConnected() { return this._transport.isConnected(); }
setTimeout(timeout) { this._transport.setTimeout(timeout); }
} |
JavaScript | class SpaceShuttleClass {
constructor(targetPlanet) {
this.targetPlanet = targetPlanet;
}
} |
JavaScript | class Thermostat {
constructor(fahrenheit){
this._fahrenheit = fahrenheit;
}
get temperature(){
return (5 / 9) * (this._fahrenheit - 32);
}
set temperature(celsius){
this._fahrenheit = (celsius * 9.0) / 5 + 32;
}
} |
JavaScript | class CSHandler{
/**
* Constructs a new Handler and
* declares a store instance to use.
* @constructor
*/
constructor(){
//For easy access
Object.defineProperty(this,'centralState',{
get: ()=>{return Store._state}
});
}
/**
* @param {Object} partialstate object with keys and
* properties to assign to the current state
*/
setCentralState(partialstate){
Store.setPartial(partialstate);
}
/**
* Adds a callback to be called when at least one
* of the state properties with its key belonging
* to triggers changes
* @param {Function} callback function to
* call when the change occurs
* @param {...string} triggers properties keys that
* will trigger the callback on changing
*/
addCentralStateListener(callback,...triggers){
Store.addListener(callback,...triggers)
}
/**
* Removes a callback if it is registered.
* @param {Function} callback function registered
* with addCentralStateListener
*/
removeCentralStateListener(callback){
Store.removeListener(callback)
}
} |
JavaScript | class Tree {
/**
* Creates a Tree Object
*/
constructor() {
this.margin = {top: 20, right: 90, bottom: 30, left: 90};
this.width = 500 - this.margin.left - this.margin.right;
this.height = 700 - this.margin.top - this.margin.bottom;
}
/**
* Creates a node/edge structure and renders a tree layout based on the input data
*
* @param treeData an array of objects that contain parent/child information.
*/
createTree(treeData) {
// ******* TODO: PART VI *******
//Create a tree and give it a size() of 800 by 300.
//Create a root for the tree using d3.stratify();
//Add nodes and links to the tree.
this.treeData = treeData;
treeData = treeData.map(game => {
game["ParentGame"] = treeData[game["ParentGame"]] ? treeData[game["ParentGame"]].id : null;
return game;
});
var treeData1 = d3.stratify()
.id(function(d) { return d.id; })
.parentId(function(d) { return d.ParentGame; })
(treeData);
// assign the name to each node
treeData1.each(function(d) {
d.name = d.Team;
});
// set the dimensions and margins of the diagram
var margin = this.margin;
var width = this.width;
var height = this.height;
// declares a tree layout and assigns the size
var treemap = d3.tree()
.size([height, width]);
// assigns the data to a hierarchy using parent-child relationships
var nodes = d3.hierarchy(treeData1, function(d) {
return d.children;
});
// maps the node data to the tree layout
nodes = treemap(nodes);
// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#treeSvg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom);
var g = svg.select("#tree")
.attr("transform", "translate("
+ margin.left + "," + margin.top + ")");
// adds the links between the nodes
var link = g.selectAll(".link")
.data( nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("id", d => d.data.data.Team)
.attr("d", function(d) {
return "M" + d.y + "," + d.x
+ "C" + (d.y + d.parent.y) / 2 + "," + d.x
+ " " + (d.y + d.parent.y) / 2 + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});
// adds each node as a group
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("g")
.attr("class", function(d) {
return "node" +
(d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")"; });
// adds the circle to the node
node.append("circle")
.attr("r", 5)
.attr("class", d => d.data.data.Wins == "1" ? "winner" : "loser")
// adds the text to the node
node.append("text")
.attr("dy", ".35em")
.attr("x", function(d) { return d.children ? -13 : 13; })
.attr("id", d => d.data.data.Team)
.style("text-anchor", function(d) {
return d.children ? "end" : "start"; })
.text(function(d) {
return d.data.data.Team;
});
};
/**
* Updates the highlighting in the tree based on the selected team.
* Highlights the appropriate team nodes and labels.
*
* @param row a string specifying which team was selected in the table.
*/
updateTree(row) {
// ******* TODO: PART VII *******
if (!row) return;
d3.selectAll("text#" + row.key).each(function () {
d3.select(this).attr("class", "selectedLabel")
})
d3.selectAll("path#" + row.key).each(function () {
d3.select(this).attr("class", "selected")
})
}
/**
* Removes all highlighting from the tree.
*/
clearTree() {
// ******* TODO: PART VII *******
d3.selectAll("path.selected")
.attr("class", "link")
d3.selectAll("text.selectedLabel")
.attr("class", "")
// You only need two lines of code for this! No loops!
}
} |
JavaScript | class CharacterController extends CreatureController {
/**
* Creates a Character Controller
* @param {string} id
* @param {BABYLON.AbstractMesh} mesh
* @param {object} entityObject
*/
constructor(id = "", mesh = null, entityObject = {}) {
if (EntityController.debugMode) console.group(`Creating new CharacterController(${id}, meshObject, entityObject)`);
if (!(super(id, mesh, entityObject) instanceof CreatureController)) {
return undefined;
}
this._equipmentMeshIDsAttachedToBones = {};
this.helmetVisible = true;
this.bHasRunPostConstructCharacter = false;
CharacterController.set(this.id, this);
if (EntityController.debugMode) console.info(`Finished creating new CharacterController(${this.id})`);
if (EntityController.debugMode) console.groupEnd();
this.postConstruct();
}
postConstruct() {
if (this.bHasRunPostConstructCharacter) {
return 0;
}
super.postConstruct();
this.bHasRunPostConstructCharacter = true;
return 0;
}
detachFromAllBones(destroyMesh = true) {
if (!(this.skeleton instanceof BABYLON.Skeleton)) {
return 0;
}
for (let boneID in this._equipmentMeshIDsAttachedToBones) {
for (let meshID in this._equipmentMeshIDsAttachedToBones[boneID]) {
if (this._bonesAttachedToMeshes.hasOwnProperty(meshID)) {
let bone = this.getBone(boneID);
this.detachMeshFromBone(this._bonesAttachedToMeshes[meshID], bone, destroyMesh);
}
delete this._equipmentMeshIDsAttachedToBones[boneID][meshID];
}
delete this._equipmentMeshIDsAttachedToBones[boneID];
}
super.detachFromAllBones(destroyMesh);
return 0;
}
attachEquipmentMeshToBone(mesh, boneID, position, rotation, scaling, options) {
if (!this.hasBone(boneID)) {
return 1;
}
if (!this._equipmentMeshIDsAttachedToBones.hasOwnProperty(boneID)) {
this._equipmentMeshIDsAttachedToBones[boneID] = {};
}
this._equipmentMeshIDsAttachedToBones[boneID][mesh.name] = mesh.material.name;
this.attachMeshToBone(mesh, bone, position, rotation, scaling, options);
return 0;
}
attachEquipmentMeshIDToBone(meshID, materialID, boneID, position, rotation, scaling, options) {
if (!this.hasBone(boneID)) {
return 1;
}
if (!this._equipmentMeshIDsAttachedToBones.hasOwnProperty(boneID)) {
this._equipmentMeshIDsAttachedToBones[boneID] = {};
}
this._equipmentMeshIDsAttachedToBones[boneID][meshID] = materialID;
this.attachMeshIDToBone(meshID, materialID, boneID, position, rotation, scaling, options);
return 0;
}
detachEquipmentMeshID(meshID) {
return 0;
}
detachEquipmentMesh(mesh) {
return 0;
}
detachEquipmentMeshesFromBone(boneID, destroyMesh = true) {
let bone = null;
if (boneID instanceof BABYLON.Bone) {
bone = boneID;
boneID = bone.id;
}
else if (!this.hasBone(boneID)) {
return 1;
}
else {
bone = this.getBone(boneID);
}
for (let meshID in this._equipmentMeshIDsAttachedToBones[boneID]) {
if (this._bonesAttachedToMeshes.hasOwnProperty(meshID)) {
this.detachMeshFromBone(this._bonesAttachedToMeshes[meshID], boneID, destroyMesh)
}
}
delete this._equipmentMeshIDsAttachedToBones[boneID];
return 0;
}
detachEquipmentMeshes(destroyMesh = true) {
for (let boneID in this._equipmentMeshIDsAttachedToBones) {
for (let meshID in this._equipmentMeshIDsAttachedToBones[boneID]) {
if (this._bonesAttachedToMeshes.hasOwnProperty(meshID)) {
let bone = this.getBone(boneID);
this.detachMeshFromBone(this._bonesAttachedToMeshes[meshID], bone, destroyMesh);
}
delete this._equipmentMeshIDsAttachedToBones[boneID][meshID];
}
delete this._equipmentMeshIDsAttachedToBones[boneID];
}
return 0;
}
populateFromEntity(entityObject, overwrite = true) {
if (EntityController.debugMode) console.group(`Running {CharacterController} ${this.id}.populateFromEntity(entityObject)`);
if (!(entityObject instanceof Object)) {
if (EntityController.debugMode) console.warn(`entityObject was not an object`);
if (EntityController.debugMode) console.groupEnd();
return 2;
}
super.populateFromEntity(entityObject);
let equipmentObject = null;
let meshID = null;
let materialID = null;
if (entityObject.hasOwnProperty("equipment")) {
for (let boneID in entityObject["equipment"]) {
if (!(entityObject["equipment"][boneID] instanceof Object)) {
if (overwrite) {
this.detachEquipmentMeshesFromBone(boneID, true);
}
}
else {
equipmentObject = entityObject["equipment"][boneID];
if (equipmentObject.hasOwnProperty("meshID")) {
meshID = entityObject.equipment[boneID]["meshID"];
if (equipmentObject.hasOwnProperty("materialID")) {
materialID = entityObject.equipment[boneID]["materialID"];
}
else if (equipmentObject.hasOwnProperty("textureID")) {
materialID = entityObject.equipment[boneID]["textureID"];
}
else {
material = "missingMaterial";
}
this.attachEquipmentMeshIDToBone(meshID, materialID, boneID);
}
}
}
}
if (EntityController.debugMode) console.info(`Finished running {CharacterController} ${this.id}.populateFromEntity(entityObject)`);
if (EntityController.debugMode) console.groupEnd();
return 0;
}
updateFromEntity(thatEntity) {
super.updateFromEntity(thatEntity);
let thisEntity = Game.getCachedEntity(this.entityID);
if (thisEntity.hasOwnProperty("equipment") && thatEntity.hasOwnProperty("equipment")) {
for (let equipmentSlot in thisEntity.equipment) {
if (thatEntity["equipment"][equipmentSlot] == null) {
this.detachEquipmentMeshesFromBone(equipmentSlot);
}
else if (thisEntity["equipment"][equipmentSlot] == null) {
this.attachEquipmentMeshToBone(thatEntity["equipment"][equipmentSlot]["meshID"], thatEntity["equipment"][equipmentSlot]["materialID"], equipmentSlot);
}
else if (thisEntity["equipment"][equipmentSlot]["id"] != thatEntity["equipment"][equipmentSlot]["id"]) {
this.detachEquipmentMeshesFromBone(equipmentSlot);
this.attachEquipmentMeshToBone(thatEntity["equipment"][equipmentSlot]["meshID"], thatEntity["equipment"][equipmentSlot]["materialID"], equipmentSlot);
}
}
}
return 0;
}
hideHelmet() {
if (!(this.skeleton instanceof BABYLON.Skeleton)) {
return 2;
}
if (this._meshesAttachedToBones.hasOwnProperty("head")) {
for (let mesh in this._meshesAttachedToBones["head"]) {
if (this._meshesAttachedToBones["head"][mesh] instanceof BABYLON.AbstractMesh) {
this._meshesAttachedToBones["head"][mesh].isVisible = false;
}
}
}
this.helmetVisible = false;
return 0;
}
showHelmet() {
if (!(this.skeleton instanceof BABYLON.Skeleton)) {
return 2;
}
if (this._meshesAttachedToBones.hasOwnProperty("head")) {
for (let mesh in this._meshesAttachedToBones["head"]) {
if (this._meshesAttachedToBones["head"][mesh] instanceof BABYLON.AbstractMesh) {
this._meshesAttachedToBones["head"][mesh].isVisible = true;
}
}
}
this.helmetVisible = true;
return 0;
}
detachFromAllBones(destroyMesh = true) {
if (!(this.skeleton instanceof BABYLON.Skeleton)) {
return 2;
}
super.detachFromAllBones(destroyMesh);
return 0;
}
generateHitboxes() {
switch (this.meshID) {
case "aardwolfM":
case "aardwolfF":
case "foxM":
case "foxF":
case "foxSkeletonN": {
this.attachToROOT("hitbox.canine", "collisionMaterial");
this.attachToHead("hitbox.canine.head", "collisionMaterial", { isHitbox: true });
this.attachToNeck("hitbox.canine.neck", "collisionMaterial", { isHitbox: true });
this.attachToChest("hitbox.canine.chest", "collisionMaterial", { isHitbox: true });
this.attachToLeftHand("hitbox.canine.hand.l", "collisionMaterial", { isHitbox: true });
this.attachToRightHand("hitbox.canine.hand.r", "collisionMaterial", { isHitbox: true });
this.attachToSpine("hitbox.canine.spine", "collisionMaterial", { isHitbox: true });
this.attachToPelvis("hitbox.canine.pelvis", "collisionMaterial", { isHitbox: true });
break;
}
}
return 0;
}
/**
* Generates attached organ meshes :V
* @returns {null} null
*/
generateOrganMeshes() {
if (!this.hasSkeleton()) {
return 1;
}
super.generateOrganMeshes();
return 0;
}
/**
* Generates attached cosmetic meshes according to entity's cosmetics
* @returns {null} null
*/
generateCosmeticMeshes() { // TODO
if (!this.hasSkeleton()) {
return 1;
}
return 0;
}
/**
* Generated attached equipment meshes according to entity's equipment
* @returns {null} null
*/
generateEquippedMeshes() {
if (!this.hasSkeleton()) {
return 1;
}
return 0;
}
updateID(newID) {
super.updateID(newID);
CharacterController.updateID(this.id, newID);
return 0;
}
dispose() {
this.setLocked(true);
this.setEnabled(false);
this.detachEquipmentMeshes(true);
CharacterController.remove(this.id);
super.dispose();
return undefined;
}
getClassName() {
return "CharacterController";
}
static initialize() {
CharacterController.characterControllerList = {};
EntityController.debugMode = false;
EntityController.debugVerbosity = 2;
}
static get(id) {
if (CharacterController.has(id)) {
return CharacterController.characterControllerList[id];
}
return 1;
}
static has(id) {
return CharacterController.characterControllerList.hasOwnProperty(id);
}
static set(id, characterController) {
CharacterController.characterControllerList[id] = characterController;
return 0;
}
static remove(id) {
delete CharacterController.characterControllerList[id];
return 0;
}
static list() {
return CharacterController.characterControllerList;
}
static clear() {
for (let i in CharacterController.characterControllerList) {
CharacterController.characterControllerList[i].dispose();
}
CharacterController.characterControllerList = {};
return 0;
}
static updateID(oldID, newID) {
if (!CharacterController.has(oldID)) {
return 1;
}
CharacterController.set(newID, CharacterController.get(oldID));
CharacterController.remove(oldID);
return 0;
}
static setDebugMode(debugMode) {
if (debugMode == true) {
EntityController.debugMode = true;
for (let characterController in CharacterController.characterControllerList) {
CharacterController.characterControllerList[characterController].debugMode = true;
}
}
else if (debugMode == false) {
EntityController.debugMode = false;
for (let characterController in CharacterController.characterControllerList) {
CharacterController.characterControllerList[characterController].debugMode = false;
}
}
return 0;
}
static getDebugMode() {
return EntityController.debugMode === true;
}
} |
JavaScript | class NodeDifference extends Difference {
/**
* Constructor for NodeDifference objects.
* Sets key of the node that the difference belongs to.
* @param nodeKey Key of the node, i.e. the SyncMeta id of it.
* @param nodeValue Value of the node.
*/
constructor(nodeKey, nodeValue, type) {
super(nodeKey, nodeValue, type);
}
/**
* Getter for the type of the node which has changed.
* @returns {*} Type of the node which has changed.
*/
getType() {
return this.getValue()["type"];
}
/**
* Creates the HTML representation of the changed node.
* @param checkboxListener Only set when checkbox should be displayed.
* @returns {HTMLDivElement} HTML representation of the changed node.
*/
toHTMLElement(checkboxListener) {
const element = super.toHTMLElement(checkboxListener);
// set text value
const textElement = element.getElementsByClassName("text")[0];
textElement.innerText = this.getType();
if(this.hasNonEmptyAttributes()) {
// details div should include node attributes
const detailsDiv = element.getElementsByClassName("details")[0];
detailsDiv.appendChild(this.attributesToHTMLElement());
} else {
// remove button for expanding/collapsing details (because no details/non-empty attributes exist)
element.getElementsByClassName("button-expand-collapse")[0].remove();
// set margin right to text, because when removing the button, this is needed
element.getElementsByClassName("text")[0].style.setProperty("margin-right", "1.5em");
}
return element;
}
/**
* Creates a HTML element displaying the attributes of the node.
* @returns {HTMLDivElement} HTML element displaying the attribute of the node.
*/
attributesToHTMLElement() {
const div = document.createElement("div");
const attributes = this.getAttributes();
for(const [key, value] of Object.entries(attributes)) {
// only show those attributes that are set to something
if(value.toString() != "") {
const p = document.createElement("p");
// set key as class, this will then be used to highlight the attribute which got edited (if its a node-update)
p.setAttribute("class", key);
p.innerText = key + ": " + value;
p.style.setProperty("margin-right", "1.5em");
div.appendChild(p);
}
}
return div;
}
/**
* Checks if one of the attribute values of the node is not the empty string.
* @returns {boolean} Whether at least one node attribute exists where the value is not the empty string.
*/
hasNonEmptyAttributes() {
let hasNonEmptyAttributes = false;
for(const [key, value] of Object.entries(this.getAttributes())) {
if(value != "") {
hasNonEmptyAttributes = true;
break;
}
}
return hasNonEmptyAttributes;
}
/**
* Returns a map where the name of an attribute gets mapped to the value of the attribute.
* @returns {Object} Map where the name of an attribute gets mapped to the value of the attribute.
*/
getAttributes() {
const nodeValue = this.getValue();
const syncMetaAttributeMap = nodeValue.attributes;
let attributeMap = new Object();
for(const value of Object.values(syncMetaAttributeMap)) {
const attributeName = value.name;
const attributeValue = value.value.value;
attributeMap[attributeName] = attributeValue;
}
return attributeMap;
}
} |
JavaScript | class Cart {
/**
* Adds two numbers and returns the result
* @param {number} price
* @param {number} item
* @return {number} the result
*/
addition(price, item) {
return price + item;
}
/**
* Divides two numbers and return the result
* @param {number} price
* @param {number} item
* @return {number} the result
*/
divide(price, item) {
return price / item;
}
/**
* Multiplies two numbers and return the result
* @param {number} price
* @param {number} item
* @return {number} the result
*/
multiplication(price, item) {
return price * item;
}
} |
JavaScript | class SubjectWithoutIdentifierError extends TypeORMError {
constructor(subject) {
super(`Internal error. Subject ${subject.metadata.targetName} must have an identifier to perform operation.`);
}
} |
JavaScript | class OverlayFile extends PreloadFile {
constructor(fs, path, flag, stats, data) {
super(fs, path, flag, stats, data);
}
sync(cb) {
if (!this.isDirty()) {
cb(null);
return;
}
this._fs._syncAsync(this, (err) => {
this.resetDirty();
cb(err);
});
}
syncSync() {
if (this.isDirty()) {
this._fs._syncSync(this);
this.resetDirty();
}
}
close(cb) {
this.sync(cb);
}
closeSync() {
this.syncSync();
}
} |
JavaScript | class DevicesManager extends EventEmitter {
constructor(serial, options = {}) {
super();
checkSerial(serial);
this.serial = serial;
this.devices = [];
this.portFilter =
options.portFilter === undefined
? [
{ usbProductId: 37384, usbVendorId: 6991 },
{ usbProductId: 60000, usbVendorId: 4292 },
]
: options.portFilter;
this.baudRate = options.baudRate || 115200;
this.interCommandDelay =
options.interCommandDelay === undefined ? 100 : options.interCommandDelay;
this.defaultCommandExpirationDelay =
options.defaultCommandExpirationDelay === undefined
? 100
: options.defaultCommandExpirationDelay;
}
/**
* By calling this method from a click you give users the possibility to allow access to some devices
*/
async requestDevices() {
await this.serial.requestPort({
filters: this.portFilter,
});
return this.updateDevices();
}
/**
* Update this.devices
*/
async updateDevices() {
const serialPorts = await this.serial.getPorts();
debug('updateDevices');
const missingDevicesSerialPort = this.devices.filter(
(device) => !serialPorts.includes(device.serialPort),
);
for (let device of missingDevicesSerialPort) {
if (device.status !== STATUS_MISSING && device.status !== STATUS_CLOSED) {
device.close();
}
device.status = STATUS_MISSING;
}
for (let serialPort of serialPorts) {
let device = this.devices.filter(
(device) => device.serialPort === serialPort,
)[0];
if (device) {
await device.ensureOpen();
} else {
let newDevice = new Device(serialPort, {
baudRate: this.baudRate,
interCommandDelay: this.interCommandDelay,
defaultCommandExpirationDelay: this.defaultCommandExpirationDelay,
});
this.devices.push(newDevice);
await newDevice.open();
}
}
// check if there are any new ports
}
/**
* Update this.devices every `scanInterval` [ms].
* @param {object} [options={}]
* @param {number} [options.scanInterval=1000] Delay between `updateDevices()` calls
* @param {number} [options.callback] Callback to execute on each update
*/
async continuousUpdateDevices(options = {}) {
const { scanInterval = 1000, callback } = options;
while (true) {
await this.updateDevices();
if (callback) {
callback(this.devices);
}
await delay(scanInterval);
}
}
/**
* Returns this.devices
* @param {object} [options={}]
* @param {bool} [options.ready=false] If `true` returns only currently connected device. If `false` returns all devices ever connected.
* @returns {Array<object>}
*/
getDevicesList(options = {}) {
let { ready = false } = options;
return this.devices
.filter((device) => !ready || device.isReady())
.map((device) => ({
status: device.status,
id: device.id,
queueLength: device.queue.length,
}));
}
// private function
findDevice(id) {
if (id === undefined) return undefined;
let devices = this.devices.filter(
(device) => device.id === id && device.status === STATUS_OPENED,
);
if (devices.length === 0) return undefined;
if (devices.length > 1) {
throw new Error(`Many devices have the same id: ${id}`);
}
return devices[0];
}
/**
* Send a serial command to a device.
* @param {number} id ID of the device
* @param {string} command Command to send
*/
async sendCommand(id, command) {
const device = this.findDevice(id);
if (!device) {
throw Error(`Device ${id} not found`);
}
if (device && device.isReady()) return device.get(command);
throw Error(`Device ${id} not ready: ${device.port.path}`);
}
} |
JavaScript | class Injection extends Item {
/**
* @constructor
* @param {number} x The x-position of the item
* @param {number} y The y-position of the item
* @param {Phaser.Scene} scene The current scene
*/
constructor( x, y, scene ) {
super( { x: x, y: y, scene: scene, key: 'injection' } );
/**
* The amount to heal the player upon use
* @type {number}
*/
this.amount = 5;
/**
* This item can be used anywhere
* @type {ItemType}
*/
this.itemType = ItemType.ANY;
/**
* The name of the item
* @type {string}
*/
this.name = 'Injection';
}
/**
* Uses the item to either heal or hurt the player
* @param {ItemUseConfig} config The configuration passed in
*/
use( config ) {
const player = config.player;
if ( player.health === player.maxHealth ) {
player.injure( this.amount );
player.scene.cameras.main.shake( 200, 0.0025 );
player.scene.cameras.main.flash( 200, 150, 0, 0 );
}
else {
player.heal( this.amount );
}
}
} |
JavaScript | class InputController extends SlotController {
constructor(host, callback) {
super(host, [
'input',
() => document.createElement('input'),
(host, node) => {
if (host.value) {
node.setAttribute('value', host.value);
}
if (host.type) {
node.setAttribute('type', host.type);
}
// Ensure every instance has unique ID
const uniqueId = (InputController._uniqueInputId = 1 + InputController._uniqueInputId || 0);
host._inputId = `${host.localName}-${uniqueId}`;
node.id = host._inputId;
if (typeof callback == 'function') {
callback(node);
}
}
]);
}
} |
JavaScript | class Route53Metrics {
static healthCheckPercentageHealthyAverage(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'HealthCheckPercentageHealthy',
dimensions,
statistic: 'Average',
};
}
static connectionTimeAverage(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'ConnectionTime',
dimensions,
statistic: 'Average',
};
}
static healthCheckStatusMinimum(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'HealthCheckStatus',
dimensions,
statistic: 'Minimum',
};
}
static sslHandshakeTimeAverage(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'SSLHandshakeTime',
dimensions,
statistic: 'Average',
};
}
static childHealthCheckHealthyCountAverage(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'ChildHealthCheckHealthyCount',
dimensions,
statistic: 'Average',
};
}
static timeToFirstByteAverage(dimensions) {
return {
namespace: 'AWS/Route53',
metricName: 'TimeToFirstByte',
dimensions,
statistic: 'Average',
};
}
} |
JavaScript | class URLTokenBaseHTTPClient {
constructor(tokenHeader, baseServer, port, defaultHeaders = {}) {
this.defaultHeaders = defaultHeaders;
const baseServerURL = new Url(baseServer, {});
if (typeof port !== 'undefined') {
baseServerURL.set('port', port.toString());
}
if (baseServerURL.protocol.length === 0) {
throw new Error('Invalid base server URL, protocol must be defined.');
}
this.baseURL = baseServerURL;
this.tokenHeader = tokenHeader;
}
/**
* Compute the URL for a path relative to the instance's address
* @param relativePath - A path string
* @returns A URL string
*/
addressWithPath(relativePath) {
const address = new Url(path.posix.join(this.baseURL.pathname, relativePath), this.baseURL);
return address.toString();
}
/**
* Convert a superagent response to a valid BaseHTTPClientResponse
* Modify the superagent response
* @private
*/
static superagentToHTTPClientResponse(res) {
if (res.body instanceof ArrayBuffer) {
// Handle the case where the body is an arraybuffer which happens in the browser
res.body = new Uint8Array(res.body);
}
return res;
}
/**
* Make a superagent error more readable. For more info, see https://github.com/visionmedia/superagent/issues/1074
*/
static formatSuperagentError(err) {
if (err.response) {
try {
const decoded = JSON.parse(Buffer.from(err.response.body).toString());
// eslint-disable-next-line no-param-reassign
err.message = `Network request error. Received status ${err.response.status}: ${decoded.message}`;
}
catch (err2) {
// ignore any error that happened while we are formatting the original error
}
}
return err;
}
async get(relativePath, query, requestHeaders = {}) {
const r = request
.get(this.addressWithPath(relativePath))
.set(this.tokenHeader)
.set(this.defaultHeaders)
.set(requestHeaders)
.responseType('arraybuffer')
.query(query);
try {
const res = await r;
return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res);
}
catch (err) {
throw URLTokenBaseHTTPClient.formatSuperagentError(err);
}
}
async post(relativePath, data, query, requestHeaders = {}) {
const r = request
.post(this.addressWithPath(relativePath))
.set(this.tokenHeader)
.set(this.defaultHeaders)
.set(requestHeaders)
.query(query)
.serialize((o) => o) // disable serialization from superagent
.responseType('arraybuffer')
.send(Buffer.from(data)); // Buffer.from necessary for superagent
try {
const res = await r;
return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res);
}
catch (err) {
throw URLTokenBaseHTTPClient.formatSuperagentError(err);
}
}
async delete(relativePath, data, query, requestHeaders = {}) {
const r = request
.delete(this.addressWithPath(relativePath))
.set(this.tokenHeader)
.set(this.defaultHeaders)
.set(requestHeaders)
.query(query)
.serialize((o) => o) // disable serialization from superagent
.responseType('arraybuffer')
.send(Buffer.from(data)); // Buffer.from necessary for superagent
try {
const res = await r;
return URLTokenBaseHTTPClient.superagentToHTTPClientResponse(res);
}
catch (err) {
throw URLTokenBaseHTTPClient.formatSuperagentError(err);
}
}
} |
JavaScript | class Player{
// Constructor for player class with the parameters of x position, y position, width, height, and color.
constructor (x,y,w,h, color){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
// Creating a draw function to draw each player.
draw() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
}
// Adding movement to the player.
moveUp(){
// Clearing the previous object to draw a new one. Decreasing its y position, and redrawing it.
ctx.clearRect(this.x,this.y,this.w,this.h);
if (this.y < 0){
this.y = canvas.height;
this.draw();
}
else {
this.y -= 30;
this.draw;
}
}
moveDown(){
// Clearing the previous object to draw a new one. Increasing its y position, and redrawing it.
ctx.clearRect(this.x,this.y,this.w,this.h);
if (this.y > canvas.height){
this.y = 0;
this.draw();
}
else {
this.y += 30;
this.draw;
}
}
moveRight(){
// Clearing the previous object to draw a new one. Increasing its x position, and redrawing it.
ctx.clearRect(this.x,this.y,this.w,this.h);
if (this.x < canvas.width-60){
this.x += 20;
this.draw();
}
}
moveLeft(){
// Clearing the previous object to draw a new one. Decreasing its x position, and redrawing it.
ctx.clearRect(this.x,this.y,this.w,this.h);
if (this.x>0){
this.x -= 20;
this.draw();
}
}
} |
JavaScript | class Projectile{
// Constructor with the parameters x position, y position, radius, and color.
constructor(x,y,h,w,color, speed){
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.color = color;
this.speed = speed;
}
// Creating a draw function to draw each projectile.
draw(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
ctx.fill();
}
// Adding movement to the projectile.
move(){
//ctx.clearRect(this.x,this.y, this.r*2, this.r*2);
this.draw();
this.x += 50;
}
} |
JavaScript | class Tabs extends React.Component {
state = {
updatedActiveTab: null,
updatedTabs: null
};
componentDidMount() {
const { updatedTabs } = this.state;
if (updatedTabs === null) {
this.setTabData();
}
}
componentDidUpdate(prevProps) {
const { tabs } = this.props;
const customizer = (valueA, valueB) => {
if (typeof valueA === 'function' && typeof valueB === 'function') {
return valueA.toString() === valueB.toString();
}
return undefined;
};
if (!_isEqualWith(prevProps.tabs, tabs, customizer)) {
this.setTabData();
}
}
/**
* On tab selected
*
* @event onTab
* @param {object} params
* @param {number} params.index
*/
onTab = ({ index }) => {
const { onTab } = this.props;
this.setState(
{
updatedActiveTab: index
},
() => onTab({ index })
);
};
/**
* Convert tab objects into the required PF Tab format.
*/
setTabData() {
const { activeTab, defaultActiveTab, tabs } = this.props;
let updatedActiveTab = defaultActiveTab;
const updatedTabs = tabs.map(({ active, content, title }, index) => {
updatedActiveTab = active ? index : updatedActiveTab;
return (
<Tab key={title} eventKey={index} title={<TabTitleText>{title}</TabTitleText>}>
{content}
</Tab>
);
});
if (typeof activeTab === 'number') {
updatedActiveTab = activeTab;
}
this.setState({
updatedActiveTab,
updatedTabs
});
}
/**
* Apply props to tabs.
*
* @returns {Node}
*/
renderTabs() {
const { updatedActiveTab, updatedTabs } = this.state;
const { className, hasOverflowScroll } = this.props;
return (
<PfTabs
className={`curiosity-tabs${(!hasOverflowScroll && '__no-scroll') || ''} ${className || ''}`}
activeKey={updatedActiveTab}
onSelect={(event, index) => this.onTab({ event, index })}
mountOnEnter
unmountOnExit
inset={{
default: 'insetNone',
md: 'insetLg'
}}
>
{updatedTabs}
</PfTabs>
);
}
/**
* Render tabs.
*
* @returns {Node}
*/
render() {
return (
<Grid className="curiosity-tabs-container">
<GridItem span={12}>{this.renderTabs()}</GridItem>
</Grid>
);
}
} |
JavaScript | class APIObject {
constructor(apiToken = undefined, apiName = "") {
this.apiToken = apiToken;
this.baseUrl = "https://api.mindee.net/v1/products/mindee";
this.apiName = apiName;
}
/**
*/
parse() {
if (!this.apiToken) {
errorHandler.throw({
error: new Error(
`Missing API token for ${this.apiName}. \
Have you create a mindee Client with a ${this.apiName}Token in parameters ?`
),
});
}
}
/**
@param {String} url - API url for request
@param {Input} inputFile - input file for API
@param {Boolean} includeWords - Include Mindee vision words in Response
@returns {Response}
*/
async _request(url, inputFile, includeWords = false) {
const headers = {
"X-Inferuser-Token": this.apiToken,
};
const response = await request(
`${this.baseUrl}${url}`,
"POST",
headers,
inputFile,
includeWords
);
return this.wrapResponse(inputFile, response, this.apiName);
}
/**
@param {String} inputFile - Input object
@param {} response - HTTP response
@param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
@returns {Response}
*/
wrapResponse(inputFile, response, documentType) {
if (response.statusCode > 201) {
const errorMessage = JSON.stringify(response.data, null, 4);
errorHandler.throw(
new Error(
`${this.apiName} API ${response.statusCode} HTTP error: ${errorMessage}`
),
false
);
return new Response({
httpResponse: response,
documentType: documentType,
document: undefined,
input: inputFile,
error: true,
});
}
return new Response({
httpResponse: response,
documentType: documentType,
document: inputFile,
input: inputFile,
});
}
} |
JavaScript | class AMPDocument extends React.Component {
constructor(props) {
super(props);
// 'offline' is set to true if and when the document fetch fails.
this.state = {'offline': false};
/**
* `window.AMP` is set by the AMP runtime when it finishes loading.
* @const
* @private
*/
this.ampReadyPromise_ = new Promise(resolve => {
(window.AMP = window.AMP || []).push(resolve);
});
/**
* Child element that will wrap the AMP shadow root.
* @private
* @type {Element}
*/
this.container_ = null;
/**
* XMLHTTPRequest that fetches the AMP document.
* @private
* @type {XMLHTTPRequest}
*/
this.xhr_ = null;
/**
* Provides AMP functionality on the newly created shadow root after
* an AMP document is attached.
* @private
* @type {Object}
*/
this.shadowAmp_ = null;
/**
* The root node of the shadow AMP.
* @note A single node must not be reused for multiple shadow AMP docs.
* @type {Element}
*/
this.shadowRoot_ = null;
/** @private */
this.boundClickListener_ = this.clickListener_.bind(this);
}
componentDidMount() {
this.container_.addEventListener('click', this.boundClickListener_);
this.fetchAndAttachAmpDoc_(this.props.src);
}
componentWillUnmount() {
this.closeShadowAmpDoc_();
this.container_.removeEventListener('click', this.boundClickListener_);
if (this.xhr_) {
this.xhr_.abort();
this.xhr_ = null;
}
}
componentWillReceiveProps(nextProps) {
this.fetchAndAttachAmpDoc_(nextProps.src);
}
render() {
if (this.state.offline) {
return (
<div>
<h2>Houston, we have a problem.</h2>
<p>Looks like we are offline—please check your Internet connection.</p>
</div>
);
} else {
return (<div className='amp-container' ref={ref => this.container_ = ref} />);
}
}
/**
* Fetches the AMP document at `url` and attaches it as a shadow root.
* @private
* @param {string} url
*/
fetchAndAttachAmpDoc_(url) {
this.fetchDocument_(url).then(doc => {
return this.ampReadyPromise_.then(amp => {
// Hide navigational and other unwanted elements before displaying.
this.hideUnwantedElementsOnDocument_(doc);
// Replace the old shadow root with a new div element.
const oldShadowRoot = this.shadowRoot_;
this.shadowRoot_ = document.createElement('div');
if (oldShadowRoot) {
this.container_.replaceChild(this.shadowRoot_, oldShadowRoot);
} else {
this.container_.appendChild(this.shadowRoot_);
}
// Attach the shadow document to the new shadow root.
this.shadowAmp_ = amp.attachShadowDoc(this.shadowRoot_, doc, url);
});
}).catch(error => {
this.setState({'offline': true});
});
}
/**
* Cleans up internal state of current shadow AMP document.
* @private
*/
closeShadowAmpDoc_() {
if (typeof this.shadowAmp_.close === 'function') {
this.shadowAmp_.close();
}
}
/**
* Hides elements (e.g. banners) that would clash with the app shell.
* @param {!Document} doc
* @private
*/
hideUnwantedElementsOnDocument_(doc) {
const banners = doc.getElementsByClassName('banner');
for (let i = 0; i < banners.length; i++) {
banners[i].style.display = 'none';
}
}
/**
* Fetches and parses HTML at `url`.
* @private
* @param {string} url
* @return {!Promise<!Document|!string>} If fetch succeeds, resolved with {!Document}.
* Otherwise, rejects with {!string} error description.
*/
fetchDocument_(url) {
return new Promise((resolve, reject) => {
this.xhr_ = new XMLHttpRequest();
this.xhr_.open('GET', url, true);
this.xhr_.responseType = 'document';
// This is set to text/* instead of text/html because the development server
// only forwards requests to the proxy for requests whose 'Accept' header
// is NOT text/html.
// https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development
this.xhr_.setRequestHeader('Accept', 'text/*');
this.xhr_.onreadystatechange = () => {
if (this.xhr_.readyState < /* STATUS_RECEIVED */ 2) {
return;
}
if (this.xhr_.status < 100 || this.xhr_.status > 599) {
this.xhr_.onreadystatechange = null;
reject(new Error(`Unknown HTTP status ${this.xhr_.status}`));
this.xhr_ = null;
return;
}
if (this.xhr_.readyState === /* COMPLETE */ 4) {
if (this.xhr_.responseXML) {
resolve(this.xhr_.responseXML);
} else {
reject(new Error('No xhr.responseXML'));
}
this.xhr_ = null;
}
};
this.xhr_.onerror = () => { reject(new Error('Network failure')); };
this.xhr_.onabort = () => { reject(new Error('Request aborted')); };
this.xhr_.send();
});
}
/**
* Event listener that redirects clicks on same-domain links to react-router.
* This avoids page reload due to navigation from same-domain links in the AMP document,
* which affords seamless UX in the style of a single-page app.
* @private
* @param e {!Event}
*/
clickListener_(e) {
if (e.defaultPrevented) {
return false;
}
let a = null;
if (e.path) {
// Check `path` since events that cross the Shadow DOM boundary are retargeted.
// See http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-301/#toc-events
for (let i = 0; i < e.path.length; i++) {
const node = e.path[i];
if (node.tagName === 'A') {
a = node;
break;
}
}
} else {
// Polyfill for `path`.
let node = e.target;
while (node && node.tagName !== 'A') {
node = node.parentNode;
}
a = node;
}
if (a && a.href) {
const url = new URL(a.href);
if (url.origin === window.location.origin) {
// Perform router push instead of page navigation.
e.preventDefault();
// Clean up current shadow AMP document.
this.closeShadowAmpDoc_();
// Router push reuses current component with new props.
this.props.router.push(url.pathname);
return false;
}
}
return true;
}
} |
JavaScript | class DependencyField extends Combo {
//region Config
static get $name() {
return 'DependencyField';
}
// Factoryable type name
static get type() {
return 'dependencyfield';
}
static get defaultConfig() {
return {
listCls : 'b-predecessor-list',
valueField : 'name',
displayField : 'name',
picker : {
floating : true,
scrollAction : 'realign',
itemsFocusable : false,
activateOnMouseover : true,
align : {
align : 't0-b0',
axisLock : true
},
maxHeight : 324,
minHeight : 161,
scrollable : {
overflowY : true
},
autoShow : false,
focusOnHover : false
},
/**
* Delimiter between dependency ids in the field
* @config {String}
* @default
*/
delimiter : ';',
/**
* The other task's relationship with this field's contextual task.
* This will be `'from'` if we are editing predecessors, and `'to'` if
* we are editing successors.
* @config {String}
*/
otherSide : null,
/**
* This field's contextual task's relationship with the other task.
* This will be `'to'` if we are editing predecessors, and `'from'` if
* we are editing successors.
* @config {String}
*/
ourSide : null
};
}
//endregion
construct(config) {
const
me = this,
{ ourSide, otherSide } = config;
//<debug>
if (!fromTo[ourSide] || !fromTo[otherSide] || ourSide === otherSide) {
throw new Error('DependencyField needs "ourSide" and "otherSide" configs of "from" or "to"');
}
//</debug>
me.dependencies = new Collection({
extraKeys : otherSide
});
me.startCollection = new Collection({
extraKeys : otherSide
});
super.construct(config);
me.delimiterRegEx = new RegExp(`\\s*${me.delimiter}\\s*`);
// Update when changing locale
LocaleManager.on({
locale() {
dependencyTypes = me.L('L{DependencyType.short}');
dependencySuffixRe = buildDependencySuffixRe();
me.syncInputFieldValue();
},
thisObj : me
});
}
internalOnInput() {
// Avoid combo filtering. That's done from our FilterField
if (this.isValid) {
this.clearError();
TextField.prototype.internalOnInput.call(this);
}
else {
this.setError('Invalid dependency format');
}
}
onInternalKeyDown(keyEvent) {
const
{ key } = keyEvent;
// Don't pass Enter down, that selects when ComboBox passes it down
// to its list. We want default action on Enter.
// Our list has its own, built in filter field which provides key events.
if (key !== 'Enter') {
super.onInternalKeyDown && super.onInternalKeyDown(keyEvent);
}
if (this.pickerVisible && key === 'ArrowDown') {
this.filterField.focus();
}
}
onTriggerClick() {
if (this.pickerVisible) {
super.onTriggerClick();
}
else {
this.doFilter(this.filterInput ? this.filterInput.value : null);
}
}
set store(store) {
const
me = this;
// Filter the store to hide the field's Task
store = store.makeChained(r => !me.owner || !me.owner.record || (r.id !== me.owner.record.id));
// Gantt TaskStores are TreeStores. We need to flatten.
store.tree = false;
super.store = store;
}
get store() {
return super.store;
}
changePicker(picker, oldPicker) {
const
me = this,
myInput = me.input,
filterField = me.filterField || (me.filterField = new TextField({
cls : 'b-dependency-list-filter',
owner : me,
clearable : true,
placeholder : 'Filter',
triggers : {
filter : {
cls : 'b-icon b-icon-filter',
align : 'start'
}
},
listeners : {
input({ value }) {
me.input = filterFieldInput;
me.filterList(value);
me.input = myInput;
},
clear() {
me.input = filterFieldInput;
me.filterList();
me.input = myInput;
}
}
})),
filterFieldInput = me.filterInput = filterField.input,
result = DependencyField.reconfigure(oldPicker, picker ? Objects.merge({
owner : me,
store : me.store,
cls : me.listCls,
itemTpl : me.listItemTpl,
forElement : me[me.pickerAlignElement],
align : {
anchor : me.overlayAnchor,
target : me[me.pickerAlignElement]
},
navigator : {
keyEventTarget : filterFieldInput,
processEvent : e => {
if (e.key === 'Escape') {
me.hidePicker();
}
else {
return e;
}
}
},
onItem : me.onPredecesssorClick,
getItemClasses : function(task) {
const
result = List.prototype.getItemClasses.call(this, task),
dependency = me.dependencies.getBy(me.otherSide + 'Event', task),
cls = dependency ? ` b-selected b-${dependency.getConnectorString(1).toLowerCase()}` : '';
return result + cls;
}
}, picker) : null, me);
// May have been set to null (destroyed)
if (result) {
filterField.render(result.contentElement);
}
// If it has been destroyed, destroy orphaned filterField
else {
me.destroyProperties('filterField');
}
return result;
}
showPicker(focusPicker) {
// Ensure this field's Task is filtered out.
// See our set store which owns the chainedFilterFn.
this.store.fillFromMaster();
super.showPicker(focusPicker);
}
onPickerShow({ source : picker }) {
const
me = this,
filterField = me.filterField,
ourInput = me.input;
picker.minWidth = me[me.pickerAlignElement].offsetWidth;
picker.contentElement.insertBefore(filterField.element, picker.contentElement.firstChild);
// Combo superclass focuses this.input upon picker show.
// This must focus the filter field, not the predecessor text.
me.input = me.filterInput;
super.onPickerShow();
me.input = ourInput;
}
listItemTpl(task) {
return `<div class="b-predecessor-item-text">${task.name}</div>
<div class="b-sch-box b-from" data-side="from"></div>
<div class="b-sch-box b-to" data-side="to"></div>`;
}
get isValid() {
return Boolean(!this.owner || this.parseDependencies(this.input.value));
}
set value(dependencies) {
const
me = this,
predecessorsCollection = me.dependencies,
startCollection = me.startCollection;
// Convert strings, eg: '1fs-2h;2ss+1d' to Dependency records
if (typeof dependencies === 'string') {
me.input.value = dependencies;
dependencies = me.parseDependencies(dependencies);
if (!dependencies) {
me.updateInvalid();
return;
}
for (let i = 0; i < dependencies.length; i++) {
// Create a new one.
// See if we always had a dependency pointing to the "other" task.
const newPredecessor = new me.dependencyStore.modelClass(dependencies[i]);
let existingPredecessor = startCollection.getBy(me.otherSide, newPredecessor.fromEvent);
if (existingPredecessor) {
// We must create a clone because the record is "live".
// Updates to it go back to the UI.
existingPredecessor = existingPredecessor.copy(existingPredecessor.id);
existingPredecessor.type = newPredecessor.type;
existingPredecessor.fullLag = newPredecessor.fullLag;
}
// Use the existing one if there is an exact match
dependencies[i] = existingPredecessor || newPredecessor;
}
}
else {
me.startCollection.clear();
me.startCollection.values = dependencies;
}
predecessorsCollection.clear();
predecessorsCollection.values = dependencies;
// If there has been a change, update the textual value.
if (!me.inputting) {
me.syncInputFieldValue();
}
}
get value() {
return this.dependencies.values;
}
get inputValue() {
return this.constructor.predecessorsToString(this.dependencies.values, this.otherSide, this.delimiter);
}
onPredecesssorClick({ source : list, item, record : task, index, event }) {
const
me = this.owner,
dependencies = me.dependencies,
box = event.target.closest('.b-sch-box'),
side = box && box.dataset.side;
let dependency = dependencies.getBy(me.otherSide + 'Event', task);
// Prevent regular selection continuing after this click handler.
item.dataset.noselect = true;
// Click text to remove predecessor completely
if (dependency && !box) {
dependencies.remove(dependency);
}
else {
// Clicking a connect side box toggles that
if (dependency) {
// We must create a clone because the record is "live".
// Updates to it go back to the UI.
// Also we cannot really modify record here. When editing will finish editor will compare `toJSON`
// output of models, which refers to the `model.data` field. And if we modify record instance, change
// won't go to the data object, it will be kept in the field though. Only way to sync model.data.type and
// model.type here is to instantiate model with correct data already
const
{ id, type } = dependency;
// Using private argument here to avoid copying record current values, we're only interested in data object
dependency = dependency.copy({ id, type : toggleTypes[side][type] }, { skipFieldIdentifiers : true });
// HACK: Above code results having serialized values in `${me.otherSide}Event` field
// and we expect to find task instance when doing code like:
// dependencies.getBy(me.otherSide + 'Event', task)
// So let's put the task instance there manually.
dependency[`${me.otherSide}Event`] = task;
// Replace the old predecessor link with the new, modified one.
// Collection will *replace* in-place due to ID matching.
dependencies.add(dependency);
}
// Create a new dependency to/from the clicked task
else {
dependencies.add(me.dependencyStore.createRecord({
[`${me.otherSide}Event`] : task,
[`${me.ourSide}Event`] : me.owner.record
}, true));
}
}
me.syncInputFieldValue();
list.refresh();
}
static predecessorsToString(dependencies, otherSide, delimiter = ';') {
const getSideId = dependency => {
const otherSideEvent = dependency[otherSide + 'Event'];
return otherSideEvent && otherSideEvent.isModel ? otherSideEvent.id : (otherSideEvent || '');
};
if (dependencies && dependencies.length) {
const result = dependencies.sort((a, b) => getSideId(a) - getSideId(b)).map(dependency =>
`${getSideId(dependency)}${Dependencies.getLocalizedDependencyType(dependency.getConnectorString())}${dependency.getLag()}`
);
return result.join(delimiter);
}
return '';
}
// static * predecessorsToStringGenerator(dependencies, otherSide, delimiter = ';') {
// const result = [];
//
// if (dependencies && dependencies.length) {
// for (const dependency of dependencies) {
// const
// otherSideEvent = yield dependency.$[otherSide + 'Event'],
// otherSideEventId = otherSideEvent ? otherSideEvent.id : (otherSideEvent || '');
//
// result.push(`${otherSideEventId}${yield dependency.getConnectorString()}${dependency.getLag()}`);
// }
// }
//
// return result.join(delimiter);
// }
parseDependencies(value) {
const
me = this,
grid = me.grid,
task = me.owner.record,
taskStore = me.store,
dependencyStore = me.dependencyStore,
dependencies = value.split(me.delimiterRegEx),
DependencyModel = dependencyStore.modelClass,
result = [];
for (let i = 0; i < dependencies.length; i++) {
const
predecessorText = dependencies[i];
if (predecessorText) {
let idLen = predecessorText.length + 1,
predecessorId,
predecessor = null;
for (; idLen && !predecessor; idLen--) {
predecessorId = predecessorText.substr(0, idLen);
predecessor = taskStore.getById(predecessorId);
}
if (!predecessor) {
return null;
}
// Chop off connector and lag specification, ie the "SS-1h" part
const
remainder = predecessorText.substr(idLen + 1),
// Start the structure of the dependency we are describing
dependency = {
// This will be "from" if we're editing predecessors
// and "to" if we're editing successors
[`${me.otherSide}Event`] : predecessor,
// This will be "to" if we're editing predecessors
// and "from" if we're editing successors
[`${me.ourSide}Event`] : task,
type : DependencyModel.Type.EndToStart
};
// There's a trailing edge/lag spec
if (remainder.length) {
const
edgeAndLag = dependencySuffixRe.exec(remainder);
if (edgeAndLag && (edgeAndLag[1] || edgeAndLag[2])) {
// The SS/FF bit
if (edgeAndLag[1]) {
dependency.type = dependencyTypes.indexOf(edgeAndLag[1].toUpperCase());
}
// The -1h bit
if (edgeAndLag[2]) {
const
parsedLag = DateHelper.parseDuration(edgeAndLag[2], true, grid.timeAxis.unit);
dependency.lag = parsedLag.magnitude;
dependency.lagUnit = parsedLag.unit;
}
}
else {
return null;
}
}
result.push(dependency);
}
}
return result;
}
} |
JavaScript | class PrimitiveUser {
constructor(name, email) {
this.name = name;
this.email = email;
}
getEmail() {
return this.email;
}
getUsername() {
return this.name;
}
} |
JavaScript | class RTK {
/**
* Construct RTK object which will manage a set of resources.
*
* @param {Array} resources: an array of resources which contain version value
* @param {Object} opts: optional settings
* - dryRun: when true, changelog file won't be modified
*/
constructor(resources, opts) {
this.resources = resources || {};
this.opts = opts || {};
this.releaseSchemes = {
rtk: rtkReleaseScheme
};
this.resourceTypes = {
json: jsonResourceType,
makefile: makefileResourceType,
yaml: yamlResourceType
};
this.resourceTypes['keep-a-changelog'] = keepAChangelogResourceType;
}
/**
* Execute release steps for the specified release scheme.
*
* @param {String} releaseSchemeName: release scheme name that defines the steps involved in a release step
* @param {String} versionSchemeName: version scheme name that defines the release and pre-release version value
* @param {String} scmSchemeName: name of SCM used by the repository to be released
* @param {Function} cb: standard cb(err, result) callback
*/
release(releaseSchemeName, versionSchemeName, scmSchemeName, cb) {
const self = this;
releaseSchemeName = releaseSchemeName || 'rtk';
versionSchemeName = versionSchemeName || 'semver';
scmSchemeName = scmSchemeName || 'git';
let releaseScheme;
function versionTask(cb) {
// uses first resource as the source of truth and the correct pre-release version
const preReleaseResource = self.resources[0];
function versionCb(err, result) {
if (!err) {
const ReleaseSchemeClass = self.releaseSchemes[releaseSchemeName];
releaseScheme = new ReleaseSchemeClass(versionSchemeName, scmSchemeName, result, self.opts);
}
cb(err, result);
}
const resourceType = self.resourceTypes[preReleaseResource.type];
resourceType.getVersion(preReleaseResource, versionCb);
}
function preTask(cb) {
releaseScheme.pre(self.resources, self.opts, cb);
}
function releaseTask(cb) {
releaseScheme.release(self.resources, self.opts, cb);
}
function postTask(cb) {
releaseScheme.post(self.resources, self.opts, cb);
}
async.series([versionTask, preTask, releaseTask, postTask], cb);
}
} |
JavaScript | class ArcServer extends AbstractLoadingServer {
/**
* Constructor.
*/
constructor() {
super();
this.providerType = ogc.ID;
/**
* @type {IArcLoader}
* @private
*/
this.loader_ = null;
/**
* @type {?string}
* @private
*/
this.version_ = null;
/**
* @type {Logger}
* @protected
*/
this.log = logger;
}
/**
* Get the Arc version
*
* @return {?string}
*/
getVersion() {
return this.version_;
}
/**
* Set the Arc version
*
* @param {?string} value
*/
setVersion(value) {
this.version_ = value;
}
/**
* @inheritDoc
*/
configure(config) {
super.configure(config);
var url = /** @type {string} */ (config['url']);
var i = url.indexOf('/rest/services');
if (i == -1) {
url += '/rest/services';
}
// trim trailing slashes
url = url.replace(/\/+$/, '');
if (config['id']) {
this.setId(/** @type {string} */ (config['id']));
}
this.setUrl(url);
}
/**
* @inheritDoc
*/
load(opt_ping) {
asserts.assert(this.url, 'Attempted to load server ' + this.getLabel() + ' without URL!');
super.load(opt_ping);
log.info(this.log, this.getLabel() + ' requesting Arc Server capabilities.');
this.setChildren(null);
this.loader_ = arc.getArcLoader(new SlickTreeNode(), this.url, this);
this.loader_.load();
this.loader_.listen(EventType.SUCCESS, this.onLoad, false, this);
this.loader_.listen(EventType.ERROR, this.onError, false, this);
}
/**
* Handler for Arc server load success.
*
* @param {GoogEvent} event
* @protected
*/
onLoad(event) {
log.info(this.log, this.getLabel() + ' base Arc server capabilities loaded.');
this.loader_.unlisten(EventType.SUCCESS, this.onLoad, false, this);
this.loader_.unlisten(EventType.ERROR, this.onError, false, this);
this.setChildren(this.loader_.getNode().getChildren());
this.disposeLoader_();
this.setLoading(false);
}
/**
* Handler for Arc server load errors.
*
* @param {GoogEvent} event
* @protected
*/
onError(event) {
var errors = this.loader_.getErrors();
this.loader_.unlisten(EventType.SUCCESS, this.onLoad, false, this);
this.loader_.unlisten(EventType.ERROR, this.onError, false, this);
this.disposeLoader_();
var href = this.getUrl();
var msg = 'Request failed for <a target="_blank" href="' + href + '">Arc Server Capabilities</a>';
if (errors && errors.length) {
msg += `: ${errors.join(', ')}`;
}
this.logError(msg);
this.setLoading(false);
}
/**
* Logs an error and sets the server to an error state.
*
* @param {string} msg The error message.
* @protected
*/
logError(msg) {
if (!this.getError()) {
var errorMsg = 'Server [' + this.getLabel() + ']: ' + msg;
if (!this.getPing()) {
AlertManager.getInstance().sendAlert(errorMsg, AlertEventSeverity.ERROR);
}
log.error(logger, errorMsg);
this.setErrorMessage(errorMsg);
this.setLoading(false);
}
}
/**
* Disposes of the loader.
*
* @private
*/
disposeLoader_() {
if (this.loader_) {
dispose(this.loader_);
this.loader_ = null;
}
}
} |
JavaScript | class Kwall {
/**
* Class constructor.
*
* @constructor
*
* @param {string} path
*/
constructor(path) {
this._base_path = path;
}
/**
* Initializes and returns the application port.
*
* @param {function} callback
* @return {int}
*/
initialize(callback) {
try {
this._setAlises(() => {
const App = Use('Kwall/Core/App');
const Port = App.getPort;
/**
* Initializes the server.
*/
App.getApp.listen(Port, () => {
callback.call(null, null, Port);
});
});
} catch (error) {
callback.call(null, error, null);
}
}
/**
* Defines the aliases and executes the dependencies of the application.
*
* @private
*
* @param {function} callback
*/
_setAlises(callback) {
/**
* Imports, executes and sets the Loader class alias.
*/
const Loader = new (require('./Loader'))();
Loader.set('Kwall/Loader', Loader);
/**
* Defines the alias of this class.
*/
Loader.set('Kwall', this);
/**
* Sets the global `Use` function.
*
* @param {string} aliasName
* @return {class}
*/
global.Use = (aliasName => {
return Loader.load(aliasName || null);
});
/**
* Imports, executes and sets the Config class alias.
*/
const Config = new (require('./Config'))();
Loader.set('Kwall/Config', Config);
/**
* Imports, executes, and sets the App class alias.
*/
const App = new (require('./Core/App'))();
Loader.set('Kwall/Core/App', App);
/**
* Sets the aliases shortcuts:
*/
Loader.setAliasesShortcuts();
/**
* Imports, executes, and sets the Middleware class alias.
*/
const Middleware = new (require('./Core/Middleware'))();
Loader.set('Kwall/Core/Middleware', Middleware);
/**
* Get the user-defined middlewares:
*/
Middleware.getUserMiddlewares();
/**
* Imports, executes and sets the Router class alias.
*/
const Router = new (require('./Router'))();
Loader.set('Kwall/Router', Router);
Router.initialize();
/**
* Executes a callback after all aliases have been defined.
*/
callback.call(this);
}
/**
* Gets the base path of the application.
*
* @return {string}
*/
get basePath() {
return this._base_path;
}
/**
* Gets the `app` directory path.
*/
get appPath() {
return Path.join(this._base_path, 'app');
}
/**
* Gets the `config` directory path.
*/
get configPath() {
return Path.join(this._base_path, 'config');
}
} |
JavaScript | class QualityAttributesFormGroup extends React.Component {
popoverContent = (qualityAttribute) => {
return(
<span>
<div>{qualityAttribute.description}. </div>
<div>
The following scoring creteria apply:
<ul>
{qualityAttribute.classificationLabels.map(classification =>
<li key={classification.id}>{classification.label} ({classification.score}): {classification.criteria} </li>
)}
</ul>
</div>
</span>
)
}
hussleClassifications = (classifications) => {
let newData = {}
if(classifications){
for (var value of classifications.values()) {
let qualityAttributeId = value.qualityAttribute.id;
newData[qualityAttributeId] = value.id
}
}
return newData
}
render() {
const { form, classifications, scope } = this.props;
let oldValues = this.hussleClassifications(classifications)
return (
<Query
query = { ALL_QUALITY_ATTRIBUTES }
variables= {{ filter: { appliesToObject: scope } }}
>
{({ loading, data, error }) => {
if (loading) return <Select placeholder="Loading..." />
if (error) return <Select placeholder="Error loading..." />
let qualityAttributes = data.qualityAttributes
let i = 0
return(
qualityAttributes.map( qualityAttribute =>
<Form.Item
key={qualityAttribute.id}
label={
<span>
{qualityAttribute.name}
<Popover title={qualityAttribute.name} content={this.popoverContent(qualityAttribute)}>
<Icon type="question-circle-o" />
</Popover>
</span>
}>
{form.getFieldDecorator("classification[" + i++ + "]" , {
initialValue: oldValues[qualityAttribute.id],
})(
<Select
placeholder="Classification"
allowClear
>
{qualityAttribute.classificationLabels.map(classification =>
<Option key={classification.id}>({classification.score}) {classification.label}</Option>
)}
</Select>
)}
</Form.Item>
)
)
}}
</Query>
)
}
} |
JavaScript | class MyException {
/**
* @param {?} status
* @param {?} body
*/
constructor(status, body) {
this.status = status;
this.body = body;
}
} |
JavaScript | class ClickOutsideDirective {
/**
* @param {?} _elementRef
*/
constructor(_elementRef) {
this._elementRef = _elementRef;
this.clickOutside = new EventEmitter();
}
/**
* @param {?} event
* @param {?} targetElement
* @return {?}
*/
onClick(event, targetElement) {
if (!targetElement) {
return;
}
/** @type {?} */
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(event);
}
}
} |
JavaScript | class DataService {
constructor() {
this.filteredData = [];
this.subject = new Subject();
}
/**
* @param {?} data
* @return {?}
*/
setData(data) {
this.filteredData = data;
this.subject.next(data);
}
/**
* @return {?}
*/
getData() {
return this.subject.asObservable();
}
/**
* @return {?}
*/
getFilteredData() {
if (this.filteredData && this.filteredData.length > 0) {
return this.filteredData;
}
else {
return [];
}
}
} |
JavaScript | class ListFilterPipe {
/**
* @param {?} ds
*/
constructor(ds) {
this.ds = ds;
this.filteredList = [];
}
/**
* @param {?} items
* @param {?} filter
* @param {?} searchBy
* @return {?}
*/
transform(items, filter, searchBy) {
if (!items || !filter) {
this.ds.setData(items);
return items;
}
this.filteredList = items.filter((item) => this.applyFilter(item, filter, searchBy));
this.ds.setData(this.filteredList);
return this.filteredList;
}
/**
* @param {?} item
* @param {?} filter
* @param {?} searchBy
* @return {?}
*/
applyFilter(item, filter, searchBy) {
/** @type {?} */
let found = false;
if (searchBy.length > 0) {
if (item.grpTitle) {
found = true;
}
else {
for (var t = 0; t < searchBy.length; t++) {
if (filter && item[searchBy[t]] && item[searchBy[t]] != "") {
if (item[searchBy[t]].toString().toLowerCase().indexOf(filter.toLowerCase()) >= 0) {
found = true;
}
}
}
}
}
else {
if (item.grpTitle) {
found = true;
}
else {
for (var prop in item) {
if (filter && item[prop]) {
if (item[prop].toString().toLowerCase().indexOf(filter.toLowerCase()) >= 0) {
found = true;
}
}
}
}
}
return found;
}
} |
JavaScript | class VirtualScrollComponent {
/**
* @param {?} element
* @param {?} renderer
* @param {?} zone
*/
constructor(element, renderer, zone) {
this.element = element;
this.renderer = renderer;
this.zone = zone;
this.window = window;
this._enableUnequalChildrenSizes = false;
this.useMarginInsteadOfTranslate = false;
this._bufferAmount = 0;
this.scrollAnimationTime = 750;
this.resizeBypassRefreshTheshold = 5;
this._checkResizeInterval = 1000;
this._items = [];
this.compareItems = (item1, item2) => item1 === item2;
this.update = new EventEmitter();
this.vsUpdate = new EventEmitter();
this.change = new EventEmitter();
this.vsChange = new EventEmitter();
this.start = new EventEmitter();
this.vsStart = new EventEmitter();
this.end = new EventEmitter();
this.vsEnd = new EventEmitter();
this.calculatedScrollbarWidth = 0;
this.calculatedScrollbarHeight = 0;
this.padding = 0;
this.previousViewPort = /** @type {?} */ ({});
this.cachedPageSize = 0;
this.previousScrollNumberElements = 0;
this.horizontal = false;
this.scrollThrottlingTime = 0;
this.resetWrapGroupDimensions();
}
/**
* @return {?}
*/
get viewPortIndices() {
/** @type {?} */
let pageInfo = this.previousViewPort || /** @type {?} */ ({});
return {
startIndex: pageInfo.startIndex || 0,
endIndex: pageInfo.endIndex || 0
};
}
/**
* @return {?}
*/
get enableUnequalChildrenSizes() {
return this._enableUnequalChildrenSizes;
}
/**
* @param {?} value
* @return {?}
*/
set enableUnequalChildrenSizes(value) {
if (this._enableUnequalChildrenSizes === value) {
return;
}
this._enableUnequalChildrenSizes = value;
this.minMeasuredChildWidth = undefined;
this.minMeasuredChildHeight = undefined;
}
/**
* @return {?}
*/
get bufferAmount() {
return Math.max(this._bufferAmount, this.enableUnequalChildrenSizes ? 5 : 0);
}
/**
* @param {?} value
* @return {?}
*/
set bufferAmount(value) {
this._bufferAmount = value;
}
/**
* @return {?}
*/
get scrollThrottlingTime() {
return this._scrollThrottlingTime;
}
/**
* @param {?} value
* @return {?}
*/
set scrollThrottlingTime(value) {
this._scrollThrottlingTime = value;
this.refresh_throttled = /** @type {?} */ (this.throttleTrailing(() => {
this.refresh_internal(false);
}, this._scrollThrottlingTime));
}
/**
* @return {?}
*/
get checkResizeInterval() {
return this._checkResizeInterval;
}
/**
* @param {?} value
* @return {?}
*/
set checkResizeInterval(value) {
if (this._checkResizeInterval === value) {
return;
}
this._checkResizeInterval = value;
this.addScrollEventHandlers();
}
/**
* @return {?}
*/
get items() {
return this._items;
}
/**
* @param {?} value
* @return {?}
*/
set items(value) {
if (value === this._items) {
return;
}
this._items = value || [];
this.refresh_internal(true);
}
/**
* @return {?}
*/
get horizontal() {
return this._horizontal;
}
/**
* @param {?} value
* @return {?}
*/
set horizontal(value) {
this._horizontal = value;
this.updateDirection();
}
/**
* @return {?}
*/
revertParentOverscroll() {
/** @type {?} */
const scrollElement = this.getScrollElement();
if (scrollElement && this.oldParentScrollOverflow) {
scrollElement.style['overflow-y'] = this.oldParentScrollOverflow.y;
scrollElement.style['overflow-x'] = this.oldParentScrollOverflow.x;
}
this.oldParentScrollOverflow = undefined;
}
/**
* @return {?}
*/
get parentScroll() {
return this._parentScroll;
}
/**
* @param {?} value
* @return {?}
*/
set parentScroll(value) {
if (this._parentScroll === value) {
return;
}
this.revertParentOverscroll();
this._parentScroll = value;
this.addScrollEventHandlers();
/** @type {?} */
const scrollElement = this.getScrollElement();
if (scrollElement !== this.element.nativeElement) {
this.oldParentScrollOverflow = { x: scrollElement.style['overflow-x'], y: scrollElement.style['overflow-y'] };
scrollElement.style['overflow-y'] = this.horizontal ? 'visible' : 'auto';
scrollElement.style['overflow-x'] = this.horizontal ? 'auto' : 'visible';
}
}
/**
* @return {?}
*/
ngOnInit() {
this.addScrollEventHandlers();
}
/**
* @return {?}
*/
ngOnDestroy() {
this.removeScrollEventHandlers();
this.revertParentOverscroll();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
/** @type {?} */
let indexLengthChanged = this.cachedItemsLength !== this.items.length;
this.cachedItemsLength = this.items.length;
/** @type {?} */
const firstRun = !changes.items || !changes.items.previousValue || changes.items.previousValue.length === 0;
this.refresh_internal(indexLengthChanged || firstRun);
}
/**
* @return {?}
*/
ngDoCheck() {
if (this.cachedItemsLength !== this.items.length) {
this.cachedItemsLength = this.items.length;
this.refresh_internal(true);
}
}
/**
* @return {?}
*/
refresh() {
this.refresh_internal(true);
}
/**
* @param {?} item
* @param {?=} alignToBeginning
* @param {?=} additionalOffset
* @param {?=} animationMilliseconds
* @param {?=} animationCompletedCallback
* @return {?}
*/
scrollInto(item, alignToBeginning = true, additionalOffset = 0, animationMilliseconds = undefined, animationCompletedCallback = undefined) {
/** @type {?} */
let index = this.items.indexOf(item);
if (index === -1) {
return;
}
this.scrollToIndex(index, alignToBeginning, additionalOffset, animationMilliseconds, animationCompletedCallback);
}
/**
* @param {?} index
* @param {?=} alignToBeginning
* @param {?=} additionalOffset
* @param {?=} animationMilliseconds
* @param {?=} animationCompletedCallback
* @return {?}
*/
scrollToIndex(index, alignToBeginning = true, additionalOffset = 0, animationMilliseconds = undefined, animationCompletedCallback = undefined) {
/** @type {?} */
let maxRetries = 5;
/** @type {?} */
let retryIfNeeded = () => {
--maxRetries;
if (maxRetries <= 0) {
if (animationCompletedCallback) {
animationCompletedCallback();
}
return;
}
/** @type {?} */
let dimensions = this.calculateDimensions();
/** @type {?} */
let desiredStartIndex = Math.min(Math.max(index, 0), dimensions.itemCount - 1);
if (this.previousViewPort.startIndex === desiredStartIndex) {
if (animationCompletedCallback) {
animationCompletedCallback();
}
return;
}
this.scrollToIndex_internal(index, alignToBeginning, additionalOffset, 0, retryIfNeeded);
};
this.scrollToIndex_internal(index, alignToBeginning, additionalOffset, animationMilliseconds, retryIfNeeded);
}
/**
* @param {?} index
* @param {?=} alignToBeginning
* @param {?=} additionalOffset
* @param {?=} animationMilliseconds
* @param {?=} animationCompletedCallback
* @return {?}
*/
scrollToIndex_internal(index, alignToBeginning = true, additionalOffset = 0, animationMilliseconds = undefined, animationCompletedCallback = undefined) {
animationMilliseconds = animationMilliseconds === undefined ? this.scrollAnimationTime : animationMilliseconds;
/** @type {?} */
let scrollElement = this.getScrollElement();
/** @type {?} */
let offset = this.getElementsOffset();
/** @type {?} */
let dimensions = this.calculateDimensions();
/** @type {?} */
let scroll = this.calculatePadding(index, dimensions, false) + offset + additionalOffset;
if (!alignToBeginning) {
scroll -= dimensions.wrapGroupsPerPage * dimensions[this._childScrollDim];
}
if (!animationMilliseconds) {
this.renderer.setProperty(scrollElement, this._scrollType, scroll);
this.refresh_internal(false, animationCompletedCallback);
return;
}
}
/**
* @return {?}
*/
checkScrollElementResized() {
/** @type {?} */
let boundingRect = this.getScrollElement().getBoundingClientRect();
/** @type {?} */
let sizeChanged;
if (!this.previousScrollBoundingRect) {
sizeChanged = true;
}
else {
/** @type {?} */
let widthChange = Math.abs(boundingRect.width - this.previousScrollBoundingRect.width);
/** @type {?} */
let heightChange = Math.abs(boundingRect.height - this.previousScrollBoundingRect.height);
sizeChanged = widthChange > this.resizeBypassRefreshTheshold || heightChange > this.resizeBypassRefreshTheshold;
}
if (sizeChanged) {
this.previousScrollBoundingRect = boundingRect;
if (boundingRect.width > 0 && boundingRect.height > 0) {
this.refresh_internal(false);
}
}
}
/**
* @return {?}
*/
updateDirection() {
if (this.horizontal) {
this._invisiblePaddingProperty = 'width';
this._offsetType = 'offsetLeft';
this._pageOffsetType = 'pageXOffset';
this._childScrollDim = 'childWidth';
this._marginDir = 'margin-left';
this._translateDir = 'translateX';
this._scrollType = 'scrollLeft';
}
else {
this._invisiblePaddingProperty = 'height';
this._offsetType = 'offsetTop';
this._pageOffsetType = 'pageYOffset';
this._childScrollDim = 'childHeight';
this._marginDir = 'margin-top';
this._translateDir = 'translateY';
this._scrollType = 'scrollTop';
}
}
/**
* @param {?} func
* @param {?} wait
* @return {?}
*/
throttleTrailing(func, wait) {
/** @type {?} */
let timeout = undefined;
/** @type {?} */
const result = function () {
/** @type {?} */
const _this = this;
/** @type {?} */
const _arguments = arguments;
if (timeout) {
return;
}
if (wait <= 0) {
func.apply(_this, _arguments);
}
else {
timeout = setTimeout(function () {
timeout = undefined;
func.apply(_this, _arguments);
}, wait);
}
};
return result;
}
/**
* @param {?} itemsArrayModified
* @param {?=} refreshCompletedCallback
* @param {?=} maxRunTimes
* @return {?}
*/
refresh_internal(itemsArrayModified, refreshCompletedCallback = undefined, maxRunTimes = 2) {
//note: maxRunTimes is to force it to keep recalculating if the previous iteration caused a re-render (different sliced items in viewport or scrollPosition changed).
//The default of 2x max will probably be accurate enough without causing too large a performance bottleneck
//The code would typically quit out on the 2nd iteration anyways. The main time it'd think more than 2 runs would be necessary would be for vastly different sized child items or if this is the 1st time the items array was initialized.
//Without maxRunTimes, If the user is actively scrolling this code would become an infinite loop until they stopped scrolling. This would be okay, except each scroll event would start an additional infinte loop. We want to short-circuit it to prevent his.
this.zone.runOutsideAngular(() => {
requestAnimationFrame(() => {
if (itemsArrayModified) {
this.resetWrapGroupDimensions();
}
/** @type {?} */
let viewport = this.calculateViewport();
/** @type {?} */
let startChanged = itemsArrayModified || viewport.startIndex !== this.previousViewPort.startIndex;
/** @type {?} */
let endChanged = itemsArrayModified || viewport.endIndex !== this.previousViewPort.endIndex;
/** @type {?} */
let scrollLengthChanged = viewport.scrollLength !== this.previousViewPort.scrollLength;
/** @type {?} */
let paddingChanged = viewport.padding !== this.previousViewPort.padding;
this.previousViewPort = viewport;
if (scrollLengthChanged) {
this.renderer.setStyle(this.invisiblePaddingElementRef.nativeElement, this._invisiblePaddingProperty, `${viewport.scrollLength}px`);
}
if (paddingChanged) {
if (this.useMarginInsteadOfTranslate) {
this.renderer.setStyle(this.contentElementRef.nativeElement, this._marginDir, `${viewport.padding}px`);
}
else {
this.renderer.setStyle(this.contentElementRef.nativeElement, 'transform', `${this._translateDir}(${viewport.padding}px)`);
this.renderer.setStyle(this.contentElementRef.nativeElement, 'webkitTransform', `${this._translateDir}(${viewport.padding}px)`);
}
}
if (startChanged || endChanged) {
this.zone.run(() => {
// update the scroll list to trigger re-render of components in viewport
this.viewPortItems = viewport.startIndexWithBuffer >= 0 && viewport.endIndexWithBuffer >= 0 ? this.items.slice(viewport.startIndexWithBuffer, viewport.endIndexWithBuffer + 1) : [];
this.update.emit(this.viewPortItems);
this.vsUpdate.emit(this.viewPortItems);
{
if (startChanged) {
this.start.emit({ start: viewport.startIndex, end: viewport.endIndex });
this.vsStart.emit({ start: viewport.startIndex, end: viewport.endIndex });
}
if (endChanged) {
this.end.emit({ start: viewport.startIndex, end: viewport.endIndex });
this.vsEnd.emit({ start: viewport.startIndex, end: viewport.endIndex });
}
if (startChanged || endChanged) {
this.change.emit({ start: viewport.startIndex, end: viewport.endIndex });
this.vsChange.emit({ start: viewport.startIndex, end: viewport.endIndex });
}
}
if (maxRunTimes > 0) {
this.refresh_internal(false, refreshCompletedCallback, maxRunTimes - 1);
return;
}
if (refreshCompletedCallback) {
refreshCompletedCallback();
}
});
}
else {
if (maxRunTimes > 0 && (scrollLengthChanged || paddingChanged)) {
this.refresh_internal(false, refreshCompletedCallback, maxRunTimes - 1);
return;
}
if (refreshCompletedCallback) {
refreshCompletedCallback();
}
}
});
});
}
/**
* @return {?}
*/
getScrollElement() {
return this.parentScroll instanceof Window ? document.scrollingElement || document.documentElement || document.body : this.parentScroll || this.element.nativeElement;
}
/**
* @return {?}
*/
addScrollEventHandlers() {
/** @type {?} */
let scrollElement = this.getScrollElement();
this.removeScrollEventHandlers();
this.zone.runOutsideAngular(() => {
if (this.parentScroll instanceof Window) {
this.disposeScrollHandler = this.renderer.listen('window', 'scroll', this.refresh_throttled);
this.disposeResizeHandler = this.renderer.listen('window', 'resize', this.refresh_throttled);
}
else {
this.disposeScrollHandler = this.renderer.listen(scrollElement, 'scroll', this.refresh_throttled);
if (this._checkResizeInterval > 0) {
this.checkScrollElementResizedTimer = /** @type {?} */ (setInterval(() => { this.checkScrollElementResized(); }, this._checkResizeInterval));
}
}
});
}
/**
* @return {?}
*/
removeScrollEventHandlers() {
if (this.checkScrollElementResizedTimer) {
clearInterval(this.checkScrollElementResizedTimer);
}
if (this.disposeScrollHandler) {
this.disposeScrollHandler();
this.disposeScrollHandler = undefined;
}
if (this.disposeResizeHandler) {
this.disposeResizeHandler();
this.disposeResizeHandler = undefined;
}
}
/**
* @return {?}
*/
getElementsOffset() {
/** @type {?} */
let offset = 0;
if (this.containerElementRef && this.containerElementRef.nativeElement) {
offset += this.containerElementRef.nativeElement[this._offsetType];
}
if (this.parentScroll) {
/** @type {?} */
let scrollElement = this.getScrollElement();
/** @type {?} */
let elementClientRect = this.element.nativeElement.getBoundingClientRect();
/** @type {?} */
let scrollClientRect = scrollElement.getBoundingClientRect();
if (this.horizontal) {
offset += elementClientRect.left - scrollClientRect.left;
}
else {
offset += elementClientRect.top - scrollClientRect.top;
}
if (!(this.parentScroll instanceof Window)) {
offset += scrollElement[this._scrollType];
}
}
return offset;
}
/**
* @return {?}
*/
countItemsPerWrapGroup() {
/** @type {?} */
let propertyName = this.horizontal ? 'offsetLeft' : 'offsetTop';
/** @type {?} */
let children = ((this.containerElementRef && this.containerElementRef.nativeElement) || this.contentElementRef.nativeElement).children;
/** @type {?} */
let childrenLength = children ? children.length : 0;
if (childrenLength === 0) {
return 1;
}
/** @type {?} */
let firstOffset = children[0][propertyName];
/** @type {?} */
let result = 1;
while (result < childrenLength && firstOffset === children[result][propertyName]) {
++result;
}
return result;
}
/**
* @return {?}
*/
getScrollPosition() {
/** @type {?} */
let windowScrollValue = undefined;
if (this.parentScroll instanceof Window) {
/** @type {?} */
var window;
windowScrollValue = window[this._pageOffsetType];
}
return windowScrollValue || this.getScrollElement()[this._scrollType] || 0;
}
/**
* @return {?}
*/
resetWrapGroupDimensions() {
/** @type {?} */
const oldWrapGroupDimensions = this.wrapGroupDimensions;
this.wrapGroupDimensions = {
maxChildSizePerWrapGroup: [],
numberOfKnownWrapGroupChildSizes: 0,
sumOfKnownWrapGroupChildWidths: 0,
sumOfKnownWrapGroupChildHeights: 0
};
if (!this.enableUnequalChildrenSizes || !oldWrapGroupDimensions || oldWrapGroupDimensions.numberOfKnownWrapGroupChildSizes === 0) {
return;
}
/** @type {?} */
const itemsPerWrapGroup = this.countItemsPerWrapGroup();
for (let wrapGroupIndex = 0; wrapGroupIndex < oldWrapGroupDimensions.maxChildSizePerWrapGroup.length; ++wrapGroupIndex) {
/** @type {?} */
const oldWrapGroupDimension = oldWrapGroupDimensions.maxChildSizePerWrapGroup[wrapGroupIndex];
if (!oldWrapGroupDimension || !oldWrapGroupDimension.items || !oldWrapGroupDimension.items.length) {
continue;
}
if (oldWrapGroupDimension.items.length !== itemsPerWrapGroup) {
return;
}
/** @type {?} */
let itemsChanged = false;
/** @type {?} */
let arrayStartIndex = itemsPerWrapGroup * wrapGroupIndex;
for (let i = 0; i < itemsPerWrapGroup; ++i) {
if (!this.compareItems(oldWrapGroupDimension.items[i], this.items[arrayStartIndex + i])) {
itemsChanged = true;
break;
}
}
if (!itemsChanged) {
++this.wrapGroupDimensions.numberOfKnownWrapGroupChildSizes;
this.wrapGroupDimensions.sumOfKnownWrapGroupChildWidths += oldWrapGroupDimension.childWidth || 0;
this.wrapGroupDimensions.sumOfKnownWrapGroupChildHeights += oldWrapGroupDimension.childHeight || 0;
this.wrapGroupDimensions.maxChildSizePerWrapGroup[wrapGroupIndex] = oldWrapGroupDimension;
}
}
}
/**
* @return {?}
*/
calculateDimensions() {
/** @type {?} */
let scrollElement = this.getScrollElement();
/** @type {?} */
let itemCount = this.items.length;
/** @type {?} */
const maxCalculatedScrollBarSize = 25; // Note: Formula to auto-calculate doesn't work for ParentScroll, so we default to this if not set by consuming application
this.calculatedScrollbarHeight = Math.max(Math.min(scrollElement.offsetHeight - scrollElement.clientHeight, maxCalculatedScrollBarSize), this.calculatedScrollbarHeight);
this.calculatedScrollbarWidth = Math.max(Math.min(scrollElement.offsetWidth - scrollElement.clientWidth, maxCalculatedScrollBarSize), this.calculatedScrollbarWidth);
/** @type {?} */
let viewWidth = scrollElement.offsetWidth - (this.scrollbarWidth || this.calculatedScrollbarWidth || (this.horizontal ? 0 : maxCalculatedScrollBarSize));
/** @type {?} */
let viewHeight = scrollElement.offsetHeight - (this.scrollbarHeight || this.calculatedScrollbarHeight || (this.horizontal ? maxCalculatedScrollBarSize : 0));
/** @type {?} */
let content = (this.containerElementRef && this.containerElementRef.nativeElement) || this.contentElementRef.nativeElement;
/** @type {?} */
let itemsPerWrapGroup = this.countItemsPerWrapGroup();
/** @type {?} */
let wrapGroupsPerPage;
/** @type {?} */
let defaultChildWidth;
/** @type {?} */
let defaultChildHeight;
if (!this.enableUnequalChildrenSizes) {
if (content.children.length > 0) {
if (!this.childWidth || !this.childHeight) {
if (!this.minMeasuredChildWidth && viewWidth > 0) {
this.minMeasuredChildWidth = viewWidth;
}
if (!this.minMeasuredChildHeight && viewHeight > 0) {
this.minMeasuredChildHeight = viewHeight;
}
}
/** @type {?} */
let child = content.children[0];
/** @type {?} */
let clientRect = child.getBoundingClientRect();
this.minMeasuredChildWidth = Math.min(this.minMeasuredChildWidth, clientRect.width);
this.minMeasuredChildHeight = Math.min(this.minMeasuredChildHeight, clientRect.height);
}
defaultChildWidth = this.childWidth || this.minMeasuredChildWidth || viewWidth;
defaultChildHeight = this.childHeight || this.minMeasuredChildHeight || viewHeight;
/** @type {?} */
let itemsPerRow = Math.max(Math.ceil(viewWidth / defaultChildWidth), 1);
/** @type {?} */
let itemsPerCol = Math.max(Math.ceil(viewHeight / defaultChildHeight), 1);
wrapGroupsPerPage = this.horizontal ? itemsPerRow : itemsPerCol;
}
else {
/** @type {?} */
let scrollOffset = scrollElement[this._scrollType] - (this.previousViewPort ? this.previousViewPort.padding : 0);
/** @type {?} */
let arrayStartIndex = this.previousViewPort.startIndexWithBuffer || 0;
/** @type {?} */
let wrapGroupIndex = Math.ceil(arrayStartIndex / itemsPerWrapGroup);
/** @type {?} */
let maxWidthForWrapGroup = 0;
/** @type {?} */
let maxHeightForWrapGroup = 0;
/** @type {?} */
let sumOfVisibleMaxWidths = 0;
/** @type {?} */
let sumOfVisibleMaxHeights = 0;
wrapGroupsPerPage = 0;
for (let i = 0; i < content.children.length; ++i) {
++arrayStartIndex;
/** @type {?} */
let child = content.children[i];
/** @type {?} */
let clientRect = child.getBoundingClientRect();
maxWidthForWrapGroup = Math.max(maxWidthForWrapGroup, clientRect.width);
maxHeightForWrapGroup = Math.max(maxHeightForWrapGroup, clientRect.height);
if (arrayStartIndex % itemsPerWrapGroup === 0) {
/** @type {?} */
let oldValue = this.wrapGroupDimensions.maxChildSizePerWrapGroup[wrapGroupIndex];
if (oldValue) {
--this.wrapGroupDimensions.numberOfKnownWrapGroupChildSizes;
this.wrapGroupDimensions.sumOfKnownWrapGroupChildWidths -= oldValue.childWidth || 0;
this.wrapGroupDimensions.sumOfKnownWrapGroupChildHeights -= oldValue.childHeight || 0;
}
++this.wrapGroupDimensions.numberOfKnownWrapGroupChildSizes;
/** @type {?} */
const items = this.items.slice(arrayStartIndex - itemsPerWrapGroup, arrayStartIndex);
this.wrapGroupDimensions.maxChildSizePerWrapGroup[wrapGroupIndex] = {
childWidth: maxWidthForWrapGroup,
childHeight: maxHeightForWrapGroup,
items: items
};
this.wrapGroupDimensions.sumOfKnownWrapGroupChildWidths += maxWidthForWrapGroup;
this.wrapGroupDimensions.sumOfKnownWrapGroupChildHeights += maxHeightForWrapGroup;
if (this.horizontal) {
/** @type {?} */
let maxVisibleWidthForWrapGroup = Math.min(maxWidthForWrapGroup, Math.max(viewWidth - sumOfVisibleMaxWidths, 0));
if (scrollOffset > 0) {
/** @type {?} */
let scrollOffsetToRemove = Math.min(scrollOffset, maxVisibleWidthForWrapGroup);
maxVisibleWidthForWrapGroup -= scrollOffsetToRemove;
scrollOffset -= scrollOffsetToRemove;
}
sumOfVisibleMaxWidths += maxVisibleWidthForWrapGroup;
if (maxVisibleWidthForWrapGroup > 0 && viewWidth >= sumOfVisibleMaxWidths) {
++wrapGroupsPerPage;
}
}
else {
/** @type {?} */
let maxVisibleHeightForWrapGroup = Math.min(maxHeightForWrapGroup, Math.max(viewHeight - sumOfVisibleMaxHeights, 0));
if (scrollOffset > 0) {
/** @type {?} */
let scrollOffsetToRemove = Math.min(scrollOffset, maxVisibleHeightForWrapGroup);
maxVisibleHeightForWrapGroup -= scrollOffsetToRemove;
scrollOffset -= scrollOffsetToRemove;
}
sumOfVisibleMaxHeights += maxVisibleHeightForWrapGroup;
if (maxVisibleHeightForWrapGroup > 0 && viewHeight >= sumOfVisibleMaxHeights) {
++wrapGroupsPerPage;
}
}
++wrapGroupIndex;
maxWidthForWrapGroup = 0;
maxHeightForWrapGroup = 0;
}
}
/** @type {?} */
let averageChildWidth = this.wrapGroupDimensions.sumOfKnownWrapGroupChildWidths / this.wrapGroupDimensions.numberOfKnownWrapGroupChildSizes;
/** @type {?} */
let averageChildHeight = this.wrapGroupDimensions.sumOfKnownWrapGroupChildHeights / this.wrapGroupDimensions.numberOfKnownWrapGroupChildSizes;
defaultChildWidth = this.childWidth || averageChildWidth || viewWidth;
defaultChildHeight = this.childHeight || averageChildHeight || viewHeight;
if (this.horizontal) {
if (viewWidth > sumOfVisibleMaxWidths) {
wrapGroupsPerPage += Math.ceil((viewWidth - sumOfVisibleMaxWidths) / defaultChildWidth);
}
}
else {
if (viewHeight > sumOfVisibleMaxHeights) {
wrapGroupsPerPage += Math.ceil((viewHeight - sumOfVisibleMaxHeights) / defaultChildHeight);
}
}
}
/** @type {?} */
let itemsPerPage = itemsPerWrapGroup * wrapGroupsPerPage;
/** @type {?} */
let pageCount_fractional = itemCount / itemsPerPage;
/** @type {?} */
let numberOfWrapGroups = Math.ceil(itemCount / itemsPerWrapGroup);
/** @type {?} */
let scrollLength = 0;
/** @type {?} */
let defaultScrollLengthPerWrapGroup = this.horizontal ? defaultChildWidth : defaultChildHeight;
if (this.enableUnequalChildrenSizes) {
/** @type {?} */
let numUnknownChildSizes = 0;
for (let i = 0; i < numberOfWrapGroups; ++i) {
/** @type {?} */
let childSize = this.wrapGroupDimensions.maxChildSizePerWrapGroup[i] && this.wrapGroupDimensions.maxChildSizePerWrapGroup[i][this._childScrollDim];
if (childSize) {
scrollLength += childSize;
}
else {
++numUnknownChildSizes;
}
}
scrollLength += Math.round(numUnknownChildSizes * defaultScrollLengthPerWrapGroup);
}
else {
scrollLength = numberOfWrapGroups * defaultScrollLengthPerWrapGroup;
}
return {
itemCount: itemCount,
itemsPerWrapGroup: itemsPerWrapGroup,
wrapGroupsPerPage: wrapGroupsPerPage,
itemsPerPage: itemsPerPage,
pageCount_fractional: pageCount_fractional,
childWidth: defaultChildWidth,
childHeight: defaultChildHeight,
scrollLength: scrollLength
};
}
/**
* @param {?} arrayStartIndexWithBuffer
* @param {?} dimensions
* @param {?} allowUnequalChildrenSizes_Experimental
* @return {?}
*/
calculatePadding(arrayStartIndexWithBuffer, dimensions, allowUnequalChildrenSizes_Experimental) {
if (dimensions.itemCount === 0) {
return 0;
}
/** @type {?} */
let defaultScrollLengthPerWrapGroup = dimensions[this._childScrollDim];
/** @type {?} */
let startingWrapGroupIndex = Math.ceil(arrayStartIndexWithBuffer / dimensions.itemsPerWrapGroup) || 0;
if (!this.enableUnequalChildrenSizes) {
return defaultScrollLengthPerWrapGroup * startingWrapGroupIndex;
}
/** @type {?} */
let numUnknownChildSizes = 0;
/** @type {?} */
let result = 0;
for (let i = 0; i < startingWrapGroupIndex; ++i) {
/** @type {?} */
let childSize = this.wrapGroupDimensions.maxChildSizePerWrapGroup[i] && this.wrapGroupDimensions.maxChildSizePerWrapGroup[i][this._childScrollDim];
if (childSize) {
result += childSize;
}
else {
++numUnknownChildSizes;
}
}
result += Math.round(numUnknownChildSizes * defaultScrollLengthPerWrapGroup);
return result;
}
/**
* @param {?} scrollPosition
* @param {?} dimensions
* @return {?}
*/
calculatePageInfo(scrollPosition, dimensions) {
/** @type {?} */
let scrollPercentage = 0;
if (this.enableUnequalChildrenSizes) {
/** @type {?} */
const numberOfWrapGroups = Math.ceil(dimensions.itemCount / dimensions.itemsPerWrapGroup);
/** @type {?} */
let totalScrolledLength = 0;
/** @type {?} */
let defaultScrollLengthPerWrapGroup = dimensions[this._childScrollDim];
for (let i = 0; i < numberOfWrapGroups; ++i) {
/** @type {?} */
let childSize = this.wrapGroupDimensions.maxChildSizePerWrapGroup[i] && this.wrapGroupDimensions.maxChildSizePerWrapGroup[i][this._childScrollDim];
if (childSize) {
totalScrolledLength += childSize;
}
else {
totalScrolledLength += defaultScrollLengthPerWrapGroup;
}
if (scrollPosition < totalScrolledLength) {
scrollPercentage = i / numberOfWrapGroups;
break;
}
}
}
else {
scrollPercentage = scrollPosition / dimensions.scrollLength;
}
/** @type {?} */
let startingArrayIndex_fractional = Math.min(Math.max(scrollPercentage * dimensions.pageCount_fractional, 0), dimensions.pageCount_fractional) * dimensions.itemsPerPage;
/** @type {?} */
let maxStart = dimensions.itemCount - dimensions.itemsPerPage - 1;
/** @type {?} */
let arrayStartIndex = Math.min(Math.floor(startingArrayIndex_fractional), maxStart);
arrayStartIndex -= arrayStartIndex % dimensions.itemsPerWrapGroup;
/** @type {?} */
let arrayEndIndex = Math.ceil(startingArrayIndex_fractional) + dimensions.itemsPerPage - 1;
arrayEndIndex += (dimensions.itemsPerWrapGroup - ((arrayEndIndex + 1) % dimensions.itemsPerWrapGroup)); // round up to end of wrapGroup
if (isNaN(arrayStartIndex)) {
arrayStartIndex = 0;
}
if (isNaN(arrayEndIndex)) {
arrayEndIndex = 0;
}
arrayStartIndex = Math.min(Math.max(arrayStartIndex, 0), dimensions.itemCount - 1);
arrayEndIndex = Math.min(Math.max(arrayEndIndex, 0), dimensions.itemCount - 1);
/** @type {?} */
let bufferSize = this.bufferAmount * dimensions.itemsPerWrapGroup;
/** @type {?} */
let startIndexWithBuffer = Math.min(Math.max(arrayStartIndex - bufferSize, 0), dimensions.itemCount - 1);
/** @type {?} */
let endIndexWithBuffer = Math.min(Math.max(arrayEndIndex + bufferSize, 0), dimensions.itemCount - 1);
return {
startIndex: arrayStartIndex,
endIndex: arrayEndIndex,
startIndexWithBuffer: startIndexWithBuffer,
endIndexWithBuffer: endIndexWithBuffer
};
}
/**
* @return {?}
*/
calculateViewport() {
/** @type {?} */
let dimensions = this.calculateDimensions();
/** @type {?} */
let offset = this.getElementsOffset();
/** @type {?} */
let scrollPosition = this.getScrollPosition();
if (scrollPosition > dimensions.scrollLength && !(this.parentScroll instanceof Window)) {
scrollPosition = dimensions.scrollLength;
}
else {
scrollPosition -= offset;
}
scrollPosition = Math.max(0, scrollPosition);
/** @type {?} */
let pageInfo = this.calculatePageInfo(scrollPosition, dimensions);
/** @type {?} */
let newPadding = this.calculatePadding(pageInfo.startIndexWithBuffer, dimensions, true);
/** @type {?} */
let newScrollLength = dimensions.scrollLength;
return {
startIndex: pageInfo.startIndex,
endIndex: pageInfo.endIndex,
startIndexWithBuffer: pageInfo.startIndexWithBuffer,
endIndexWithBuffer: pageInfo.endIndexWithBuffer,
padding: Math.round(newPadding),
scrollLength: Math.round(newScrollLength)
};
}
} |
JavaScript | class RoleCheckBox extends RoleInput
{
/**
* @param {boolean|string} checked
*/
set checked(checked) {
this.setAttr(AriaChecked, checked)
}
/**
* @returns {boolean|string}
*/
get checked() {
return this.getAttr(AriaChecked) || false
}
/**
* @param {boolean} readOnly
*/
set readOnly(readOnly) {
this.setAttr(AriaReadOnly, readOnly)
}
/**
* @returns {boolean}
*/
get readOnly() {
return this.getAttr(AriaReadOnly)
}
} |
JavaScript | class Flashcard {
static existingCards = [];
isFlipped = false;
/**
* Make a flashcard.
*
* @param front the card's front side, e.g. a word
* @param back the card's back side, e.g. a definition
* @returns flashcard with front "front" and back "back"
*/
static make(front, back){
const newCard = new Flashcard(front, back);
Flashcard.existingCards.push(newCard);
return newCard;
}
/**
* Creates a unique string identifier to represent a flashcard
* @param front the card's front side, e.g. a word
* @param back the card's back side, e.g. a definition
* @returns the flashcard's unique string representation
*/
static getKey(front, back){
return JSON.stringify([front, back]);
}
/**
* Creates flashcard with front "front" and back "back"
*
* @param front this card's front side, e.g. a vocabulary word
* @param back this card's back side, e.g. its definition
*/
constructor(front, back) {
this.front = front;
this.back = back;
}
/**
* Creates a string representation of a flashcard
* in the form {front}/{back}
*
* @returns the flashcard's string representation
*/
toString() {
return this.front + "/" + this.back;
}
} |
JavaScript | class EducationalBanner extends Banner {
constructor() {
super();
const fragment = this.getTemplate();
this.attachShadow({mode: 'open'}).appendChild(fragment);
}
/**
* Returns the HTML template for the Educational Banner.
* @returns {!Node}
*/
getTemplate() {
return htmlTemplate.content.cloneNode(true);
}
/**
* Get the concrete banner instance.
* @returns {!EducationalBanner}
* @private
*/
getBannerInstance_() {
const parent = this.getRootNode() && this.getRootNode().host;
let bannerInstance = this;
// In the case the educational-banner web component is not the root node
// (e.g. it is contained within another web component) prefer the outer
// component.
if (parent && parent instanceof EducationalBanner) {
bannerInstance = parent;
}
return bannerInstance;
}
/**
* Called when the web component is connected to the DOM. This will be called
* for both the inner warning-banner component and the concrete
* implementations that extend from it.
*/
connectedCallback() {
// If an EducationalBanner subclass overrides the default dismiss button
// the button will not exist in the shadowRoot. Add the event listener to
// the overridden dismiss button first and fall back to the default button
// if no overridden button.
const overridenDismissButton =
this.querySelector('[slot="dismiss-button"]');
const defaultDismissButton =
this.shadowRoot.querySelector('#dismiss-button');
if (overridenDismissButton) {
overridenDismissButton.addEventListener(
'click', event => this.onDismissClickHandler_(event));
} else if (defaultDismissButton) {
defaultDismissButton.addEventListener(
'click', event => this.onDismissClickHandler_(event));
}
// Attach an onclick handler to the extra-button slot. This enables a new
// element to leverage the href tag on the element to have a URL opened.
// TODO(crbug.com/1228128): Add UMA trigger to capture number of extra
// button clicks.
const extraButton = this.querySelector('[slot="extra-button"]');
if (extraButton) {
extraButton.addEventListener('click', (e) => {
util.visitURL(extraButton.getAttribute('href'));
if (extraButton.hasAttribute('dismiss-banner-when-clicked')) {
this.dispatchEvent(
new CustomEvent(Banner.Event.BANNER_DISMISSED_FOREVER, {
bubbles: true,
composed: true,
detail: {banner: this.getBannerInstance_()}
}));
}
e.preventDefault();
});
}
}
/**
* Only show the banner 3 Files app sessions (unless dismissed). Please refer
* to the Banner externs for information about Files app session.
* @returns {number}
*/
showLimit() {
return 3;
}
/**
* All banners that inherit this class should override with their own
* volume types to allow. Setting this explicitly as an empty array ensures
* banners that don't override this are not shown by default.
* @returns {!Array<!Banner.AllowedVolume>}
*/
allowedVolumes() {
return [];
}
/**
* Handler for the dismiss button on click, switches to the custom banner
* dismissal event to ensure the controller can catch the event.
* @param {!Event} event The click event.
* @private
*/
onDismissClickHandler_(event) {
this.dispatchEvent(new CustomEvent(Banner.Event.BANNER_DISMISSED_FOREVER, {
bubbles: true,
composed: true,
detail: {banner: this.getBannerInstance_()}
}));
}
} |
JavaScript | class UnwatchedFile extends AsyncObject {
constructor (fileName, listener) {
super(fileName, listener)
}
syncCall () {
return (fileName, listener) => {
this.file = fileName
fs.unwatchFile(fileName, listener)
}
}
onResult () {
return this.file
}
} |
JavaScript | class ExcelToJSON {
constructor () {
this.parseExcel = function (file) {
var reader = new FileReader()
reader.onload = function (e) {
var data = e.target.result
// parsing data
var workbook = XLSX.read(data, {
type: 'binary'
})
// All main run here
const sheets = workbook.Sheets
const jsonData = makeJson(sheets)
jsonData.forEach(sheet => {
makeTable(sheet, linksTable)
})
}
reader.onerror = function (ex) {
console.log(ex)
}
reader.readAsBinaryString(file)
}
}
} |
JavaScript | class StringIdGenerator {
constructor (chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars
this._nextId = [0]
}
next () {
const r = []
for (const char of this._nextId) {
r.unshift(this._chars[char])
}
this._increment()
return r.join('')
}
_increment () {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i]
if (val >= this._chars.length) {
this._nextId[i] = 0
} else {
return
}
}
this._nextId.push(0)
}
* [Symbol.iterator] () {
while (true) {
yield this.next()
}
}
} |
JavaScript | class Subscription {
// The constructor of a subscription
// key: The key of store items to listen to notifications for
constructor(key) {
this.key = key;
this.subscribers = [];
}
// Adds a subscriber to the subscription
// subscriber: A subscriber (see Subscriber.js for details)
addSubscriber(subscriber) {
// add the subscriber instance to the subscribers Array property
this.subscribers.push(subscriber);
// set the subscription of the subscriber instance to this subscription
subscriber.subscription = this;
return subscriber;
}
// Removes a subscriber from the subscription
// subscriber: A subscriber (see Subscriber.js for details)
removeSubscriber(subscriber) {
// remove the subscriber instance from the subscribers Array property
const index = this.subscribers.findIndex(f => f === subscriber);
this.subscribers.splice(index, 1);
// unset the subscription of the subscriber instance
subscriber.subscription = null;
return subscriber;
}
// Notifies all the subscribers by sending a store item and notification options to them
// storeItem: A store item
// notificationOptions: An object with options in the properties:
// e.g. { isRouting: true }
notify(storeItem, notificationOptions) {
this.subscribers.forEach(s => s.notify(storeItem, notificationOptions));
}
} |
JavaScript | class BaseWrapper extends React.Component {
constructor(props) {
super(props);
props.init(props.store)
}
render() {
return(
null
)
}
} |
JavaScript | class Dataset {
// Constructor
constructor(x) {
this.x = x;
}
// Returns a copy of this dataset
clone() {
let nx = [];
// Copy all instances
for (let i = 0; i < this.no_examples(); i++) {
// Copy attributes of current instance
let e = this.x[i];
let new_e = [];
for (let a = 0; a < e.length; a++) {
new_e.push(e[a]);
}
// Add to new data arrays
nx.push(new_e);
}
// Create new dataset
let new_data = new Dataset(nx);
return new_data;
}
// Returns thenumber of examples (size) of this dataset.
no_examples() {
return this.x.length;
}
// Returns the number of attributes in this dataset.
no_attr() {
return this.x[0].length;
}
// Feature-wise normalization where we subtract the mean and divide with stdev
normalize() {
for (let c = 0; c < this.no_attr(); c++) {
let m = this.attr_mean(c); // mean
let std = this.attr_stdev(c, m); // stdev
for (let i = 0; i < this.no_examples(); i++) {
this.x[i][c] = (this.x[i][c] - m) / std;
}
}
}
// Randomly shuffles the dataset examples
shuffle() {
// Create new arrays
let nx = [];
// Holds which instances that have been copied or not
let done = new Array(this.x.length).fill(0);
// Continue until all ínstances have been copied
while (nx.length < this.x.length) {
// Find a random instance that has not been copied
let i = -1;
while (i == -1) {
let ti = Math.floor(rnd() * this.x.length);
if (done[ti] == 0) {
// Not copied. Use this index.
done[ti] = 1;
i = ti;
}
else {
// Already copied. Get new index.
i = -1;
}
}
// Get values
let xv = this.x[i];
// Copy to new arrays
nx.push(xv);
}
this.x = nx;
}
// Calculates the mean value of an attribute
attr_mean(c) {
let m = 0;
for (let i = 0; i < this.no_examples(); i++) {
m += this.x[i][c];
}
m /= this.no_examples();
return m;
}
// Calculates the min value of an attribute
attr_min(c) {
let m = 100000;
for (let i = 0; i < this.no_examples(); i++) {
if (this.x[i][c] < m) {
m = this.x[i][c];
}
}
return m;
}
// Calculates the max value of an attribute
attr_max(c) {
let m = -100000;
for (let i = 0; i < this.no_examples(); i++) {
if (this.x[i][c] > m) {
m = this.x[i][c];
}
}
return m;
}
// Calculates the standard deviation of an attribute
attr_stdev(c, m) {
let std = 0;
for (let i = 0; i < this.no_examples(); i++) {
std += Math.pow(this.x[i][c] - m, 2);
}
std = Math.sqrt(std / (this.no_examples() - 1));
return std;
}
} |
JavaScript | class Cloud extends MeshObject {
/**
*
* @param {CANNON.World} world The physics world to add the object to
* @param {Object} programs Object containing named shader programs to pick
* the right one out of
* @param {Array<number>} startPosition The position to start at
* @param {Array<number>} endPosition The position to end at
* @param {number} speed The speed at which to move
* @param {Object} meshes Object containing the meshes to pick the right one
* out of
* @param {object} [options={}] Optional options for the object
* If none is given, one will be constructed from the physics meshes
* @param {Array<number>} [options.orientation] The object's default
* orientation
* @param {Array<number>} [options.scale] The object's default scale
* @param {Object} [options.lightParams] The object's light coefficients
* @param {number} [options.collisionFilterGroup] The object's collision
* group
* @param {number} [options.collisionFilterMask] The object's collision
* mask
*/
constructor(world, programs, startPosition, endPosition, speed, meshes,
options = {}) {
options.mass = 0;
options.portable = false;
options.color = [1, 1, 1, 0.3];
options.graphicalMesh = meshes['cloudG'];
options.position = startPosition;
super(world, programs['colored'], 'colored', [], options);
this.physicsBody.type = CANNON.Body.KINEMATIC;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.distanceToTravel = GLMAT.vec3.dist(startPosition, endPosition);
// Calculate velocity to move at
const velocity = GLMAT.vec3.create();
GLMAT.vec3.sub(velocity, endPosition, startPosition);
GLMAT.vec3.normalize(velocity, velocity);
GLMAT.vec3.scale(velocity, velocity, speed);
// Set constant velocity for kinematic body, moves the cloud constantly
this.physicsBody.velocity = new CANNON.Vec3(
velocity[0], velocity[1], velocity[2]);
}
/**
* Update the cloud to make it reset its position
*/
update() {
// If the cloud reaches its endPosition, reset it to its startPosition
// Because the cloud moves linearly from startPosition to endPosition
// with no other directions taken, checking for distance to
// startPosition is sufficient
if (GLMAT.vec3.dist(this.position, this.startPosition)
> this.distanceToTravel) {
this.physicsBody.position = new CANNON.Vec3(this.startPosition[0],
this.startPosition[1], this.startPosition[2]);
}
super.update();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.