language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class LoginModal extends React.Component {
constructor(props, context) {
super(props, context);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
show: false
};
}
handleClose() {
this.setState({ show: false });
}
handleShow() {
this.setState({ show: true });
}
render() {
return (
<div>
<Button id="login-btn" onClick={this.handleShow} className="modal-btn">
Login
</Button>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<Modal.Title>
<div className="text-center">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="text-danger">Login</h1></div>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
Please fill every field
</p>
<UserLogin
checkNamePassword = {this.props.checkNamePassword}
handleClose = {this.handleClose}
/>
</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
</div>
);
}
} |
JavaScript | class LinkedList {
/**
* Constructor
*/
constructor() {
this.head = null
this.tail = null
}
/**
*
* Method that inserts a new node at the start of the list (head)
*
*
* @param data
* @returns {Node}
*/
push(data) {
const newNode = new Node(data)
/* Make next of newNode as head and prev as null */
newNode.next = this.head
newNode.prev = null
/* change prev of head newNode */
if (this.head !== null) {
this.head.prev = newNode
}
/* Move the head to point to newNode */
this.head = newNode
if (newNode.next === null) {
this.tail = newNode
}
return newNode
}
/**
*
* Method that inserts a new node as a new Node after {prevNode}
*
* @param {Node} prevNode
* @param data
* @returns {Node}
*/
insertAfter(prevNode, data) {
this._validateNode(prevNode)
const newNode = new Node(data)
/* Make next of newNode as next of prevNode */
newNode.next = prevNode.next
/* Make next of prevNode to be newNode */
prevNode.next = newNode
/* Make prev of nextNode as prevNode */
newNode.prev = prevNode
/* Change previous of newNode's next node */
if (newNode.next === null) {
this.tail = newNode
} else {
newNode.next.prev = newNode
}
return newNode
}
/**
*
* Method that appends a new node at the end of the list (tail)
*
* @param data
* @returns {Node}
*/
append(data) {
const newNode = new Node(data)
/* this newNode will be the last(tail) so it's next is null */
newNode.next = null
/* if the list is empty then make newNode as head and tail*/
if (this.head === null) {
newNode.prev = null
this.head = newNode
this.tail = newNode
return newNode
}
this.tail.next = newNode
newNode.prev = this.tail
this.tail = newNode
return newNode
}
/**
*
* Validates node to be a correct instance of class Node
*
* @param node
* @private
*/
_validateNode(node) {
if (node == null) {
throw new Error('previous node cannot be null')
}
if (!(node instanceof Node)) {
throw new Error('previous node must be an instance of Node class')
}
}
print() {
let currentNode = this.head
while (currentNode !== null) {
console.log(currentNode.data + '\n')
currentNode = currentNode.next
}
}
} |
JavaScript | class TwigVisual {
constructor(options) {
this.container = null;
this.loading = false;
this.parentElement = null;
this.dataKey = 'source';
this.data = {};
this.actions = [];
this.timer = null;
this.components = [];
this.options = Object.assign({
templateName: '',
templates: [],
pageFields: [],
uiOptions: {},
locale: 'en'
}, options);
this.translations = window.twv_translations || {};
this.state = 'inactive';
this.listenerOnMouseOver = this.onMouseOver.bind(this);
this.listenerOnMouseOut = this.onMouseOut.bind(this);
this.listenerOnMouseWheel = this.onMouseWheel.bind(this);
this.listenerOnMouseClick = this.onSelectedElementClick.bind(this);
this.currentElements = [];
this.selectedElement = null;
TwigVisual.onReady(this.init.bind(this));
}
static onLoad(cb) {
if (document.readyState === 'complete') {
cb();
} else {
window.addEventListener('load', cb);
}
};
static onReady(cb) {
if (document.readyState !== 'loading') {
cb();
} else {
document.addEventListener('DOMContentLoaded', cb);
}
};
init() {
this.container = this.createContainer();
// Start button
const buttonStart = this.container.querySelector('.twv-button-start-select');
buttonStart.addEventListener('click', (e) => {
e.preventDefault();
e.target.setAttribute('disabled', 'disabled');
this.removeSelectionInner();
this.selectModeToggle(document.body, 'source');
});
// Add new theme
const buttonAddTheme = this.container.querySelector('.twv-button-new-theme');
buttonAddTheme.addEventListener('click', (e) => {
e.preventDefault();
if (this.state === 'active') {
this.selectModeToggle();
}
this.selectionModeDestroy(true);
this.addNewThemeInit();
});
this.container.querySelector('.twv-button-new-template').addEventListener('click', (e) => {
e.preventDefault();
if (this.state === 'active') {
this.selectModeToggle();
}
this.selectionModeDestroy(true);
this.addNewTemplateInit();
});
document.body.addEventListener('keyup', (e) => {
if (e.code === 'Escape') {
if (this.state === 'active') {
this.selectModeToggle();
}
this.selectionModeDestroy();
}
if (e.code === 'Enter') {
if (this.state === 'active') {
const selectedEl = document.querySelector('.twv-selected');
this.selectModeApply(selectedEl);
}
}
});
// Panel position recovery
const panelClassName = this.getCookie('twv-panel-class-name');
if (panelClassName) {
this.container.className = panelClassName;
this.container.classList.add('twig-visual-container');
}
}
trans(str, data = {}) {
let output;
if (!this.translations[this.options.locale]) {
output = str;
} else {
output = this.translations[this.options.locale][str] || str;
}
Object.keys(data).forEach((key) => {
output = output.replace(`{${key}}`, data[key]);
});
return output;
}
selectModeToggle(parentEl, dataKey = 'source', hidePanel = true) {
parentEl = parentEl || this.parentElement;
if (this.state === 'inactive') {
this.parentElement = parentEl;
this.dataKey = dataKey;
if (hidePanel) {
this.container.style.display = 'none';
}
parentEl.addEventListener('mouseover', this.listenerOnMouseOver);
parentEl.addEventListener('mouseout', this.listenerOnMouseOut);
parentEl.addEventListener('wheel', this.listenerOnMouseWheel, {passive: false});
parentEl.addEventListener('click', this.listenerOnMouseClick);
this.state = 'active';
} else {
this.container.style.display = 'block';
parentEl.removeEventListener('mouseover', this.listenerOnMouseOver);
parentEl.removeEventListener('mouseout', this.listenerOnMouseOut);
parentEl.removeEventListener('wheel', this.listenerOnMouseWheel);
parentEl.removeEventListener('click', this.listenerOnMouseClick);
// Remove attribute disabled
if (this.container.querySelector('.twv-ui-components')) {
const buttons = this.container.querySelector('.twv-ui-components').querySelectorAll('button');
Array.from(buttons).forEach((buttonEl) => {
buttonEl.removeAttribute('disabled');
});
}
const buttonStart = this.container.querySelector('.twv-button-start-select');
buttonStart.removeAttribute('disabled');
this.state = 'inactive';
this.onAfterSelect();
}
}
onAfterSelect() {
switch (this.dataKey) {
case 'moveTarget':
const innerContainerEl = this.container.querySelector('.twv-inner');
const buttonStart = this.container.querySelector('.twv-button-start-select');
this.makeButtonSelected(buttonStart, true, () => {
this.selectionModeDestroy(true);
return true;
});
this.removeOverlay();
innerContainerEl.innerHTML = '';
const div = document.createElement('div');
div.className = 'twv-pt-1 twv-mb-3';
div.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block">
<input type="radio" name="insertMode" value="inside" checked="checked">
${this.trans('Insert')}
</label>
<label class="twv-display-block">
<input type="radio" name="insertMode" value="before">
${this.trans('Insert before')}
</label>
<label class="twv-display-block">
<input type="radio" name="insertMode" value="after">
${this.trans('Insert after')}
</label>
</div>
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Apply')}
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
`;
innerContainerEl.appendChild(div);
const buttonSubmit = innerContainerEl.querySelector('.twv-button-submit');
const buttonCancel = innerContainerEl.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
const insertMode = innerContainerEl.querySelector('input[name="insertMode"]:checked').value;
this.showLoading(true);
this.request('/twigvisual/move_element', {
templateName: this.options.templateName,
xpath: this.data.source.xpath,
xpathTarget: this.data.moveTarget.xpath,
insertMode
}, (res) => {
if (res.success) {
this.windowReload();
} else {
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
this.showLoading(false);
}, 'POST');
});
// Submit data
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
innerContainerEl.innerHTML = '';
this.selectionModeDestroy(true);
});
break;
}
}
onMouseOver(e) {
const xpath = this.getXPathForElement(e.target, true);
if (!xpath || this.getXPathForElement(e.target, true).indexOf('twig-visual-container') > -1) {
return;
}
this.currentElements = [];
this.updateXPathInfo(e.target);
e.target.classList.add('twv-selected');
this.displayPadding(e.target);
}
onMouseOut(e) {
const xpath = this.getXPathForElement(e.target, true);
if (!xpath || this.getXPathForElement(e.target, true).indexOf('twig-visual-container') > -1) {
return;
}
this.currentElements = [];
const elements = Array.from(document.querySelectorAll('.twv-selected'));
elements.forEach((element) => {
element.classList.remove('twv-selected');
element.style.boxShadow = '';
});
}
onSelectedElementClick(e) {
const xpath = this.getXPathForElement(e.target, true);
if (!xpath || this.getXPathForElement(e.target, true).indexOf('twig-visual-container') > -1) {
return;
}
e.preventDefault();
e.stopPropagation();
this.selectModeApply(e.target);
}
selectModeApply(element = null) {
let currentElement = this.currentElements.length > 0
? this.currentElements[this.currentElements.length - 1]
: element;
if (!currentElement) {
return;
}
this.removeOverlay();
const currentElementXpath = this.getXPathForElement(currentElement);
this.data[this.dataKey] = {
xpath: currentElementXpath,
className: currentElement.className
};
// Clear selection
if (this.data[this.dataKey]) {
const xpath = this.data[this.dataKey].xpath;
this.removeSelectionInnerByXPath(xpath);
}
if (this.state === 'active') {
this.selectModeToggle();
}
this.selectionModeDestroy();
if (this.dataKey === 'source') {
this.parentElement = currentElement;
this.createSelectionOptions(currentElementXpath);
} else {
this.highlightElement();
currentElement.classList.add('twv-selected-success');
const index = this.components.findIndex((item) => {
return item.name === this.dataKey;
});
if (index > -1) {
if (currentElement.getAttribute('title') && !currentElement.dataset.twvTitle) {
currentElement.dataset.twvTitle = currentElement.getAttribute('title');
}
currentElement.setAttribute('title', this.components[index].title);
}
this.componentButtonMakeSelected(this.dataKey);
}
}
/**
* Destroy selection mode
* @param {boolean} reset
* @param {boolean} resetData
*/
selectionModeDestroy(reset = false, resetData = true) {
if (document.querySelector('.twv-info')) {
this.removeEl(document.querySelector('.twv-info'));
}
const elements = Array.from(document.querySelectorAll('.twv-selected'));
elements.forEach((element) => {
element.classList.remove('twv-selected');
element.style.boxShadow = '';
});
if (reset) {
if (resetData) {
this.data = {};
}
this.currentElements = [];
this.components = [];
const buttonStart = this.container.querySelector('.twv-button-start-select');
// Remove options
buttonStart.parentNode.classList.remove('twv-block-active-status-active');
this.container.querySelector('.twv-inner').innerHTML = '';
this.removeOverlay();
// Remove selection of parent element
const elementSelected = document.querySelector('.twv-selected-element');
if (elementSelected) {
elementSelected.contentEditable = false;
if (elementSelected.dataset.twvContent) {
elementSelected.innerHTML = elementSelected.dataset.twvContent;
elementSelected.dataset.twvContent = '';
}
elementSelected.classList.remove('twv-selected-element');
elementSelected.style.transform = '';
elementSelected.style.transition = '';
this.setToParents(elementSelected, {transform: '', transition: ''});
}
this.removeSelectionInner();
}
}
onMouseWheel(e) {
if (this.getXPathForElement(e.target).indexOf('twig-visual-container') > -1) {
return;
}
e.preventDefault();
let currentElement = this.currentElements.length > 0
? this.currentElements[this.currentElements.length - 1]
: e.target;
if (e.deltaY < 0) {
currentElement.classList.remove('twv-selected');
currentElement.style.boxShadow = '';
this.currentElements.push(currentElement.parentNode);
this.updateXPathInfo(currentElement.parentNode);
currentElement.parentNode.classList.add('twv-selected');
this.displayPadding(currentElement.parentNode);
} else {
currentElement.classList.remove('twv-selected');
currentElement.style.boxShadow = '';
this.currentElements.splice(this.currentElements.length - 1, 1);
currentElement = this.currentElements.length > 0
? this.currentElements[this.currentElements.length - 1]
: e.target;
this.updateXPathInfo(currentElement);
currentElement.classList.add('twv-selected');
this.displayPadding(currentElement);
}
}
/**
* Remove selection of inner elements
*/
removeSelectionInner() {
const selectedElements = Array.from(document.querySelectorAll('.twv-selected-success'));
selectedElements.forEach((element) => {
if (element.dataset.twvTitle) {
element.setAttribute('title', element.dataset.twvTitle);
} else {
element.removeAttribute('title');
}
element.classList.remove('twv-selected-success');
});
}
/**
* Remove selection by XPath
* @param xpath
*/
removeSelectionInnerByXPath(xpath) {
this.removeOverlay();
const element = this.getElementByXPath(xpath);
if (!element) {
return false;
}
this.highlightElement();
if (element.dataset.twvTitle) {
element.setAttribute('title', element.dataset.twvTitle);
} else {
element.removeAttribute('title');
}
element.classList.remove('twv-selected-success');
return true;
}
/**
* Add overlay for element
* @param element
* @param targetClassName
*/
highlightElement(element = null, targetClassName = 'twv-selected-element') {
if (!element) {
element = this.parentElement;
}
if (!element || element.tagName === 'BODY' || document.querySelector('.twv-back-overlay')) {
return;
}
element.classList.add(targetClassName);
const compStyles = window.getComputedStyle(element);
const position = compStyles.getPropertyValue('position');
const backgroundColor = compStyles.getPropertyValue('background-color');
if (position === 'static') {
element.style.position = 'relative';
}
if (['rgba(0, 0, 0, 0)', 'transparent'].indexOf(backgroundColor) > -1) {
// element.style.backgroundColor = '#fff';
}
element.style.transform = 'none';
element.style.transition = 'none';
this.setToParents(element, {transform: 'none', transition: 'none'});
const backgroundOverlay = document.createElement(element.tagName === 'LI' ? 'li' : 'div');
backgroundOverlay.className = 'twv-back-overlay';
this.insertBefore(backgroundOverlay, element);
}
/**
* Remove overlay
*/
removeOverlay() {
if (document.querySelector('.twv-back-overlay')) {
this.removeEl(document.querySelector('.twv-back-overlay'));
}
}
updateXPathInfo(element) {
const xpath = this.getXPathForElement(element, true);
if (xpath.indexOf('twig-visual-container') > -1) {
return;
}
let div = document.querySelector('.twv-info');
if (!div) {
div = document.createElement('div');
div.className = 'twv-info small';
document.body.appendChild(div);
}
div.style.display = 'block';
div.innerHTML = `<div>${xpath}</div>`;
}
getXPathForElement(element, getAttributes = false) {
if (element.id !== '')
return 'id("' + element.id + '")';
if (element.tagName === 'HTML')
return ('/HTML[1]').toLowerCase();
if (element === document.body)
return ('/HTML[1]/BODY[1]').toLowerCase();
if (!element.parentNode)
return '';
let ix = 0;
const siblings = element.parentNode.childNodes;
for (let i = 0; i < siblings.length; i++) {
const sibling = siblings[i];
if (sibling === element) {
return this.getXPathForElement(element.parentNode, getAttributes) + '/'
+ element.tagName.toLowerCase() + '[' + (ix + 1) + ']'
+ (getAttributes ? this.getXpathElementAttributes(element) : '');
}
if (sibling.nodeType === Node.ELEMENT_NODE && sibling.tagName === element.tagName)
ix++;
}
}
getXpathElementAttributes(element) {
if (element.hasAttribute('id')) {
return `id("${element.id}")`;
} else if(element.hasAttribute('class') && element.getAttribute('class')) {
return `[@class="${element.getAttribute('class')}"]`;
}
return '';
}
getElementByXPath(xpath, parentEl = window.document) {
const result = document.evaluate(xpath, parentEl, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
createContainer() {
const containerEl = document.createElement('div');
containerEl.id = 'twig-visual-container';
containerEl.className = 'twig-visual-container twv-panel-right';
containerEl.innerHTML = `
<div class="twv-panel-header">
<div class="twv-panel-header-buttons">
<button class="twv-btn twv-btn-sm twv-ml-1 twv-button-undo" type="button" title="${this.trans('Undo the last action')}">
<i class="twv-icon-undo"></i>
</button>
<button class="twv-btn twv-btn-sm twv-ml-1 twv-button-execute-batch" type="button" title="${this.trans('Execute batch of operations')}" style="display: none;">
<i class="twv-icon-format_list_bulleted"></i>
<span></span>
</button>
</div>
<button class="twv-btn twv-btn-sm twv-mr-1 twv-button-panel-left" type="button" title="${this.trans('Move left')}">
<i class="twv-icon-arrow_back"></i>
</button>
<button class="twv-btn twv-btn-sm twv-button-panel-right" type="button" title="${this.trans('Move right')}">
<i class="twv-icon-arrow_forward"></i>
</button>
</div>
<div class="twv-mb-2">
<button type="button" class="twv-btn twv-btn-block twv-button-new-theme">
<i class="twv-icon-add"></i>
${this.trans('Create new theme')}
</button>
</div>
<div class="twv-mb-2">
<button type="button" class="twv-btn twv-btn-block twv-button-new-template">
<i class="twv-icon-add"></i>
${this.trans('Create new template')}
</button>
</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-btn-block twv-button-start-select">
<i class="twv-icon-center_focus_strong"></i>
${this.trans('Interface item')}
</button>
</div>
<div class="twv-inner-wrapper">
<div class="twv-inner"></div>
</div>
`;
document.body.appendChild(containerEl);
containerEl.querySelector('.twv-button-panel-left').addEventListener('click', (e) => {
e.preventDefault();
this.panelMove('left');
});
containerEl.querySelector('.twv-button-panel-right').addEventListener('click', (e) => {
e.preventDefault();
this.panelMove('right');
});
containerEl.querySelector('.twv-button-execute-batch').addEventListener('click', (e) => {
e.preventDefault();
this.executeActionBatch();
});
containerEl.querySelector('.twv-button-undo').addEventListener('click', (e) => {
e.preventDefault();
this.restoreFromTemplateCopyA();
});
return containerEl;
}
panelMove(direction) {
const newClassName = `twv-panel-${direction}`;
if (this.container.classList.contains(newClassName)) {
this.container.classList.add('twv-panel-hidden');
this.setCookie('twv-panel-class-name', this.container.className);
return;
} else if (this.container.classList.contains('twv-panel-hidden')) {
this.container.classList.remove('twv-panel-hidden');
this.setCookie('twv-panel-class-name', this.container.className);
return;
}
this.container.classList.remove('twv-panel-' + (direction === 'left' ? 'right' : 'left'));
this.container.classList.add(newClassName);
this.setCookie('twv-panel-class-name', this.container.className);
}
/**
* Change block type
* @param parentElement
* @param typeValue
*/
onBlockUiTypeChange(parentElement, typeValue) {
const componentsContainer = this.container.querySelector('.twv-ui-components');
componentsContainer.innerHTML = '';
this.removeSelectionInner();
if (!typeValue) {
return;
}
if (!this.options.uiOptions[typeValue]) {
return;
}
// Clean components data
Object.keys(this.data).forEach((key) => {
if (key !== 'source') {
delete this.data[key];
}
});
const opt = this.options.uiOptions[typeValue];
this.components = opt.components;
this.createComponentsControls(componentsContainer);
const div = document.createElement('div');
div.className = 'twv-pt-1 twv-mb-3';
div.innerHTML = `
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Apply')}
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
`;
componentsContainer.appendChild(div);
const buttonSubmit = this.container.querySelector('.twv-button-submit');
const buttonCancel = this.container.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
const data = {
templateName: this.options.templateName,
data: this.data
};
Array.from(componentsContainer.querySelectorAll('input[type="text"]')).forEach((el) => {
data.data[el.name] = el.value;
});
Array.from(componentsContainer.querySelectorAll('input[type="number"]')).forEach((el) => {
data.data[el.name] = el.value;
});
Array.from(componentsContainer.querySelectorAll('select')).forEach((el) => {
data.data[el.name] = el.value;
});
Array.from(componentsContainer.querySelectorAll('input[type="checkbox"]')).forEach((el) => {
data.data[el.name] = el.checked;
});
Array.from(componentsContainer.querySelectorAll('input[type="radio"]:checked')).forEach((el) => {
data.data[el.name] = el.value;
});
if (!this.checkRequired(data.data, this.components)) {
return;
}
const isInsertMode = opt.isInsertMode || false;
const requestUrl = isInsertMode
? `/twigvisual/move_element/${typeValue}`
: `/twigvisual/create_component/${typeValue}`;
buttonSubmit.setAttribute('disabled', 'disabled');
buttonCancel.setAttribute('disabled', 'disabled');
this.showLoading(true);
this.request(requestUrl, data, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
const selectEl = this.container.querySelector('.twv-ui-element-select > select');
const elementSelected = document.querySelector('.twv-selected-element');
if (document.querySelector('.twv-info')) {
this.removeEl(document.querySelector('.twv-info'));
}
if (this.state === 'active') {
this.selectModeToggle();
return;
}
if (selectEl.value) {
selectEl.value = '';
this.selectionModeDestroy();
this.onBlockUiTypeChange(elementSelected);
} else {
this.selectionModeDestroy(true);
}
});
}
/**
* Create controls for the components
* @param {HTMLElement} componentsContainer
*/
createComponentsControls(componentsContainer) {
const div = document.createElement('div');
div.className = 'twv-pt-1 twv-mb-3';
let optionsHTML;
this.components.forEach((cmp) => {
const d = document.createElement('div');
d.className = '';
switch (cmp.type) {
case 'elementSelect':
d.innerHTML = `<div class="twv-mb-2">
<button data-twv-key="${cmp.name}" class="twv-btn twv-btn-block twv-text-overflow">${cmp.title}</button>
</div>
`;
d.querySelector('button').addEventListener('click', (e) => {
e.preventDefault();
if (this.state === 'active') {
return;
}
e.target.setAttribute('disabled', 'disabled');
this.selectModeToggle(this.parentElement, cmp.name, false);
});
div.appendChild(d);
break;
case 'text':
case 'number':
let value = cmp.value || '';
if (cmp.styleName) {
const compStyles = window.getComputedStyle(this.parentElement);
if (compStyles[cmp.styleName]) {
value = value ? value + ' ' + compStyles[cmp.styleName] : compStyles[cmp.styleName];
}
}
d.innerHTML = `
<div class="twv-mb-2">
<label class="twv-display-block twv-mb-1" for="tww-field-option-${cmp.name}">${cmp.title}</label>
<input type="${cmp.type}" id="tww-field-option-${cmp.name}" class="twv-form-control" name="${cmp.name}" value="${value}">
</div>
`;
div.appendChild(d);
break;
case 'checkbox':
d.innerHTML = `
<div class="twv-mb-2">
<input type="checkbox" id="tww-field-option-${cmp.name}" name="${cmp.name}" value="1">
<label class="twv-display-inline twv-small twv-ml-1" for="tww-field-option-${cmp.name}">${cmp.title}</label>
</div>
`;
div.appendChild(d);
break;
case 'radio':
let html = '';
if (cmp.title) {
html += `<div class="twv-mb-2">${cmp.title}</div>`;
}
if (cmp.options) {
cmp.options.forEach((option, index) => {
html += `
<label class="twv-display-block">
<input type="radio" name="${cmp.name}" value="${option.value}">
${this.trans(option.title)}
</label>
`;
});
}
d.innerHTML = html;
d.className = 'twv-mb-3';
div.appendChild(d);
d.querySelector('input').checked = true;
break;
case 'pageField':
optionsHTML = '';
this.options.pageFields.forEach((pageField) => {
optionsHTML += `<option value="${pageField.name}" data-type="${pageField.type}">${pageField.name} - ${pageField.type}</option>`;
});
d.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-option-${cmp.name}">${cmp.title}</label>
<select id="tww-field-option-${cmp.type}" class="twv-custom-select" name="fieldName">
${optionsHTML}
</select>
</div>
`;
div.appendChild(d);
const onFieldSelectChange = (value, type) => {
const keyFieldEl = componentsContainer.querySelector('input[name="key"]');
if (keyFieldEl) {
const textFieldBlockEl = keyFieldEl.parentNode;
textFieldBlockEl.style.display = ['object', 'array'].indexOf(type) > -1 ? 'block' : 'none';
if (['object', 'array'].indexOf(type) === -1) {
keyFieldEl.value = '';
}
}
};
d.querySelector('select').addEventListener('change', (e) => {
const selectEl = e.target;
const selectedOption = selectEl.options[selectEl.selectedIndex];
onFieldSelectChange(selectEl.value, selectedOption.dataset.type);
});
setTimeout(() => {
onFieldSelectChange(d.querySelector('select').value, d.querySelector('select').querySelector('option').dataset.type);
}, 1);
break;
case 'include':
optionsHTML = '';
this.showLoading(true);
this.request(`/twigvisual/includes`, {}, (res) => {
if (res.templates) {
res.templates.forEach((templateName) => {
optionsHTML += `<option value="${templateName}">${templateName}</option>`;
});
d.querySelector('select').innerHTML = optionsHTML;
}
this.showLoading(false);
}, (err) => {
this.addAlertMessage(err.error || err);
this.showLoading(false);
});
d.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-option-${cmp.name}">${cmp.title}</label>
<select id="tww-field-option-${cmp.type}" class="twv-custom-select" name="${cmp.name}">
${optionsHTML}
</select>
</div>
`;
div.appendChild(d);
break;
}
});
componentsContainer.appendChild(div);
}
checkRequired(data, components) {
let result = true;
for (var cmp of components) {
if (cmp.required && !data[cmp.name]) {
result = false;
alert(this.trans('The "{title}" field is required.', {title: cmp.title}));
break;
}
}
return result;
}
componentButtonMakeSelected(dataKey) {
const componentsContainer = this.container.querySelector('.twv-ui-components');
if (!componentsContainer) {
return;
}
let buttons = Array.from(componentsContainer.querySelectorAll('button'));
buttons = buttons.filter((buttonEl) => {
return buttonEl.dataset.twvKey === dataKey;
});
if (buttons.length === 1) {
this.makeButtonSelected(buttons[0], true, () => {
const xpath = this.data[dataKey] ? this.data[dataKey].xpath : null;
if (this.removeSelectionInnerByXPath(xpath)) {
delete this.data[dataKey];
return true;
}
return false;
});
}
}
/**
* Mark button as selected
* @param buttonEl
* @param selected
* @param cancelFunc
*/
makeButtonSelected(buttonEl, selected = true, cancelFunc = null) {
buttonEl.removeAttribute('disabled');
if (buttonEl.parentNode.classList.contains('twv-block-active-status')) {
if (selected) {
buttonEl.parentNode.classList.add('twv-block-active-status-active');
} else {
buttonEl.parentNode.classList.remove('twv-block-active-status-active');
}
return;
}
const title = buttonEl.textContent.trim();
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-block-active-status twv-block-active-status-active">
<div class="twv-block-active-status-active-content">
<div class="twv-input-group">
<span class="twv-input-group-text twv-flex-fill" title="${title}">
<i class="twv-icon-done twv-mr-2 twv-text-success"></i>
${this.trans('Selected')}
</span>
<div class="twv-input-group-append">
<button class="twv-btn twv-block-active-status-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
</div>
</div>
</div>
`;
buttonEl.classList.add('twv-block-active-status-inactive-content');
this.insertAfter(div, buttonEl);
div.querySelector('.twv-block-active-status').appendChild(buttonEl);
buttonEl.parentNode.querySelector('.twv-block-active-status-button-cancel').addEventListener('click', (e) => {
e.preventDefault();
if (typeof cancelFunc === 'function') {
cancelFunc() && this.makeButtonSelected(buttonEl, false);
} else {
this.makeButtonSelected(buttonEl, false);
}
});
}
createSelectionOptions(xpath) {
const elementSelected = this.getElementByXPath(xpath);
if (!elementSelected) {
throw new Error('Element for XPath not found.');
}
const buttonStart = this.container.querySelector('.twv-button-start-select');
this.makeButtonSelected(buttonStart, true, () => {
this.selectionModeDestroy(true);
return true;
});
this.container.querySelector('.twv-inner').innerHTML = '';
let optionsHTML = '';
Object.keys(this.options.uiOptions).forEach((key) => {
optionsHTML += `<option value="${key}">${this.options.uiOptions[key].title}</option>`;
});
const xpathEscaped = xpath.replace(/[\"]/g, '"');
const div = document.createElement('div');
div.innerHTML = `
<b>XPath:</b>
<div class="twv-p-1 twv-mb-3 twv-small twv-bg-gray">
<div class="twv-text-overflow" title="${xpathEscaped}">${xpath}</div>
</div>
<div class="twv-mb-3 twv-nowrap">
<button type="button" class="twv-btn twv-mr-1 twv-button-edit-text" title="${this.trans('Edit text content')}">
<i class="twv-icon-createmode_editedit"></i>
</button>
<button type="button" class="twv-btn twv-mr-1 twv-button-edit-link" title="${this.trans('Edit link')}">
<i class="twv-icon-linkinsert_link"></i>
</button>
<button type="button" class="twv-btn twv-mr-1 twv-button-replace-image" title="${this.trans('Replace image')}">
<i class="twv-icon-insert_photoimagephoto"></i>
</button>
<button type="button" class="twv-btn twv-mr-1 twv-button-delete-element" title="${this.trans('Delete element')}">
<i class="twv-icon-delete_outline"></i>
</button>
<button type="button" class="twv-btn twv-mr-1 twv-button-move-element" title="${this.trans('Move element')}">
<i class="twv-icon-move"></i>
</button>
<button type="button" class="twv-btn twv-mr-1 twv-button-restore-static" title="${this.trans('Restore static')}">
<i class="twv-icon-cached"></i>
</button>
</div>
<div class="twv-mb-3 twv-ui-element-select">
<select class="twv-custom-select">
<option value="">- ${this.trans('Interface item type')} -</option>
${optionsHTML}
</select>
</div>
<div class="twv-mb-3 twv-ui-components"></div>
`;
this.container.querySelector('.twv-inner').appendChild(div);
const selectEl = this.container.querySelector('.twv-ui-element-select > select');
// Select UI element type
selectEl.addEventListener('change', (e) => {
this.onBlockUiTypeChange(elementSelected, e.target.value);
});
// Button edit text
this.container.querySelector('.twv-button-edit-text').addEventListener('click', (e) => {
e.preventDefault();
this.editTextContentInit(elementSelected);
});
// Button edit link
this.container.querySelector('.twv-button-edit-link').addEventListener('click', (e) => {
e.preventDefault();
this.editLinkInit(elementSelected);
});
// Replace image
this.container.querySelector('.twv-button-replace-image').addEventListener('click', (e) => {
e.preventDefault();
this.replaceImageInit(elementSelected);
});
// Button delete element
this.container.querySelector('.twv-button-delete-element').addEventListener('click', (e) => {
e.preventDefault();
this.deleteElementInit(elementSelected);
});
this.container.querySelector('.twv-button-move-element').addEventListener('click', (e) => {
e.preventDefault();
e.target.setAttribute('disabled', 'disabled');
this.moveElementInit();
});
this.container.querySelector('.twv-button-restore-static').addEventListener('click', (e) => {
e.preventDefault();
this.restoreStaticInit();
});
this.highlightElement(elementSelected, 'twv-selected-element');
}
/**
* Edit text content
* @param {HTMLElement} elementSelected
*/
editTextContentInit(elementSelected) {
this.clearMessage();
const componentsContainer = this.container.querySelector('.twv-ui-components');
const innerHTML = elementSelected.innerHTML;
componentsContainer.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Save')}
</button>
<button type="button" class="twv-btn twv-btn twv-mr-1 twv-button-add-list" title="${this.trans('Add to operations list')}">
<i class="twv-icon-format_list_bulleted"></i>
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
`;
componentsContainer.appendChild(div);
elementSelected.dataset.twvContent = innerHTML;
elementSelected.contentEditable = true;
elementSelected.focus();
const buttonSubmit = this.container.querySelector('.twv-button-submit');
const buttonCancel = this.container.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
elementSelected.contentEditable = false;
buttonSubmit.setAttribute('disabled', 'disabled');
buttonCancel.setAttribute('disabled', 'disabled');
this.showLoading(true);
this.request('/twigvisual/edit_content', {
templateName: this.options.templateName,
xpath: this.data.source.xpath,
textContent: elementSelected.innerHTML
}, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Add to action list
this.container.querySelector('.twv-button-add-list')
.addEventListener('click', (e) => {
e.preventDefault();
this.addToActionBatch('edit_content', this.data.source.xpath, {value: elementSelected.innerHTML});
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
elementSelected.contentEditable = false;
componentsContainer.innerHTML = '';
elementSelected.innerHTML = innerHTML;
});
}
/**
* Edit link
* @param {HTMLElement} elementSelected
*/
editLinkInit(elementSelected) {
if (elementSelected.tagName.toLowerCase() !== 'a') {
alert(this.trans('The selected item must have tag {tagName}.', {tagName: 'A'}));
return;
}
this.clearMessage();
const componentsContainer = this.container.querySelector('.twv-ui-components');
const href = elementSelected.getAttribute('href');
const target = elementSelected.getAttribute('target');
componentsContainer.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-element-link">${this.trans('URL')}</label>
<input type="text" id="tww-field-element-link" class="twv-form-control" value="${href}">
</div>
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-element-link">${this.trans('Open in')}</label>
<select id="tww-field-link-target" class="twv-custom-select">
<option value="_self"${target != '_blank' ? ' selected="selected"' : ''}>${this.trans('the current tab')}</option>
<option value="_blank"${target == '_blank' ? ' selected="selected"' : ''}>${this.trans('a new tab')}</option>
</select>
</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Save')}
</button>
<button type="button" class="twv-btn twv-btn twv-mr-1 twv-button-add-list" title="${this.trans('Add to operations list')}">
<i class="twv-icon-format_list_bulleted"></i>
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
`;
componentsContainer.appendChild(div);
const buttonSubmit = this.container.querySelector('.twv-button-submit');
const buttonCancel = this.container.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
this.showLoading(true);
this.request('/twigvisual/edit_link', {
templateName: this.options.templateName,
xpath: this.data.source.xpath,
href: div.querySelector('input[type="text"]').value,
target: div.querySelector('select').value
}, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Add to action list
this.container.querySelector('.twv-button-add-list')
.addEventListener('click', (e) => {
e.preventDefault();
this.addToActionBatch('edit_link', this.data.source.xpath, {
href: div.querySelector('input[type="text"]').value,
target: div.querySelector('select').value
});
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
elementSelected.contentEditable = false;
componentsContainer.innerHTML = '';
elementSelected.setAttribute('href', href);
});
}
/**
* Replace image
* @param elementSelected
*/
replaceImageInit(elementSelected) {
let currentImageUrl = '';
let attributeName = 'src';
if (elementSelected.tagName.toLowerCase() !== 'img') {
const compStyles = window.getComputedStyle(elementSelected);
if (compStyles['background-image'] === 'none') {
alert(this.trans('The selected item must have tag {tagName} or have a background image.', {tagName: 'IMG'}));
return;
}
const found = compStyles['background-image'].match(/url\(\"([^\"]+)\"\)/);
currentImageUrl = found ? found[1] : '';
attributeName = 'style';
} else {
currentImageUrl = elementSelected.getAttribute('src');
}
this.clearMessage();
const componentsContainer = this.container.querySelector('.twv-ui-components');
componentsContainer.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3 twv-text-center"><img class="twv-image-preview" style="max-width: 80%;"></div>
<input type="file" style="display: none;" name="image_file">
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Save')}
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
`;
componentsContainer.appendChild(div);
const buttonSubmit = this.container.querySelector('.twv-button-submit');
const buttonCancel = this.container.querySelector('.twv-button-cancel');
const fileField = this.container.querySelector('input[type="file"]');
const imagePreviewEl = this.container.querySelector('.twv-image-preview');
imagePreviewEl.setAttribute('src', currentImageUrl);
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('templateName', this.options.templateName);
formData.append('xpath', this.data.source.xpath);
formData.append('imageFile', fileField.files[0]);
formData.append('attributeName', attributeName);
this.showLoading(true);
this.request('/twigvisual/replace_image', formData, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
elementSelected.contentEditable = false;
componentsContainer.innerHTML = '';
});
function readURL(input) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
imagePreviewEl.setAttribute('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
// File field
fileField.addEventListener('change', (e) => {
readURL(e.target);
});
fileField.click();
imagePreviewEl.addEventListener('click', (e) => {
e.preventDefault();
fileField.click();
});
}
/**
* Delete selected element
* @param {HTMLElement} elementSelected
*/
deleteElementInit(elementSelected) {
this.clearMessage();
const componentsContainer = this.container.querySelector('.twv-ui-components');
const textContent = elementSelected.textContent.trim();
componentsContainer.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-2">Вы уверены, что хотите удалить выбранный элемент?</div>
<div class="twv-mb-3">
<input type="checkbox" id="tww-field-clean" name="clean" value="1">
<label class="twv-display-inline twv-small twv-ml-1" for="tww-field-clean">${this.trans('Clean content')}</label>
</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Confirm')}
</button>
<button type="button" class="twv-btn twv-btn twv-mr-1 twv-button-add-list" title="${this.trans('Add to operations list')}">
<i class="twv-icon-format_list_bulleted"></i>
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
`;
componentsContainer.appendChild(div);
const buttonSubmit = this.container.querySelector('.twv-button-submit');
const buttonCancel = this.container.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
this.showLoading(true);
this.request('/twigvisual/delete_element', {
templateName: this.options.templateName,
xpath: this.data.source.xpath,
clean: this.container.querySelector('input[name="clean"]').checked
}, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
componentsContainer.innerHTML = '';
});
// Add to action list
this.container.querySelector('.twv-button-add-list')
.addEventListener('click', (e) => {
e.preventDefault();
this.addToActionBatch('delete', this.data.source.xpath);
});
}
moveElementInit() {
const componentsContainer = this.container.querySelector('.twv-ui-components');
componentsContainer.innerHTML = '';
this.selectionModeDestroy(true, false);
setTimeout(() => {
this.selectModeToggle(document.body, 'moveTarget');
}, 1);
}
restoreStaticInit() {
this.clearMessage();
const componentsContainer = this.container.querySelector('.twv-ui-components');
componentsContainer.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3">${this.trans('Are you sure you want to return the item to its original state?')}</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">
<i class="twv-icon-done"></i>
${this.trans('Confirm')}
</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel" title="${this.trans('Cancel')}">
<i class="twv-icon-clearclose"></i>
</button>
</div>
`;
componentsContainer.appendChild(div);
const buttonSubmit = componentsContainer.querySelector('.twv-button-submit');
const buttonCancel = componentsContainer.querySelector('.twv-button-cancel');
// Submit data
buttonSubmit.addEventListener('click', (e) => {
e.preventDefault();
this.showLoading(true);
this.request('/twigvisual/restore_static', {
templateName: this.options.templateName,
xpath: this.data.source.xpath
}, (res) => {
if (res.success) {
this.windowReload();
} else {
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonSubmit.removeAttribute('disabled');
buttonCancel.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
// Cancel
buttonCancel.addEventListener('click', (e) => {
e.preventDefault();
this.clearMessage();
componentsContainer.innerHTML = '';
});
}
addNewThemeInit() {
this.clearMessage();
const innerContainerEl = this.container.querySelector('.twv-inner');
innerContainerEl.innerHTML = '';
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-theme-name">${this.trans('Theme name')}</label>
<input type="text" id="tww-field-theme-name" class="twv-form-control">
</div>
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-theme-mainpage">${this.trans('HTML-file of the main page')}</label>
<input type="text" id="tww-field-theme-mainpage" class="twv-form-control" value="index.html">
</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">${this.trans('Create')}</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel">${this.trans('Cancel')}</button>
</div>
`;
innerContainerEl.appendChild(div);
innerContainerEl.querySelector('button.twv-button-submit').addEventListener('click', (e) => {
e.preventDefault();
const fieldThemeEl = document.getElementById('tww-field-theme-name');
const fieldMainpageEl = document.getElementById('tww-field-theme-mainpage');
const buttonEl = e.target;
if (!fieldThemeEl.value || !fieldMainpageEl.value) {
return;
}
this.clearMessage();
this.showLoading(true);
buttonEl.setAttribute('disabled', 'disabled');
this.request('/twigvisual/create', {
theme: fieldThemeEl.value,
mainpage: fieldMainpageEl.value
}, (res) => {
buttonEl.removeAttribute('disabled');
this.showLoading(false);
if (res && res.success) {
innerContainerEl.innerHTML = '';
}
if (res.message) {
this.addAlertMessage(res.message, 'success');
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonEl.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
innerContainerEl.querySelector('button.twv-button-cancel').addEventListener('click', (e) => {
e.preventDefault();
innerContainerEl.innerHTML = '';
});
}
addNewTemplateInit() {
this.clearMessage();
const innerContainerEl = this.container.querySelector('.twv-inner');
innerContainerEl.innerHTML = '';
let optionsHTML = '';
this.options.templates.forEach((templatePath) => {
optionsHTML += `<option value="${templatePath}">${templatePath}</option>`;
});
this.showLoading(true);
this.request('/twigvisual/html_files', {}, (res) => {
if (res.files) {
let html = '';
res.files.forEach((fileName) => {
html += `<option value="${fileName}">${fileName}</option>`;
});
document.getElementById('tww-field-source-file').innerHTML = html;
}
this.showLoading(false);
}, (err) => {
this.addAlertMessage(err.error || err);
this.showLoading(false);
});
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-source-file">${this.trans('HTML-file')}</label>
<select id="tww-field-source-file" class="twv-custom-select"></select>
</div>
<div class="twv-mb-3">
<label class="twv-display-block twv-mb-1" for="tww-field-template-name">${this.trans('Template name')}</label>
<select id="tww-field-template-name" class="twv-custom-select">
${optionsHTML}
</select>
</div>
<div class="twv-mb-3">
<button type="button" class="twv-btn twv-btn-primary twv-mr-1 twv-button-submit">${this.trans('Create')}</button>
<button type="button" class="twv-btn twv-btn twv-button-cancel">${this.trans('Cancel')}</button>
</div>
`;
innerContainerEl.appendChild(div);
innerContainerEl.querySelector('button.twv-button-submit').addEventListener('click', (e) => {
e.preventDefault();
const fieldFileNameEl = document.getElementById('tww-field-source-file');
const fieldTemplateNameEl = document.getElementById('tww-field-template-name');
const buttonEl = e.target;
if (!fieldFileNameEl.value || !fieldTemplateNameEl.value) {
return;
}
this.showLoading(true);
buttonEl.setAttribute('disabled', 'disabled');
this.request('/twigvisual/create_template', {
fileName: fieldFileNameEl.value,
templateName: fieldTemplateNameEl.value
}, (res) => {
buttonEl.removeAttribute('disabled');
this.showLoading(false);
innerContainerEl.innerHTML = '';
if (res.message) {
this.addAlertMessage(res.message, 'success');
}
}, (err) => {
this.addAlertMessage(err.error || err);
buttonEl.removeAttribute('disabled');
this.showLoading(false);
}, 'POST');
});
innerContainerEl.querySelector('button.twv-button-cancel').addEventListener('click', (e) => {
e.preventDefault();
innerContainerEl.innerHTML = '';
});
}
/**
* Add operation for batch execution
* @param {string} action
* @param {string} xpath
* @param {object} options
*/
addToActionBatch(action, xpath, options = {}) {
this.actions.push({
action,
xpath,
options
});
this.selectionModeDestroy(true);
const buttonEl = this.container.querySelector('.twv-button-execute-batch');
buttonEl.querySelector('span').textContent = `${this.actions.length}`;
buttonEl.style.display = 'inline-block';
this.actions.forEach((action) => {
const element = this.getElementByXPath(action.xpath);
if (element) {
element.classList.add('twv-selected-success');
}
});
}
/**
* Execute actions batch
*/
executeActionBatch() {
if (this.actions.length === 0) {
return;
}
this.showLoading(true);
this.request('/twigvisual/batch', {
templateName: this.options.templateName,
actions: this.actions
}, (res) => {
if (res.success) {
this.windowReload();
}
this.showLoading(false);
}, (err) => {
this.addAlertMessage(err.error || err);
this.showLoading(false);
}, 'POST');
}
restoreFromTemplateCopyA() {
this.showLoading(true);
this.request('/twigvisual/restore_backup', {
templateName: this.options.templateName
}, (res) => {
if (res.success) {
this.windowReload();
}
this.showLoading(false);
}, (err) => {
this.addAlertMessage(err.error || err);
this.showLoading(false);
}, 'POST');
}
showLoading(enabled = true) {
this.loading = enabled;
if (enabled) {
this.container.classList.add('twv-loading');
} else {
this.container.classList.remove('twv-loading');
}
}
/**
* Show message
* @param message
* @param type
*/
addAlertMessage(message, type = 'danger') {
clearTimeout(this.timer);
const innerContainerEl = this.container.querySelector('.twv-inner');
if (innerContainerEl.querySelector('.twv-alert')) {
this.removeEl(innerContainerEl.querySelector('.twv-alert'));
}
const div = document.createElement('div');
div.innerHTML = `
<div class="twv-alert twv-alert-${type}">${message}</div>
`;
innerContainerEl.appendChild(div);
div.addEventListener('mouseenter', () => {
clearTimeout(this.timer);
});
div.addEventListener('mouseleave', () => {
this.timer = setTimeout(this.clearMessage.bind(this), 4000);
});
this.timer = setTimeout(this.clearMessage.bind(this), 4000);
}
clearMessage() {
const innerContainerEl = this.container.querySelector('.twv-inner');
if (innerContainerEl.querySelector('.twv-alert')) {
this.removeEl(innerContainerEl.querySelector('.twv-alert'));
}
}
/**
* Display padding of the HTML element
* @param element
*/
displayPadding(element) {
const compStyles = window.getComputedStyle(element);
let boxShadow = '0 0 0 2px #007bff';
if (compStyles['padding-top'] !== '0px') {
boxShadow += `, inset 0 ${compStyles['padding-top']} 0 0 rgba(50,168,82,0.15)`;
}
if (compStyles['padding-bottom'] !== '0px') {
boxShadow += `, inset 0 -${compStyles['padding-bottom']} 0 0 rgba(50,168,82,0.15)`;
}
if (compStyles['padding-left'] !== '0px') {
boxShadow += `, inset ${compStyles['padding-left']} 0 0 0 rgba(50,168,82,0.15)`;
}
if (compStyles['padding-right'] !== '0px') {
boxShadow += `, inset -${compStyles['padding-right']} 0 0 0 rgba(50,168,82,0.15)`;
}
if (boxShadow) {
element.style.boxShadow = boxShadow;
}
}
/**
* Ajax request
* @param url
* @param data
* @param successFn
* @param failFn
* @param method
*/
request(url, data, successFn, failFn, method = 'GET') {
const request = new XMLHttpRequest();
request.open(method, url, true);
request.onload = function() {
const result = ['{','['].indexOf(request.responseText.substr(0,1)) > -1
? JSON.parse(request.responseText)
: {};
if (request.status >= 200 && request.status < 400) {
if (typeof successFn === 'function') {
successFn(result);
}
} else {
if (typeof failFn === 'function') {
failFn(result);
}
}
};
request.onerror = function() {
if (typeof failFn === 'function') {
failFn(request);
}
};
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if (!(data instanceof FormData)) {
data = JSON.stringify(data);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
}
if (method === 'POST') {
request.send(data);
} else {
request.send();
}
}
windowReload() {
let locationHref = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
window.location.href = locationHref;
}
/**
* Set styles to parents
* @param element
* @param styles
*/
setToParents(element, styles) {
if (!element
|| !element.parentNode
|| element.tagName === 'BODY'
|| element.parentNode.tagName === 'BODY') {
return;
}
Object.keys(styles).forEach((key) => {
element.parentNode.style[key] = styles[key];
});
if (element.tagName !== 'BODY') {
this.setToParents(element.parentNode, styles);
}
}
/**
* Remove HTML element
* @param el
*/
removeEl(el) {
el.parentNode.removeChild(el);
};
/**
* Insert HTML element after other one
* @param newNode
* @param referenceNode
*/
insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
/**
* Insert HTML element before other one
* @param newNode
* @param referenceNode
*/
insertBefore(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode);
}
/**
*
* @param element
* @param nodeType
* @param count
* @returns {Node | null}
*/
getNodePreviousSiblingByType(element, nodeType, count) {
if (element.previousSibling && element.previousSibling.nodeType !== nodeType && count > 0) {
return this.getNodePreviousSiblingByType(element.previousSibling, nodeType, --count);
}
return element.previousSibling;
}
generateRandomString(length = 8) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
setCookie(cname, cvalue, exdays = 7) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = 'expires=' + d.toUTCString();
document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}
getCookie(cname) {
var name = cname + '=';
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
} |
JavaScript | class components {
/**
* There is no constructor.
*/
constructor() {}
/**
* This HTML tag, "check-box", adds functionality and a consistent and convenient API to the HTML provided <code>checkbox</code> tag.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> checked </td><td> pre-selects the element </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the label associated with the checkbox.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> uncheck the box </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets focus on control </td></tr>
* <tr><td> getValue() </td><td> returns <code>true</code> if checked and <code>false</code> if unchecked </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if the user changed its state </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if the control is disabled </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if the control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if the control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if the control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code> whenever the state of this control changes. <code>fun</code> is passed the value of the control. </td></tr>
* <tr><td> processChanges(flg) </td><td> if <code>false</code>, checkbox should not register changes (no data was changed) See Utils.someControlValueChanged() </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> if <code>val</code> is <code>true</code> check the box, uncheck if <code>false</code> </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static check_box() {}
/**
* This HTML tag, "date-input", adds functionality and a consistent and convenient API for user date input.
* This control is custom and doesn't use the native browser date input offering the advantage of a significantly smaller width requirements. Also see native-date-input tag.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> max="20181231" </td><td> the maximum date allowed </td></tr>
* <tr><td> min="20180101" </td><td> the minimum date allowed </td></tr>
* <tr><td> required </td><td> an entry is required </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the placeholder or what is shown as a prompt inside the control when there is no value.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> clear the control value </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getDateValue() </td><td> returns the date as a <code>Date</code> instance </td></tr>
* <tr><td> getIntValue() </td><td> returns the date as an integer with the "YYYYMMDD" format </td></tr>
* <tr><td> getSQLValue() </td><td> returns the date as a string with the "YYYY-MM-DD" format </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if the user changed the value </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if the control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if the control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if the control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if the control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code>whenever the state of this control changes. </td></tr>
* <tr><td> onEnter(fun) </td><td> execute fun when enter key hit </td></tr>
* <tr><td> readOnly([flg]) </td><td> set control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> set control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> sets the control value. <code>val</code> may be a <code>Date</code>, <code>number</code> (20180608), or <code>string</code> ("2018-06-08") </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static date_input() {}
/**
* This HTML tag, "drop-down", adds functionality and a consistent and convenient API to the HTML provided <code>select</code> tag.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> default-option="label" </td><td> what is shown before the user makes a selection. This would often be something like "(choose)" </td></tr>
* <tr><td> required </td><td> a selection is required </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the HTML that would normally be inside an HTML <code>select</code> element. This would only be used
* in cases of a static list. List contents that depended on data would use the <code>add</code> method.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> add(val, lbl, data) </td><td> add a new list item. <code>val</code> is the value associated to the option, <code>lbl</code> is the text shown in the list, and <code>data</data> represents optional and arbitrary data associated to the option </td></tr>
* <tr><td> addItems(items, valField, lblField [, dataField]) </td><td> used to add an array of items at one time. <code>items</code> is the array of items to add. <code>valField</code> and <code>lblField</code> are the names of the fields in the array. <code>dataField</code> is the name of a field whose data is stored along with the item. If null, the whole item is stored. </td></tr>
* <tr><td> clear() </td><td> remove the list contents except the <code>default-option</code> </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets focus on the control </td></tr>
* <tr><td> getAllLabels() </td><td> returns an array of all the labels </td></tr>
* <tr><td> getData(idx) </td><td> returns the data associated to an option. If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getIntValue(idx) </td><td> returns the integer value associated to an option (returns an array if <code>multiple</code> attribute included). If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getLabel(idx) </td><td> returns the label associated to an option. If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getValue(idx) </td><td> returns the string value associated to an option (returns an array if <code>multiple</code> attribute included). If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty([flg]) </td><td> <code>true</code> if user changed value (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if control is disabled </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if control is hidden (not visible) </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code>whenever the state of this control changes. <code>fun</code> is called as follows <code>fun(val, lbl, data)</code> </td></tr>
* <tr><td> readOnly([flg]) </td><td> make control read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> make control read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> removeByIndex(idx) </td><td> remove the row indicated by <code>idx</code> </td></tr>
* <tr><td> selectedIndex() </td><td> returns the index of the selected item (-1 if none) </td></tr>
* <tr><td> selectIndex(row) </td><td> selects the indicated row index </td></tr>
* <tr><td> setLabel(lbl, idx) </td><td> sets a row label to <code>lbl</code>. If <code>idx</code> is undefined, the selected row is affected otherwise the row indexed by <code>idx</code> is updated. </td></tr>
* <tr><td> setValue(val, idx) </td><td> sets a row value to <code>val</code>. If <code>idx</code> is undefined, the selected row is affected otherwise the row indexed by <code>idx</code> is updated. </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> size() </td><td> returns the number of rows in the list (including <code>default-option</code> </td></tr>
* </table>
*/
static drop_down() {}
/**
* This HTML tag, "file-upload", adds functionality and a consistent and convenient API to the HTML provided file input.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> multiple </td><td> the user may select multiple files </td></tr>
* <tr><td> required </td><td> an entry is required (at least 1 file) </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> of this control is unused.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> erases the contents of the control </td></tr>
* <tr><td> click() </td><td> simulate a user click on the control </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getFormData() </td><td> gets the upload file data for transmission to the back-end </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> has the control contents been changed by user </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isDisabled() </td><td> is the control disabled? </td></tr>
* <tr><td> isHidden() </td><td> is the control hidden? </td></tr>
* <tr><td> isReadOnly() </td><td> is the control read-only? </td></tr>
* <tr><td> isVisible() </td><td> is the control visible? </td></tr>
* <tr><td> numberOfUploadFiles() </td><td> the number of files the user selected is returned </td></tr>
* <tr><td> onChange(fun) </td><td> execute fun when control changes </td></tr>
* <tr><td> readOnly([flg]) </td><td> set control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> set control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> uploadFile(idx) </td><td> the JavaScript <code>File</code> object of file number <code>idx</code> </td></tr>
* <tr><td> uploadFileExtension(idx) </td><td> the file name extension of file number <code>idx</code> </td></tr>
* <tr><td> uploadFilename(idx) </td><td> the name of file number <code>idx</code> </td></tr>
* </table>
*/
static file_upload() {}
/**
* This HTML tag, "list-box", adds functionality and a consistent and convenient API to the HTML provided <code>select</code> tag.
* <br><br>
* Be sure to call the <code>clear()</code> method between uses otherwise the system won't detect the same file
* being accessed.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> default-option="label" </td><td> what is the default selection </td></tr>
* <tr><td> multiple </td><td> multiple entries may be selected (an array will be returned) </td></tr>
* <tr><td> required </td><td> a selection is required </td></tr>
* <tr><td> size="20" </td><td> the <em>minimum</em> number of visible lines (will expand to fill the area it is in) </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the HTML that would normally be inside an HTML <code>select</code> element. This would only be used
* in cases of a static list. List contents that depended on data would use the <code>add</code> method.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> add(val, lbl, data) </td><td> add a new list item. <code>val</code> is the value associated to the option, <code>lbl</code> is the text shown in the list, and <code>data</data> represents optional and arbitrary data associated to the option </td></tr>
* <tr><td> addItems(items, valField, lblField [, dataField]) </td><td> used to add an array of items at one time. <code>items</code> is the array of items to add. <code>valField</code> and <code>lblField</code> are the names of the fields in the array. <code>dataField</code> is the name of a field whose data is stored along with the item. If null, the whole item is stored. </td></tr>
* <tr><td> clear() </td><td> remove the list contents except the <code>default-option</code> </td></tr>
* <tr><td> clearSelection() </td><td> de-select all elements </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets focus on control </td></tr>
* <tr><td> getAllLabels() </td><td> returns an array of all the labels </td></tr>
* <tr><td> getData(idx) </td><td> returns the data associated to an option. If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getIntValue(idx) </td><td> returns the integer value associated to an option (returns an array if <code>multiple</code> attribute included). If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getLabel(idx) </td><td> returns the label associated to an option. If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> getValue(idx) </td><td> returns the string value associated to an option (returns an array if <code>multiple</code> attribute included). If <code>idx</code> is undefined, the selected row is used otherwise the row indexed by <code>idx</code> is used. </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if user has changed control value </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code>whenever the state of this control changes. <code>fun</code> is called as follows <code>fun(val, lbl, data)</code> </td></tr>
* <tr><td> onClick(fun) </td><td> execute <code>fun</code>whenever the user clicks on an item. <code>fun</code> is called as follows <code>fun(val, lbl, data)</code> </td></tr>
* <tr><td> onDblClick(fun) </td><td> execute <code>fun</code>whenever the user double-clicks on an item. <code>fun</code> is called as follows <code>fun(val, lbl, data)</code> </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> removeByIndex(idx) </td><td> remove the row indicated by <code>idx</code> </td></tr>
* <tr><td> setLabel(lbl, idx) </td><td> sets a row label to <code>lbl</code>. If <code>idx</code> is undefined, the selected row is affected otherwise the row indexed by <code>idx</code> is updated. </td></tr>
* <tr><td> setValue(val, idx) </td><td> sets a row value to <code>val</code>. If <code>idx</code> is undefined, the selected row is affected otherwise the row indexed by <code>idx</code> is updated. </td></tr>
* <tr><td> selectedIndex() </td><td> returns the index of the selected item (-1 if none) </td></tr>
* <tr><td> selectIndex(row) </td><td> selects the indicated row index </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> size() </td><td> returns the number of rows in the list </td></tr>
* </table>
*/
static list_box() {}
/**
* This HTML tag, "native-date-input", adds functionality and a consistent and convenient API to the HTML provided date input.
* Also see the date-input tag.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> max="20181231" </td><td> the maximum date allowed </td></tr>
* <tr><td> min="20180101" </td><td> the minimum date allowed </td></tr>
* <tr><td> required </td><td> an entry is required </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the placeholder or what is shown as a prompt inside the control when there is no value.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> clear the control value </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getDateValue() </td><td> returns the date as a <code>Date</code> instance </td></tr>
* <tr><td> getIntValue() </td><td> returns the date as an integer with the "YYYYMMDD" format </td></tr>
* <tr><td> getSQLValue() </td><td> returns the date as a string with the "YYYY-MM-DD" format </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if the user changed the value </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if the control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if the control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if the control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if the control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code>whenever the state of this control changes. </td></tr>
* <tr><td> onEnter(fun) </td><td> execute fun when enter key hit </td></tr>
* <tr><td> readOnly([flg]) </td><td> set control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> set control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> sets the control value. <code>val</code> may be a <code>Date</code>, <code>number</code> (20180608), or <code>string</code> ("2018-06-08") </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static native_date_input() {}
/**
* This HTML tag, "numeric-input", adds functionality and a consistent and convenient API to the HTML input text element. For example, it will
* only accept numbers, can verify decimal places, and formats the number when the control is exited by the user.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> decimal-places="2" </td><td> controls the maximum number of digits past the decimal point (default 0) </td></tr>
* <tr><td> dollar-sign </td><td> adds a dollar sign when formatting the number </td></tr>
* <tr><td> min="20" </td><td> sets the minimum acceptable value (default 0) </td></tr>
* <tr><td> max="200" </td><td> sets the maximum acceptable value </td></tr>
* <tr><td> money </td><td> sets <code>min="0" dollar-sign decimal-places="2"</code> </td></tr>
* <tr><td> no-comma </td><td> do not format number with commas </td></tr>
* <tr><td> required </td><td> an entry is required </td></tr>
* <tr><td> show-zero </td><td> show zero values (instead of blank if zero) </td></tr>
* <tr><td> size="20" </td><td> width of control in number of characters (default 20) </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the placeholder or what is shown as a prompt inside the control when there is no value.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> erases the contents of the control </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getValue() </td><td> returns the numeric value of the control </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> did user change control content? </td></tr>
* <tr><td> isDisabled() </td><td> is control disabled? </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> is control hidden? </td></tr>
* <tr><td> isReadOnly() </td><td> is control read-only? </td></tr>
* <tr><td> isVisible() </td><td> is control visible? </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code>whenever the user exits the control </td></tr>
* <tr><td> onEnter(fun) </td><td> execute fun when enter key hit </td></tr>
* <tr><td> onKeyUp(fun) </td><td> execute fun when key up </td></tr>
* <tr><td> readOnly([flg]) </td><td> set control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> set control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> sets the numeric value of the control </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static numeric_input() {}
/**
* This HTML tag, "popup", adds the ability to define a popup window. Within it, the tags "popup-title" and "popup-body"
* should be used to define the respective parts of the popup window.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> height="400px" </td><td> sets the height of the body of the popup window </td></tr>
* <tr><td> width="200px" </td><td> sets the width of the body of the popup window </td></tr>
* </table>
*/
static popup() {}
/**
* This HTML tag, "push-button", adds functionality and a consistent and convenient API to the HTML provided button input.
* <br><br>
* No new attributes are defined.
* <br><br>
* <strong>Content</strong>
* <br><br>
* No element content is defined.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> click() </td><td> simulate a button click </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets focus to control </td></tr>
* <tr><td> getValue() </td><td> returns the label on the push button </td></tr>
* <tr><td> hide([flg]) </td><td> hides the control (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if control is disabled </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if control is visible (not hidden) </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> onclick(fun) </td><td> <code>fun</code> is executed when the user clicks on the button </td></tr>
* <tr><td> setValue(val) </td><td> sets the label on the push button </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static push_button() {}
/**
* This HTML tag, "radio-button", adds functionality and a consistent and convenient API to the HTML provided radio input element.
* <br><br>
* One thing that makes this control different from the others is that it can be referred to with the <code>$$</code> function
* by its group name or the individual radio button id. When the group name is used, the entire group is effected. When an
* individual radio button is addressed by its id, only that control is effected.
* <br><br>
* All the radio buttons in the same group should share the
* same group name.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> align-horizontal </td><td> align the buttons horizontally (default) </td></tr>
* <tr><td> align-vertical </td><td> align the buttons vertically </td></tr>
* <tr><td> button-style="style" </td><td> style used for the button portion of the radio button </td></tr>
* <tr><td> checked </td><td> pre-selects the particular radio button </td></tr>
* <tr><td> group="name" </td><td> the name of the group this radio button is a part of (the same for each radio button in a group) </td></tr>
* <tr><td> label-style="style" </td><td> style used for the label portion of the radio button </td></tr>
* <tr><td> name="name" </td><td> this is an alternate to the <code>group</code> attribute for HTML consistency </td></tr>
* <tr><td> required </td><td> a selection is required </td></tr>
* <tr><td> value="name" </td><td> required unique value associate with each radio button (different for each radio button) </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* This is the label associated with the radio button.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> sets the radio button group to none selected </td></tr>
* <tr><td> disable([flg]) </td><td> set the control to disabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> set the control to enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> set focus on the current control </td></tr>
* <tr><td> getIntValue() </td><td> the integer value of the selected ratio button group </td></tr>
* <tr><td> getValue() </td><td> the string value of the selected ratio button group </td></tr>
* <tr><td> hide([flg]) </td><td> hides the control (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if the user changed the value </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if the control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden(desc) </td><td> <code>true</code> if the control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if the control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if the control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute <code>fun</code> whenever the state of this control changes. <code>fun</code> is passed the value of the control group. </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets the control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets the control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> selects the button with the associated value </td></tr>
* <tr><td> show([flg]) </td><td> sets the control to show (not hide) (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
* </table>
*/
static radio_button() {}
/**
* This HTML tag, "textbox-input", adds functionality and a consistent and convenient API to the HTML provided multi-line text input.
*
* Static HTML content can be used inside this control.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> minlength="5" </td><td> sets the minimum acceptable string length </td></tr>
* <tr><td> maxlength="200" </td><td> sets the maximum number of characters </td></tr>
* <tr><td> password </td><td> the character are not shown on the screen </td></tr>
* <tr><td> placeholder="" </td><td> text to be displaced in the control until the user enters data </td><tr>
* <tr><td> required </td><td> an entry is required (at least 1 character) </td></tr>
* <tr><td> upcase </td><td> when the user enters text, it is auto-upcased </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the placeholder or what is shown as a prompt inside the control when there is no value.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> erases the contents of the control </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getValue() </td><td> returns the string associated with the control </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if user changed control contents </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if user control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute fun when control changes </td></tr>
* <tr><td> onKeyUp(fun) </td><td> execute fun when key up </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> sets the string inside the control </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static textbox_input() {}
/**
* This HTML tag, "text-input", adds functionality and a consistent and convenient API to the HTML provided text input.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> minlength="5" </td><td> sets the minimum acceptable string length </td></tr>
* <tr><td> maxlength="20" </td><td> sets the maximum number of characters </td></tr>
* <tr><td> password </td><td> the character are not shown on the screen </td></tr>
* <tr><td> required </td><td> an entry is required (at least 1 character) </td></tr>
* <tr><td> size="20" </td><td> width of control in number of characters (default 20) </td></tr>
* <tr><td> upcase </td><td> when the user enters text, it is auto-upcased </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the placeholder or what is shown as a prompt inside the control when there is no value.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> erases the contents of the control </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getValue() </td><td> returns the string associated with the control </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> has the control contents been changed by user </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isDisabled() </td><td> is the control disabled? </td></tr>
* <tr><td> isHidden() </td><td> is the control hidden? </td></tr>
* <tr><td> isReadOnly() </td><td> is the control read-only? </td></tr>
* <tr><td> isVisible() </td><td> is the control visible? </td></tr>
* <tr><td> onChange(fun) </td><td> execute fun if control value changed, as it loses focus </td></tr>
* <tr><td> onEnter(fun) </td><td> execute fun when enter key hit </td></tr>
* <tr><td> onKeyUp(fun) </td><td> execute fun when key up </td></tr>
* <tr><td> readOnly([flg]) </td><td> set control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> set control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setPassword(val) </td><td> if <code>true</code>, treat as a password control; if <code>false</code>, treat as text input - previous value is returned </td></tr>
* <tr><td> setValue(val) </td><td> sets the string inside the control </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static text_input() {}
/**
* This HTML tag, "text-label", adds functionality and a consistent and convenient API to the HTML provided label tag when the 'for' attribute is
* used or the 'span' tag otherwise.
* <br><br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the content of the label.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> erases the contents of the control </td></tr>
* <tr><td> getValue() </td><td> returns the string associated with the control </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isHidden() </td><td> is the control hidden? </td></tr>
* <tr><td> isVisible() </td><td> is the control visible? </td></tr>
* <tr><td> onclick(fun) </td><td> <code>fun</code> is executed when the user clicks on the text </td></tr>
* <tr><td> setColor(val) </td><td> sets the color of the text </td></tr>
* <tr><td> setValue(val) </td><td> sets the string inside the control </td></tr>
* <tr><td> setHTMLValue(val) </td><td> sets the HTML inside the control </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static text_label() {}
/**
* This HTML tag, "time-input", provides a control where the user can enter a time. The time appear like "3:30 PM". A 24 hour clock is also supported automatically (like 14:30).
* The values this control interacts with is a plain integer in the form HHMM in a 24 hour clock. So, "1:30 PM" would be <code>1330</code>.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 100px;">Attribute</th><th align="left">Description</th></tr>
* <tr><td> min="0800" </td><td> the minimum time allowed </td></tr>
* <tr><td> min="1800" </td><td> the maximum time allowed </td></tr>
* <tr><td> required </td><td> an entry is required </td></tr>
* <tr><td> size="20" </td><td> width of control in number of characters (default 20) </td></tr>
* <tr><td> zero-fill </td><td> zero fill the display </td></tr>
* </table>
* <br>
* <strong>Content</strong>
* <br><br>
* The <em>Content</em> represents the HTML that would normally be inside an HTML <code>select</code> element. This would only be used
* in cases of a static list. List contents that depended on data would use the <code>add</code> method.
* <br><br>
* <table>
* <tr><th align="left" style="padding-right: 120px;">API</th><th align="left">Description</th></tr>
* <tr><td> clear() </td><td> remove the value associated with the control </td></tr>
* <tr><td> disable([flg]) </td><td> the control remains visible but inactive (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> enable([flg]) </td><td> the control is set to visible and enabled (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> focus() </td><td> sets the focus (where the cursor is located) to this control </td></tr>
* <tr><td> getValue() </td><td> returns the value associated with the control </td></tr>
* <tr><td> hide([flg]) </td><td> the control is hidden (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> isDirty() </td><td> <code>true</code> if user changed control value </td></tr>
* <tr><td> isDisabled() </td><td> <code>true</code> if control is disabled </td></tr>
* <tr><td> isError(desc) </td><td> used for error checking. If error, display error message and return <code>true</code>. <code>desc</code> is a description of the user field. </td></tr>
* <tr><td> isHidden() </td><td> <code>true</code> if control is hidden (not visible) </td></tr>
* <tr><td> isReadOnly() </td><td> <code>true</code> if control is read-only </td></tr>
* <tr><td> isVisible() </td><td> <code>true</code> if control is visible (not hidden) </td></tr>
* <tr><td> onChange(fun) </td><td> execute fun if control value changed, as it loses focus </td></tr>
* <tr><td> onEnter(fun) </td><td> execute fun when enter key hit </td></tr>
* <tr><td> readOnly([flg]) </td><td> sets control to read-only (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> readWrite([flg]) </td><td> sets control to read-write (or the reverse if the optional argument is <code>false</code>) </td></tr>
* <tr><td> setValue(val) </td><td> sets the value associated with the control </td></tr>
* <tr><td> show([flg]) </td><td> the control is made visible (or the reverse if the optional argument is <code>false</code>) </td></tr>
* </table>
*/
static time_input() {}
} |
JavaScript | class ConstantPool {
/**
* @param {Array<Object>} pool
*/
constructor(pool) {
/** @type {{Array<Object>} pool} */
this.pool = pool;
}
/**
* The 1-based index into the Constant Pool for which you wish to retrieve
* the entry from.
*
* Indices MUST be: `1 ≤ index ≤ ConstantPool#size`
*
* @see https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.5
* @param {Number} idx
* @return {Object|false} - returns false if the index passed is the second
* half (empty) of a Double or Long entry in the Constant Pool. See the
* Oracle link below for more information.
*/
at(idx) {
return this.pool[idx - 1];
}
/**
* Decodes the entry's value at the Constant Pool index specified.
* @param {Number} idx - index of the entry to decode.
* @return {Number|string|undefined} returns undefined if the entry was not able to be decoded.
*/
valueAt(idx) {
let entry = this.at(idx);
switch (entry.tag) {
case TAG_STRING:
return this.at(entry.info.string_index).info.bytes;
case TAG_INTEGER:
return entry.info.value;
case TAG_LONG: {
let low = entry.info.low_bytes;
let high = entry.info.high_bytes;
return (high << 32) + low;
}
case TAG_FLOAT: {
let bits = entry.value;
if (bits === F_POSITIVE_INFINITY) {
return Number.POSITIVE_INFINITY;
} else if (bits === F_NEGATIVE_INFINITY) {
return Number.NEGATIVE_INFINITY;
}
if ((bits > F_POSITIVE_INFINITY && bits <= 0x7fffffff)
|| (bits > F_NEGATIVE_INFINITY && bits <= 0xffffffff)) {
return NaN;
}
let sign = ((bits >> 31) === 0) ? 1 : -1;
let exponent = ((bits >> 23) & 0xff);
let mantisa = (exponent === 0) ?
(bits & 0x7fffff) << 1 :
(bits & 0x7fffff) | 0x800000;
return sign * mantisa * Math.pow(2, exponent - 150);
}
case TAG_DOUBLE: {
let low = entry.info.low_bytes;
let high = entry.info.high_bytes;
let bits = (high << 32) + low;
if (bits === L_POSITIVE_INFINITY) {
return Number.POSITIVE_INFINITY;
} else if (bits === L_NEGATIVE_INFINITY) {
return Number.NEGATIVE_INFINITY;
}
if ((bits > L_POSITIVE_INFINITY && bits <= 0x7fffffffffffffff)
|| (bits > L_NEGATIVE_INFINITY && bits <= 0xffffffffffffffff)) {
return NaN;
}
let sign = ((bits >> 63) === 0) ? 1 : -1;
let exponent = ((bits >> 52) & 0x7ff);
let mantisa = (exponent === 0) ?
(bits & 0xfffffffffffff) << 1 :
(bits & 0xfffffffffffff) | 0x10000000000000;
return sign * mantisa * Math.pow(2, exponent - 1075);
}
case TAG_CLASS:
return this.at(entry.info.name_index).info.bytes;
}
}
/**
* Attempts to find the first entry in the pool matching the specified
* criteria going from the first index to the last.
* @see https://lodash.com/docs#find
* @see https://lodash.com/docs#matches
* @param {Object} criteria Search criteria
* @return {Object|undefined} returns {@link undefined} if no match could be found
*/
find(criteria) {
return _.find(this.pool, criteria);
}
/**
* The total size of the Constant Pool.
* @return {Number}
*/
get size() {
return _.size(this.pool);
}
/**
* Serialized version of this class without circular references.
* @return {Object}
*/
toObject() {
return {
constant_pool_count: this.size,
entries: this.pool
};
}
} |
JavaScript | class DomainEventPayload {
/**
* @param {?} value
*/
constructor(value) {
this.value = value;
}
/**
* @return {?}
*/
getValue() {
return this.value;
}
} |
JavaScript | class GridPlateLayoutOptions {
constructor() {
this.layouts = {
"1": {
columnLayout: "1: full width",
xs: ["100%"],
sm: ["100%"],
md: ["100%"],
lg: ["100%"],
xl: ["100%"]
},
"1-1": {
columnLayout: "2: equal width",
xs: ["100%", "100%"],
sm: ["50%", "50%"],
md: ["50%", "50%"],
lg: ["50%", "50%"],
xl: ["50%", "50%"]
},
"2-1": {
columnLayout: "2: wide & narrow",
xs: ["100%", "100%"],
sm: ["50%", "50%"],
md: ["66.6666667%", "33.3333337%"],
lg: ["66.6666667%", "33.3333337%"],
xl: ["66.6666667%", "33.3333337%"]
},
"1-2": {
columnLayout: "2: narrow & wide",
xs: ["100%", "100%"],
sm: ["50%", "50%"],
md: ["33.3333333%", "66.6666667%"],
lg: ["33.3333333%", "66.6666667%"],
xl: ["33.3333333%", "66.6666667%"]
},
"3-1": {
columnLayout: "2: wider & narrower",
xs: ["100%", "100%"],
sm: ["50%", "50%"],
md: ["75%", "25%"],
lg: ["75%", "25%"],
xl: ["75%", "25%"]
},
"1-3": {
columnLayout: "2: narrower & wider",
xs: ["100%", "100%"],
sm: ["50%", "50%"],
md: ["25%", "75%"],
lg: ["25%", "75%"],
xl: ["25%", "75%"]
},
"1-1-1": {
columnLayout: "3: equal width",
xs: ["100%", "100%", "100%"],
sm: ["100%", "100%", "100%"],
md: ["33.3333333%", "33.3333333%", "33.3333333%"],
lg: ["33.3333333%", "33.3333333%", "33.3333333%"],
xl: ["33.3333333%", "33.3333333%", "33.3333333%"]
},
"2-1-1": {
columnLayout: "3: wide, narrow, and narrow",
xs: ["100%", "100%", "100%"],
sm: ["100%", "50%", "50%"],
md: ["50%", "25%", "25%"],
lg: ["50%", "25%", "25%"],
xl: ["50%", "25%", "25%"]
},
"1-2-1": {
columnLayout: "3: narrow, wide, and narrow",
xs: ["100%", "100%", "100%"],
sm: ["100%", "100%", "100%"],
md: ["25%", "50%", "25%"],
lg: ["25%", "50%", "25%"],
xl: ["25%", "50%", "25%"]
},
"1-1-2": {
columnLayout: "3: narrow, narrow, and wide",
xs: ["100%", "100%", "100%"],
sm: ["50%", "50%", "100%"],
md: ["25%", "25%", "50%"],
lg: ["25%", "25%", "50%"],
xl: ["25%", "25%", "50%"]
},
"1-1-1-1": {
columnLayout: "4: equal width",
xs: ["100%", "100%", "100%", "100%"],
sm: ["50%", "50%", "50%", "50%"],
md: ["25%", "25%", "25%", "25%"],
lg: ["25%", "25%", "25%", "25%"],
xl: ["25%", "25%", "25%", "25%"]
},
"1-1-1-1-1": {
columnLayout: "5: equal width",
xs: ["100%", "100%", "100%", "100%", "100%"],
sm: ["50%", "50%", "50%", "50%", "50%"],
md: ["20%", "20%", "20%", "20%", "20%"],
lg: ["20%", "20%", "20%", "20%", "20%"],
xl: ["20%", "20%", "20%", "20%", "20%"]
},
"1-1-1-1-1-1": {
columnLayout: "6: equal width",
xs: ["100%", "100%", "100%", "100%", "100%", "100%"],
sm: ["50%", "50%", "50%", "50%", "50%", "50%"],
md: [
"33.3333333%",
"33.3333333%",
"33.3333333%",
"33.3333333%",
"33.3333333%",
"33.3333333%"
],
lg: [
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%"
],
xl: [
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%",
"16.6666667%"
]
}
};
this.options = {};
let layoutFlip = Object.keys(this.layouts);
//loop through all the supplied layouts to get the HAX layout options & descriptions
for (let i = 0; i < layoutFlip.length; i++) {
this.options[layoutFlip[i]] = this.layouts[layoutFlip[i]].columnLayout;
}
}
} |
JavaScript | class GridPlate extends PolymerElement {
constructor() {
super();
window.SimpleColorsStyles.requestAvailability();
import("@polymer/paper-icon-button/paper-icon-button.js");
import("@polymer/iron-icons/iron-icons.js");
}
static get template() {
return html`
<style>
:host {
display: block;
--grid-plate-row-margin: 0px;
--grid-plate-row-padding: 0px;
--grid-plate-item-margin: 15px;
--grid-plate-editable-border-color: #bbbbbb;
--grid-plate-active-border-color: #000000;
--grid-plate-col-transition: all 0.2s ease-in-out;
}
:host .row {
width: 100%;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: stretch;
margin: var(--grid-plate-row-margin);
padding: var(--grid-plate-row-padding);
}
:host .column {
width: 100%;
flex: 0 0 auto;
transition: var(--grid-plate-col-transition);
}
:host([edit-mode]) .column {
min-height: 150px;
}
:host([edit-mode]) .column {
outline: 1px dotted var(--grid-plate-editable-border-color);
}
:host .column[style="min-height: unset"] {
display: none;
}
:host([edit-mode]) .column[style="min-height: unset"]:not(:empty) {
display: block;
outline: 1px solid red;
width: 20%;
margin-top: var(--grid-plate-item-margin);
}
:host([edit-mode])
.column[style="min-height: unset"]:not(:empty):before {
content: "Layout hides this column (" attr(id) ")";
color: red;
margin: var(--grid-plate-item-margin);
padding: 15px 0;
min-height: 150px;
}
:host .column ::slotted(*) {
margin: var(--grid-plate-item-margin);
padding: var(--grid-plate-item-margin);
transition: var(--grid-plate-col-transition);
}
:host([edit-mode]) .column ::slotted(img) {
display: block;
width: calc(100% - 32px - var(--grid-plate-item-margin));
}
:host([edit-mode]) .column ::slotted(.mover) {
outline: 2px dashed var(--grid-plate-editable-border-color);
outline-offset: 4px;
}
:host([edit-mode]) .column.mover {
outline: 2px dashed var(--grid-plate-editable-border-color);
outline-offset: 0px;
}
:host([edit-mode]) .column ::slotted(.active-item) {
outline: 2px dashed var(--grid-plate-active-border-color);
background-color: var(--simple-colors-default-theme-yellow-1);
outline-offset: 4px;
}
:host([edit-mode]) .column ::slotted(*:focus),
:host([edit-mode]) .column ::slotted(*:hover),
:host([edit-mode]) .column ::slotted(*:active) {
cursor: move;
background-color: var(--simple-colors-default-theme-yellow-3);
}
:host([edit-mode]) .column ::slotted(.mover) {
background-color: var(--simple-colors-default-theme-orange-1);
padding: 16px;
}
:host([edit-mode]) .column ::slotted([data-draggable].mover:hover) {
background-color: var(--simple-colors-default-theme-yellow-2);
}
:host([edit-mode]) .column.mover {
content: "Double click to create a paragraph here";
background-color: var(--simple-colors-default-theme-orange-1);
}
:host([edit-mode]) .column.mover:hover {
background-color: var(--simple-colors-default-theme-yellow-1);
}
:host([edit-mode]) .column ::slotted(.hovered) {
background-color: var(
--simple-colors-default-theme-orange-3
) !important;
outline: dashed 4px var(--grid-plate-active-border-color);
}
:host([edit-mode]) .column.hovered {
background-color: var(
--simple-colors-default-theme-orange-3
) !important;
}
paper-icon-button {
display: none;
position: absolute;
margin: 0;
padding: 0;
outline: none;
width: 20px;
height: 20px;
color: black;
background-color: #eeeeee;
border-radius: 50%;
box-sizing: content-box !important;
z-index: 1;
min-width: unset;
}
paper-icon-button[disabled] {
color: #aaa;
background-color: #ddd;
}
paper-icon-button[disabled]:focus,
paper-icon-button[disabled]:hover {
cursor: not-allowed;
}
paper-icon-button.active {
display: block;
}
.button-holding-pen {
position: relative;
}
</style>
<div class="button-holding-pen">
<paper-icon-button
icon="icons:arrow-upward"
title="move item up"
id="up"
on-click="moveActiveElement"
>
</paper-icon-button>
<paper-icon-button
icon="icons:arrow-forward"
title="move item right"
id="right"
on-click="moveActiveElement"
>
</paper-icon-button>
<paper-icon-button
icon="icons:arrow-downward"
title="move item down"
id="down"
on-click="moveActiveElement"
>
</paper-icon-button>
<paper-icon-button
icon="icons:arrow-back"
title="move item left"
id="left"
on-click="moveActiveElement"
>
</paper-icon-button>
</div>
<div class="row">
<div
class="column"
id="col1"
style$="[[_getColumnWidth(0,columnWidths)]]"
>
<slot name="col-1"></slot>
</div>
<div
class="column"
id="col2"
style$="[[_getColumnWidth(1,columnWidths)]]"
>
<slot name="col-2"></slot>
</div>
<div
class="column"
id="col3"
style$="[[_getColumnWidth(2,columnWidths)]]"
>
<slot name="col-3"></slot>
</div>
<div
class="column"
id="col4"
style$="[[_getColumnWidth(3,columnWidths)]]"
>
<slot name="col-4"></slot>
</div>
<div
class="column"
id="col5"
style$="[[_getColumnWidth(4,columnWidths)]]"
>
<slot name="col-5"></slot>
</div>
<div
class="column"
id="col6"
style$="[[_getColumnWidth(5,columnWidths)]]"
>
<slot name="col-6"></slot>
</div>
</div>
<iron-a11y-keys
target="[[activeItem]]"
keys="enter"
on-keys-pressed="setActiveElement"
></iron-a11y-keys>
<iron-a11y-keys
target="[[activeItem]]"
keys="esc"
on-keys-pressed="cancelActive"
></iron-a11y-keys>
`;
}
static get tag() {
return "grid-plate";
}
/**
* life cycle
*/
connectedCallback() {
super.connectedCallback();
afterNextRender(this, function() {
for (var j = 1; j <= this.columns; j++) {
if (this.shadowRoot.querySelector("#col" + j) !== undefined) {
let col = this.shadowRoot.querySelector("#col" + j);
col.addEventListener("drop", this.dropEvent.bind(this));
col.addEventListener("dblclick", this.dblclick.bind(this));
col.addEventListener("dragstart", this.dragStart.bind(this));
col.addEventListener("dragenter", this.dragEnter.bind(this));
col.addEventListener("dragleave", this.dragLeave.bind(this));
col.addEventListener("dragend", this.dragEnd.bind(this));
col.addEventListener("dragover", function(e) {
e.preventDefault();
});
col.setAttribute("data-draggable", true);
}
}
this.addEventListener("focusin", this._focusIn.bind(this));
// listen for HAX if it's around
window.addEventListener(
"hax-store-property-updated",
this._haxStorePropertyUpdated.bind(this)
);
// listen for HAX insert events if it exists
window.addEventListener(
"hax-insert-content",
this.haxInsertContent.bind(this)
);
// Establish hax property binding
this.HAXWiring = new HAXWiring();
this.HAXWiring.setup(GridPlate.haxProperties, GridPlate.tag, this);
});
window.ResponsiveUtility.requestAvailability();
window.dispatchEvent(
new CustomEvent("responsive-element", {
detail: {
element: this,
attribute: "responsive-size",
relativeToParent: false,
sm: this.breakpointSm,
md: this.breakpointMd,
lg: this.breakpointLg,
xl: this.breakpointXl
}
})
);
}
/**
* life cycle
*/
disconnectedCallback() {
for (var j = 1; j <= this.columns; j++) {
if (this.shadowRoot.querySelector("#col" + j) !== undefined) {
let col = this.shadowRoot.querySelector("#col" + j);
col.removeEventListener("drop", this.dropEvent.bind(this));
col.removeEventListener("dblclick", this.dblclick.bind(this));
col.removeEventListener("dragstart", this.dragStart.bind(this));
col.removeEventListener("dragenter", this.dragEnter.bind(this));
col.removeEventListener("dragleave", this.dragLeave.bind(this));
col.removeEventListener("dragend", this.dragEnd.bind(this));
col.removeEventListener("dragover", function(e) {
e.preventDefault();
});
col.removeAttribute("data-draggable");
}
}
this.removeEventListener("focusin", this._focusIn.bind(this));
// listen for HAX if it's around
window.removeEventListener(
"hax-store-property-updated",
this._haxStorePropertyUpdated.bind(this)
);
// listen for HAX insert events if it exists
window.removeEventListener(
"hax-insert-content",
this.haxInsertContent.bind(this)
);
super.disconnectedCallback();
}
static get haxProperties() {
return {
canScale: true,
canPosition: true,
canEditSource: false,
settings: {
quick: [],
configure: [
{
property: "layout",
title: "Column Layout",
description:
"Style to present these items (may change for small screens)",
inputMethod: "select",
options: new GridPlateLayoutOptions().options
}
],
advanced: [
{
property: "breakpointSm",
title: "Small Breakpoint",
description:
"Anything less than this number (in pixels) will render with the smallest version of this layout",
inputMethod: "textfield",
validationType: "number"
},
{
property: "breakpointMd",
title: "Medium Breakpoint",
description:
"Anything less than this number (in pixels) will render with the small version of this layout",
inputMethod: "textfield",
validationType: "number"
},
{
property: "breakpointLg",
title: "Large Breakpoint",
description:
"Anything less than this number (in pixels) will render with the medium version of this layout.",
inputMethod: "textfield",
validationType: "number"
},
{
property: "breakpointXl",
title: "Extra-Large Breakpoint",
description:
"Anything less than this number (in pixels) will render with the large version of this layout. Anything greater than or equal to this number will display with the maximum number of columns for this layout.",
inputMethod: "textfield",
validationType: "number"
}
]
},
saveOptions: {
unsetAttributes: [
"active-item",
"edit-mode",
"layouts",
"columns",
"options"
]
}
};
}
static get properties() {
return {
droppable: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: "_droppableChanged"
},
ignoreHax: {
type: Boolean,
value: false
},
/**
* Custom small breakpoint for the layouts; only updated on attached
*/
breakpointSm: {
type: Number,
value: 900
},
/**
* Custom medium breakpoint for the layouts; only updated on attached
*/
breakpointMd: {
type: Number,
value: 1200
},
/**
* Custom large breakpoint for the layouts; only updated on attached
*/
breakpointLg: {
type: Number,
value: 1500
},
/**
* Custom extra-large breakpoint for the layouts; only updated on attached
*/
breakpointXl: {
type: Number,
value: 1800
},
/**
* number of columns at this layout / responsive size
*/
columns: {
type: Number,
value: 6,
reflectToAttribute: true
},
/**
* disables responsive layouts for HAX preview
*/
disableResponsive: {
type: Boolean,
value: false,
notify: true
},
/**
* If the grid plate is in a state where its items
* can be modified as far as order or column placement.
*/
editMode: {
reflectToAttribute: true,
type: Boolean,
value: false,
observer: "_editModeChanged"
},
/**
* an object with a layout's column sizes
* at the current responsive width
*/
layout: {
type: String,
value: "1-1",
observer: "layoutChanged",
reflectToAttribute: true
},
/**
* Predefined layouts of column sizes and various responsive widths.
* For example:```
{
"1-1-1-1": { //the name of the layout
"xs": ["100%","100%","100%","100%] //the responsive width of each column when the grid is extra small
"sm": ["50%","50%","50%","50%"] //the responsive width of each column when the grid is small
"md": ["50%","50%","50%","50%"] //the responsive width of each column when the grid is medium
"lg": ["25%","25%","25%","25%"] //the responsive width of each column when the grid is large
"xl": ["25%","25%","25%","25%"] //the responsive width of each column when the grid is extra large
},
{...}
}```
*/
layouts: {
type: Object,
readOnly: true,
value: new GridPlateLayoutOptions().layouts
},
/**
* Responsive size as `xs`, `sm`, `md`, `lg`, or `xl`
*/
responsiveSize: {
type: String,
value: "xs",
reflectToAttribute: true
},
/**
* Track active item
*/
activeItem: {
type: Object,
observer: "_activeItemChanged"
},
/**
* name of selected layout
*/
columnWidths: {
type: String,
computed:
"_getColumnWidths(responsiveSize,layout,layouts,disableResponsive)"
}
};
}
/**
* Implements preProcessHaxInsertContent to clean up output on save
*/
preProcessHaxInsertContent(detail) {
// ensure this is wiped to avoid issues in building
delete detail.properties.activeItem;
return detail;
}
_droppableChanged(newValue) {
if (newValue) {
this.editMode = true;
}
}
/**
* Cancel active element
*/
cancelActive(e) {
this.activeItem = null;
}
/**
* Determines if the item can move a set number of slots.
*
* @param {object} the item
* @param {number} -1 for left or +1 for right
* @returns {boolean} if the item can move a set number of slots
*/
canMoveSlot(item, before) {
let dir = before ? -1 : 1,
max = this.shadowRoot.querySelectorAll(".column").length,
col = item.getAttribute("slot").split("-"),
dest = parseInt(col[1]) + dir;
return dest >= 1 && dest <= max;
}
layoutChanged(newValue, oldValue) {
if (newValue && typeof oldValue !== typeof undefined) {
// ensure we apply things correctly
if (this.editMode) {
this.editMode = false;
setTimeout(() => {
this.editMode = true;
}, 100);
}
}
}
/**
* Moves an item a set number of slots.
*
* @param {object} the item
* @param {number} -1 for left or +1 for right
*/
moveSlot(item, before) {
let dir = before ? -1 : 1,
col = item.getAttribute("slot").split("-"),
dest = parseInt(col[1]) + dir;
item.setAttribute("slot", "col-" + dest);
}
/**
* Determines if the item can move a set number of slots.
*
* @param {object} the item
* @param {boolean} move item before previous? (false for move item after next)
* @returns {boolean} if the item can move a set number of slots
*/
canMoveOrder(item, before) {
let nodes = this.shadowRoot
.querySelector('slot[name="' + item.getAttribute("slot") + '"')
.assignedNodes({ flatten: true });
let target = null,
position = 0;
for (var i in nodes) {
if (item === nodes[i]) {
position = i;
}
}
if (before && parseInt(position) - 1 >= 0) {
target = nodes[parseInt(position) - 1];
} else if (!before && parseInt(position) + 1 <= nodes.length - 1) {
target = nodes[parseInt(position) + 1];
}
return target !== null && typeof target !== typeof undefined;
}
/**
* Moves an item's order within a slot.
*
* @param {object} the item
* @param {boolean} move item before previous? (false for move item after next)
*/
moveOrder(item, before = true) {
let nodes = this.shadowRoot
.querySelector('slot[name="' + item.getAttribute("slot") + '"')
.assignedNodes({ flatten: true });
let target = null,
position = 0;
for (var i in nodes) {
if (item === nodes[i]) {
position = i;
}
}
if (before) {
target = nodes[parseInt(position) - 1];
dom(this).insertBefore(this.activeItem, target);
} else {
target = nodes[parseInt(position) + 1];
dom(this).insertBefore(target, this.activeItem);
}
}
/**
* Move the active element based on which button got pressed.
*/
moveActiveElement(e) {
var normalizedEvent = dom(e);
var local = normalizedEvent.localTarget;
// see if this was an up down left or right movement
switch (local.id) {
case "up":
this.moveOrder(this.activeItem, true);
break;
case "down":
this.moveOrder(this.activeItem, false);
break;
case "left":
this.moveSlot(this.activeItem, true);
break;
case "right":
this.moveSlot(this.activeItem, false);
break;
}
// ensure arrows are correctly positioned after the move
setTimeout(() => {
if (this.activeItem && typeof this.activeItem.focus === "function") {
this.positionArrows(this.activeItem);
this.activeItem.focus();
}
}, 100);
}
/**
* Notice changes to what's active and ensure UX associated w/ it is visble
*/
_activeItemChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined && newValue != null) {
// position arrows
newValue.classList.add("active-item");
this.positionArrows(newValue);
} else if (newValue == null) {
this.positionArrows(newValue);
}
// if we had a previous value then remove the active item class
if (typeof oldValue !== typeof undefined && oldValue != null) {
oldValue.classList.remove("active-item");
oldValue.blur();
}
}
/**
* Set the target element to active
*/
setActiveElement(e) {
// support HAX text operations should take priority
if (
window.HaxStore &&
window.HaxStore.instance &&
window.HaxStore.instance.isTextElement(this.activeItem)
) {
return true;
}
this.shadowRoot.querySelector("#right").focus();
}
/**
* gets the column widths based on selected layout and current responsive width
*
* @param {string} a string that describes the current responsive width
* @param {string} the name of selected layout
* @param {object} predefined layouts of column sizes and various responsive widths
* @param {boolean} disable responsive sizing?
* @returns {object} an object with a layout's column sizes at the current responsive width
*/
_getColumnWidths(
responsiveSize = "sm",
layout = "1-1",
layouts,
disableResponsive
) {
if (layouts) {
let newl = layouts[layout],
//how old layout names map to the new ones
oldLayouts = {
"12": "1",
"8/4": "2-1",
"6/6": "1-1",
"4/8": "1-2",
"4/4/4": "1-1-1",
"3/3/3/3": "1-1-1-1"
},
size = disableResponsive !== false ? "xl" : responsiveSize;
let oldl = oldLayouts[layout];
if (newl !== undefined && newl[size] !== undefined) {
//return the layout
return layouts[layout][size];
} else if (
layouts[oldl] !== undefined &&
layouts[oldl][size] !== undefined
) {
//return new layout that maps to old one
return layouts[oldl][size];
} else if (typeof layouts["1-1"] !== typeof undefined) {
//return 2-column layout
return layouts["1-1"][size];
}
}
}
/**
* gets a given column's current width based on layout and current responsive width
*
* @param {number} the index of the column
* @param {object} an object with a layout's column sizes at the current responsive width
* @returns {string} a given column's current width based on layout and current responsive width
*/
_getColumnWidth(column, columnWidths) {
return columnWidths !== undefined && columnWidths[column] !== undefined
? "width:" + columnWidths[column]
: "min-height: unset";
}
/**
* gets a given column's current width based on layout and current responsive width
*
* @param {string} the name of selected layout
* @returns {number} the number of columns in this layout
*/
_getColumns(columnWidths) {
return columnWidths.length;
}
/**
* Focus / tab / click event normalization
*/
_focusIn(e) {
if (this.editMode) {
var normalizedEvent = dom(e);
var local = normalizedEvent.localTarget;
// only activate if we touch something that's in the slot of the grid plate
if (dom(local).parentNode === this) {
this.activeItem = local;
}
}
}
/**
* Position the arrows to change directions around something
*/
positionArrows(item) {
if (item == null) {
this.shadowRoot.querySelector("#up").classList.remove("active");
this.shadowRoot.querySelector("#down").classList.remove("active");
this.shadowRoot.querySelector("#left").classList.remove("active");
this.shadowRoot.querySelector("#right").classList.remove("active");
} else {
this.shadowRoot.querySelector("#up").classList.add("active");
this.shadowRoot.querySelector("#down").classList.add("active");
this.shadowRoot.querySelector("#left").classList.add("active");
this.shadowRoot.querySelector("#right").classList.add("active");
// ensure we disable invalid options contextually
// test for an element above us
this.shadowRoot.querySelector("#up").disabled = !this.canMoveOrder(
item,
true
);
// test for an element below us
this.shadowRoot.querySelector("#down").disabled = !this.canMoveOrder(
item,
false
);
// test for a column to the left of us
this.shadowRoot.querySelector("#left").disabled = !this.canMoveSlot(
item,
true
);
// test for a column to the right of us
this.shadowRoot.querySelector("#right").disabled = !this.canMoveSlot(
item,
false
);
// get coordinates of the page and active element
let bodyRect = this.getBoundingClientRect();
let elemRect = item.getBoundingClientRect();
let topOffset = elemRect.top - bodyRect.top;
let leftOffset = elemRect.left - bodyRect.left;
// set the arrows to position correctly at all 4 sides
this.shadowRoot.querySelector("#up").style.top = topOffset - 20 + "px";
this.shadowRoot.querySelector("#down").style.top =
topOffset + elemRect.height + "px";
this.shadowRoot.querySelector("#left").style.top =
topOffset + elemRect.height / 2 + "px";
this.shadowRoot.querySelector("#right").style.top =
topOffset + elemRect.height / 2 + "px";
this.shadowRoot.querySelector("#up").style.left =
leftOffset + elemRect.width / 2 - 10 + "px";
this.shadowRoot.querySelector("#down").style.left =
leftOffset + elemRect.width / 2 - 10 + "px";
this.shadowRoot.querySelector("#left").style.left =
leftOffset - 20 + "px";
this.shadowRoot.querySelector("#right").style.left =
leftOffset + elemRect.width + "px";
}
}
/**
* Notice edit state has changed
*/
_editModeChanged(newValue, oldValue) {
// flipping from false to true
let children = dom(this).getEffectiveChildNodes();
if (typeof children === "object") {
if (newValue && !oldValue) {
// walk the children and apply the draggable state needed
for (var i in children) {
if (typeof children[i].tagName !== typeof undefined) {
children[i].addEventListener("drop", this.dropEvent.bind(this));
children[i].addEventListener(
"dragenter",
this.dragEnter.bind(this)
);
children[i].addEventListener(
"dragleave",
this.dragLeave.bind(this)
);
children[i].addEventListener(
"dragstart",
this.dragStart.bind(this)
);
children[i].addEventListener("dragend", this.dragEnd.bind(this));
children[i].addEventListener("dragover", function(e) {
e.preventDefault();
});
children[i].setAttribute("draggable", true);
children[i].setAttribute("data-draggable", true);
// ensure they can be focused
children[i].setAttribute("tabindex", 0);
}
}
}
// flipping from true to false
else if (!newValue && oldValue) {
// unset active to clean up state
this.activeItem = null;
// walk the children and remove the draggable state needed
for (var i in children) {
if (typeof children[i].tagName !== typeof undefined) {
children[i].removeEventListener("drop", this.dropEvent.bind(this));
children[i].removeEventListener(
"dragstart",
this.dragStart.bind(this)
);
children[i].removeEventListener(
"dragenter",
this.dragEnter.bind(this)
);
children[i].removeEventListener(
"dragleave",
this.dragLeave.bind(this)
);
children[i].removeEventListener("dragend", this.dragEnd.bind(this));
children[i].removeEventListener("dragover", function(e) {
e.preventDefault();
});
children[i].removeAttribute("draggable");
children[i].removeAttribute("data-draggable");
children[i].removeAttribute("tabindex");
}
}
}
}
}
/**
* Enter an element, meaning we've over it while dragging
*/
dragEnter(e) {
if (this.editMode) {
e.preventDefault();
e.target.classList.add("hovered");
}
}
/**
* Leaving an element while dragging.
*/
dragLeave(e) {
if (this.editMode) {
e.target.classList.remove("hovered");
}
}
/**
* On double check, fire an event for HAX to insert a paragraph.
* If they aren't using HAX then it won't do anything
*/
dblclick(e) {
if (this.editMode && e.target.id) {
let detail = {};
detail.properties = {
slot: e.target.id.replace("col", "col-")
};
this.dispatchEvent(
new CustomEvent("grid-plate-add-item", {
bubbles: true,
cancelable: true,
composed: true,
detail: detail
})
);
}
}
/**
* Drop an item onto another
*/
dropEvent(e) {
if (this.editMode) {
var normalizedEvent = dom(e);
var local = normalizedEvent.localTarget;
// if we have a slot on what we dropped into then we need to mirror that item
// and place ourselves below it in the DOM
if (
typeof this.activeItem !== typeof undefined &&
this.activeItem !== null &&
typeof local !== typeof undefined &&
local.getAttribute("slot") != null &&
this.activeItem !== local
) {
this.activeItem.setAttribute("slot", local.getAttribute("slot"));
dom(this).insertBefore(this.activeItem, local);
// ensure that if we caught this event we process it
e.preventDefault();
e.stopPropagation();
}
// special case for dropping on an empty column or between items
// which could involve a miss on the column
else if (local.tagName === "DIV" && local.classList.contains("column")) {
var col = local.id.replace("col", "");
this.activeItem.setAttribute("slot", "col-" + col);
dom(this).appendChild(this.activeItem);
// ensure that if we caught this event we process it
e.preventDefault();
e.stopPropagation();
}
let children = dom(this).children;
// walk the children and apply the draggable state needed
for (var i in children) {
if (typeof children[i].classList !== typeof undefined) {
children[i].classList.remove("mover");
}
}
for (var j = 1; j <= this.columns; j++) {
if (this.shadowRoot.querySelector("#col" + j) !== undefined) {
this.shadowRoot.querySelector("#col" + j).classList.remove("mover");
}
}
// position arrows / set focus in case the DOM got updated above
setTimeout(() => {
if (this.activeItem && typeof this.activeItem.focus === "function") {
this.positionArrows(this.activeItem);
this.activeItem.focus();
}
}, 100);
}
}
/**
* Start a drag event, this is an element being dragged
*/
dragStart(e) {
if (this.editMode) {
let children = dom(this).children;
// walk the children and apply the draggable state needed
for (var i in children) {
if (typeof children[i].classList !== typeof undefined) {
children[i].classList.add("mover");
}
}
for (var j = 1; j <= this.columns; j++) {
if (this.shadowRoot.querySelector("#col" + j) !== undefined) {
this.shadowRoot.querySelector("#col" + j).classList.add("mover");
}
}
}
}
/**
* When we end dragging ensure we remove the mover class.
*/
dragEnd(e) {
if (this.editMode) {
let children = dom(this).children;
// walk the children and apply the draggable state needed
for (var i in children) {
if (typeof children[i].classList !== typeof undefined) {
children[i].classList.remove("mover", "hovered");
}
}
for (var j = 1; j <= this.columns; j++) {
if (this.shadowRoot.querySelector("#col" + j) !== undefined) {
this.shadowRoot
.querySelector("#col" + j)
.classList.remove("mover", "hovered");
}
}
}
}
/**
* Insert event noticed by HAX
*/
haxInsertContent(e) {
// see if WE are the thing that's active when insert was fired
if (this === window.HaxStore.instance.activeContainerNode) {
// trick events into rebinding since this event is only possible
// when we are in an edit state
this.editMode = false;
// delay and then set it back, re-applying all events
setTimeout(() => {
this.editMode = true;
if (this.activeItem && typeof this.activeItem.focus === "function") {
this.positionArrows(this.activeItem);
this.activeItem.focus();
}
}, 100);
}
}
/**
* Store updated, sync.
*/
_haxStorePropertyUpdated(e) {
if (
e.detail &&
typeof e.detail.value !== typeof undefined &&
e.detail.property
) {
if (typeof e.detail.value === "object") {
this.set(e.detail.property, null);
}
if (e.detail.property === "editMode" && this.ignoreHax) {
// do nothing, we were told to ignore hax
} else {
this.set(e.detail.property, e.detail.value);
}
}
}
} |
JavaScript | class Engineer extends Person {
constructor(name, department) {
super(name, department);
console.log('Engineer child class');
this.drive = null;
}
} |
JavaScript | class ModalScreen extends Component {
constructor(props) {
super(props);
if (this.props.type === 'add') {
this.state = {
modal: false,
title: '',
date: '',
emotion: 'Happy',
body: ''
};
} else {
this.state = {
dropdownOpen: false,
modal: false,
title: this.props.entry.title,
date: this.props.entry.date,
emotion: this.props.entry.emotion,
body: ''
}
}
// binding for toggling modal
this.toggle = this.toggle.bind(this);
this.handleClose = this.handleClose.bind(this);
// binding data changes for form
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.toggleDropdown = this.toggleDropdown.bind(this);
this.handleBody = this.handleBody.bind(this);
this.saveButtonRender = this.saveButtonRender.bind(this);
// binding buttons/submissions for form
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.resetStateToNone = this.resetStateToNone.bind(this);
this.resetStateToInitial = this.resetStateToInitial.bind(this);
}
// whenever the edit journal is clicked you need to rerender the modal screen to bring back the new changes?
toggle() {
this.setState({ modal: !this.state.modal });
}
handleClose() {
if (this.props.type === 'add') this.resetStateToNone();
if (this.props.type ==='edit') this.resetStateToInitial();
this.toggle();
}
toggleDropdown() {
this.setState({ dropdownOpen: !this.state.dropdownOpen });
}
handleTitleChange(event) {
this.setState({ title: event.target.value });
}
handleDateChange(event) {
this.setState({ date: event.target.value });
}
handleBody(value) {
this.setState({ body: value });
}
handleEmotion(event) {
this.setState({ emotion: event.target.id });
}
saveButtonRender() {
let emptyConditions = (this.state.title === '')
|| (this.state.date === '')
|| (this.state.body === '');
// let unChangedConditions;
// if (this.props.type === 'edit') {
// unChangedConditions = (this.state.title === this.props.entry.title)
// && (this.state.date === this.props.entry.date)
// && (this.state.body === this.props.entry.body);
// } else {
// unChangedConditions = true;
// }
if (emptyConditions) {
return <Button color="danger" disabled onClick={this.handleSave}>Save</Button>;
} else {
return <Button color="danger" onClick={this.handleSave}>Save</Button>;
}
}
render() {
let editor, toggleBtn, deleteBtn, saveBtn;
if (this.props.type === 'add') {
editor = <ModalEditor
type={this.props.type}
onChange={(value) => this.handleBody(value)}
/>;
toggleBtn = <Button color="light" onClick={this.toggle}>{this.props.buttonLabel}</Button>;
} else {
editor = <ModalEditor
type={this.props.type}
value={this.props.entry.body}
onChange={(value) => this.handleBody(value)}
/>;
toggleBtn = <Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
deleteBtn = <Button color="danger" onClick={this.handleDelete}>Delete</Button>;
}
saveBtn = this.saveButtonRender();
return (
<div>
{toggleBtn}
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.handleClose}>{this.state.title}</ModalHeader>
<ModalBody>
<form onSubmit={this.handleSubmit}>
<div className="inputs">
<label className="modal-title">
Title:
<input type="text" value={this.state.title} onChange={this.handleTitleChange} />
</label>
<label className="modal-title">
Date:
<input type="date" value={this.state.date} onChange={this.handleDateChange} />
</label>
</div>
<ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggleDropdown}>
<DropdownToggle caret>
{this.state.emotion}
</DropdownToggle>
<DropdownMenu>
<DropdownItem id="Happy" onClick={(event) => this.handleEmotion(event)}>Happy</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Excited" onClick={(event) => this.handleEmotion(event)}>Excited</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Calm" onClick={(event) => this.handleEmotion(event)}>Calm</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Afraid" onClick={(event) => this.handleEmotion(event)}>Afraid</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Sad" onClick={(event) => this.handleEmotion(event)}>Sad</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Disgusted" onClick={(event) => this.handleEmotion(event)}>Disgusted</DropdownItem>
<DropdownItem divider />
<DropdownItem id="Angry" onClick={(event) => this.handleEmotion(event)}>Angry</DropdownItem>
</DropdownMenu>
</ButtonDropdown>
<div>
{editor}
</div>
</form>
</ModalBody>
<ModalFooter>
{saveBtn}
{' '}
{deleteBtn}
<Button color="danger" onClick={this.handleClose}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
);
}
handleSubmit(event) {
event.preventDefault();
}
handleCancel(event) {
this.setState();
this.toggle();
}
handleDelete(event) {
console.log(this.props.userId);
let userJournals = firebase.database().ref(`users/${this.props.userId}/${this.props.entry.id}`);
console.log(this.props.entry.id);
let deleteEntry = {};
deleteEntry[this.props.entry.id] = null;
userJournals.set(deleteEntry).catch(console.log);
this.toggle(); // toggle modal screen
}
handleSave(event) {
let userJournals = firebase.database().ref(`users/${this.props.userId}`);
let newEntry = {
title: this.state.title,
date: this.state.date,
emotion: this.state.emotion,
body: this.state.body
};
if (this.props.type === 'add') { // push entry as a new child of userJournals
userJournals.push(newEntry).catch(console.log);
} else { // modal screen used for editting
userJournals = firebase.database().ref(`users/${this.props.userId}/${this.props.entry.id}`);
userJournals.set(newEntry).catch(console.log);
}
if (this.props.type === 'add') {
this.resetStateToNone();
}
this.toggle();
}
resetStateToNone() {
this.setState({
modal: false,
title: '',
date: '',
emotion: 'Happy',
body: ''
});
}
resetStateToInitial() {
this.setState({
title: this.props.entry.title,
date: this.props.entry.date,
emotion: this.props.entry.emotion,
body: ''
});
}
} |
JavaScript | class AuthDataInmemory extends AuthData {
constructor(data){
super(data.address, data.secrets, data.contacts, data.mnemonic);
}
// create(opts:Map<string, any>) => Promise<AuthDataInmemory> -- create and return Promise of instance.
static create(opts) {
const authData = new AuthDataInmemory({address: opts.address, secrets: [], contacts: [], mnemonic: ""});
return authData.save();
}
// restore() => AuthDataInmemory -- restore from sessionStorage and return instance.
static restore() {
if(!$window.sessionStorage[AuthData.SESSION_KEY]) throw new Error('No authdata in session.');
try {
return new AuthDataInmemory(JSON.parse($window.sessionStorage.authdata))
} catch(e) {
const errorMsg = `File wallet in session corrupted, cleaned up!\n${$window.sessionStorage[AuthData.SESSION_KEY]}\n${e}`;
delete $window.sessionStorage[AuthData.SESSION_KEY];
throw new Error(errorMsg)
}
}
// load(...opts:any[]) => Promise<AuthDataInmemory> -- fake-load from sessionStorage and return Promise of instance.
static load(opts) {
console.log(opts)
return AuthDataInmemory.create(opts)
}
// store() => AuthDataInmemory -- store in sessionStorage and return instance.
store() {
$window.sessionStorage[AuthData.SESSION_KEY] = JSON.stringify({
address: this.address,
contacts: this.contacts,
secrets: this.secrets,
mnemonic: this.mnemonic
});
return this;
}
// save() => Promise<AuthDataInmemory> -- fake-save and return Promise of current instance.
save() {
return new Promise((resolve, reject) => {
try {
resolve(this.store());
} catch(e) {
reject(e)
}
})
}
} |
JavaScript | class TableView extends Component {
constructor(props) {
super(props)
this.state = {
data: this.props.data,
fields: [],
sortField: ''
}
}
componentDidMount() {
this.parseFields()
}
parseFields() {
for (const d in this.props.data) {
if (this.props.data.hasOwnProperty(d)) {
const data = this.props.data[d]
const fieldsArray = []
for (const i in data) {
fieldsArray.push(i)
}
this.setState({ fields: fieldsArray })
}
}
}
sort(e) {
/* get the selected field */
let field = e.target.getAttribute('data-field-name')
if (field === null) {
field = e.target.parentNode.getAttribute('data-field-name')
}
/* get the current sort direction */
let sortDirection = 'DESC'
const $elem = ReactDOM.findDOMNode(this.refs[field])
if ($elem.className === 'down') {
sortDirection = 'ASC'
}
/* clear all field sort classes */
for (let i = 0; i < this.state.fields.length; i++) {
const $fieldElem = ReactDOM.findDOMNode(this.refs[this.state.fields[i]])
$fieldElem.className = ''
}
this.sortByField(field, sortDirection)
}
sortByField(field, direction) {
/* set sortField for compare function */
this.setState({ sortField: field })
const { data } = this.state
data.sort(this.compare.bind(this))
const $elem = ReactDOM.findDOMNode(this.refs[field])
if (direction === 'ASC') {
$elem.className = 'up'
data.reverse()
} else {
$elem.className = 'down'
}
this.setState({ data })
}
compare(a, b) {
if (a[this.state.sortField] < b[this.state.sortField]) return -1
if (a[this.state.sortField] > b[this.state.sortField]) return 1
return 0
}
render() {
let { columns } = this.props
let { fields } = this.state
return (
<TableViewWrapper>
<table>
<thead>
<tr>
{this.state.fields.map((f, i) => (
<th key={i} onClick={this.sort.bind(this)} data-field-name={f}>
<span>{f}</span>
<i ref={f} />
</th>
))}
</tr>
</thead>
<tbody>
{this.props.data.map(function(d, i) {
return (
<tr key={i}>
{fields.map(function(f, j) {
if (columns && columns[f]) {
return <td key={j}>{columns[f](d)}</td>
} else {
return <td key={j}>{d[f]}</td>
}
})}
</tr>
)
})}
</tbody>
</table>
</TableViewWrapper>
)
}
} |
JavaScript | class BtnBehavior {
constructor() {
this.index = 0;
this.buttons = expectedButtonIndices;
this.forward = this.forward.bind(this);
this.backward = this.backward.bind(this);
}
forward() {
this.index = (this.index + 1) % 3;
return this.current();
}
backward() {
this.index = (this.index + 3 - 1) % 3;
return this.current();
}
current() {
return this.buttons[`button${this.index + 1}Focused`];
}
reset() {
this.index = 0;
}
} |
JavaScript | class Logging {
/**
* Filters an object intended for logging.
* @param {Object} in_obj An object that may contain properties that shouldn't be logged.
* @param {Object} in_filters An array of keys containing the names of properties to filter out.
* @param {?number=} in_maxArrayLength Overrides the maximum length of arrays in a log message.
* Defaults to MAX_ARRAY_LENGTH if left unspecified.
* @return {Object} The filtered object.
* @static
*/
static filterLogObject(in_obj, in_filters, in_maxArrayLength) {
in_maxArrayLength = in_maxArrayLength || MAX_ARRAY_LENGTH;
return _.mapValues(in_obj, function(value, key) {
if (value && in_filters.indexOf(key) > -1) {
if (key === 'changeSet' || key === 'value') {
var loggedValue = value;
if (typeof value !== 'string' && _.isObject(value)) {
loggedValue = JSON.stringify(value);
}
return loggedValue.length > MAX_LOGGED_STRING_LENGTH ?
loggedValue.substring(0, MAX_LOGGED_STRING_LENGTH) + `... string[${loggedValue.length}]` :
value;
}
return '<redacted>';
}
if (typeof value === 'string') {
return value.length > MAX_LOGGED_STRING_LENGTH ?
value.substring(0, MAX_LOGGED_STRING_LENGTH) + `... string[${value.length}]` : value;
}
if (value instanceof Date) {
return value.getTime();
}
if (value && value.constructor === Array) {
let loggedArray = [];
const arrayLength = Math.min(value.length, in_maxArrayLength);
for (let i = 0; i < arrayLength; i++) {
loggedArray.push(Logging.filterLogObject(value[i], in_filters, in_maxArrayLength));
}
if (value.length > in_maxArrayLength) {
loggedArray.push('... Array[' + value.length + ']');
}
return loggedArray;
}
if (_.isObject(value)) {
return Logging.filterLogObject(value, in_filters, in_maxArrayLength);
}
return value;
});
}
} |
JavaScript | class header extends React.Component {
state = {
active: false,
};
handleClick = () => {
console.log("here");
this.setState({ active: !this.state.active });
};
render() {
return (
<div className="header">
<Link to="/">
<h1 className="restaurant-name">{"Jokbal House"}</h1>
</Link>
<div className="menu-items">
<Link to="/menu-page/">
<h1 className="menu-names">{"Menu"}</h1>
</Link>
<Link to="/hours-and-location-page/">
<h1 className="menu-names">{"Hours & Location"}</h1>
</Link>
<Link to="/join-us/">
<h1 className="menu-names">{"Join Us"}</h1>
</Link>
</div>
<img
src={hamburger}
className="hamburger"
onClick={() => {
this.handleClick();
}}
/>
<Drawer
variant="temporary"
anchor="right"
open={this.state.active}
transitionDuration={{ enter: 500, exit: 500 }}
>
<div className="drawer">
<div className="close-icon">
<CloseIcon
onClick={() => {
this.handleClick();
}}
/>
</div>
<div style={{ padding: 32, textAlign: "center" }}>
<Link to="/">
<h1 className="menu-drawer-items">Home</h1>
</Link>
<Link to="/menu-page/">
<h1 className="menu-drawer-items">Menu</h1>
</Link>
<Link to="/hours-and-location-page/">
<h1 className="menu-drawer-items">Hours & Location</h1>
</Link>
<Link to="/join-us/">
<h1 className="menu-drawer-items">Join Us</h1>
</Link>
</div>
</div>
</Drawer>
</div>
);
}
} |
JavaScript | class DCOfferCreateBcCommand extends Command {
constructor(ctx) {
super(ctx);
this.config = ctx.config;
this.logger = ctx.logger;
this.blockchain = ctx.blockchain;
this.remoteControl = ctx.remoteControl;
this.replicationService = ctx.replicationService;
}
/**
* Executes command and produces one or more events
* @param command
*/
async execute(command) {
const {
internalOfferId,
dataSetId,
dataRootHash,
redLitigationHash,
greenLitigationHash,
blueLitigationHash,
holdingTimeInMinutes,
tokenAmountPerHolder,
dataSizeInBytes,
litigationIntervalInMinutes,
handler_id,
urgent,
} = command.data;
let result;
try {
result = await this.blockchain.createOffer(
Utilities.normalizeHex(this.config.erc725Identity),
dataSetId,
dataRootHash,
redLitigationHash,
greenLitigationHash,
blueLitigationHash,
Utilities.normalizeHex(this.config.identity),
holdingTimeInMinutes,
tokenAmountPerHolder,
dataSizeInBytes,
litigationIntervalInMinutes,
urgent,
);
} catch (error) {
if (error.message.includes('Gas price higher than maximum allowed price')) {
const delay = constants.GAS_PRICE_VALIDITY_TIME_IN_MILLS / 60 / 1000;
this.logger.info(`Gas price too high, delaying call for ${delay} minutes`);
const handler = await Models.handler_ids.findOne({
where: { handler_id },
});
const handler_data = JSON.parse(handler.data);
handler_data.status = 'DELAYED';
handler.timestamp = Date.now();
handler.data = JSON.stringify(handler_data);
await handler.save({ fields: ['data', 'timestamp'] });
const message = `Offer creation has been delayed on ${(new Date(Date.now())).toUTCString()} due to high gas price`;
await Models.offers.update({ message }, { where: { id: internalOfferId } });
return Command.repeat();
}
throw error;
}
this.logger.important(`Offer with internal ID ${internalOfferId} for data set ${dataSetId} written to blockchain. Waiting for DHs...`);
const offer = await Models.offers.findOne({ where: { id: internalOfferId } });
offer.transaction_hash = result.transactionHash;
offer.status = 'PUBLISHED';
offer.message = 'Offer has been published to Blockchain';
await offer.save({ fields: ['status', 'message', 'transaction_hash'] });
this.remoteControl.offerUpdate({
id: internalOfferId,
});
await Models.handler_ids.update({ timestamp: Date.now() }, { where: { handler_id } });
await this.blockchain.executePlugin('fingerprint-plugin', {
dataSetId,
dataRootHash,
});
const { data } = command;
return this.continueSequence(this.pack(data), command.sequence);
}
/**
* Recover system from failure
* @param command
* @param err
*/
async recover(command, err) {
return this.invalidateOffer(command, err);
}
/**
* Execute strategy when event is too late
* @param command
*/
async expired(command) {
return this.invalidateOffer(
command,
Error('The offer creation command is too late.'),
);
}
async invalidateOffer(command, err) {
const { dataSetId, internalOfferId, handler_id } = command.data;
this.logger.notify(`Offer for data set ${dataSetId} has not been started. ${err.message}`);
const errorData = {
internalOfferId,
};
const offer = await Models.offers.findOne({ where: { id: internalOfferId } });
if (offer) {
offer.status = 'FAILED';
offer.global_status = 'FAILED';
offer.message = `Offer for data set ${dataSetId} has not been started. ${err.message}`;
await offer.save({ fields: ['status', 'message', 'global_status'] });
errorData.tokenAmountPerHolder = offer.token_amount_per_holder;
errorData.litigationIntervalInMinutes = offer.litigation_interval_in_minutes;
errorData.datasetId = offer.data_set_id;
errorData.holdingTimeInMinutes = offer.holding_time_in_minutes;
await this.replicationService.cleanup(offer.id);
} else {
this.logger.warn(`Offer with internal id ${internalOfferId} not found in database.`);
}
this.remoteControl.offerUpdate({
id: internalOfferId,
});
await Models.handler_ids.update({ status: 'FAILED' }, { where: { handler_id } });
this.errorNotificationService.notifyError(
err,
errorData,
constants.PROCESS_NAME.offerHandling,
);
return Command.empty();
}
/**
* Builds default command
* @param map
* @returns {{add, data: *, delay: *, deadline: *}}
*/
default(map) {
const command = {
name: 'dcOfferCreateBcCommand',
delay: 0,
period: constants.GAS_PRICE_VALIDITY_TIME_IN_MILLS,
deadline_at: Date.now() + (5 * constants.GAS_PRICE_VALIDITY_TIME_IN_MILLS),
transactional: false,
};
Object.assign(command, map);
return command;
}
} |
JavaScript | class OscillatorBank {
constructor(context) {
this.context = context;
this.oscillators = [];
}
borrowOscillator() {
if (this.oscillators.length) {
return this.oscillators.pop();
}
return this.context.createOscillator();
}
returnOscillator(oscillator) {
oscillator.disconnect();
oscillator.stop();
this.oscillators.push(oscillator);
}
} |
JavaScript | class PaymentTransactionCancelDTO {
/**
* Constructs a new <code>PaymentTransactionCancelDTO</code>.
* @alias module:model/PaymentTransactionCancelDTO
* @class
*/
constructor() {
}
/**
* Constructs a <code>PaymentTransactionCancelDTO</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PaymentTransactionCancelDTO} obj Optional instance to populate.
* @return {module:model/PaymentTransactionCancelDTO} The populated <code>PaymentTransactionCancelDTO</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PaymentTransactionCancelDTO();
if (data.hasOwnProperty('reason')) {
obj['reason'] = ApiClient.convertToType(data['reason'], 'String');
}
if (data.hasOwnProperty('amount')) {
obj['amount'] = ApiClient.convertToType(data['amount'], 'Number');
}
if (data.hasOwnProperty('reduce_stakeholder_payment')) {
obj['reduce_stakeholder_payment'] = ApiClient.convertToType(data['reduce_stakeholder_payment'], 'Boolean');
}
}
return obj;
}
/**
* The reason of this cancel or refund
* @member {String} reason
*/
reason = undefined;
/**
* partial or full refund amount, \"0\" means full refund
* @member {Number} amount
*/
amount = undefined;
/**
* Mixed-Basket: (percentage) reduce the stakeholder amount too
* @member {Boolean} reduce_stakeholder_payment
* @default false
*/
reduce_stakeholder_payment = false;
} |
JavaScript | class Manage extends Component {
static navigationOptions = {
title: 'Manage',
// header: null,
tabBarLabel: 'Manage',
tabBarIcon: () => (
<Icon style={page_styles.logo} name='cog' type="entypo" color='white'></Icon>
),
};
constructor(props) {
super(props)
this.state = {
loading: false,
user: ''
}
this.logout = this.logout.bind(this);
this.changePage = this.changePage.bind(this);
};
componentWillMount(){
AsyncStorage.getItem('user_data').catch((error) => {
console.log(error);
}).then((value) => {
let user_data = JSON.parse(value);
console.log(user_data);
this.setState({user: user_data});
// AlertIOS.alert(`${this.state.test.email}`)
});
}
logout (){
AsyncStorage.removeItem('user_detail').then(() => {
firebaseRef.auth().signOut();
this.props.navigation.navigate("Login")
});
}
changePage = (page) => {
this.props.navigation.navigate(`${page}`);
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={ { backgroundColor: 'gray', flex: 1 } }>
<View style={ { flex: 1, marginTop: 50 } }>
<SettingsList>
<SettingsList.Header headerText='Subject' headerStyle={ { color: 'white' } }/>
<SettingsList.Item title="Register" hasNavArrow={true}/>
</SettingsList>
</View>
</View>
);
}
} |
JavaScript | class CustomListGroup extends React.Component {
render() {
return (
<ul className="list-group">
{this.props.children}
</ul>
);
}
} |
JavaScript | class Stream
{
/**
*
* @param {Buffer} buffer
*/
constructor(buffer)
{
if (!(buffer instanceof Buffer) && Array.isArray(buffer))
throw new Error('only Array and Buffer are accepted');
if (Array.isArray(buffer))
buffer = Buffer.from(buffer);
this.defaultEncode = 'utf-8';
this.buffer = buffer;
this.invert = false;
this.offset = 0;
}
addOffset(bytes)
{
let offset = this.offset;
this.offset += bytes;
return offset;
}
/**
* @returns {number}
*/
getByte()
{
return this.buffer.readInt8(this.addOffset(1));
}
/**
* @returns {number}
*/
getUByte()
{
return this.buffer.readUInt8(this.addOffset(1));
}
/**
* @returns {number}
*/
getShort()
{
return this.invert ? this.buffer.readInt16LE(this.addOffset(2)) : this.buffer.readInt16BE(this.addOffset(2));
}
/**
* @returns {number}
*/
getUShort()
{
return this.invert ? this.buffer.readUInt16LE(this.addOffset(2)) : this.buffer.readUInt16BE(this.addOffset(2));
}
/**
* @returns {number}
*/
getInt()
{
return this.invert ? this.buffer.readInt32LE(this.addOffset(4)) : this.buffer.readInt32BE(this.addOffset(4));
}
/**
* @returns {number}
*/
getUInt()
{
return this.invert ? this.buffer.readUInt32LE(this.addOffset(4)) : this.buffer.readUInt32BE(this.addOffset(4));
}
/**
* @returns {number}
*/
getLong()
{
let data = [
this.getByte(), this.getByte(), this.getByte(), this.getByte(),
this.getByte(), this.getByte(), this.getByte(), this.getByte()
];
return (new Int64BE(Buffer.from(this.invert ? data.reverse() : data))).toNumber();
}
getULong()
{
let data = [
this.getByte(), this.getByte(), this.getByte(), this.getByte(),
this.getByte(), this.getByte(), this.getByte(), this.getByte()
];
return (new Uint64LE(Buffer.from(this.invert ? data.reverse() : data))).toNumber();
}
getFloat()
{
return this.invert ? this.buffer.readFloatLE(this.addOffset(4)) : this.buffer.readFloatBE(this.addOffset(4));
}
getDouble()
{
return this.invert ? this.buffer.readDoubleLE(this.addOffset(8)) : this.buffer.readDoubleBE(this.addOffset(8));
}
getBoolean()
{
return this.getByte() !== 0;
}
getChar()
{
return String.fromCharCode(this.getByte());
}
getString(length, encode)
{
length = Util.nvli(length, this.getByte());
return this.buffer.toString(Util.nvl(encode, this.defaultEncode), this.addOffset(length), this.offset);
}
length()
{
return this.buffer.length;
}
size()
{
return this.length() - this.offset;
}
} |
JavaScript | class TxGasUtil {
constructor(provider, store, getPublicKeyFor) {
this.query = new EthQuery(provider);
this.store = store;
this.getPublicKeyFor = getPublicKeyFor;
}
/**
@param {Object} txMeta - the txMeta object
@returns {GasAnalysisResult} The result of the gas analysis
*/
async analyzeGasUsage(txMeta) {
log.debug('analyzeGasUsage', txMeta)
const chainInfo = await new Promise((resolve, reject) => {
return this.query.getChainInfo((err, res) => {
if (err) {
return reject(err);
}
return resolve(res);
});
});
log.debug({ chainInfo })
const blockNumber = chainInfo && chainInfo.head ? chainInfo.head.number : 0;
// maxGasAmount is dynamical adjusted, today it is about 40000000
const maxGasAmount = new BigNumber(40000000, 10).toString(16);
const gasLimit = addHexPrefix(maxGasAmount);
const block = { number: blockNumber, gasLimit };
log.debug({ block })
// fallback to block gasLimit
const blockGasLimitBN = hexToBn(block.gasLimit);
const saferGasLimitBN = BnMultiplyByFraction(blockGasLimitBN, 19, 20);
let estimatedGasHex = bnToHex(saferGasLimitBN);
log.debug('estimatedGasHex1', { estimatedGasHex })
let simulationFails;
try {
estimatedGasHex = await this.estimateTxGas(txMeta);
log.debug('estimatedGasHex2', { estimatedGasHex })
} catch (error) {
log.warn({ error });
simulationFails = {
reason: error.message,
errorKey: error.errorKey,
debug: { blockNumber: block.number, blockGasLimit: block.gasLimit },
};
}
return { blockGasLimit: block.gasLimit, estimatedGasHex, simulationFails };
}
/**
Estimates the tx's gas usage
@param {Object} txMeta - the txMeta object
@returns {string} the estimated gas limit as a hex string
*/
async estimateTxGas(txMeta) {
// log.debug('estimateTxGas', { txMeta })
// const txParams = cloneDeep(txMeta.txParams);
// // `eth_estimateGas` can fail if the user has insufficient balance for the
// // value being sent, or for the gas cost. We don't want to check their
// // balance here, we just want the gas estimate. The gas price is removed
// // to skip those balance checks. We check balance elsewhere.
// delete txParams.gasPrice;
// // estimate tx gas requirements
// return await this.query.estimateGas(txParams);
const maxGasAmount = 40000000;
const gasUnitPrice = txMeta.txParams.gasPrice || 1;
const expirationTimestampSecs = await this.getExpirationTimestampSecs(txMeta.txParams);
const selectedAddressHex = txMeta.txParams.from;
const selectedPublicKeyHex = await this.getPublicKeyFor(selectedAddressHex);
if (!selectedPublicKeyHex) {
throw new Error(`Starmask: selected account's public key is null`);
}
const selectedSequenceNumber = await new Promise((resolve, reject) => {
return this.query.getResource(
txMeta.txParams.from,
'0x00000000000000000000000000000001::Account::Account',
(err, res) => {
if (err) {
return reject(err);
}
const sequence_number = res && res.value[6][1].U64 || 0;
return resolve(new BigNumber(sequence_number, 10).toNumber());
},
);
});
const chainId = txMeta.metamaskNetworkId.id;
const transactionPayload = encoding.bcsDecode(
starcoin_types.TransactionPayload,
txMeta.txParams.data,
);
const rawUserTransaction = utils.tx.generateRawUserTransaction(
selectedAddressHex,
transactionPayload,
maxGasAmount,
gasUnitPrice,
selectedSequenceNumber,
expirationTimestampSecs,
chainId,
);
const rawUserTransactionHex = encoding.bcsEncode(rawUserTransaction);
const dryRunRawResult = await new Promise((resolve, reject) => {
return this.query.dryRunRaw(
rawUserTransactionHex,
selectedPublicKeyHex,
(err, res) => {
if (err) {
return reject(err);
}
return resolve(res);
},
);
});
let estimatedGasHex;
if (dryRunRawResult.status === 'Executed') {
estimatedGasHex = new BigNumber(dryRunRawResult.gas_used, 10).toString(16);
} else {
if (typeof dryRunRawResult.status === 'string') {
throw new Error(`Starmask: contract.dry_run_raw failed. status: ${dryRunRawResult.status}, Error: ${dryRunRawResult.explained_status.Error}`)
}
throw new Error(`Starmask: contract.dry_run_raw failed. Error: ${JSON.stringify(dryRunRawResult.explained_status)}`)
}
return estimatedGasHex;
}
async getExpirationTimestampSecs(txParams) {
// because the time system in dev network is relatively static,
// we should use nodeInfo.now_secondsinstead of using new Date().getTime()
const nowSeconds = await new Promise((resolve, reject) => {
return this.query.getNodeInfo((err, res) => {
if (err) {
return reject(err);
}
return resolve(res.now_seconds);
});
});
// expired after 30 minutes since Unix Epoch by default
const expiredSecs = txParams.expiredSecs ? Number(conversionUtil(txParams.expiredSecs, {
fromNumericBase: 'hex',
toNumericBase: 'dec',
})) : 1800;
const expirationTimestampSecs = nowSeconds + expiredSecs;
return expirationTimestampSecs;
}
/**
Adds a gas buffer with out exceeding the block gas limit
@param {string} initialGasLimitHex - the initial gas limit to add the buffer too
@param {string} blockGasLimitHex - the block gas limit
@returns {string} the buffered gas limit as a hex string
*/
addGasBuffer(initialGasLimitHex, blockGasLimitHex, multiplier = 1.5) {
const initialGasLimitBn = hexToBn(initialGasLimitHex);
const blockGasLimitBn = hexToBn(blockGasLimitHex);
const upperGasLimitBn = blockGasLimitBn.muln(0.9);
const bufferedGasLimitBn = initialGasLimitBn.muln(multiplier);
// if initialGasLimit is above blockGasLimit, dont modify it
if (initialGasLimitBn.gt(upperGasLimitBn)) {
return bnToHex(initialGasLimitBn);
}
// if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
if (bufferedGasLimitBn.lt(upperGasLimitBn)) {
return bnToHex(bufferedGasLimitBn);
}
// otherwise use blockGasLimit
return bnToHex(upperGasLimitBn);
}
async getBufferedGasLimit(txMeta, multiplier) {
const {
blockGasLimit,
estimatedGasHex,
simulationFails,
} = await this.analyzeGasUsage(txMeta);
// add additional gas buffer to our estimation for safety
const gasLimit = this.addGasBuffer(
addHexPrefix(estimatedGasHex),
blockGasLimit,
multiplier,
);
return { gasLimit, simulationFails };
}
} |
JavaScript | class MatBottomSheetConfig {
constructor() {
/** Data being injected into the child component. */
this.data = null;
/** Whether the bottom sheet has a backdrop. */
this.hasBackdrop = true;
/** Whether the user can use escape or clicking outside to close the bottom sheet. */
this.disableClose = false;
/** Aria label to assign to the bottom sheet element. */
this.ariaLabel = null;
/**
* Whether the bottom sheet should close when the user goes backwards/forwards in history.
* Note that this usually doesn't include clicking on links (unless the user is using
* the `HashLocationStrategy`).
*/
this.closeOnNavigation = true;
// Note that this is disabled by default, because while the a11y recommendations are to focus
// the first focusable element, doing so prevents screen readers from reading out the
// rest of the bottom sheet content.
/** Whether the bottom sheet should focus the first focusable element on open. */
this.autoFocus = false;
/**
* Whether the bottom sheet should restore focus to the
* previously-focused element, after it's closed.
*/
this.restoreFocus = true;
}
} |
JavaScript | class Main extends React.Component {
render() {
return (
<div>
<NavBar />
<Calculate />
</div>
)
}
} |
JavaScript | class NavBar extends React.Component {
render() {
return (
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<div class="container-fluid">
<a class="navbar-brand" href="#">Card Game</a>
</div>
</nav>
)
}
} |
JavaScript | class Calculate extends React.Component {
state = { text: "" }
//get the number of people from html input
getNumOfPeople = (e) => {
event.preventDefault();
const numOfPeople = event.target.numOfPeople.value;
//fetch data from server url
fetch("./index.php/card/card_json?num=" + numOfPeople)
.then(res => { return res.text() })
.then(data => {this.setState({ text: data })});
}
render() {
return (
<main class="container">
<div class="bg-light p-5 rounded">
<h2 class="mb-3">Let's Play</h2>
<form class="needs-validation" novalidate onSubmit={(e) => {
this.getNumOfPeople(e);
}}>
<div class="input-group mb-3">
<input type="number" max="53" min="2" class="form-control" placeholder="Number of people" aria-label="Recipient's username" aria-describedby="basic-addon2" required name="numOfPeople" />
<div class="input-group-append">
<button class="btn btn-primary" type="submit">Play</button>
</div>
</div>
</form>
</div>
<div class="bg-light pl-5 pb-5 rounded">
<h5 class="pb-3"> * Spade = S, Heart = H, Diamond = D, Club = C </h5>
<span dangerouslySetInnerHTML={{ __html: this.state.text }} />
</div>
</main>
)
}
} |
JavaScript | class Queue extends Collection {
/**
* @throws {UnimplementedError} If directly instantiated.
*/
constructor() {
super();
if (this.constructor.name === 'Queue') {
throw new UnimplementedError('Queue');
}
}
/**
* Returns the maximum number of elements the queue can hold
*
* @return {number}
*/
get capacity() {
throw new UnimplementedError('get capacity');
}
/**
* Sets the maximum number of elements the queue can hold. Throws {@link IllegalArgumentError} If `capacity` is less than or equal to 0.
*
* @default Number.POSITIVE_INFINITY
*
* @throws {IllegalArgumentError} If `capacity` is less than or equal to 0.
*
* @param {number} capacity
*/
set capacity(capacity) {
throw new UnimplementedError('set capacity');
}
/**
* Returns and removes the head element of the queue
*
* @thorws {EmptyCollectionError} If the queue is empty
*
* @return {E} The head element in the queue
*/
dequeue() {
throw new UnimplementedError('dequeue');
}
/**
* Adds an element to the tail of the queue. If adding the element to the queue
* would cause its size to be grater than its capacity then the head element of the
* queue is removed.
*
* The same is true for {@link Queue#add}
*
* @param {E} element - The element to be added to the tail queue
* @return {Queue}
*/
enqueue(element) {
throw new UnimplementedError('enqueue');
}
/**
* Adds each element to the tail of the queue. If adding the element to the queue
* would cause its size to be grater than its capacity then the head element of the
* queue is removed.
*
* The same is true for {@link Queue#addAll}
*
* @param {...E} elements - The elements to be added to the queue
* @return {Queue}
*/
enqueueAll(...elements) {
throw new UnimplementedError('enqueueAll');
}
/**
* Returns but does not remove the head of the queue
*
* @thorws {EmptyCollectionError} If the queue is empty
*
* @return {E} The head element in the queue
*/
peek() {
throw new UnimplementedError('peek');
}
/**
* Returns but does not remove the tail element of the queue
*
* @thorws {EmptyCollectionError} If the queue is empty
*
* @return {E} The tail element on the queue
*/
poll() {
throw new UnimplementedError('poll');
}
} |
JavaScript | class Editor extends Component {
constructor() {
super()
this.state = {
content: '<h1>React.js 小书</h1>'
}
}
render() {
return (
<div>
<div className='editor-wrapper'>
{this.state.content}
</div>
<div className='editor-wrapper' dangerouslySetInnerHTML={{ __html: this.state.content }}>
</div>
<h1 style={{ fontSize: '16px', color: 'red' }}>
React.js 小书 in Component
</h1>
</div>
)
}
} |
JavaScript | class AppUtils {
static deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* Iterate through a class methods and binds them to itself
* @param classObj - the class object to bind
*/
static bindClassMethods(classObj) {
const prototype = classObj.constructor.prototype;
const propertyNames = Object.getOwnPropertyNames(
Object.getPrototypeOf(classObj)
);
for (const prop of propertyNames) {
if (
prop !== 'constructor' &&
typeof prototype[prop] === 'function'
) {
classObj[prop] = classObj[prop].bind(classObj);
}
}
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
tasks: [],
taskTextInput: ""
}
this.addTask = this.addTask.bind(this);
}
addTask() {
if (this.state.taskTextInput !== "") {
/* If a task whith empty text has not been passed */
Keyboard.dismiss();
let newState = this.state;
let newTask = {
completed: false,
text: this.state.taskTextInput // captures the passed text
}
newState.tasks.push(newTask);
newState.taskTextInput = ""; // reset input
this.setState(newState);
}
}
/* Funcion responsible for rendering task list */
_renderTaskList() {
let tasksView = this.state.tasks.map((task, key) => {
return (<Task text={task.text} completed={task.completed} key={key} />)
});
return tasksView;
}
render() {
return (
<Container>
<SimpleHeader />
<Content>
<Form>
<Item regular>
<Input
placeholder="Nova Tarefa"
onChangeText={(taskTextInput) => this.setState({ taskTextInput: taskTextInput })}
value={this.state.taskTextInput}
/>
</Item>
<Button onPress={this.addTask} success full>
<Text>Adicionar</Text>
</Button>
</Form>
<ScrollView>
{
this._renderTaskList()
}
</ScrollView>
</Content>
</Container>
);
}
} |
JavaScript | class EventListener {
constructor() {
this.events = [];
}
removeListener(kind, scope, func) {
if (this.events[kind] == null) {
return;
}
let scopeFunctions = null;
let i;
for (i = 0; i < this.events[kind].length; i++) {
if (this.events[kind][i].scope === scope) {
scopeFunctions = this.events[kind][i];
break;
}
}
if (scopeFunctions == null) {
return;
}
for (i = 0; i < scopeFunctions.functions.length; i++) {
if (scopeFunctions.functions[i] === func) {
scopeFunctions.functions.splice(i, 1);
return;
}
}
}
addListener(kind, scope, func) {
if (this.events[kind] === undefined) {
this.events[kind] = [];
}
let i;
let scopeFunctions = null;
for (i = 0; i < this.events[kind].length; i++) {
if (this.events[kind][i].scope === scope) {
scopeFunctions = this.events[kind][i];
break;
}
}
if (scopeFunctions === null) {
this.events[kind].push({ scope: scope, functions: [] });
scopeFunctions = this.events[kind][this.events[kind].length - 1];
}
for (i = 0; i < scopeFunctions.functions.length; i++) {
if (scopeFunctions.functions[i] === func) {
return;
}
}
scopeFunctions.functions.push(func);
}
fireEvent(kind, event) {
// TODO: Should add a deep clone here ...
if (this.events[kind] !== undefined) {
for (let i = 0; i < this.events[kind].length; i++) {
const objects = this.events[kind][i];
const functs = objects.functions;
const scope = objects.scope;
for (let j = 0; j < functs.length; j++) {
const func = functs[j];
func.call(scope, event);
}
}
}
}
} |
JavaScript | class Parser {
constructor (options) {
this.options = options;
this.uniqueNodeId = 1;
this.root = null;
this.version = null;
this.nodes = {};
this.models = new Common.Map();
this.handlers = new Common.Map();
}
// loads and parses a scenario
async init() {
if (!this.options.graph) {
try {
var graph = await this.options.loadScenario(this.options.scenario);
return await this.normalizeGraph(graph);
}
catch(err) {
console.error(`error loading scenario. options: ${util.inspect(this.options)}, error: ${util.inspect(err)}`);
throw new Error(`Error loading scenario '${this.options.scenario}': ${err.message}`);
}
}
// graph was provided
return await this.normalizeGraph(this.options.graph);
}
// gets a node instance by its Id
getNodeInstanceById(id) {
var node = this.nodes[id];
return node && node._instance;
}
// normalize the graph
async normalizeGraph(origGraph) {
try {
// create a copy of the graph object
var graph = {};
extend(true, graph, origGraph);
console.log('loading scenario:', graph.id);
this.updateModels(graph.models);
await this.recursive(graph);
// first iteration- create Node instances
var nodes = this.nodes;
for (var nodeId in nodes) {
var node = nodes[nodeId];
var inst = new Node(node, node.type);
node._instance = inst;
}
// second iteration- connect reference to Node instances
for (var nodeId in nodes) {
var node = nodes[nodeId];
var inst = node._instance;
if (node._parent) inst.parent = node._parent._instance;
if (node._prev) inst.prev = node._prev._instance;
if (node._next) inst.next = node._next._instance;
for (let step of node.steps || []) {
inst.steps.add(step._instance);
}
for (let scenario of node.scenarios || []) {
var scene = new Scenario( scenario.condition,
scenario.nodeId ? this.nodes[scenario.nodeId]._instance : null);
for (let step of scenario.steps || []) {
scene.steps.add(step._instance);
};
inst.scenarios.add(scene);
}
}
// third iteration- remove unneccessary data/references
for (var nodeId in nodes) {
var node = nodes[nodeId];
var inst = node._instance;
delete node._visited;
delete node._parent;
delete node._prev;
delete node._next;
}
this.root = graph._instance;
this.version = graph.version || this.calculateHash(JSON.stringify(origGraph));
}
catch(err) {
console.error(`error normalizing graph: ${util.inspect(origGraph)}, error: ${util.inspect(err)}`);
throw new Error(`Error normalizing graph '${util.inspect(origGraph)}': ${err.message}`);
}
}
// initialize a node in the graph
async initNode(parent, nodes, nodeItem, index) {
try {
if (nodeItem._visited) return;
nodeItem._visited = true;
nodeItem.id = nodeItem.id || `_node_${this.uniqueNodeId++}`;
if (parent) nodeItem._parent = parent;
if (index > 0) nodeItem._prev = nodes[index - 1];
if (nodes.length > index + 1) nodeItem._next = nodes[index + 1];
if (this.isSubScenario(nodeItem)) {
console.log("sub-scenario for node: " + nodeItem.id + " [embedding sub scenario: " + nodeItem.subScenario + "]");
var scenarioObj = await this.options.loadScenario(nodeItem.subScenario);
extend(true, nodeItem, scenarioObj);
this.updateModels(scenarioObj.models);
console.log('node:', nodeItem.id, nodeItem._parent && nodeItem._parent.id ? '[parent: ' + nodeItem._parent.id + ']' : '', nodeItem._next && nodeItem._next.id ? '[next: ' + nodeItem._next.id + ']' : '', nodeItem._prev && nodeItem._prev.id ? '[prev: ' + nodeItem._prev.id + ']' : '');
return this.recursive(nodeItem);
}
if (nodeItem.type === 'handler') {
var handler = nodeItem.data.name || '';
console.log("loading handler for node: " + nodeItem.id + " [embedding sub scenario: " + handler + "]");
var jsCode = null;
if (nodeItem.data.js) {
var content = nodeItem.data.js;
if (Array.isArray(content))
jsCode = content.join('\n');
}
else {
try {
jsCode = await this.options.loadHandler(handler);
}
catch(err) {
console.error(`error loading handler: ${handler}: error: ${err.message}`);
}
}
var func = this.getHandlerFunc(jsCode);
if (!func) {
console.error(`error loading handler ${handler}: js code: ${jsCode}`);
throw new Error(`error loading handler ${handler}: js code: ${jsCode}`);
}
this.handlers.add(handler, func);
}
console.log('node:', nodeItem.id, nodeItem._parent && nodeItem._parent.id ? '[parent: ' + nodeItem._parent.id + ']' : '', nodeItem._next && nodeItem._next.id ? '[next: ' + nodeItem._next.id + ']' : '', nodeItem._prev && nodeItem._prev.id ? '[prev: ' + nodeItem._prev.id + ']' : '');
await this.recursive(nodeItem);
}
catch(err) {
console.error(`error initNode: ${util.inspect(arguments)}, error: ${util.inspect(err)}`);
throw new Error(`Error initNode'${util.inspect(node)}': ${err.message}`);
}
}
// initialize a collecton of nodes
async initNodes(parent, nodes = []) {
for (var i=0; i<nodes.length; i++)
await this.initNode(parent, nodes, nodes[i], i);
}
// recursively init a node and its childrens
async recursive(node) {
node.id = node.id || `_node_${this.uniqueNodeId++}`;
await this.initNodes(null, [node]);
await this.initNodes(node, node.steps);
// althogh this is slower than using the following command:
// await Promise.all((node.scenarios || []).map(async scenario => await this.initNodes(node, scenario.steps)));
// it keeps the order of the calls such that it waits for a call the end before invoking the next one.
// this is what we want to do, since the order is important.
for (let scenario of node.scenarios || []) {
await this.initNodes(node, scenario.steps);
}
this.nodes[node.id] = node;
}
// checks if this is a sub-scenario node
isSubScenario(nodeItem) {
if (!nodeItem.subScenario) return false;
var parent = nodeItem._parent;
while (parent) {
if (nodeItem.subScenario === parent.id) {
console.error(`recursive subScenario found: ${nodeItem.subScenario}`);
throw new Error(`recursive subScenario found: ${nodeItem.subScenario}`);
}
parent = parent._parent;
}
return true;
}
// gets a handler function from a string
getHandlerFunc(funcText) {
var text = `(() => {
return module => {
${funcText}
}
})()`;
var wrapperFunc = eval(text);
var m = {};
wrapperFunc(m);
return typeof m.exports === 'function' ? m.exports : null;
}
// updates the internal LUIS models collection
updateModels(models = []) {
for (let model of models) {
this.models.add(model.name, new Luis.LuisModel(model.name, model.url));
}
}
// calculates hash of an input text
calculateHash(text) {
return crypto.createHash('md5').update(text).digest('hex');
}
} |
JavaScript | class SVConfig {
constructor() {
/**
* 间距,默认:`32`
*/
this.gutter = 32;
/**
* 布局,默认:`horizontal`
*/
this.layout = 'horizontal';
/**
* 列数,默认:`3`
*/
this.col = 3;
/**
* 是否显示默认值,当内容为空值时显示 `-`,默认:`true`
*/
this.default = true;
/**
* `label` 固定宽度,若 `null` 或 `undefined` 表示非固定,默认:`null`
*/
this.labelWidth = null;
}
} |
JavaScript | class Food extends GameObject {
constructor(x,y) {
super(x, y, true, document.getElementById('apple'));
this.color = 'red';
}
//Specific update method for all instances of Food class. If destroyed,
// food disappears and appears on different spot
update() {
if (this.isDestroyed) {
this.position.X = Helper.getRandomPositionX(0, Helper.FieldSize.WIDTH - this.size.WIDTH);
this.position.Y = Helper.getRandomPositionY(0, Helper.FieldSize.HEIGHT - this.size.HEIGHT);
this.isDestroyed = false;
}
}
} |
JavaScript | class RgbRamp {
constructor(ramp) {
this.ramp = ramp;
}
at(factor) {
const at = Math.min(this.ramp.length - 1, this.ramp.length * factor);
return this.ramp[at];
}
} |
JavaScript | class Client {
/**
* Primary entry point for building a new Client.
*/
static buildClient(config, fetchFunction) {
const newConfig = new Config(config);
const client = new Client(newConfig, GraphQLJSClient, fetchFunction);
client.config = newConfig;
return client;
}
/**
* @constructs Client
* @param {Config} config An instance of {@link Config} used to configure the Client.
*/
constructor(config, GraphQLClientClass = GraphQLJSClient, fetchFunction) {
const url = `https://${config.domain}/api/${config.apiVersion}/graphql`;
const headers = {
'X-SDK-Variant': 'javascript',
'X-SDK-Version': version,
'X-Shopify-Storefront-Access-Token': config.storefrontAccessToken
};
if (config.source) {
headers['X-SDK-Variant-Source'] = config.source;
}
const languageHeader = config.language ? config.language : '*';
headers['Accept-Language'] = languageHeader;
if (fetchFunction) {
headers['Content-Type'] = 'application/json';
headers.Accept = 'application/json';
this.graphQLClient = new GraphQLClientClass(types, {
fetcher: function fetcher(graphQLParams) {
return fetchFunction(url, {
body: JSON.stringify(graphQLParams),
method: 'POST',
mode: 'cors',
headers
}).then((response) => response.json());
}
});
} else {
this.graphQLClient = new GraphQLClientClass(types, {
url,
fetcherOptions: {headers}
});
}
this.product = new ProductResource(this.graphQLClient);
this.collection = new CollectionResource(this.graphQLClient);
this.shop = new ShopResource(this.graphQLClient);
this.checkout = new CheckoutResource(this.graphQLClient);
this.image = new ImageResource(this.graphQLClient);
this.customer = new CustomerResource(this.graphQLClient);
}
/**
* Fetches the next page of models
*
* @example
* client.fetchNextPage(products).then((nextProducts) => {
* // Do something with the products
* });
*
* @param {models} [Array] The paginated set to fetch the next page of
* @return {Promise|GraphModel[]} A promise resolving with an array of `GraphModel`s of the type provided.
*/
fetchNextPage(models) {
return this.graphQLClient.fetchNextPage(models);
}
} |
JavaScript | class Workflow extends internal_1.Saveable {
constructor({ extensionFields, loadingOptions, id, class_, label, doc, inputs, outputs, requirements, hints, cwlVersion, intent, steps }) {
super();
this.extensionFields = extensionFields !== null && extensionFields !== void 0 ? extensionFields : {};
this.loadingOptions = loadingOptions !== null && loadingOptions !== void 0 ? loadingOptions : new internal_1.LoadingOptions({});
this.id = id;
this.class_ = class_;
this.label = label;
this.doc = doc;
this.inputs = inputs;
this.outputs = outputs;
this.requirements = requirements;
this.hints = hints;
this.cwlVersion = cwlVersion;
this.intent = intent;
this.steps = steps;
}
/**
* Used to construct instances of {@link Workflow }.
*
* @param __doc Document fragment to load this record object from.
* @param baseuri Base URI to generate child document IDs against.
* @param loadingOptions Context for loading URIs and populating objects.
* @param docRoot ID at this position in the document (if available)
* @returns An instance of {@link Workflow }
* @throws {@link ValidationException} If the document fragment is not a
* {@link Dictionary} or validation of fields fails.
*/
static fromDoc(__doc, baseuri, loadingOptions, docRoot) {
return __awaiter(this, void 0, void 0, function* () {
const _doc = Object.assign({}, __doc);
const __errors = [];
let id;
if ('id' in _doc) {
try {
id = yield (0, internal_1.loadField)(_doc.id, internal_1.LoaderInstances.uriunionOfundefinedtypeOrstrtypeTrueFalseNone, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `id` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
const originalidIsUndefined = (id === undefined);
if (originalidIsUndefined) {
if (docRoot != null) {
id = docRoot;
}
else {
id = "_" + (0, uuid_1.v4)();
}
}
else {
baseuri = id;
}
let class_;
try {
class_ = yield (0, internal_1.loadField)(_doc.class, internal_1.LoaderInstances.uriWorkflow_classLoaderFalseTrueNone, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `class` field is not valid because: ', [e]));
}
else {
throw e;
}
}
let label;
if ('label' in _doc) {
try {
label = yield (0, internal_1.loadField)(_doc.label, internal_1.LoaderInstances.unionOfundefinedtypeOrstrtype, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `label` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let doc;
if ('doc' in _doc) {
try {
doc = yield (0, internal_1.loadField)(_doc.doc, internal_1.LoaderInstances.unionOfundefinedtypeOrstrtypeOrarrayOfstrtype, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `doc` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let inputs;
try {
inputs = yield (0, internal_1.loadField)(_doc.inputs, internal_1.LoaderInstances.idmapinputsarrayOfWorkflowInputParameterLoader, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `inputs` field is not valid because: ', [e]));
}
else {
throw e;
}
}
let outputs;
try {
outputs = yield (0, internal_1.loadField)(_doc.outputs, internal_1.LoaderInstances.idmapoutputsarrayOfWorkflowOutputParameterLoader, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `outputs` field is not valid because: ', [e]));
}
else {
throw e;
}
}
let requirements;
if ('requirements' in _doc) {
try {
requirements = yield (0, internal_1.loadField)(_doc.requirements, internal_1.LoaderInstances.idmaprequirementsunionOfundefinedtypeOrarrayOfunionOfInlineJavascriptRequirementLoaderOrSchemaDefRequirementLoaderOrLoadListingRequirementLoaderOrDockerRequirementLoaderOrSoftwareRequirementLoaderOrInitialWorkDirRequirementLoaderOrEnvVarRequirementLoaderOrShellCommandRequirementLoaderOrResourceRequirementLoaderOrWorkReuseLoaderOrNetworkAccessLoaderOrInplaceUpdateRequirementLoaderOrToolTimeLimitLoaderOrSubworkflowFeatureRequirementLoaderOrScatterFeatureRequirementLoaderOrMultipleInputFeatureRequirementLoaderOrStepInputExpressionRequirementLoader, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `requirements` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let hints;
if ('hints' in _doc) {
try {
hints = yield (0, internal_1.loadField)(_doc.hints, internal_1.LoaderInstances.idmaphintsunionOfundefinedtypeOrarrayOfanyType, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `hints` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let cwlVersion;
if ('cwlVersion' in _doc) {
try {
cwlVersion = yield (0, internal_1.loadField)(_doc.cwlVersion, internal_1.LoaderInstances.uriunionOfundefinedtypeOrCWLVersionLoaderFalseTrueNone, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `cwlVersion` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let intent;
if ('intent' in _doc) {
try {
intent = yield (0, internal_1.loadField)(_doc.intent, internal_1.LoaderInstances.uriunionOfundefinedtypeOrarrayOfstrtypeTrueFalseNone, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `intent` field is not valid because: ', [e]));
}
else {
throw e;
}
}
}
let steps;
try {
steps = yield (0, internal_1.loadField)(_doc.steps, internal_1.LoaderInstances.idmapstepsunionOfarrayOfWorkflowStepLoader, baseuri, loadingOptions);
}
catch (e) {
if (e instanceof internal_1.ValidationException) {
__errors.push(new internal_1.ValidationException('the `steps` field is not valid because: ', [e]));
}
else {
throw e;
}
}
const extensionFields = {};
for (const [key, value] of Object.entries(_doc)) {
if (!Workflow.attr.has(key)) {
if (key.includes(':')) {
const ex = (0, internal_1.expandUrl)(key, '', loadingOptions, false, false);
extensionFields[ex] = value;
}
else {
__errors.push(new internal_1.ValidationException(`invalid field ${key}, \
expected one of: \`id\`,\`label\`,\`doc\`,\`inputs\`,\`outputs\`,\`requirements\`,\`hints\`,\`cwlVersion\`,\`intent\`,\`class\`,\`steps\``));
break;
}
}
}
if (__errors.length > 0) {
throw new internal_1.ValidationException("Trying 'Workflow'", __errors);
}
const schema = new Workflow({
extensionFields: extensionFields,
loadingOptions: loadingOptions,
id: id,
label: label,
doc: doc,
inputs: inputs,
outputs: outputs,
requirements: requirements,
hints: hints,
cwlVersion: cwlVersion,
intent: intent,
class_: class_,
steps: steps
});
return schema;
});
}
save(top = false, baseUrl = '', relativeUris = true) {
const r = {};
for (const ef in this.extensionFields) {
r[(0, internal_1.prefixUrl)(ef, this.loadingOptions.vocab)] = this.extensionFields.ef;
}
if (this.id != null) {
const u = (0, internal_1.saveRelativeUri)(this.id, baseUrl, true, relativeUris, undefined);
if (u != null) {
r.id = u;
}
}
if (this.class_ != null) {
const u = (0, internal_1.saveRelativeUri)(this.class_, this.id, false, relativeUris, undefined);
if (u != null) {
r.class = u;
}
}
if (this.label != null) {
r.label = (0, internal_1.save)(this.label, false, this.id, relativeUris);
}
if (this.doc != null) {
r.doc = (0, internal_1.save)(this.doc, false, this.id, relativeUris);
}
if (this.inputs != null) {
r.inputs = (0, internal_1.save)(this.inputs, false, this.id, relativeUris);
}
if (this.outputs != null) {
r.outputs = (0, internal_1.save)(this.outputs, false, this.id, relativeUris);
}
if (this.requirements != null) {
r.requirements = (0, internal_1.save)(this.requirements, false, this.id, relativeUris);
}
if (this.hints != null) {
r.hints = (0, internal_1.save)(this.hints, false, this.id, relativeUris);
}
if (this.cwlVersion != null) {
const u = (0, internal_1.saveRelativeUri)(this.cwlVersion, this.id, false, relativeUris, undefined);
if (u != null) {
r.cwlVersion = u;
}
}
if (this.intent != null) {
const u = (0, internal_1.saveRelativeUri)(this.intent, this.id, true, relativeUris, undefined);
if (u != null) {
r.intent = u;
}
}
if (this.steps != null) {
r.steps = (0, internal_1.save)(this.steps, false, this.id, relativeUris);
}
if (top) {
if (this.loadingOptions.namespaces != null) {
r.$namespaces = this.loadingOptions.namespaces;
}
if (this.loadingOptions.schemas != null) {
r.$schemas = this.loadingOptions.schemas;
}
}
return r;
}
} |
JavaScript | class UniversalWallet {
/**
*
* @class UniversalWallet
*
* @param agent - aries agent.
* @param user - unique wallet user identifier, the one used to create wallet profile.
*
*/
constructor({agent, user} = {}) {
this.agent = agent
this.user = user
}
/**
* Unlocks given wallet's key manager instance & content store and
* returns a authorization token to be used for performing wallet operations.
*
* @param {Object} options
* @param {String} options.localKMSPassphrase - (optional) passphrase for local kms for key operations.
* @param {Object} options.webKMSAuth - (optional) WebKMSAuth for authorizing access to web/remote kms.
* @param {String} options.webKMSAuth.authToken - (optional) Http header 'authorization' bearer token to be used, i.e access token.
* @param {String} options.webKMSAuth.capability - (optional) Capability if ZCAP sign header feature to be used for authorizing access.
* @param {String} options.webKMSAuth.authzKeyStoreURL - (optional) authz key store URL if ZCAP sign header feature to be used for authorizing access.
* @param {String} options.webKMSAuth.secretShare - (optional) secret share if ZCAP sign header feature to be used for authorizing access.
* @param {Object} options.edvUnlocks - (optional) for authorizing access to wallet's EDV content store.
* @param {String} options.edvUnlocks.authToken - (optional) Http header 'authorization' bearer token to be used, i.e access token.
* @param {String} options.edvUnlocks.capability - (optional) Capability if ZCAP sign header feature to be used for authorizing access.
* @param {String} options.edvUnlocks.authzKeyStoreURL - (optional) authz key store URL if ZCAP sign header feature to be used for authorizing access.
* @param {String} options.edvUnlocks.secretShare - (optional) secret share if ZCAP sign header feature to be used for authorizing access.
* @param {Time} options.expiry - (optional) time duration in milliseconds for which this profile will be unlocked.
*
* @returns {Promise<Object>} - 'object.token' - auth token subsequent use of wallet features.
*/
async open({localKMSPassphrase, webKMSAuth, edvUnlocks, expiry} = {}) {
return await this.agent.vcwallet.open({userID: this.user, localKMSPassphrase, webKMSAuth, edvUnlocks, expiry})
}
/**
* Expires token issued to this VC wallet, removes wallet's key manager instance and closes wallet content store.
*
* @returns {Promise<Object>} - 'object.closed' - bool flag false if token is not found or already expired for this wallet user.
*/
async close() {
return await this.agent.vcwallet.close({userID: this.user})
}
/**
* Adds given content to wallet content store.
*
* @param {Object} request
* @param {String} request.auth - authorization token for performing this wallet operation.
* @param {Object} request.contentType - type of the content to be added to the wallet, refer aries vc wallet for supported types.
* @param {String} request.content - content to be added wallet store.
* @param {String} request.collectionID - (optional) ID of the wallet collection to which the content should belong.
*
* @returns {Promise<Object>} - empty promise or an error if adding content to wallet store fails.
*/
async add({auth, contentType, content = {}, collectionID} = {}) {
return await this.agent.vcwallet.add({userID: this.user, auth, contentType, collectionID, content})
}
/**
* remove given content from wallet content store.
*
* @param {Object} request
* @param {String} request.auth - authorization token for performing this wallet operation.
* @param {Object} request.contentType - type of the content to be removed from the wallet.
* @param {String} request.contentID - id of the content to be removed from wallet.
*
* @returns {Promise<Object>} - empty promise or an error if operation fails.
*/
async remove({auth = '', contentType = '', contentID = ''} = {}) {
return await this.agent.vcwallet.remove({userID: this.user, auth, contentType, contentID})
}
/**
* gets wallet content by ID from wallet content store.
*
* @param {Object} request
* @param {String} request.auth - authorization token for performing this wallet operation.
* @param {Object} request.contentType - type of the content to be removed from the wallet.
* @param {String} request.contentID - id of the content to be returned from wallet.
*
* @returns {Promise<Object>} - promise containing content or an error if operation fails.
*/
async get({auth = '', contentType = '', contentID = ''} = {}) {
return await this.agent.vcwallet.get({userID: this.user, auth, contentType, contentID})
}
/**
* gets all wallet contents from wallet content store for given type.
*
* @param {Object} request
* @param {String} request.auth - authorization token for performing this wallet operation.
* @param {Object} request.contentType - type of the contents to be returned from wallet.
* @param {String} request.collectionID - id of the collection on which the response contents to be filtered.
*
* @returns {Promise<Object>} - promise containing response contents or an error if operation fails.
*/
async getAll({auth, contentType, collectionID} = {}) {
return await this.agent.vcwallet.getAll({userID: this.user, auth, contentType, collectionID})
}
/**
* runs credential queries against wallet credential contents.
*
* @param {String} auth - authorization token for performing this wallet operation.
* @param {Object} query - credential query, refer: https://w3c-ccg.github.io/vp-request-spec/#format
*
* @returns {Promise<Object>} - promise of presentation(s) containing credential results or an error if operation fails.
*/
async query(auth = '', query = []) {
return await this.agent.vcwallet.query({userID: this.user, auth, query})
}
/**
* runs credential queries against wallet credential contents.
*
* @param {String} auth - authorization token for performing this wallet operation.
* @param {Object} credential - credential to be signed from wallet.
* @param {Object} proofOptions - proof options for issuing credential.
* @param {String} proofOptions.controller - DID to be used for signing.
* @param {String} proofOptions.verificationMethod - (optional) VerificationMethod is the URI of the verificationMethod used for the proof.
* By default, Controller public key matching 'assertion' for issue or 'authentication' for prove functions.
* @param {String} proofOptions.created - (optional) Created date of the proof.
* By default, current system time will be used.
* @param {String} proofOptions.domain - (optional) operational domain of a digital proof.
* By default, domain will not be part of proof.
* @param {String} proofOptions.challenge - (optional) random or pseudo-random value option authentication.
* By default, challenge will not be part of proof.
* @param {String} proofOptions.proofType - (optional) signature type used for signing.
* By default, proof will be generated in Ed25519Signature2018 format.
* @param {String} proofOptions.proofRepresentation - (optional) type of proof data expected ( "proofValue" or "jws").
* By default, 'proofValue' will be used.
*
* @returns {Promise<Object>} - promise of credential issued or an error if operation fails.
*/
async issue(auth = '', credential = {}, proofOptions = {}) {
return await this.agent.vcwallet.issue({
userID: this.user,
auth,
credential,
proofOptions
})
}
/**
* produces a Verifiable Presentation from wallet.
*
* @param {String} auth - authorization token for performing this wallet operation.
* @param {Object} credentialOptions - credential/presentations to verify..
* @param {Array<string>} credentialOptions.storedCredentials - (optional) ids of the credentials already saved in wallet content store.
* @param {Array<Object>} credentialOptions.rawCredentials - (optional) list of raw credentials to be presented.
* @param {Object} credentialOptions.presentation - (optional) presentation to be proved.
* @param {Object} proofOptions - proof options for issuing credential.
* @param {String} proofOptions.controller - DID to be used for signing.
* @param {String} proofOptions.verificationMethod - (optional) VerificationMethod is the URI of the verificationMethod used for the proof.
* By default, Controller public key matching 'assertion' for issue or 'authentication' for prove functions.
* @param {String} proofOptions.created - (optional) Created date of the proof.
* By default, current system time will be used.
* @param {String} proofOptions.domain - (optional) operational domain of a digital proof.
* By default, domain will not be part of proof.
* @param {String} proofOptions.challenge - (optional) random or pseudo-random value option authentication.
* By default, challenge will not be part of proof.
* @param {String} proofOptions.proofType - (optional) signature type used for signing.
* By default, proof will be generated in Ed25519Signature2018 format.
* @param {String} proofOptions.proofRepresentation - (optional) type of proof data expected ( "proofValue" or "jws").
* By default, 'proofValue' will be used.
*
* @returns {Promise<Object>} - promise of signed presentation or an error if operation fails.
*/
async prove(auth = '', {storedCredentials = [], rawCredentials = [], presentation = {}} = {},
proofOptions = {}) {
return await this.agent.vcwallet.prove({
userID: this.user,
auth,
storedCredentials,
rawCredentials,
presentation,
proofOptions
})
}
/**
* verifies credential/presentation from wallet.
*
* @param {String} auth - authorization token for performing this wallet operation.
* @param {String} verificationOption - credential/presentation to be verified.
* @param {String} verificationOption.storedCredentialID - (optional) id of the credential already saved in wallet content store.
* @param {Object} verificationOption.rawCredential - (optional) credential to be verified.
* @param {Object} verificationOption.presentation - (optional) presentation to be verified.
*
* @returns {Promise<Object>} - promise of verification result(bool) and error containing cause if verification fails.
*/
async verify(auth = '', {storedCredentialID = '', rawCredential = {}, presentation = {}} = {}) {
return await this.agent.vcwallet.verify({
userID: this.user,
auth,
storedCredentialID,
rawCredential,
presentation
})
}
/**
* derives a credential from wallet.
*
* @param {String} auth - authorization token for performing this wallet operation.
*
* @param {String} credentialOption - credential to be dervied.
* @param {String} credentialOption.storedCredentialID - (optional) id of the credential already saved in wallet content store.
* @param {Object} credentialOption.rawCredential - (optional) credential to be derived.
*
* @param {Object} deriveOption - derive options.
* @param {Object} deriveOption.frame - JSON-LD frame used for derivation.
* @param {String} deriveOption.nonce - (optional) to prove uniqueness or freshness of the proof..
*
* @returns {Promise<Object>} - promise of derived credential or error if operation fails.
*/
async derive(auth = '', {storedCredentialID = '', rawCredential = {}}, deriveOption = {}) {
return await this.agent.vcwallet.derive({
userID: this.user,
auth,
storedCredentialID,
rawCredential,
deriveOption
})
}
/**
* creates a key pair from wallet.
*
* @param {Object} request
* @param {String} request.auth - authorization token for performing this wallet operation.
* @param {String} request.keyType - type of the key to be created, refer aries kms for supported key types.
*
* @returns {Promise<Object>} - promise of derived credential or error if operation fails.
*/
async createKeyPair(auth, {keyType} = {}) {
return await this.agent.vcwallet.createKeyPair({
userID: this.user,
auth,
keyType
})
}
} |
JavaScript | class DragDrop extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'DragDrop';
}
/**
* @inheritDoc
*/
static get requires() {
return [ ClipboardPipeline, Widget ];
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const view = editor.editing.view;
/**
* The live range over the original content that is being dragged.
*
* @private
* @type {module:engine/model/liverange~LiveRange}
*/
this._draggedRange = null;
/**
* The UID of current dragging that is used to verify if the drop started in the same editor as the drag start.
*
* **Note**: This is a workaround for broken 'dragend' events (they are not fired if the source text node got removed).
*
* @private
* @type {String}
*/
this._draggingUid = '';
/**
* The reference to the model element that currently has a `draggable` attribute set (it is set while dragging).
*
* @private
* @type {module:engine/model/element~Element}
*/
this._draggableElement = null;
/**
* A throttled callback updating the drop marker.
*
* @private
* @type {Function}
*/
this._updateDropMarkerThrottled = throttle( targetRange => this._updateDropMarker( targetRange ), 40 );
/**
* A delayed callback removing the drop marker.
*
* @private
* @type {Function}
*/
this._removeDropMarkerDelayed = delay( () => this._removeDropMarker(), 40 );
/**
* A delayed callback removing draggable attributes.
*
* @private
* @type {Function}
*/
this._clearDraggableAttributesDelayed = delay( () => this._clearDraggableAttributes(), 40 );
view.addObserver( ClipboardObserver );
view.addObserver( MouseObserver );
this._setupDragging();
this._setupContentInsertionIntegration();
this._setupClipboardInputIntegration();
this._setupDropMarker();
this._setupDraggableAttributeHandling();
this.listenTo( editor, 'change:isReadOnly', ( evt, name, isReadOnly ) => {
if ( isReadOnly ) {
this.forceDisabled( 'readOnlyMode' );
} else {
this.clearForceDisabled( 'readOnlyMode' );
}
} );
this.on( 'change:isEnabled', ( evt, name, isEnabled ) => {
if ( !isEnabled ) {
this._finalizeDragging( false );
}
} );
if ( env.isAndroid ) {
this.forceDisabled( 'noAndroidSupport' );
}
}
/**
* @inheritDoc
*/
destroy() {
if ( this._draggedRange ) {
this._draggedRange.detach();
this._draggedRange = null;
}
this._updateDropMarkerThrottled.cancel();
this._removeDropMarkerDelayed.cancel();
this._clearDraggableAttributesDelayed.cancel();
return super.destroy();
}
/**
* Drag and drop events handling.
*
* @private
*/
_setupDragging() {
const editor = this.editor;
const model = editor.model;
const modelDocument = model.document;
const view = editor.editing.view;
const viewDocument = view.document;
// The handler for the drag start; it is responsible for setting data transfer object.
this.listenTo( viewDocument, 'dragstart', ( evt, data ) => {
const selection = modelDocument.selection;
// Don't drag the editable element itself.
if ( data.target && data.target.is( 'editableElement' ) ) {
data.preventDefault();
return;
}
// TODO we could clone this node somewhere and style it to match editing view but without handles,
// selection outline, WTA buttons, etc.
// data.dataTransfer._native.setDragImage( data.domTarget, 0, 0 );
// Check if this is dragstart over the widget (but not a nested editable).
const draggableWidget = data.target ? findDraggableWidget( data.target ) : null;
if ( draggableWidget ) {
const modelElement = editor.editing.mapper.toModelElement( draggableWidget );
this._draggedRange = LiveRange.fromRange( model.createRangeOn( modelElement ) );
// Disable toolbars so they won't obscure the drop area.
if ( editor.plugins.has( 'WidgetToolbarRepository' ) ) {
editor.plugins.get( 'WidgetToolbarRepository' ).forceDisabled( 'dragDrop' );
}
}
// If this was not a widget we should check if we need to drag some text content.
else if ( !viewDocument.selection.isCollapsed ) {
const selectedElement = viewDocument.selection.getSelectedElement();
if ( !selectedElement || !isWidget( selectedElement ) ) {
this._draggedRange = LiveRange.fromRange( selection.getFirstRange() );
}
}
if ( !this._draggedRange ) {
data.preventDefault();
return;
}
this._draggingUid = uid();
data.dataTransfer.effectAllowed = this.isEnabled ? 'copyMove' : 'copy';
data.dataTransfer.setData( 'application/ckeditor5-dragging-uid', this._draggingUid );
const draggedSelection = model.createSelection( this._draggedRange.toRange() );
const content = editor.data.toView( model.getSelectedContent( draggedSelection ) );
viewDocument.fire( 'clipboardOutput', { dataTransfer: data.dataTransfer, content, method: evt.name } );
if ( !this.isEnabled ) {
this._draggedRange.detach();
this._draggedRange = null;
this._draggingUid = '';
}
}, { priority: 'low' } );
// The handler for finalizing drag and drop. It should always be triggered after dragging completes
// even if it was completed in a different application.
// Note: This is not fired if source text node got removed while downcasting a marker.
this.listenTo( viewDocument, 'dragend', ( evt, data ) => {
this._finalizeDragging( !data.dataTransfer.isCanceled && data.dataTransfer.dropEffect == 'move' );
}, { priority: 'low' } );
// Dragging over the editable.
this.listenTo( viewDocument, 'dragenter', () => {
if ( !this.isEnabled ) {
return;
}
view.focus();
} );
// Dragging out of the editable.
this.listenTo( viewDocument, 'dragleave', () => {
// We do not know if the mouse left the editor or just some element in it, so let us wait a few milliseconds
// to check if 'dragover' is not fired.
this._removeDropMarkerDelayed();
} );
// Handler for moving dragged content over the target area.
this.listenTo( viewDocument, 'dragging', ( evt, data ) => {
if ( !this.isEnabled ) {
data.dataTransfer.dropEffect = 'none';
return;
}
this._removeDropMarkerDelayed.cancel();
const targetRange = findDropTargetRange( editor, data.targetRanges, data.target );
// If this is content being dragged from another editor, moving out of current editor instance
// is not possible until 'dragend' event case will be fixed.
if ( !this._draggedRange ) {
data.dataTransfer.dropEffect = 'copy';
}
// In Firefox it is already set and effect allowed remains the same as originally set.
if ( !env.isGecko ) {
if ( data.dataTransfer.effectAllowed == 'copy' ) {
data.dataTransfer.dropEffect = 'copy';
} else if ( [ 'all', 'copyMove' ].includes( data.dataTransfer.effectAllowed ) ) {
data.dataTransfer.dropEffect = 'move';
}
}
/* istanbul ignore else */
if ( targetRange ) {
this._updateDropMarkerThrottled( targetRange );
}
}, { priority: 'low' } );
}
/**
* Integration with the `clipboardInput` event.
*
* @private
*/
_setupClipboardInputIntegration() {
const editor = this.editor;
const view = editor.editing.view;
const viewDocument = view.document;
// Update the event target ranges and abort dropping if dropping over itself.
this.listenTo( viewDocument, 'clipboardInput', ( evt, data ) => {
if ( data.method != 'drop' ) {
return;
}
const targetRange = findDropTargetRange( editor, data.targetRanges, data.target );
// The dragging markers must be removed after searching for the target range because sometimes
// the target lands on the marker itself.
this._removeDropMarker();
/* istanbul ignore if */
if ( !targetRange ) {
this._finalizeDragging( false );
evt.stop();
return;
}
// Since we cannot rely on the drag end event, we must check if the local drag range is from the current drag and drop
// or it is from some previous not cleared one.
if ( this._draggedRange && this._draggingUid != data.dataTransfer.getData( 'application/ckeditor5-dragging-uid' ) ) {
this._draggedRange.detach();
this._draggedRange = null;
this._draggingUid = '';
}
// Do not do anything if some content was dragged within the same document to the same position.
const isMove = getFinalDropEffect( data.dataTransfer ) == 'move';
if ( isMove && this._draggedRange && this._draggedRange.containsRange( targetRange, true ) ) {
this._finalizeDragging( false );
evt.stop();
return;
}
// Override the target ranges with the one adjusted to the best one for a drop.
data.targetRanges = [ editor.editing.mapper.toViewRange( targetRange ) ];
}, { priority: 'high' } );
}
/**
* Integration with the `contentInsertion` event of the clipboard pipeline.
*
* @private
*/
_setupContentInsertionIntegration() {
const clipboardPipeline = this.editor.plugins.get( ClipboardPipeline );
clipboardPipeline.on( 'contentInsertion', ( evt, data ) => {
if ( !this.isEnabled || data.method !== 'drop' ) {
return;
}
// Update the selection to the target range in the same change block to avoid selection post-fixing
// and to be able to clone text attributes for plain text dropping.
const ranges = data.targetRanges.map( viewRange => this.editor.editing.mapper.toModelRange( viewRange ) );
this.editor.model.change( writer => writer.setSelection( ranges ) );
}, { priority: 'high' } );
clipboardPipeline.on( 'contentInsertion', ( evt, data ) => {
if ( !this.isEnabled || data.method !== 'drop' ) {
return;
}
// Remove dragged range content, remove markers, clean after dragging.
const isMove = getFinalDropEffect( data.dataTransfer ) == 'move';
// Whether any content was inserted (insertion might fail if the schema is disallowing some elements
// (for example an image caption allows only the content of a block but not blocks themselves.
// Some integrations might not return valid range (i.e., table pasting).
const isSuccess = !data.resultRange || !data.resultRange.isCollapsed;
this._finalizeDragging( isSuccess && isMove );
}, { priority: 'lowest' } );
}
/**
* Adds listeners that add the `draggable` attribute to the elements while the mouse button is down so the dragging could start.
*
* @private
*/
_setupDraggableAttributeHandling() {
const editor = this.editor;
const view = editor.editing.view;
const viewDocument = view.document;
// Add the 'draggable' attribute to the widget while pressing the selection handle.
// This is required for widgets to be draggable. In Chrome it will enable dragging text nodes.
this.listenTo( viewDocument, 'mousedown', ( evt, data ) => {
// The lack of data can be caused by editor tests firing fake mouse events. This should not occur
// in real-life scenarios but this greatly simplifies editor tests that would otherwise fail a lot.
if ( env.isAndroid || !data ) {
return;
}
this._clearDraggableAttributesDelayed.cancel();
// Check if this is a mousedown over the widget (but not a nested editable).
let draggableElement = findDraggableWidget( data.target );
// Note: There is a limitation that if more than a widget is selected (a widget and some text)
// and dragging starts on the widget, then only the widget is dragged.
// If this was not a widget then we should check if we need to drag some text content.
// In Chrome set a 'draggable' attribute on closest editable to allow immediate dragging of the selected text range.
// In Firefox this is not needed. In Safari it makes the whole editable draggable (not just textual content).
// Disabled in read-only mode because draggable="true" + contenteditable="false" results
// in not firing selectionchange event ever, which makes the selection stuck in read-only mode.
if ( env.isBlink && !editor.isReadOnly && !draggableElement && !viewDocument.selection.isCollapsed ) {
const selectedElement = viewDocument.selection.getSelectedElement();
if ( !selectedElement || !isWidget( selectedElement ) ) {
draggableElement = viewDocument.selection.editableElement;
}
}
if ( draggableElement ) {
view.change( writer => {
writer.setAttribute( 'draggable', 'true', draggableElement );
} );
// Keep the reference to the model element in case the view element gets removed while dragging.
this._draggableElement = editor.editing.mapper.toModelElement( draggableElement );
}
} );
// Remove the draggable attribute in case no dragging started (only mousedown + mouseup).
this.listenTo( viewDocument, 'mouseup', () => {
if ( !env.isAndroid ) {
this._clearDraggableAttributesDelayed();
}
} );
}
/**
* Removes the `draggable` attribute from the element that was used for dragging.
*
* @private
*/
_clearDraggableAttributes() {
const editing = this.editor.editing;
editing.view.change( writer => {
// Remove 'draggable' attribute.
if ( this._draggableElement && this._draggableElement.root.rootName != '$graveyard' ) {
writer.removeAttribute( 'draggable', editing.mapper.toViewElement( this._draggableElement ) );
}
this._draggableElement = null;
} );
}
/**
* Creates downcast conversion for the drop target marker.
*
* @private
*/
_setupDropMarker() {
const editor = this.editor;
// Drop marker conversion for hovering over widgets.
editor.conversion.for( 'editingDowncast' ).markerToHighlight( {
model: 'drop-target',
view: {
classes: [ 'ck-clipboard-drop-target-range' ]
}
} );
// Drop marker conversion for in text drop target.
editor.conversion.for( 'editingDowncast' ).markerToElement( {
model: 'drop-target',
view: ( data, { writer } ) => {
const inText = editor.model.schema.checkChild( data.markerRange.start, '$text' );
if ( !inText ) {
return;
}
return writer.createUIElement( 'span', { class: 'ck ck-clipboard-drop-target-position' }, function( domDocument ) {
const domElement = this.toDomElement( domDocument );
// Using word joiner to make this marker as high as text and also making text not break on marker.
domElement.innerHTML = '⁠<span></span>⁠';
return domElement;
} );
}
} );
}
/**
* Updates the drop target marker to the provided range.
*
* @private
* @param {module:engine/model/range~Range} targetRange The range to set the marker to.
*/
_updateDropMarker( targetRange ) {
const editor = this.editor;
const markers = editor.model.markers;
editor.model.change( writer => {
if ( markers.has( 'drop-target' ) ) {
if ( !markers.get( 'drop-target' ).getRange().isEqual( targetRange ) ) {
writer.updateMarker( 'drop-target', { range: targetRange } );
}
} else {
writer.addMarker( 'drop-target', {
range: targetRange,
usingOperation: false,
affectsData: false
} );
}
} );
}
/**
* Removes the drop target marker.
*
* @private
*/
_removeDropMarker() {
const model = this.editor.model;
this._removeDropMarkerDelayed.cancel();
this._updateDropMarkerThrottled.cancel();
if ( model.markers.has( 'drop-target' ) ) {
model.change( writer => {
writer.removeMarker( 'drop-target' );
} );
}
}
/**
* Deletes the dragged content from its original range and clears the dragging state.
*
* @private
* @param {Boolean} moved Whether the move succeeded.
*/
_finalizeDragging( moved ) {
const editor = this.editor;
const model = editor.model;
this._removeDropMarker();
this._clearDraggableAttributes();
if ( editor.plugins.has( 'WidgetToolbarRepository' ) ) {
editor.plugins.get( 'WidgetToolbarRepository' ).clearForceDisabled( 'dragDrop' );
}
this._draggingUid = '';
if ( !this._draggedRange ) {
return;
}
// Delete moved content.
if ( moved && this.isEnabled ) {
model.deleteContent( model.createSelection( this._draggedRange ), { doNotAutoparagraph: true } );
}
this._draggedRange.detach();
this._draggedRange = null;
}
} |
JavaScript | class UpdateCuratedEntities extends ServiceBase {
/**
* Constructor to insert/update entries in curated entities.
*
* @param {object} params
* @param {object} params.current_admin
* @param {string} params.entity_kind
* @param {number} params.entity_id
* @param {string} params.position
*
* @augments ServiceBase
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.currentAdminId = params.current_admin.id;
oThis.entityKind = params.entity_kind;
oThis.entityId = +params.entity_id;
oThis.newPosition = params.position;
}
/**
* Async perform.
*
* @returns {Promise<result>}
* @private
*/
async _asyncPerform() {
const oThis = this;
await oThis.validateAndSanitize();
await oThis.fetchExistingEntities();
await oThis.logAdminActivity();
return responseHelper.successWithData({});
}
/**
* Validate and sanitize input parameters.
*
* @returns {Promise<never>}
*/
async validateAndSanitize() {
const oThis = this;
switch (oThis.entityKind) {
case curatedEntitiesConstants.userEntityKind: {
await oThis.fetchAndValidateUser();
break;
}
case curatedEntitiesConstants.tagsEntityKind: {
await oThis.fetchAndValidateTag();
break;
}
case curatedEntitiesConstants.channelsEntityKind: {
await oThis.fetchAndValidateChannel();
break;
}
default: {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_a_c_i_1',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['invalid_entity_kind'],
debug_options: { entityKind: oThis.entityKind }
})
);
}
}
}
/**
* Fetch existing entities.
*
* @returns {Promise<never>}
*/
async fetchExistingEntities() {
const oThis = this;
const cacheResponse = await new CuratedEntityIdsByKindCache({ entityKind: oThis.entityKind }).fetch();
if (!cacheResponse || cacheResponse.isFailure()) {
return Promise.reject(cacheResponse);
}
const entityIdsArray = cacheResponse.data.entityIds;
if (entityIdsArray.indexOf(oThis.entityId) === -1) {
// If entityId does not exists in the curated entities table, insert new entry.
await new CuratedEntityModel().insertIntoCuratedEntity(oThis.entityId, oThis.entityKind, oThis.newPosition);
} else {
// If entityId already exists in the curated entities table, update its position.
await new CuratedEntityModel().updatePositionForCuratedEntity(
oThis.entityId,
oThis.entityKind,
oThis.newPosition
);
}
}
/**
* Log admin activity.
*
* @returns {Promise<void>}
* @private
*/
async logAdminActivity() {
const oThis = this;
await new AdminActivityLogModel().insertAction({
adminId: oThis.currentAdminId,
actionOn: oThis.entityId,
extraData: JSON.stringify({ eids: [oThis.entityId], enk: oThis.entityKind }),
action: adminActivityLogConstants.updateCuratedEntity
});
}
/**
* Fetch and validate user.
*
* @returns {Promise<never>}
*/
async fetchAndValidateUser() {
const oThis = this;
const userDetailsCacheResponse = await new UserCache({ ids: [oThis.entityId] }).fetch();
if (userDetailsCacheResponse.isFailure()) {
return Promise.reject(userDetailsCacheResponse);
}
const userObj = userDetailsCacheResponse.data[oThis.entityId];
if (!CommonValidators.validateNonEmptyObject(userObj)) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_a_c_i_2',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['invalid_entity_id'],
debug_options: { entityId: oThis.entityId }
})
);
}
if (userObj.status !== userConstants.activeStatus) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_a_c_i_4',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['user_not_active'],
debug_options: {}
})
);
}
}
/**
* Fetch and validate tag.
*
* @returns {Promise<never>}
*/
async fetchAndValidateTag() {
const oThis = this;
const tagsCacheResponse = await new TagMultiCache({ ids: [oThis.entityId] }).fetch();
if (tagsCacheResponse.isFailure()) {
return Promise.reject(tagsCacheResponse);
}
const tagData = tagsCacheResponse.data[oThis.entityId];
if (!CommonValidators.validateNonEmptyObject(tagData) || tagData.status !== tagConstants.activeStatus) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_a_c_i_3',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['invalid_entity_id'],
debug_options: { entityId: oThis.entityId }
})
);
}
}
/**
* Fetch and validate channel.
*
* @returns {Promise<never>}
*/
async fetchAndValidateChannel() {
const oThis = this;
const channelByIdsCacheResponse = await new ChannelByIdsCache({ ids: [oThis.entityId] }).fetch();
if (channelByIdsCacheResponse.isFailure()) {
return Promise.reject(channelByIdsCacheResponse);
}
const channelObj = channelByIdsCacheResponse.data[oThis.entityId];
if (!CommonValidators.validateNonEmptyObject(channelObj) || channelObj.status !== channelsConstants.activeStatus) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_c_u_j_fc_1',
api_error_identifier: 'invalid_api_params',
params_error_identifiers: ['channel_not_active'],
debug_options: {
channelId: oThis.channelId
}
})
);
}
}
} |
JavaScript | class UnrecoverableError extends Error {
constructor(message) {
super('Unrecoverable! '+ message);
}
} |
JavaScript | class Tm2 extends Device {
constructor(dev) {
super(dev);
}
/**
* Enter the given device into loopback operation mode that uses the given file as input for
* raw data
* @param {String} file Path to bag file with raw data for loopback
* @return {undefined}
*/
enableLoopback(file) {
const funcName = 'Tm2.enableLoopback()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkFileExistence(file);
this.cxxDev.enableLoopback(file);
}
/**
* Restores the given device into normal operation mode
* @return {undefined}
*/
disableLoopback() {
this.cxxDev.disableLoopback();
}
/**
* Checks if the device is in loopback mode or not
* @return {Boolean}
*/
get loopbackEnabled() {
return this.cxxDev.isLoopbackEnabled();
}
/**
* Connects to a given tm2 controller
* @param {ArrayBuffer} macAddress The MAC address of the desired controller
* @return {undefined}
*/
connectController(macAddress) {
const funcName = 'Tm2.connectController()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'ArrayBuffer', 0, funcName);
this.cxxDev.connectController(macAddress);
}
/**
* Disconnects a given tm2 controller
* @param {Integer} id The ID of the desired controller
* @return {undefined}
*/
disconnectController(id) {
const funcName = 'Tm2.disconnectController()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'integer', 0, funcName);
this.cxxDev.disconnectController(id);
}
} |
JavaScript | class StreamProfile {
constructor(cxxProfile) {
this.cxxProfile = cxxProfile;
this.streamValue = this.cxxProfile.stream();
this.formatValue = this.cxxProfile.format();
this.fpsValue = this.cxxProfile.fps();
this.indexValue = this.cxxProfile.index();
this.uidValue = this.cxxProfile.uniqueID();
this.isDefaultValue = this.cxxProfile.isDefault();
}
/**
* Get stream index the input profile in case there are multiple streams of the same type
*
* @return {Integer}
*/
get streamIndex() {
return this.indexValue;
}
/**
* Get stream type
*
* @return {Integer}
*/
get streamType() {
return this.streamValue;
}
/**
* Get binary data format
*
* @return {Integer}
*/
get format() {
return this.formatValue;
}
/**
* Expected rate for data frames to arrive, meaning expected number of frames per second
*
* @return {Integer}
*/
get fps() {
return this.fpsValue;
}
/**
* Get the identifier for the stream profile, unique within the application
*
* @return {Integer}
*/
get uniqueID() {
return this.uidValue;
}
/**
* Returns non-zero if selected profile is recommended for the sensor
* This is an optional hint we offer to suggest profiles with best performance-quality tradeof
*
* @return {Boolean}
*/
get isDefault() {
return this.isDefaultValue;
}
/**
* Extrinsics:
* @typedef {Object} ExtrinsicsObject
* @property {Float32[]} rotation - Array(9), Column-major 3x3 rotation matrix
* @property {Float32[]} translation - Array(3), Three-element translation vector, in meters
* @see [StreamProfile.getExtrinsicsTo()]{@link StreamProfile#getExtrinsicsTo}
*/
/**
* Get extrinsics from a this stream to the target stream
*
* @param {StreamProfile} toProfile the target stream profile
* @return {ExtrinsicsObject}
*/
getExtrinsicsTo(toProfile) {
const funcName = 'StreamProfile.getExtrinsicsTo()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, StreamProfile, 0, funcName);
return this.cxxProfile.getExtrinsicsTo(toProfile.cxxProfile);
}
destroy() {
if (this.cxxProfile) {
this.cxxProfile.destroy();
this.cxxProfile = undefined;
}
}
static _internalCreateStreamProfile(cxxProfile) {
if (cxxProfile.isMotionProfile()) {
return new MotionStreamProfile(cxxProfile);
} else if (cxxProfile.isVideoProfile()) {
return new VideoStreamProfile(cxxProfile);
} else {
return new StreamProfile(cxxProfile);
}
}
} |
JavaScript | class MotionStreamProfile extends StreamProfile {
constructor(cxxProfile) {
super(cxxProfile);
}
/**
* Returns scale and bias of a motion stream.
* @return {MotionIntrinsics} {@link MotionIntrinsics}
*/
getMotionIntrinsics() {
return this.cxxProfile.getMotionIntrinsics();
}
} |
JavaScript | class DeviceList {
constructor(cxxList) {
this.cxxList = cxxList;
internal.addObject(this);
}
/**
* Release resources associated with the object
*/
destroy() {
if (this.cxxList) {
this.cxxList.destroy();
this.cxxList = undefined;
}
}
/**
* Checks if a specific device is contained inside a device list.
*
* @param {Device} device the camera to be checked
* @return {Boolean} true if the camera is contained in the list, otherwise false
*/
contains(device) {
const funcName = 'DeviceList.contains()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Device, 0, funcName);
return this.cxxList.contains(device.cxxDev);
}
/**
* Creates a device by index. The device object represents a physical camera and provides the
* means to manipulate it.
*
* @param {Integer} index the zero based index of the device in the device list
* @return {Device|undefined}
*/
getDevice(index) {
const funcName = 'DeviceList.getDevice()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName, 0, this.size);
let dev = this.cxxList.getDevice(index);
return dev ? Device._internalCreateDevice(dev) : undefined;
}
get devices() {
let len = this.cxxList.size();
if (!len) {
return undefined;
}
let output = [];
for (let i = 0; i < len; i++) {
output[i] = Device._internalCreateDevice(this.cxxList.getDevice(i));
}
return output;
}
/**
* Determines number of devices in a list.
* @return {Integer}
*/
get size() {
return this.cxxList.size();
}
/**
* Get the first device
* @return {Device|undefined}
*/
get front() {
return this.getDevice(0);
}
/**
* Get the last device
* @return {Device|undefined}
*/
get back() {
if (this.size > 0) {
return this.getDevice(this.size - 1);
}
return undefined;
}
} |
JavaScript | class Sensor extends Options {
/**
* Construct a Sensor object, representing a RealSense camera subdevice
* By default, native resources associated with a Sensor object are freed
* automatically during cleanup.
*/
constructor(cxxSensor, autoDelete = true) {
super(cxxSensor);
this.cxxSensor = cxxSensor;
this._events = new EventEmitter();
if (autoDelete === true) {
internal.addObject(this);
}
}
/**
* Check if everything is OK, e.g. if the device object is connected to underlying hardware
* @return {Boolean}
*/
get isValid() {
return (this.cxxSensor !== null);
}
/**
* Open subdevice for exclusive access, by committing to a configuration.
* There are 2 acceptable forms of syntax:
* <pre><code>
* Syntax 1. open(streamProfile)
* Syntax 2. open(profileArray)
* </code></pre>
* Syntax 2 is for opening multiple profiles in one function call and should be used for
* interdependent streams, such as depth and infrared, that have to be configured together.
*
* @param {StreamProfile} streamProfile configuration commited by the device
* @param {StreamProfile[]} profileArray configurations array commited by the device
* @see [Sensor.getStreamProfiles]{@link Sensor#getStreamProfiles} for a list of all supported
* stream profiles
*/
open(streamProfile) {
const funcName = 'Sensor.open()';
checkArgumentLength(1, 1, arguments.length, funcName);
if (Array.isArray(streamProfile) && streamProfile.length > 0) {
let cxxStreamProfiles = [];
for (let i = 0; i < streamProfile.length; i++) {
if (!(streamProfile[i] instanceof StreamProfile)) {
throw new TypeError(
'Sensor.open() expects a streamProfile object or an array of streamProfile objects'); // eslint-disable-line
}
cxxStreamProfiles.push(streamProfile[i].cxxProfile);
}
this.cxxSensor.openMultipleStream(cxxStreamProfiles);
} else {
checkArgumentType(arguments, StreamProfile, 0, funcName);
this.cxxSensor.openStream(streamProfile.cxxProfile);
}
}
/**
* Check if specific camera info is supported
* @param {String|Integer} info - info type to query. See {@link camera_info} for available values
* @return {Boolean|undefined} Returns undefined if an invalid info type was specified.
* @see enum {@link camera_info}
*/
supportsCameraInfo(info) {
const funcName = 'Sensor.supportsCameraInfo()';
checkArgumentLength(1, 1, arguments.length, funcName);
const i = checkArgumentType(arguments, constants.camera_info, 0, funcName);
return this.cxxSensor.supportsCameraInfo(i);
}
/**
* Get camera information of the sensor
*
* @param {String|Integer} info - the camera_info type, see {@link camera_info} for available
* values
* @return {String|undefined}
*/
getCameraInfo(info) {
const funcName = 'Sensor.getCameraInfo()';
checkArgumentLength(1, 1, arguments.length, funcName);
const i = checkArgumentType(arguments, constants.camera_info, 0, funcName);
return (this.cxxSensor.supportsCameraInfo(i) ? this.cxxSensor.getCameraInfo(i) : undefined);
}
/**
* Stops any streaming and close subdevice.
* @return {undefined} No return value
*/
close() {
this.cxxSensor.close();
}
/**
* Delete the resource for accessing the subdevice. The device would not be accessable from
* this object after the operation.
* @return {undefined} No return value
*/
destroy() {
this._events = null;
if (this.cxxSensor) {
this.cxxSensor.destroy();
this.cxxSensor = undefined;
}
}
/**
* This callback is called when a frame is captured
* @callback FrameCallback
* @param {Frame} frame - The captured frame
*
* @see [Sensor.start]{@link Sensor#start}
*/
/**
* Start passing frames into user provided callback
* There are 2 acceptable syntax:
* <pre><code>
* Syntax 1. start(callback)
* Syntax 2. start(Syncer)
* </code></pre>
*
* @param {FrameCallback} callback
* @param {Syncer} syncer, the syncer to synchronize frames
*
* @example <caption>Simply do logging when a frame is captured</caption>
* sensor.start((frame) => {
* console.log(frame.timestamp, frame.frameNumber, frame.data);
* });
*
*/
start(callback) {
const funcName = 'Sensor.start()';
checkArgumentLength(1, 1, arguments.length, funcName);
if (arguments[0] instanceof Syncer) {
this.cxxSensor.startWithSyncer(arguments[0].cxxSyncer, false, 0);
} else {
checkArgumentType(arguments, 'function', 0, funcName);
// create object to hold frames generated from native.
this.frame = new Frame();
this.depthFrame = new DepthFrame();
this.videoFrame = new VideoFrame();
this.disparityFrame = new DisparityFrame();
this.motionFrame = new MotionFrame();
this.poseFrame = new PoseFrame();
let inst = this;
this.cxxSensor.frameCallback = function() {
// When the callback is triggered, the underlying frame bas been saved in the objects
// created above, we need to update it and callback.
if (inst.disparityFrame.isValid) {
inst.disparityFrame.updateProfile();
callback(inst.disparityFrame);
} else if (inst.depthFrame.isValid) {
inst.depthFrame.updateProfile();
callback(inst.depthFrame);
} else if (inst.videoFrame.isValid) {
inst.videoFrame.updateProfile();
callback(inst.videoFrame);
} else if (inst.motionFrame.isValid) {
inst.motionFrame.updateProfile();
callback(inst.motionFrame);
} else if (inst.poseFrame.isValid) {
inst.poseFrame.updateProfile();
callback(inst.poseFrame);
} else {
inst.frame.updateProfile();
callback(inst.frame);
}
};
this.cxxSensor.startWithCallback('frameCallback', this.frame.cxxFrame,
this.depthFrame.cxxFrame, this.videoFrame.cxxFrame, this.disparityFrame.cxxFrame,
this.motionFrame.cxxFrame, this.poseFrame.cxxFrame);
}
}
/**
* stop streaming
* @return {undefined} No return value
*/
stop() {
if (this.cxxSensor) {
this.cxxSensor.stop();
}
if (this.frame) this.frame.release();
if (this.videoFrame) this.videoFrame.release();
if (this.depthFrame) this.depthFrame.release();
}
/**
* @typedef {Object} NotificationEventObject
* @property {String} descr - The human readable literal description of the notification
* @property {Float} timestamp - The timestamp of the notification
* @property {String} severity - The severity of the notification
* @property {String} category - The category of the notification
* @property {String} serializedData - The serialized data of the notification
*/
/**
* This callback is called when there is a device notification
* @callback NotificationCallback
* @param {NotificationEventObject} info
* @param {String} info.descr - See {@link NotificationEventObject} for details
* @param {Float} info.timestamp - See {@link NotificationEventObject} for details
* @param {String} info.severity - See {@link NotificationEventObject} for details
* @param {String} info.category - See {@link NotificationEventObject} for details
* @param {String} info.serializedData - See {@link NotificationEventObject} for details
*
* @see {@link NotificationEventObject}
* @see [Sensor.setNotificationsCallback()]{@link Sensor#setNotificationsCallback}
*/
/**
* @event Sensor#notification
* @param {NotificationEventObject} evt
* @param {String} evt.descr - See {@link NotificationEventObject} for details
* @param {Float} evt.timestamp - See {@link NotificationEventObject} for details
* @param {String} evt.severity - See {@link NotificationEventObject} for details
* @param {String} evt.category - See {@link NotificationEventObject} for details
* @param {String} evt.serializedData - See {@link NotificationEventObject} for details
* @see {@link NotificationEventObject}
* @see [Sensor.setNotificationsCallback()]{@link Sensor#setNotificationsCallback}
*/
/**
* register notifications callback
* @param {NotificationCallback} callback The user-provied notifications callback
* @see {@link NotificationEventObject}
* @see [Sensor 'notification']{@link Sensor#event:notification} event
* @return {undefined}
*/
setNotificationsCallback(callback) {
const funcName = 'Sensor.setNotificationsCallback()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'function', 0, funcName);
this._events.on('notification', (info) => {
callback(info);
});
let inst = this;
if (!this.cxxSensor.notificationCallback) {
this.cxxSensor.notificationCallback = function(info) {
// convert the severity and category properties from numbers to strings to be
// consistent with documentation which are more meaningful to users
info.severity = log_severity.logSeverityToString(info.severity);
info.category = notification_category.notificationCategoryToString(info.category);
inst._events.emit('notification', info);
};
this.cxxSensor.setNotificationCallback('notificationCallback');
}
return undefined;
}
/**
* Get a list of stream profiles that given subdevice can provide. The returned profiles should be
* destroyed by calling its destroy() method.
*
* @return {StreamProfile[]} all of the supported stream profiles
* See {@link StreamProfile}
*/
getStreamProfiles() {
let profiles = this.cxxSensor.getStreamProfiles();
if (profiles) {
const array = [];
profiles.forEach((profile) => {
array.push(StreamProfile._internalCreateStreamProfile(profile));
});
return array;
}
}
} |
JavaScript | class ROISensor extends Sensor {
/**
* Create a ROISensor out of another sensor
* @param {Sensor} sensor a sensor object
* @return {ROISensor|undefined} return a ROISensor if the sensor can be
* treated as a ROISensor, otherwise return undefined.
*/
static from(sensor) {
if (sensor.cxxSensor.isROISensor()) {
return new ROISensor(sensor.cxxSensor);
}
return undefined;
}
/**
* Construct a ROISensor object, representing a RealSense camera subdevice
* The newly created ROISensor object shares native resources with the sensor
* argument. So the new object shouldn't be freed automatically to make
* sure resources released only once during cleanup.
*/
constructor(cxxSensor) {
super(cxxSensor, false);
}
/**
* @typedef {Object} RegionOfInterestObject
* @property {Float32} minX - lower horizontal bound in pixels
* @property {Float32} minY - lower vertical bound in pixels
* @property {Float32} maxX - upper horizontal bound in pixels
* @property {Float32} maxY - upper vertical bound in pixels
* @see [Device.getRegionOfInterest()]{@link Device#getRegionOfInterest}
*/
/**
* Get the active region of interest to be used by auto-exposure algorithm.
* @return {RegionOfInterestObject|undefined} Returns undefined if failed
* @see {@link RegionOfInterestObject}
*/
getRegionOfInterest() {
return this.cxxSensor.getRegionOfInterest();
}
/**
* Set the active region of interest to be used by auto-exposure algorithm
* There are 2 acceptable forms of syntax:
* <pre><code>
* Syntax 1. setRegionOfInterest(region)
* Syntax 2. setRegionOfInterest(minX, minY, maxX, maxY)
* </code></pre>
*
* @param {RegionOfInterestObject} region - the region of interest to be used.
* @param {Float32} region.minX - see {@link RegionOfInterestObject} for details.
* @param {Float32} region.minY - see {@link RegionOfInterestObject} for details.
* @param {Float32} region.maxX - see {@link RegionOfInterestObject} for details.
* @param {Float32} region.maxY - see {@link RegionOfInterestObject} for details.
*
* @param {Float32} minX - see {@link RegionOfInterestObject} for details.
* @param {Float32} minY - see {@link RegionOfInterestObject} for details.
* @param {Float32} maxX - see {@link RegionOfInterestObject} for details.
* @param {Float32} maxY - see {@link RegionOfInterestObject} for details.
*/
setRegionOfInterest(region) {
const funcName = 'ROISensor.setRegionOfInterest()';
checkArgumentLength(1, 4, arguments.length, funcName);
let minX;
let minY;
let maxX;
let maxY;
if (arguments.length === 1) {
checkArgumentType(arguments, 'object', 0, funcName);
minX = region.minX;
minY = region.minY;
maxX = region.maxX;
maxY = region.maxY;
} else if (arguments.length === 4) {
checkArgumentType(arguments, 'number', 0, funcName);
checkArgumentType(arguments, 'number', 1, funcName);
checkArgumentType(arguments, 'number', 2, funcName);
checkArgumentType(arguments, 'number', 3, funcName);
minX = arguments[0];
minY = arguments[1];
maxX = arguments[2];
maxY = arguments[3];
} else {
throw new TypeError(
'setRegionOfInterest(region) expects a RegionOfInterestObject as argument');
}
this.cxxSensor.setRegionOfInterest(minX, minY, maxX, maxY);
}
} |
JavaScript | class Context {
/**
* There are only one acceptable form of syntax to create a Context for users:
* <pre><code>
* new Context();
* </code></pre>
* other forms are reserved for internal use only.
*/
constructor(cxxCtx) {
const funcName = 'Context.constructor()';
// Internal code will create Context with cxxObject or other params
checkDiscreteArgumentLength([0, 1, 3, 4], arguments.length, funcName);
this._events = new EventEmitter();
if (arguments.length === 0) {
this.cxxCtx = new RS2.RSContext();
this.cxxCtx.create();
} else if (arguments.length === 1) {
checkArgumentType(arguments, RS2.RSContext, 0, funcName);
this.cxxCtx = cxxCtx;
} else {
checkArgumentType(arguments, 'string', 0, funcName);
checkDiscreteArgumentValue(arguments, 0, ['recording', 'playback'], funcName);
this.cxxCtx = new (Function.prototype.bind.apply(
RS2.RSContext, [null].concat(Array.from(arguments))))();
this.cxxCtx.create();
}
this.cxxCtx._events = this._events;
internal.addContext(this);
}
/**
* Cleanup underlying C++ context, and release all resources that were created by this context.
* The JavaScript Context object(s) will not be garbage-collected without call(s) to this function
*/
destroy() {
if (this.cxxCtx) {
this.cxxCtx.destroy();
this.cxxCtx = undefined;
internal.cleanupContext();
}
}
/**
* Get the events object of EventEmitter
* @return {EventEmitter}
*/
get events() {
return this._events;
}
/**
* Create a static snapshot of all connected devices at the time of the call
* @return {DeviceList|undefined} connected devices at the time of the call
*/
queryDevices() {
let list = this.cxxCtx.queryDevices();
return (list ? new DeviceList(list) : undefined);
}
/**
* Generate an array of all available sensors from all RealSense devices
* @return {Sensor[]|undefined}
*/
querySensors() {
let devList = this.queryDevices();
if (!devList) {
return undefined;
}
let devices = devList.devices;
if (devices && devices.length) {
const array = [];
devices.forEach((dev) => {
const sensors = dev.querySensors();
sensors.forEach((sensor) => {
array.push(sensor);
});
});
return array;
}
return undefined;
}
/**
* Get the device from one of its sensors
*
* @param {Sensor} sensor
* @return {Device|undefined}
*/
getSensorParent(sensor) {
const funcName = 'Context.getSensorParent()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Sensor, 0, funcName);
let cxxDev = this.cxxCtx.createDeviceFromSensor(sensor.cxxSensor);
if (!cxxDev) {
return undefined;
}
return Device._internalCreateDevice(cxxDev);
}
/**
* When one or more devices are plugged or unplugged into the system
* @event Context#device-changed
* @param {DeviceList} removed - The devices removed from the system
* @param {DeviceList} added - The devices added to the system
*/
/**
* This callback is called when number of devices is changed
* @callback devicesChangedCallback
* @param {DeviceList} removed - The devices removed from the system
* @param {DeviceList} added - The devices added to the system
*
* @see [Context.setDevicesChangedCallback]{@link Context#setDevicesChangedCallback}
*/
/**
* Register a callback function to receive device-changed notification
* @param {devicesChangedCallback} callback - devices changed callback
*/
setDevicesChangedCallback(callback) {
const funcName = 'Context.setDevicesChangedCallback()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'function', 0, funcName);
this._events.on('device-changed', (removed, added) => {
callback(removed, added);
});
let inst = this;
if (!this.cxxCtx.deviceChangedCallback) {
this.cxxCtx.deviceChangedCallback = function(removed, added) {
let rmList = (removed ? new DeviceList(removed) : undefined);
let addList = (added ? new DeviceList(added) : undefined);
inst._events.emit('device-changed', rmList, addList);
};
this.cxxCtx.setDevicesChangedCallback('deviceChangedCallback');
}
}
/**
* Create a PlaybackDevice to playback recored data file.
*
* @param {String} file - the file path
* @return {PlaybackDevice|undefined}
*/
loadDevice(file) {
const funcName = 'Context.loadDevice()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkFileExistence(file);
const cxxDev = this.cxxCtx.loadDeviceFile(file);
if (!cxxDev) {
return undefined;
}
return new PlaybackDevice(cxxDev, true);
}
/**
* Removes a PlaybackDevice from the context, if exists
*
* @param {String} file The file name that was loaded to create the playback device
*/
unloadDevice(file) {
const funcName = 'Context.unloadDevice()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkFileExistence(file);
this.cxxCtx.unloadDeviceFile(file);
}
} |
JavaScript | class RecordingContext extends Context {
/**
* @param {String} fileName The file name to store the recorded data
* @param {String} section The section name within the recording
* @param {String|Integer} mode Recording mode, default to 'blank-frames'
* @see [enum recording_mode]{@link recording_mode}
*/
constructor(fileName, section = '', mode = 'blank-frames') {
const funcName = 'RecordingContext.constructor()';
checkArgumentLength(1, 3, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkArgumentType(arguments, 'string', 1, funcName);
let m = checkArgumentType(arguments, constants.recording_mode, 2, funcName);
m = (m === undefined ? recordingMode2Int(mode) : m);
super('recording', fileName, section, m);
}
} |
JavaScript | class PlaybackContext extends Context {
/**
* @param {String} fileName The file name of the recording
* @param {String} section The section name used in recording
*/
constructor(fileName, section = '') {
const funcName = 'PlaybackContext.constructor()';
checkArgumentLength(1, 2, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkArgumentType(arguments, 'string', 1, funcName);
checkFileExistence(fileName);
super('playback', fileName, section);
}
} |
JavaScript | class RecorderDevice extends Device {
/**
* Create a RecorderDevice from another device
*
* @param {Device} device another existing device
* @return {RecorderDevice|undefined} If the the input device can be
* converted to a RecorderDevice, return the newly created RecorderDevice,
* otherwise, undefined is returned.
*/
static from(device) {
return device.cxxDev.isRecorder() ?
new RecorderDevice(null, null, device.cxxDev, false) : undefined;
}
/**
* @param {String} file the file name to store the recorded data
* @param {Device} device the actual device to be recorded
*/
constructor(file, device, cxxDev = undefined, autoDelete = true) {
const funcName = 'RecorderDevice.constructor()';
checkArgumentLength(2, 4, arguments.length, funcName);
if (arguments[0] && arguments[1]) {
checkArgumentType(arguments, 'string', 0, funcName);
checkArgumentType(arguments, Device, 1, funcName);
} else if (arguments[2]) {
checkArgumentType(arguments, 'object', 2, funcName);
checkArgumentType(arguments, 'boolean', 3, funcName);
} else {
throw new TypeError('Invalid parameters for new RecorderDevice()');
}
super(cxxDev ? cxxDev : device.cxxDev.spawnRecorderDevice(file), autoDelete);
}
/**
* Pause the recording device without stopping the actual device from streaming.
*/
pause() {
this.cxxDev.pauseRecord();
}
/**
* Resume the recording
*/
resume() {
this.cxxDev.resumeRecord();
}
/**
* Gets the name of the file to which the recorder is writing
* @return {String}
*/
get fileName() {
return this.cxxDev.getFileName();
}
} |
JavaScript | class PlaybackDevice extends Device {
/**
* Create a PlaybackDevice from another device
*
* @param {Device} device another existing device that can be converted to a
* PlaybackDevice
* @return {PlaybackDevice|undefined} If the the input device can be
* converted to a PlaybackDevice, return the newly created PlaybackDevice,
* otherwise, undefined is returned.
*/
static from(device) {
return device.cxxDev.isPlayback() ?
new PlaybackDevice(device.cxxDev, false) : undefined;
}
constructor(cxxdevice, autoDelete) {
super(cxxdevice, autoDelete);
this._events = new EventEmitter();
}
/**
* Pauses the playback
* Calling pause() in "paused" status does nothing
* If pause() is called while playback status is "playing" or "stopped", the playback will not
* play until resume() is called
* @return {undefined}
*/
pause() {
this.cxxDev.pausePlayback();
}
/**
* Resumes the playback
* Calling resume() while playback status is "playing" or "stopped" does nothing
* @return {undefined}
*/
resume() {
this.cxxDev.resumePlayback();
}
/**
* Stops playback
* @return {undefined}
*/
stop() {
this.cxxDev.stopPlayback();
}
/**
* Retrieves the name of the playback file
* @return {String}
*/
get fileName() {
return this.cxxDev.getFileName();
}
/**
* Retrieves the current position of the playback in the file in terms of time. Unit is
* millisecond
* @return {Integer}
*/
get position() {
return this.cxxDev.getPosition();
}
/**
* Retrieves the total duration of the file, unit is millisecond.
* @return {Integer}
*/
get duration() {
return this.cxxDev.getDuration();
}
/**
* Sets the playback to a specified time point of the played data
* @param {time} time the target time to seek to, unit is millisecond
* @return {undefined}
*/
seek(time) {
const funcName = 'PlaybackDevice.seek()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName);
this.cxxDev.seek(time);
}
/**
* Indicates if playback is in real time mode or non real time
* In real time mode, playback will play the same way the file was recorded. If the application
* takes too long to handle the callback, frames may be dropped.
* In non real time mode, playback will wait for each callback to finish handling the data before
* reading the next frame. In this mode no frames will be dropped, and the application controls
* the frame rate of the playback (according to the callback handler duration).
* @return {Boolean}
*/
get isRealTime() {
return this.cxxDev.isRealTime();
}
/**
* Set the playback to work in real time or non real time
* @param {boolean} val whether real time mode is used
* @return {undefined}
*/
set isRealTime(val) {
const funcName = 'PlaybackDevice.isRealTime()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'boolean', 0, funcName);
this.cxxDev.setIsRealTime(val);
}
/**
* Set the playing speed
* @param {Float} speed indicates a multiplication of the speed to play (e.g: 1 = normal,
* 0.5 half normal speed)
*/
setPlaybackSpeed(speed) {
const funcName = 'PlaybackDevice.setPlaybackSpeed()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName);
this.cxxDev.setPlaybackSpeed(speed);
}
/**
* @typedef {Object} PlaybackStatusObject
* @property {Integer} status - The status of the notification, see {@link playback_status}
* for details
* @property {String} description - The human readable literal description of the status
*/
/**
* This callback is called when the status of the playback device changed
* @callback StatusChangedCallback
* @param {PlaybackStatusObject} status
*
* @see [PlaybackDevice.setStatusChangedCallback]{@link PlaybackDevice#setStatusChangedCallback}
*/
/**
* Returns the current state of the playback device
* @return {PlaybackStatusObject}
*/
get currentStatus() {
let cxxStatus = this.cxxDev.getCurrentStatus();
if (!cxxStatus) {
return undefined;
}
return {status: cxxStatus, description: playback_status.playbackStatusToString(cxxStatus)};
}
/**
* Register a callback to receive the playback device's status changes
* @param {StatusChangedCallback} callback the callback method
* @return {undefined}
*/
setStatusChangedCallback(callback) {
const funcName = 'PlaybackDevice.setStatusChangedCallback()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'function', 0, funcName);
this._events.on('status-changed', (status) => {
callback({status: status, description: playback_status.playbackStatusToString(status)});
});
let inst = this;
if (!this.cxxDev.statusChangedCallback) {
this.cxxDev.statusChangedCallback = (status) => {
inst._events.emit('status-changed', status);
};
this.cxxDev.setStatusChangedCallbackMethodName('statusChangedCallback');
}
}
} |
JavaScript | class PointCloud extends Options {
constructor() {
super();
this.cxxPointCloud = new RS2.RSPointCloud();
this.setCxxOptionsObject(this.cxxPointCloud);
this.pointsFrame = new Points();
}
/**
* Calculate to get a frame of type {@link Points}, from the data of specified DepthFrame
* @param {DepthFrame} depthFrame the depth frame
* @return {Points|undefined}
*/
calculate(depthFrame) {
const funcName = 'PointCloud.calculate()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, DepthFrame, 0, funcName);
this.pointsFrame.release();
if (this.cxxPointCloud.calculate(depthFrame.cxxFrame, this.pointsFrame.cxxFrame)) {
return this.pointsFrame;
}
return undefined;
}
/**
* Align texture coordinate to the mappedFrame
* @param {Frame} mappedFrame the frame being mapped to
* @return {undefined}
*/
mapTo(mappedFrame) {
const funcName = 'PointCloud.mapTo()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Frame, 0, funcName);
this.cxxPointCloud.mapTo(mappedFrame.cxxFrame);
}
release() {
if (this.cxxPointCloud) this.cxxPointCloud.destroy();
if (this.pointsFrame) this.pointsFrame.destroy();
}
/**
* Destroy all resources associated with the object
*/
destroy() {
this.release();
this.cxxPointCloud = undefined;
this.pointsFrame = undefined;
}
} |
JavaScript | class Colorizer extends Options {
constructor() {
super();
this.cxxColorizer = new RS2.RSColorizer();
this.cxxColorizer.create();
this.setCxxOptionsObject(this.cxxColorizer);
this.depthRGB = new VideoFrame();
}
release() {
if (this.cxxColorizer) this.cxxColorizer.destroy();
if (this.depthRGB) this.depthRGB.destroy();
}
/**
* Destroy all resources associated with the colorizer
*/
destroy() {
this.release();
this.cxxColorizer = undefined;
this.depthRGB = undefined;
}
get colorizedFrame() {
return this.depthRGB;
}
/**
* Tranform depth data into RGB8 format
*
* @param {DepthFrame} depthFrame the depth frame
* @return {VideoFrame|undefined}
*/
colorize(depthFrame) {
const funcName = 'Colorizer.colorize()';
checkArgumentLength(1, 1, arguments.length, funcName);
// Though depth frame is expected, color frame could also be processed, so
// only check whether the type is Frame
checkArgumentType(arguments, Frame, 0, funcName);
const success = this.cxxColorizer.colorize(depthFrame.cxxFrame, this.depthRGB.cxxFrame);
this.depthRGB.updateProfile();
return success ? this.depthRGB : undefined;
}
} |
JavaScript | class Align {
/**
* @param {Integer|String} stream the stream type to be aligned to. see {@link stream} for
* avaiable values. To perform alignment of a depth frame to the other frame, set the stream
* argument to the other stream type. To perform alignment of a non depth frame to a depth frame,
* set the stream argument to stream type of depth.
*/
constructor(stream) {
const funcName = 'Align.constructor()';
checkArgumentLength(1, 1, arguments.length, funcName);
const s = checkArgumentType(arguments, constants.stream, 0, funcName);
this.cxxAlign = new RS2.RSAlign(s);
this.frameSet = new FrameSet();
internal.addObject(this);
}
/**
* Run the alignment process on the given frameset to get an aligned set of frames
* @param {FrameSet} frameSet the frames which at least has a depth frame
* @return {FrameSet}
*/
process(frameSet) {
const funcName = 'Align.process()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, FrameSet, 0, funcName);
this.frameSet.release(); // Destroy all attached-frames (depth/color/etc.)
if (this.cxxAlign.process(frameSet.cxxFrameSet, this.frameSet.cxxFrameSet)) {
this.frameSet.__update();
return this.frameSet;
}
return undefined;
}
release() {
if (this.cxxAlign) this.cxxAlign.destroy();
if (this.frameSet) this.frameSet.destroy();
}
/**
* Destroy resources associated with the object
*/
destroy() {
this.release();
this.cxxAlign = undefined;
this.frameSet = undefined;
}
} |
JavaScript | class Frame {
constructor(cxxFrame) {
this.cxxFrame = cxxFrame || new RS2.RSFrame();
this.updateProfile();
internal.addObject(this);
// called from native to reset this.arrayBuffer and this.typedArray when the
// underlying frame was replaced. The arrayBuffer and typedArray must be reset
// to avoid deprecated data to be used.
const jsWrapper = this;
this.cxxFrame._internalResetBuffer = function() {
jsWrapper.typedArray = undefined;
jsWrapper.arrayBuffer = undefined;
};
}
updateProfile() {
this.streamProfile = undefined;
if (this.cxxFrame) {
let cxxProfile = this.cxxFrame.getStreamProfile();
if (cxxProfile) {
this.streamProfile = StreamProfile._internalCreateStreamProfile(cxxProfile);
}
}
}
release() {
if (this.cxxFrame) this.cxxFrame.destroy();
if (this.streamProfile) this.streamProfile.destroy();
this.arrayBuffer = undefined;
this.typedArray = undefined;
}
/**
* Destroy the frame and its resource
*/
destroy() {
this.release();
this.cxxFrame = undefined;
this.StreamProfile = undefined;
}
/**
* Retrieve pixel format of the frame
* @return {Integer} see enum {@link format} for available values
*/
get format() {
return this.streamProfile.format;
}
/**
* Retrieve the origin stream type that produced the frame
* @return {Integer} see {@link stream} for avaiable values
*/
get streamType() {
return this.streamProfile.streamType;
}
get profile() {
return this.streamProfile;
}
get width() {
return this.streamProfile.width ? this.streamProfile.width : this.cxxFrame.getWidth();
}
get height() {
return this.streamProfile.height ? this.streamProfile.height : this.cxxFrame.getHeight();
}
/**
* Check if the frame is valid
* @return {Boolean}
*/
get isValid() {
return (this.cxxFrame && this.cxxFrame.isValid());
}
/**
* Retrieve timestamp from the frame in milliseconds
* @return {Integer}
*/
get timestamp() {
return this.cxxFrame.getTimestamp();
}
/**
* Retrieve timestamp domain. timestamps can only be comparable if they are in common domain
* (for example, depth timestamp might come from system time while color timestamp might come
* from the device)
* this method is used to check if two timestamp values are comparable (generated from the same
* clock)
* @return {Integer} see {@link timestamp_domain} for avaiable values
*/
get timestampDomain() {
return this.cxxFrame.getTimestampDomain();
}
/**
* Retrieve the current value of a single frame metadata
* @param {String|Number} metadata the type of metadata, see {@link frame_metadata} for avaiable
* values
* @return {Uint8Array} The metadata value, 8 bytes, byte order is bigendian.
*/
frameMetadata(metadata) {
const funcName = 'Frame.frameMetadata()';
checkArgumentLength(1, 1, arguments.length, funcName);
const m = checkArgumentType(arguments, constants.frame_metadata, 0, funcName);
const array = new Uint8Array(8);
return this.cxxFrame.getFrameMetadata(m, array) ? array : undefined;
}
/**
* Determine if the device allows a specific metadata to be queried
* @param {String|Number} metadata The type of metadata
* @return {Boolean} true if supported, and false if not
*/
supportsFrameMetadata(metadata) {
const funcName = 'Frame.supportsFrameMetadata()';
checkArgumentLength(1, 1, arguments.length, funcName);
const m = checkArgumentType(arguments, constants.frame_metadata, 0, funcName);
return this.cxxFrame.supportsFrameMetadata(m);
}
/**
* Retrieve frame number
* @return {Integer}
*/
get frameNumber() {
return this.cxxFrame.getFrameNumber();
}
/**
* Retrieve the frame data
* @return {Float32Array|Uint16Array|Uint8Array|undefined}
* if the frame is from the depth stream, the return value is Uint16Array;
* if the frame is from the XYZ32F or MOTION_XYZ32F stream, the return value is Float32Array;
* for other cases, return value is Uint8Array.
*/
get data() {
if (this.typedArray) return this.typedArray;
if (!this.arrayBuffer) {
this.arrayBuffer = this.cxxFrame.getData();
this.typedArray = undefined;
}
if (!this.arrayBuffer) return undefined;
this.updateProfile();
switch (this.format) {
case constants.format.FORMAT_Z16:
case constants.format.FORMAT_DISPARITY16:
case constants.format.FORMAT_Y16:
case constants.format.FORMAT_RAW16:
this.typedArray = new Uint16Array(this.arrayBuffer);
return this.typedArray;
case constants.format.FORMAT_YUYV:
case constants.format.FORMAT_UYVY:
case constants.format.FORMAT_RGB8:
case constants.format.FORMAT_BGR8:
case constants.format.FORMAT_RGBA8:
case constants.format.FORMAT_BGRA8:
case constants.format.FORMAT_Y8:
case constants.format.FORMAT_RAW8:
case constants.format.FORMAT_MOTION_RAW:
case constants.format.FORMAT_GPIO_RAW:
case constants.format.FORMAT_RAW10:
case constants.format.FORMAT_ANY:
this.typedArray = new Uint8Array(this.arrayBuffer);
return this.typedArray;
case constants.format.FORMAT_XYZ32F:
case constants.format.FORMAT_MOTION_XYZ32F:
case constants.format.FORMAT_6DOF:
case constants.format.FORMAT_DISPARITY32:
this.typedArray = new Float32Array(this.arrayBuffer);
return this.typedArray;
}
}
/**
* Get the frame buffer data
* There are 2 acceptable forms of syntax:
* <pre><code>
* Syntax 1. getData()
* Syntax 2. getData(ArrayBuffer)
* </code></pre>
*
* @param {ArrayBuffer} [buffer] The buffer that will be written to.
* @return {Float32Array|Uint16Array|Uint8Array|undefined}
* Returns a <code>TypedArray</code> or <code>undefined</code> for syntax 1,
* see {@link Frame#data};
* if syntax 2 is used, return value is not used (<code>undefined</code>).
*
* @see [VideoFrame.dataByteLength]{@link VideoFrame#dataByteLength} to determine the buffer size
* in bytes.
*/
getData(buffer) {
const funcName = 'Frame.supportsFrameMetadata()';
checkArgumentLength(0, 1, arguments.length, funcName);
if (arguments.length === 0) {
return this.data;
} else if (arguments.length === 1) {
checkArgumentType(arguments, 'ArrayBuffer', 0, funcName);
return this.cxxFrame.writeData(buffer);
}
}
/**
* communicate to the library you intend to keep the frame alive for a while
* this will remove the frame from the regular count of the frame pool
* once this function is called, the SDK can no longer guarantee 0-allocations during frame
* cycling
* @return {undefined}
*/
keep() {
this.cxxFrame.keep();
}
static _internalCreateFrame(cxxFrame) {
if (!cxxFrame) return undefined;
if (cxxFrame.isPoseFrame()) return new PoseFrame(cxxFrame);
if (cxxFrame.isMotionFrame()) return new MotionFrame(cxxFrame);
if (cxxFrame.isDisparityFrame()) return new DisparityFrame(cxxFrame);
if (cxxFrame.isDepthFrame()) return new DepthFrame(cxxFrame);
if (cxxFrame.isVideoFrame()) return new VideoFrame(cxxFrame);
return new Frame(cxxFrame);
}
} |
JavaScript | class VideoFrame extends Frame {
constructor(frame) {
super(frame);
}
/**
* Get image width in pixels
* @return {Integer}
*/
get width() {
return this.cxxFrame.getWidth();
}
/**
* Get image height in pixels
* @return {Integer}
*/
get height() {
return this.cxxFrame.getHeight();
}
/**
* Get the data length in bytes
* @return {Integer}
*/
get dataByteLength() {
return this.strideInBytes * this.height;
}
/**
* Retrieve frame stride, the actual line width in bytes (not the logical image width)
* @return {Integer}
*/
get strideInBytes() {
return this.cxxFrame.getStrideInBytes();
}
/**
* Retrieve count of bits per pixel
* @return {Integer}
*/
get bitsPerPixel() {
return this.cxxFrame.getBitsPerPixel();
}
/**
* Retrieve bytes per pixel
* @return {Integer}
*/
get bytesPerPixel() {
return this.cxxFrame.getBitsPerPixel()/8;
}
} |
JavaScript | class Points extends Frame {
constructor(cxxFrame) {
super(cxxFrame);
}
/**
* Get an array of 3D vertices.
* The coordinate system is: X right, Y up, Z away from the camera. Units: Meters
*
* @return {Float32Array|undefined}
*/
get vertices() {
if (this.verticesArray) return this.verticesArray;
if (this.cxxFrame.canGetPoints()) {
const newLength = this.cxxFrame.getVerticesBufferLen();
if (!this.verticesData || newLength !== this.verticesData.byteLength) {
this.verticesData = new ArrayBuffer(newLength);
}
if (this.cxxFrame.writeVertices(this.verticesData)) {
this.verticesArray = new Float32Array(this.verticesData);
return this.verticesArray;
}
}
return undefined;
}
release() {
if (this.cxxFrame) this.cxxFrame.destroy();
this.verticesArray = undefined;
this.verticesCoordArray = undefined;
}
destroy() {
this.release();
this.verticesData = undefined;
this.textureCoordData = undefined;
this.cxxFrame = undefined;
}
/**
* Creates a ply file of the model with the given file name.
* @param {String} fileName name of the ply file
* @param {VideoFrame} texture texture frame
* @return {undefined}
*/
exportToPly(fileName, texture) {
const funcName = 'Points.exportToPly()';
checkArgumentLength(2, 2, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkArgumentType(arguments, VideoFrame, 1, funcName);
if (this.cxxFrame) {
this.cxxFrame.exportToPly(fileName, texture.cxxFrame);
}
}
/**
* Get an array of texture coordinates per vertex
* Each coordinate represent a (u,v) pair within [0,1] range, to be mapped to texture image
*
* @return {Int32Array|undefined}
*/
get textureCoordinates() {
if (this.verticesCoordArray) return this.verticesCoordArray;
if (this.cxxFrame.canGetPoints()) {
const newLength = this.cxxFrame.getTexCoordBufferLen();
if (!this.textureCoordData || newLength !== this.textureCoordData.byteLength) {
this.textureCoordData = new ArrayBuffer(newLength);
}
if (this.cxxFrame.writeTextureCoordinates(this.textureCoordData)) {
this.verticesCoordArray = new Int32Array(this.textureCoordData);
return this.verticesCoordArray;
}
}
return undefined;
}
/**
* Get number of vertices
*
* @return {Integer}
*/
get size() {
if (this.cxxFrame.canGetPoints()) {
return this.cxxFrame.getPointsCount();
}
throw new TypeError('Can\'t get size due to invalid frame type');
}
} |
JavaScript | class DepthFrame extends VideoFrame {
constructor(cxxFrame) {
super(cxxFrame);
}
/**
* Get the distance of a point from the camera
* @param {Integer} x x coordinate of the point
* @param {Integer} y y coordinate of the point
* @return {Float}
*/
getDistance(x, y) {
const funcName = 'DepthFrame.getDistance()';
checkArgumentLength(2, 2, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName);
checkArgumentType(arguments, 'number', 1, funcName);
return this.cxxFrame.getDistance(x, y);
}
} |
JavaScript | class MotionFrame extends Frame {
constructor(frame) {
super(frame);
this._motion = {x: 0, y: 0, z: 0};
}
/**
* Get the motion data
* @return {Vector} the motion data on x, y and z coordinates
*/
get motionData() {
this.cxxFrame.getMotionData(this._motion);
return this._motion;
}
} |
JavaScript | class PoseFrame extends Frame {
constructor(frame) {
super(frame);
this._pose = {
translation: {x: 0, y: 0, z: 0},
velocity: {x: 0, y: 0, z: 0},
acceleration: {x: 0, y: 0, z: 0},
rotation: {x: 0, y: 0, z: 0, w: 0},
angularVelocity: {x: 0, y: 0, z: 0},
angularAcceleration: {x: 0, y: 0, z: 0},
trackerConfidence: 0,
mapperConfidence: 0,
};
}
/**
* Get the pose data
* @return {PoseData|undefined}
*/
get poseData() {
return (this.cxxFrame.getPoseData(this._pose)) ? this._pose : undefined;
}
} |
JavaScript | class FrameSet {
constructor(cxxFrameSet) {
this.cxxFrameSet = cxxFrameSet || new RS2.RSFrameSet();
this.cache = [];
this.cacheMetadata = [];
this.__update();
}
/**
* Count of frames
*
* @return {Integer}
*/
get size() {
return this.sizeValue;
}
/**
* Get the depth frame
*
* @return {DepthFrame|undefined}
*/
get depthFrame() {
return this.getFrame(stream.STREAM_DEPTH, 0);
}
/**
* Get the color frame
*
* @return {VideoFrame|undefined}
*/
get colorFrame() {
return this.getFrame(stream.STREAM_COLOR, 0);
}
/**
* Get the infrared frame
* @param {Integer} streamIndex index of the expected infrared stream
* @return {VideoFrame|undefined}
*/
getInfraredFrame(streamIndex = 0) {
const funcName = 'FrameSet.getInfraredFrame()';
checkArgumentLength(0, 1, arguments.length, funcName);
if (arguments.length === 1) {
checkArgumentType(arguments, 'integer', 0, funcName);
}
return this.getFrame(stream.STREAM_INFRARED, streamIndex);
}
/**
* Get the frame at specified index
*
* @param {Integer} index the index of the expected frame (Note: this is not
* stream index)
* @return {DepthFrame|VideoFrame|Frame|undefined}
*/
at(index) {
const funcName = 'FrameSet.at()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName, 0, this.size);
return this.getFrame(this.cxxFrameSet.indexToStream(index),
this.cxxFrameSet.indexToStreamIndex(index));
}
/**
* Run the provided callback function with each Frame inside the FrameSet
* @param {FrameCallback} callback the callback function to process each frame
* @return {undefined}
*/
forEach(callback) {
const funcName = 'FrameSet.forEach()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'function', 0, funcName);
const size = this.size;
for (let i = 0; i < size; i++) {
callback(this.at(i));
}
}
__internalGetFrame(stream, streamIndex) {
let cxxFrame = this.cxxFrameSet.getFrame(stream, streamIndex);
return (cxxFrame ? Frame._internalCreateFrame(cxxFrame) : undefined);
}
__internalFindFrameInCache(stream, streamIndex) {
if (stream === stream.STREAM_ANY) {
return (this.cacheMetadata.size ? 0 : undefined);
}
for (const [i, data] of this.cacheMetadata.entries()) {
if (data.stream !== stream) {
continue;
}
if (!streamIndex || (streamIndex && streamIndex === data.streamIndex)) {
return i;
}
}
return undefined;
}
__internalGetFrameCache(stream, streamIndex, callback) {
let idx = this.__internalFindFrameInCache(stream, streamIndex);
if (idx === undefined) {
let frame = callback(stream, streamIndex);
if (!frame) return undefined;
this.cache.push(frame);
// the stream parameter may be stream.STREAM_ANY, but when we store the frame in
// cache, we shall store its actual stream type.
this.cacheMetadata.push({stream: frame.streamType, streamIndex: streamIndex});
idx = this.cache.length - 1;
} else {
let frame = this.cache[idx];
if (!frame.cxxFrame) {
frame.cxxFrame = new RS2.RSFrame();
}
// as cache metadata entries always use actual stream type, we use the actual
// stream types to easy native from processing stream.STREAM_ANY
if (! this.cxxFrameSet.replaceFrame(
this.cacheMetadata[idx].stream, streamIndex, frame.cxxFrame)) {
this.cache[idx] = undefined;
this.cacheMetadata[idx] = undefined;
}
}
return this.cache[idx];
}
/**
* Get the frame with specified stream
*
* @param {Integer|String} stream stream type of the frame
* @param {Integer} streamIndex index of the stream, 0 means the first
* matching stream
* @return {DepthFrame|VideoFrame|Frame|undefined}
*/
getFrame(stream, streamIndex = 0) {
const funcName = 'FrameSet.getFrame()';
checkArgumentLength(1, 2, arguments.length, funcName);
const s = checkArgumentType(arguments, constants.stream, 0, funcName);
if (arguments.length === 2) {
checkArgumentType(arguments, 'integer', 1, funcName);
}
return this.__internalGetFrameCache(s, streamIndex, this.__internalGetFrame.bind(this));
}
__update() {
this.sizeValue = this.cxxFrameSet.getSize();
}
releaseCache() {
this.cache.forEach((f) => {
if (f && f.cxxFrame) {
f.release();
}
});
this.cache = [];
this.cacheMetadata = [];
}
release() {
this.releaseCache();
if (this.cxxFrameSet) this.cxxFrameSet.destroy();
}
/**
* Release resources associated with this object
*
* @return {undefined}
*/
destroy() {
this.release();
this.cxxFrameSet = undefined;
}
} |
JavaScript | class Pipeline {
/**
* Construct a Pipeline object
* There are 2 acceptable syntax
*
* <pre><code>
* Syntax 1. new Pipeline()
* Syntax 2. new Pipeline(context)
* </code></pre>
* Syntax 1 uses the default context.
* Syntax 2 used the context created by application
* @param {Context} [context] - the {@link Context} that is being used by the pipeline
*/
constructor(context) {
const funcName = 'Pipeline.constructor()';
checkArgumentLength(0, 1, arguments.length, funcName);
let ownCtx = true;
let ctx;
if (arguments.length === 1) {
checkArgumentType(arguments, Context, 0, funcName);
ownCtx = false;
this.ctx = arguments[0];
}
if (ownCtx === true) {
this.ctx = new Context();
}
this.cxxPipeline = new RS2.RSPipeline();
this.cxxPipeline.create(this.ctx.cxxCtx);
this.started = false;
this.frameSet = new FrameSet();
internal.addObject(this);
}
/**
* Destroy the resource associated with this pipeline
*
* @return {undefined}
*/
destroy() {
if (this.started === true) this.stop();
if (this.cxxPipeline) {
this.cxxPipeline.destroy();
this.cxxPipeline = undefined;
}
if (this.ownCtx && this.ctx) {
this.ctx.destroy();
}
this.ctx = undefined;
if (this.frameSet) {
this.frameSet.destroy();
}
this.frameSet = undefined;
}
/**
* Start streaming
* There are 2 acceptable syntax
*
* <pre><code>
* Syntax 1. start()
* Syntax 2. start(config)
* </code></pre>
* Syntax 1 uses the default configuration.
* Syntax 2 used the configured streams and or device of the config parameter
*
* @param {Config} [config] - the {@link Config} object to use for configuration
* @return {@link PipelineProfile}
*/
start() {
const funcName = 'Pipeline.start()';
checkArgumentLength(0, 1, arguments.length, funcName);
if (this.started === true) return undefined;
if (arguments.length === 0) {
this.started = true;
return new PipelineProfile(this.cxxPipeline.start());
} else {
checkArgumentType(arguments, Config, 0, funcName);
this.started = true;
return new PipelineProfile(this.cxxPipeline.startWithConfig(arguments[0].cxxConfig));
}
}
/**
* Stop streaming
*
* @return {undefined}
*/
stop() {
if (this.started === false) return;
if (this.cxxPipeline ) {
this.cxxPipeline.stop();
}
this.started = false;
if (this.frameSet) this.frameSet.release();
}
/**
* Wait until a new set of frames becomes available.
* The returned frameset includes time-synchronized frames of each enabled stream in the pipeline.
* In case of different frame rates of the streams, the frames set include a matching frame of the
* slow stream, which may have been included in previous frames set.
* The method blocks the calling thread, and fetches the latest unread frames set.
* Device frames, which were produced while the function wasn't called, are dropped.
* To avoid frame drops, this method should be called as fast as the device frame rate.
*
* @param {Integer} timeout - max time to wait, in milliseconds, default to 5000 ms
* @return {FrameSet|undefined} a FrameSet object or Undefined
* @see See [Pipeline.latestFrame]{@link Pipeline#latestFrame}
*/
waitForFrames(timeout = 5000) {
const funcName = 'Pipeline.waitForFrames()';
checkArgumentLength(0, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName);
this.frameSet.release();
if (this.cxxPipeline.waitForFrames(this.frameSet.cxxFrameSet, timeout)) {
this.frameSet.__update();
return this.frameSet;
}
return undefined;
}
get latestFrame() {
return this.frameSet;
}
/**
* Check if a new set of frames is available and retrieve the latest undelivered set.
* The frameset includes time-synchronized frames of each enabled stream in the pipeline.
* The method returns without blocking the calling thread, with status of new frames available
* or not. If available, it fetches the latest frames set.
* Device frames, which were produced while the function wasn't called, are dropped.
* To avoid frame drops, this method should be called as fast as the device frame rate.
*
* @return {FrameSet|undefined}
*/
pollForFrames() {
this.frameSet.release();
if (this.cxxPipeline.pollForFrames(this.frameSet.cxxFrameSet)) {
this.frameSet.__update();
return this.frameSet;
}
return undefined;
}
/**
* Return the active device and streams profiles, used by the pipeline.
* The pipeline streams profiles are selected during {@link Pipeline.start}. The method returns a
* valid result only when the pipeline is active -
* between calls to {@link Pipeline.start} and {@link Pipeline.stop}.
* After {@link Pipeline.stop} is called, the pipeline doesn't own the device, thus, the pipeline
* selected device may change in
* subsequent activations.
*
* @return {PipelineProfile} the actual pipeline device and streams profile, which was
* successfully configured to the streaming device on start.
*/
getActiveProfile() {
if (this.started === false) return undefined;
return new PipelineProfile(this.cxxPipeline.getActiveProfile());
}
} |
JavaScript | class PipelineProfile {
constructor(profile) {
this.cxxPipelineProfile = profile;
internal.addObject(this);
}
/**
* Check if the object is valid
* @return {Boolean}
*/
get isValid() {
return (this.cxxPipelineProfile != null);
}
/**
* Return the selected streams profiles, which are enabled in this profile.
*
* @return {StreamProfile[]} an array of StreamProfile
*/
getStreams() {
let profiles = this.cxxPipelineProfile.getStreams();
if (!profiles) return undefined;
const array = [];
profiles.forEach((profile) => {
array.push(StreamProfile._internalCreateStreamProfile(profile));
});
return array;
}
/**
* Return the selected stream profile, which are enabled in this profile.
* @param {Integer|String} streamType the stream type of the desired profile,
* see {@link stream} for avaiable values
* @param {Integer} streamIndex stream index of the desired profile, -1 for any matching
* @return {StreamProfile} the first matching stream profile
*/
getStream(streamType, streamIndex = -1) {
const funcName = 'PipelineProfile.getStream()';
checkArgumentLength(1, 2, arguments.length, funcName);
const s = checkArgumentType(arguments, constants.stream, 0, funcName);
checkArgumentType(arguments, 'number', 1, funcName);
let profiles = this.getStreams();
if (!profiles) {
return undefined;
}
for (let i = 0; i < profiles.length; i++) {
if (profiles[i].streamType === s &&
(streamIndex === -1 || (streamIndex === profiles[i].indexValue))) {
return profiles[i];
}
}
return undefined;
}
/**
* Retrieve the device used by the pipeline.
* The device class provides the application access to control camera additional settings -
* get device information, sensor options information, options value query and set, sensor
* specific extensions.
* Since the pipeline controls the device streams configuration, activation state and frames
* reading, calling the device API functions, which execute those operations, results in
* unexpected behavior. The pipeline streaming device is selected during {@link Pipeline.start}.
* Devices of profiles, which are not returned by
* {@link Pipeline.start} or {@link Pipeline.getActiveProfile}, are not guaranteed to be used by
* the pipeline.
*
* @return {Device} the pipeline selected device
*/
getDevice() {
return Device._internalCreateDevice(this.cxxPipelineProfile.getDevice());
}
/**
* Destroy the resource associated with this object
*
* @return {undefined}
*/
destroy() {
if (this.cxxPipelineProfile) {
this.cxxPipelineProfile.destroy();
this.cxxPipelineProfile = undefined;
}
}
} |
JavaScript | class Config {
constructor() {
this.cxxConfig = new RS2.RSConfig();
internal.addObject(this);
}
/**
* Enable a device stream explicitly, with selected stream parameters.
* The method allows the application to request a stream with specific configuration. If no stream
* is explicitly enabled, the pipeline configures the device and its streams according to the
* attached computer vision modules and processing blocks requirements, or default configuration
* for the first available device.
* The application can configure any of the input stream parameters according to its requirement,
* or set to 0 for don't care value. The config accumulates the application calls for enable
* configuration methods, until the configuration is applied. Multiple enable stream calls for the
* same stream override each other, and the last call is maintained.
* Upon calling {@link Config.resolve}, the config checks for conflicts between the application
* configuration requests and the attached computer vision modules and processing blocks
* requirements, and fails if conflicts are found.
* Before {@link Config.resolve} is called, no conflict check is done.
*
* @param {Integer|String} stream stream type to be enabled
* @param {Integer} index stream index, used for multiple streams of the same type. -1 indicates
* any.
* @param {Integer} width stream image width - for images streams. 0 indicates any.
* @param {Integer} height stream image height - for images streams. 0 indicates any.
* @param {Integer|String} format stream data format - pixel format for images streams, of data
* type for other streams. format.FORMAT_ANY indicates any.
* @param {Integer} fps stream frames per second. 0 indicates any.
*/
enableStream(stream, index, width, height, format, fps) {
const funcName = 'Config.enableStream()';
checkArgumentLength(6, 6, arguments.length, funcName);
const s = checkArgumentType(arguments, constants.stream, 0, funcName);
checkArgumentType(arguments, 'number', 1, funcName);
checkArgumentType(arguments, 'number', 2, funcName);
checkArgumentType(arguments, 'number', 3, funcName);
const f = checkArgumentType(arguments, constants.format, 4, funcName);
checkArgumentType(arguments, 'number', 5, funcName);
this.cxxConfig.enableStream(s, index, width, height, f, fps);
}
/**
* Disable a device stream explicitly, to remove any requests on this stream profile.
*/
disableStream(stream) {
const funcName = 'Config.disableStream()';
checkArgumentLength(1, 1, arguments.length, funcName);
const s = checkArgumentType(arguments, constants.stream, 0, funcName);
this.cxxConfig.disableStream(s);
}
/**
* Enable all device streams explicitly.
*/
enableAllStreams() {
this.cxxConfig.enableAllStreams();
}
/**
* Disable all device streams explicitly.
*/
disableAllStreams() {
this.cxxConfig.disableAllStreams();
}
/**
* Select a specific device explicitly by its serial number, to be used by the pipeline.
* The conditions and behavior of this method are similar to those of {@link Config.enableStream}.
* This method is required if the application needs to set device or sensor settings prior to
* pipeline streaming, to enforce the pipeline to use the configured device.
*
* @param {String} serial device serial number, as returned by
* Device.getCameraInfo(camera_info.CAMERA_INFO_SERIAL_NUMBER).
*/
enableDevice(serial) {
const funcName = 'Config.enableDevice()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
this.cxxConfig.enableDevice(serial);
}
/**
* Select a recorded device from a file, to be used by the pipeline through playback.
* The device available streams are as recorded to the file, and {@link Config.resolve} considers
* only this device and configuration as available.
* This request cannot be used if {@link Config.enableRecordToFile} is called for the current
* config, and vise versa
*
* @param {String} fileName the playback file of the device
* @param {Boolean} repeat whether to repeat the playback automatically
*/
enableDeviceFromFile(fileName, repeat = true) {
const funcName = 'Config.enableDeviceFromFile()';
checkArgumentLength(1, 2, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
checkArgumentType(arguments, 'boolean', 1, funcName);
checkFileExistence(fileName);
this.cxxConfig.enableDeviceFromFileRepeatOption(fileName, repeat);
}
/**
* Requires that the resolved device would be recorded to file
* This request cannot be used if {@link Config.enableDeviceFromFile} is called for the current
* config, and vise versa as available.
*
* @param {String} fileName the desired file for the output record
*/
enableRecordToFile(fileName) {
const funcName = 'Config.enableRecordToFile()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, 'string', 0, funcName);
this.cxxConfig.enableRecordToFile(fileName);
}
/**
* Resolve the configuration filters, to find a matching device and streams profiles.
* The method resolves the user configuration filters for the device and streams, and combines
* them with the requirements of the computer vision modules and processing blocks attached to the
* pipeline. If there are no conflicts of requests,
* it looks for an available device, which can satisfy all requests, and selects the first
* matching streams configuration. In the absence of any request, the config selects the first
* available device and the first color and depth streams configuration.
* The pipeline profile selection during {@link Pipeline.start} follows the same method. Thus,
* the selected profile is the same, if no change occurs to the available devices occurs.
* Resolving the pipeline configuration provides the application access to the pipeline selected
* device for advanced control.
* The returned configuration is not applied to the device, so the application doesn't own the
* device sensors. However, the application can call {@link Cofnig.enableDevice}, to enforce the
* device returned by this method is selected by pipeline start, and configure the device and
* sensors options or extensions before streaming starts.
*
* @param {Pipeline} pipeline the pipeline for which the selected filters are applied
* @return {PipelineProfile|undefined} a matching device and streams profile, which satisfies the
* filters and pipeline requests.
*/
resolve(pipeline) {
const funcName = 'Config.resolve()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Pipeline, 0, funcName);
return new PipelineProfile(this.cxxConfig.resolve(arguments[0].cxxPipeline));
}
/**
* Check if the config can resolve the configuration filters, to find a matching device and
* streams profiles. The resolution conditions are as described in {@link Config.resolve}.
*
* @param {Pipeline} pipeline the pipeline for which the selected filters are applied
* @return {boolean} true if a valid profile selection exists, false if no selection can be found
* under the config filters and the available devices.
*/
canResolve(pipeline) {
const funcName = 'Config.canResolve()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Pipeline, 0, funcName);
return this.cxxConfig.canResolve(arguments[0].cxxPipeline);
}
/**
* Release resources associated with the object
*/
destroy() {
if (this.cxxConfig) {
this.cxxConfig.destroy();
this.cxxConfig = null;
}
}
} |
JavaScript | class Syncer {
constructor() {
this.cxxSyncer = new RS2.RSSyncer();
this.frameSet = new FrameSet();
}
/*
* Wait until coherent set of frames becomes available
* @param {Number} timeout Max time in milliseconds to wait until an exception will be thrown
* @return {Frame[]|undefined} Set of coherent frames or undefined if no frames.
*/
waitForFrames(timeout = 5000) {
const funcName = 'Syncer.waitForFrames()';
checkArgumentLength(0, 1, arguments.length, funcName);
checkArgumentType(arguments, 'number', 0, funcName);
this.frameSet.release();
if (this.cxxSyncer.waitForFrames(this.frameSet.cxxFrameSet, timeout)) {
this.frameSet.__update();
return this.frameSet;
}
return undefined;
}
/**
* Check if a coherent set of frames is available, if yes return them
* @return {Frame[]|undefined} an array of frames if available and undefined if not.
*/
pollForFrames() {
this.frameSet.release();
if (this.cxxSyncer.pollForFrames(this.frameSet.cxxFrameSet)) {
this.frameSet.__update();
return this.frameSet;
}
return undefined;
}
/**
* Release resources associated with the object
*/
destroy() {
if (this.cxxSyncer) {
this.cxxSyncer.destroy();
this.cxxSyncer = undefined;
}
if (this.frameset) {
this.frameSet.destroy();
this.frameSet = undefined;
}
}
} |
JavaScript | class DeviceHub {
/**
* @param {Context} context - a librealsense2 Context
*/
constructor(context) {
const funcName = 'DeviceHub.constructor()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Context, 0, funcName);
this.context = context;
this.cxxHub = new RS2.RSDeviceHub(context.cxxCtx);
internal.addObject(this);
}
/**
* If any device is connected return it, otherwise wait until next RealSense device connects.
* Calling this method multiple times will cycle through connected devices
* @return {Device|undefined}
*/
waitForDevice() {
let dev = this.cxxHub.waitForDevice();
return (dev ? Device._internalCreateDevice(dev) : undefined);
}
/**
* Check if a device is connected
* @return {Boolean}
*/
isConnected(device) {
const funcName = 'DeviceHub.isConnected()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, Device, 0, funcName);
return this.cxxHub.isConnected(device.cxxDev);
}
/**
* Release resources associated with the object
*/
destroy() {
if (this.cxxHub) {
this.cxxHub.destroy();
this.cxxHub = undefined;
}
}
} |
JavaScript | class Filter extends Options {
constructor(type) {
super(new RS2.RSFilter(type));
internal.addObject(this);
}
_internalGetInputType() {
return DepthFrame;
}
_internalPrepareOutputFrame() {
if (!this.frame) {
this.frame = new DepthFrame();
}
}
/**
* Apply the filter processing on the frame and return the processed frame
* @param {Frame} frame the depth frame to be processed
* @return {Frame}
*/
process(frame) {
const funcName = 'Filter.process()';
checkArgumentLength(1, 1, arguments.length, funcName);
checkArgumentType(arguments, this._internalGetInputType(), 0, funcName);
this._internalPrepareOutputFrame();
if (this.cxxObj && this.cxxObj.process(frame.cxxFrame, this.frame.cxxFrame)) {
this.frame.updateProfile();
return this.frame;
}
return undefined;
}
/**
* Release resources associated with the object
*/
destroy() {
if (this.cxxObj) {
this.cxxObj.destroy();
this.cxxObj = null;
}
if (this.frame) {
this.frame.destroy();
this.frame = undefined;
}
}
} |
JavaScript | class DecimationFilter extends Filter {
constructor() {
super('decimation');
}
// override base implementation
_internalGetInputType() {
return VideoFrame;
}
_internalPrepareOutputFrame() {
if (!this.frame) {
this.frame = new VideoFrame();
}
}
} |
JavaScript | class TemporalFilter extends Filter {
constructor() {
super('temporal');
}
} |
JavaScript | class SpatialFilter extends Filter {
constructor() {
super('spatial');
}
} |
JavaScript | class HoleFillingFilter extends Filter {
constructor() {
super('hole-filling');
}
} |
JavaScript | class DisparityToDepthTransform extends Filter {
constructor() {
super('disparity-to-depth');
}
// override base implementation
_internalGetInputType() {
return DisparityFrame;
}
} |
JavaScript | class DepthToDisparityTransform extends Filter {
constructor() {
super('depth-to-disparity');
}
// override base implementation
_internalPrepareOutputFrame() {
if (!this.frame) {
this.frame = new DisparityFrame();
}
}
} |
JavaScript | class AnnotationBorderStyle {
constructor() {
this.width = 1;
this.style = AnnotationBorderStyleType.SOLID;
this.dashArray = [3];
this.horizontalCornerRadius = 0;
this.verticalCornerRadius = 0;
}
/**
* Set the width.
*
* @public
* @memberof AnnotationBorderStyle
* @param {number} width - The width.
* @param {Array} rect - The annotation `Rect` entry.
*/
setWidth(width, rect = [0, 0, 0, 0]) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || TESTING")
) {
assert(
Array.isArray(rect) && rect.length === 4,
"A valid `rect` parameter must be provided."
);
}
// Some corrupt PDF generators may provide the width as a `Name`,
// rather than as a number (fixes issue 10385).
if (isName(width)) {
this.width = 0; // This is consistent with the behaviour in Adobe Reader.
return;
}
if (Number.isInteger(width)) {
if (width > 0) {
const maxWidth = (rect[2] - rect[0]) / 2;
const maxHeight = (rect[3] - rect[1]) / 2;
// Ignore large `width`s, since they lead to the Annotation overflowing
// the size set by the `Rect` entry thus causing the `annotationLayer`
// to render it over the surrounding document (fixes bug1552113.pdf).
if (
maxWidth > 0 &&
maxHeight > 0 &&
(width > maxWidth || width > maxHeight)
) {
warn(`AnnotationBorderStyle.setWidth - ignoring width: ${width}`);
width = 1;
}
}
this.width = width;
}
}
/**
* Set the style.
*
* @public
* @memberof AnnotationBorderStyle
* @param {Name} style - The annotation style.
* @see {@link shared/util.js}
*/
setStyle(style) {
if (!isName(style)) {
return;
}
switch (style.name) {
case "S":
this.style = AnnotationBorderStyleType.SOLID;
break;
case "D":
this.style = AnnotationBorderStyleType.DASHED;
break;
case "B":
this.style = AnnotationBorderStyleType.BEVELED;
break;
case "I":
this.style = AnnotationBorderStyleType.INSET;
break;
case "U":
this.style = AnnotationBorderStyleType.UNDERLINE;
break;
default:
break;
}
}
/**
* Set the dash array.
*
* @public
* @memberof AnnotationBorderStyle
* @param {Array} dashArray - The dash array with at least one element
*/
setDashArray(dashArray) {
// We validate the dash array, but we do not use it because CSS does not
// allow us to change spacing of dashes. For more information, visit
// http://www.w3.org/TR/css3-background/#the-border-style.
if (Array.isArray(dashArray) && dashArray.length > 0) {
// According to the PDF specification: the elements in `dashArray`
// shall be numbers that are nonnegative and not all equal to zero.
let isValid = true;
let allZeros = true;
for (const element of dashArray) {
const validNumber = +element >= 0;
if (!validNumber) {
isValid = false;
break;
} else if (element > 0) {
allZeros = false;
}
}
if (isValid && !allZeros) {
this.dashArray = dashArray;
} else {
this.width = 0; // Adobe behavior when the array is invalid.
}
} else if (dashArray) {
this.width = 0; // Adobe behavior when the array is invalid.
}
}
/**
* Set the horizontal corner radius (from a Border dictionary).
*
* @public
* @memberof AnnotationBorderStyle
* @param {number} radius - The horizontal corner radius.
*/
setHorizontalCornerRadius(radius) {
if (Number.isInteger(radius)) {
this.horizontalCornerRadius = radius;
}
}
/**
* Set the vertical corner radius (from a Border dictionary).
*
* @public
* @memberof AnnotationBorderStyle
* @param {number} radius - The vertical corner radius.
*/
setVerticalCornerRadius(radius) {
if (Number.isInteger(radius)) {
this.verticalCornerRadius = radius;
}
}
} |
JavaScript | class SignInOrJoinFree extends React.Component {
static propTypes = {
/** Redirect URL */
redirect: PropTypes.string,
/** createUserQuery binding */
createUser: PropTypes.func,
/** Use this prop to use this as a controlled component */
form: PropTypes.oneOf(['signin', 'create-account']),
/** Set the initial view for the component */
defaultForm: PropTypes.oneOf(['signin', 'create-account']),
/** If provided, component will use links instead of buttons to make the switch */
routes: PropTypes.shape({
signin: PropTypes.string,
join: PropTypes.string,
}),
/** A label to use instead of the default `Create personal profile` */
createPersonalProfileLabel: PropTypes.node,
/** A label to use instead of the default `Create Organization profile` */
createOrganizationProfileLabel: PropTypes.node,
/** To display a box shadow below the card */
withShadow: PropTypes.bool,
/** Label for signIn, defaults to "Sign in using your email address:" */
signInLabel: PropTypes.node,
intl: PropTypes.object,
enforceTwoFactorAuthForLoggedInUser: PropTypes.bool,
submitTwoFactorAuthenticatorCode: PropTypes.func,
};
state = {
form: this.props.defaultForm || 'signin',
error: null,
submitting: false,
unknownEmailError: false,
email: '',
};
switchForm = form => {
// Update local state
this.setState({ form });
};
getRedirectURL() {
let currentPath = window.location.pathname;
if (window.location.search) {
currentPath = currentPath + window.location.search;
}
return encodeURIComponent(this.props.redirect || currentPath || '/');
}
signIn = async email => {
if (this.state.submitting) {
return false;
}
this.setState({ submitting: true });
try {
const userExists = await checkUserExistence(email);
if (userExists) {
const response = await signin({
user: { email },
redirect: this.getRedirectURL(),
websiteUrl: getWebsiteUrl(),
});
// In dev/test, API directly returns a redirect URL for emails like
// test*@opencollective.com.
if (response.redirect) {
await Router.replaceRoute(response.redirect);
} else {
await Router.pushRoute('signinLinkSent', { email });
}
window.scrollTo(0, 0);
} else {
this.setState({ unknownEmailError: true, submitting: false });
}
} catch (e) {
this.setState({ error: e.message || 'Server error', submitting: false });
window.scrollTo(0, 0);
}
};
createProfile = async data => {
if (this.state.submitting) {
return false;
}
const user = pick(data, ['email', 'name', 'newsletterOptIn']);
const organizationData = pick(data, ['orgName', 'githubHandle', 'twitterHandle', 'website']);
const organization = Object.keys(organizationData).length > 0 ? organizationData : null;
if (organization) {
organization.name = organization.orgName;
delete organization.orgName;
}
this.setState({ submitting: true });
try {
await this.props.createUser({
variables: {
user,
organization,
redirect: this.getRedirectURL(),
websiteUrl: getWebsiteUrl(),
},
});
await Router.pushRoute('signinLinkSent', { email: user.email });
window.scrollTo(0, 0);
} catch (error) {
this.setState({ error: error.message, submitting: false });
window.scrollTo(0, 0);
}
};
renderTwoFactorAuthBox = () => {
return (
<StyledCard maxWidth={480} width={1} boxShadow={'0px 9px 14px 1px #dedede'}>
<Box py={4} px={[3, 4]}>
<H5 as="label" fontWeight="bold" htmlFor="twoFactorAuthenticatorCode" mb={3} textAlign="left" display="block">
<FormattedMessage id="TwoFactorAuth.SignIn" defaultMessage="Please verify your login using the 2FA code:" />
</H5>
<Formik
initialValues={{
twoFactorAuthenticatorCode: '',
}}
onSubmit={(values, actions) => {
this.props.submitTwoFactorAuthenticatorCode(values, actions);
}}
>
{formik => {
const { values, handleSubmit, errors, touched, isSubmitting } = formik;
return (
<Form>
<StyledInputField
name="twoFactorAuthenticatorCode"
htmlFor="twoFactorAuthenticatorCode"
error={touched.twoFactorAuthenticatorCode && errors.twoFactorAuthenticatorCode}
label={this.props.intl.formatMessage(messages.inputLabel)}
value={values.twoFactorAuthenticatorCode}
required
mt={2}
mb={3}
>
{inputProps => (
<Field
as={StyledInput}
{...inputProps}
minWidth={300}
minHeight={75}
fontSize="20px"
placeholder="123456"
pattern="[0-9]{6}"
autoFocus
data-cy="signin-two-factor-auth-input"
/>
)}
</StyledInputField>
<Flex justifyContent={['center', 'left']} mb={4}>
<StyledButton
fontSize="13px"
minWidth="148px"
minHeight="36px"
buttonStyle="primary"
type="submit"
onSubmit={handleSubmit}
disabled={values.twoFactorAuthenticatorCode.length < 6}
loading={isSubmitting}
data-cy="signin-two-factor-auth-button"
>
<FormattedMessage id="TwoFactorAuth.Setup.Form.VerifyButton" defaultMessage="Verify" />
</StyledButton>
</Flex>
</Form>
);
}}
</Formik>
</Box>
</StyledCard>
);
};
render() {
const { submitting, error, unknownEmailError, email } = this.state;
const displayedForm = this.props.form || this.state.form;
const routes = this.props.routes || {};
const { enforceTwoFactorAuthForLoggedInUser } = this.props;
return (
<Flex flexDirection="column" width={1} alignItems="center">
{error && (
<MessageBox type="error" withIcon mb={[3, 4]}>
{error.replace('GraphQL error: ', 'Error: ')}
</MessageBox>
)}
{enforceTwoFactorAuthForLoggedInUser ? (
this.renderTwoFactorAuthBox()
) : (
<Fragment>
{displayedForm !== 'create-account' ? (
<SignIn
email={email}
onEmailChange={email => this.setState({ email })}
onSecondaryAction={routes.join || (() => this.switchForm('create-account'))}
onSubmit={this.signIn}
loading={submitting}
unknownEmail={unknownEmailError}
withShadow={this.props.withShadow}
label={this.props.signInLabel}
/>
) : (
<Flex flexDirection="column" width={1} alignItems="center">
<Flex justifyContent="center" width={1}>
<Box width={[0, null, null, 1 / 5]} />
<CreateProfile
email={email}
onEmailChange={email => this.setState({ email })}
onPersonalSubmit={this.createProfile}
onOrgSubmit={this.createProfile}
onSecondaryAction={routes.signin || (() => this.switchForm('signin'))}
submitting={submitting}
mx={[2, 4]}
createPersonalProfileLabel={this.props.createPersonalProfileLabel}
createOrganizationProfileLabel={this.props.createOrganizationProfileLabel}
/>
<CreateProfileFAQ mt={4} display={['none', null, 'block']} width={1 / 5} minWidth="335px" />
</Flex>
<P mt={4} color="black.500" fontSize="12px" mb={3} data-cy="join-conditions">
<FormattedMessage
id="SignIn.legal"
defaultMessage="By joining, you agree to our <tos-link>Terms of Service</tos-link> and <privacy-policy-link>Privacy Policy</privacy-policy-link>."
values={{
'tos-link': msg => <Link route="/tos">{msg}</Link>,
'privacy-policy-link': msg => <Link route="/privacypolicy">{msg}</Link>,
}}
/>
</P>
</Flex>
)}
</Fragment>
)}
</Flex>
);
}
} |
JavaScript | class StickyNavbar {
/**
* Constructor
* Add Article to the page if required
*/
constructor() {
this.setUpStickyNavbar();
}
/**
* Adds a parallax effect to this.HEADER
*/
setUpStickyNavbar() {
new Sticky(NAVBAR);
}
} |
JavaScript | class AmpFetcher {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const @private {!../../../src/service/xhr-impl.Xhr} */
this.xhr_ = Services.xhrFor(win);
/** @private @const {!Window} */
this.win_ = win;
}
/** @override */
fetchCredentialedJson(url) {
return this.xhr_
.fetchJson(url, {
credentials: 'include',
prerenderSafe: true,
})
.then((response) => response.json());
}
/** @override */
fetch(input, opt_init) {
return this.xhr_.fetch(input, opt_init); //needed to kepp closure happy
}
/**
* POST data to a URL endpoint, do not wait for a response.
* @param {string} url
* @param {string|!Object} data
*/
sendBeacon(url, data) {
const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
const body =
'f.req=' +
JSON.stringify(/** @type {JsonObject} */ (data.toArray(false)));
const sendBeacon = WindowInterface.getSendBeacon(this.win_);
if (sendBeacon) {
const blob = new Blob([body], {type: contentType});
sendBeacon(url, blob);
return;
}
// Only newer browsers support beacon. Fallback to standard XHR POST.
const init = {
method: 'POST',
headers: {'Content-Type': contentType},
credentials: 'include',
body,
};
this.fetch(url, init);
}
} |
JavaScript | class PostCheckoutBase extends HookBase {
shouldSkipFileCheckout() {
return (this.config['skipFileCheckout'] !== false);
}
isEnabled() {
if(this.isFileCheckout() && this.shouldSkipFileCheckout()) {
return false;
}
return HookBase.prototype.isEnabled.call(this);
}
} |
JavaScript | class State
{
constructor()
{
this.data = 0;
this.blendMode = BLEND_MODES.NORMAL;
this.polygonOffset = 0;
this.blend = true;
// this.depthTest = true;
}
/**
* Activates blending of the computed fragment color values
*
* @member {boolean}
*/
get blend()
{
return !!(this.data & (1 << BLEND));
}
set blend(value) // eslint-disable-line require-jsdoc
{
if (!!(this.data & (1 << BLEND)) !== value)
{
this.data ^= (1 << BLEND);
}
}
/**
* Activates adding an offset to depth values of polygon's fragments
*
* @member {boolean}
* @default false
*/
get offsets()
{
return !!(this.data & (1 << OFFSET));
}
set offsets(value) // eslint-disable-line require-jsdoc
{
if (!!(this.data & (1 << OFFSET)) !== value)
{
this.data ^= (1 << OFFSET);
}
}
/**
* Activates culling of polygons.
*
* @member {boolean}
* @default false
*/
get culling()
{
return !!(this.data & (1 << CULLING));
}
set culling(value) // eslint-disable-line require-jsdoc
{
if (!!(this.data & (1 << CULLING)) !== value)
{
this.data ^= (1 << CULLING);
}
}
/**
* Activates depth comparisons and updates to the depth buffer.
*
* @member {boolean}
* @default false
*/
get depthTest()
{
return !!(this.data & (1 << DEPTH_TEST));
}
set depthTest(value) // eslint-disable-line require-jsdoc
{
if (!!(this.data & (1 << DEPTH_TEST)) !== value)
{
this.data ^= (1 << DEPTH_TEST);
}
}
/**
* Specifies whether or not front or back-facing polygons can be culled.
* @member {boolean}
* @default false
*/
get clockwiseFrontFace()
{
return !!(this.data & (1 << WINDING));
}
set clockwiseFrontFace(value) // eslint-disable-line require-jsdoc
{
if (!!(this.data & (1 << WINDING)) !== value)
{
this.data ^= (1 << WINDING);
}
}
/**
* The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
* Setting this mode to anything other than NO_BLEND will automatically switch blending on.
*
* @member {boolean}
* @default PIXI.BLEND_MODES.NORMAL
* @see PIXI.BLEND_MODES
*/
get blendMode()
{
return this._blendMode;
}
set blendMode(value) // eslint-disable-line require-jsdoc
{
this.blend = (value !== BLEND_MODES.NONE);
this._blendMode = value;
}
/**
* The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill.
*
* @member {number}
* @default 0
*/
get polygonOffset()
{
return this._polygonOffset;
}
set polygonOffset(value) // eslint-disable-line require-jsdoc
{
this.offsets = !!value;
this._polygonOffset = value;
}
static for2d()
{
const state = new State();
state.depthTest = false;
state.blend = true;
return state;
}
} |
JavaScript | class IMFClass {
constructor(opts) {
opts = opts || {};
this.defaultNamespace = opts.defaultNamespace || '';
this.defaultSeparator = opts.defaultSeparator === undefined ? '.' : opts.defaultSeparator;
this.basePath = opts.basePath || 'locales/';
this.fallbackLanguages = opts.fallbackLanguages;
this.localeFileResolver = opts.localeFileResolver || function (lang) {
return this.basePath + lang + '.json';
};
this.locales = opts.locales || [];
this.langs = opts.langs;
this.fallbackLocales = opts.fallbackLocales || [];
const loadFallbacks = cb => {
this.loadLocales(this.fallbackLanguages, function (...fallbackLocales) {
this.fallbackLocales.push(...fallbackLocales);
if (cb) {
return cb(fallbackLocales);
}
}, true);
};
if (opts.languages || opts.callback) {
this.loadLocales(opts.languages, () => {
const locales = Array.from(arguments);
const runCallback = fallbackLocales => {
if (opts.callback) {
opts.callback.apply(this, [this.getFormatter(opts.namespace), this.getFormatter.bind(this), locales, fallbackLocales]);
}
};
if ({}.hasOwnProperty.call(opts, 'fallbackLanguages')) {
loadFallbacks(runCallback);
} else {
runCallback();
}
});
} else if ({}.hasOwnProperty.call(opts, 'fallbackLanguages')) {
loadFallbacks();
}
}
getFormatter(ns, sep) {
function messageForNSParts(locale, namesp, separator, key) {
let loc = locale;
const found = namesp.split(separator).every(function (nsPart) {
loc = loc[nsPart];
return loc && typeof loc === 'object';
});
return found && loc[key] ? loc[key] : '';
}
const isArray = Array.isArray;
ns = ns === undefined ? this.defaultNamespace : ns;
sep = sep === undefined ? this.defaultSeparator : sep;
ns = isArray(ns) ? ns.join(sep) : ns;
return (key, values, formats, fallback) => {
let message;
let currNs = ns;
if (key && !isArray(key) && typeof key === 'object') {
values = key.values;
formats = key.formats;
fallback = key.fallback;
key = key.key;
}
if (isArray(key)) {
// e.g., [ns1, ns2, key]
const newKey = key.pop();
currNs = key.join(sep);
key = newKey;
} else {
const keyPos = key.indexOf(sep);
if (!currNs && keyPos > -1) {
// e.g., 'ns1.ns2.key'
currNs = key.slice(0, keyPos);
key = key.slice(keyPos + 1);
}
}
function findMessage(locales) {
locales.some(function (locale) {
message = locale[(currNs ? currNs + sep : '') + key] || messageForNSParts(locale, currNs, sep, key);
return message;
});
return message;
}
findMessage(this.locales);
if (!message) {
if (typeof fallback === 'function') {
return fallback({
message: this.fallbackLocales.length && findMessage(this.fallbackLocales),
langs: this.langs,
namespace: currNs,
separator: sep,
key,
values,
formats
});
}
if (fallback !== false) {
return this.fallbackLocales.length && findMessage(this.fallbackLocales);
}
throw new Error('Message not found for locales ' + this.langs + (this.fallbackLanguages ? ' (with fallback languages ' + this.fallbackLanguages + ')' : '') + ' with key ' + key + ', namespace ' + currNs + ', and namespace separator ' + sep);
}
if (!values && !formats) {
return message;
}
const msg = new IntlMessageFormat(message, this.langs, formats);
return msg.format(values);
};
}
loadLocales(langs, cb, avoidSettingLocales) {
langs = langs || navigator.language || 'en-US';
langs = Array.isArray(langs) ? langs : [langs];
if (!avoidSettingLocales) {
this.langs = langs;
}
return getJSON(langs.map(this.localeFileResolver, this), (...locales) => {
if (!avoidSettingLocales) {
this.locales.push(...locales);
}
if (cb) {
cb.apply(this, locales);
}
});
}
} |
JavaScript | class JamilihMap extends Map {
/**
* @param {string|Element} elem
* @returns {any}
*/
get(elem) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return super.get.call(this, elem);
}
/**
* @param {string|Element} elem
* @param {any} value
* @returns {any}
*/
set(elem, value) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return super.set.call(this, elem, value);
}
/**
* @param {string|Element} elem
* @param {string} methodName
* @param {...any} args
* @returns {any}
*/
invoke(elem, methodName, ...args) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return this.get(elem)[methodName](elem, ...args);
}
} |
JavaScript | class JamilihWeakMap extends WeakMap {
/**
* @param {string|Element} elem
* @returns {any}
*/
get(elem) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return super.get.call(this, elem);
}
/**
* @param {string|Element} elem
* @param {any} value
* @returns {any}
*/
set(elem, value) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return super.set.call(this, elem, value);
}
/**
* @param {string|Element} elem
* @param {string} methodName
* @param {...any} args
* @returns {any}
*/
invoke(elem, methodName, ...args) {
elem = typeof elem === 'string' ? $$1(elem) : elem;
return this.get(elem)[methodName](elem, ...args);
}
} |
JavaScript | class Metadata {
constructor({
metadataObj
}) {
this.metadataObj = metadataObj;
}
getFieldLang(field) {
const {
metadataObj
} = this;
const fields = metadataObj && metadataObj.fields;
return fields && fields[field] && fields[field].lang;
}
getFieldMatchesLocale({
namespace,
preferredLocale,
schemaItems,
pluginsForWork
}) {
const {
metadataObj
} = this;
return field => {
const preferredLanguages = getPreferredLanguages({
namespace,
preferredLocale
});
if (pluginsForWork.isPluginField({
namespace,
field
})) {
let [,, targetLanguage] = pluginsForWork.getPluginFieldParts({
namespace,
field
});
if (targetLanguage === '{locale}') {
targetLanguage = preferredLocale;
}
return !targetLanguage || preferredLanguages.includes(targetLanguage);
}
const metaLang = this.getFieldLang(field);
const localeStrings = metadataObj && metadataObj['localization-strings']; // If this is a localized field (e.g., enum), we don't want
// to avoid as may be translated (should check though)
const hasFieldValue = localeStrings && Object.keys(localeStrings).some(lng => {
const fv = localeStrings[lng] && localeStrings[lng].fieldvalue;
return fv && fv[field];
});
return hasFieldValue || metaLang && preferredLanguages.includes(metaLang) || schemaItems.some(item => item.title === field && item.type !== 'string');
};
}
} |
JavaScript | class plot {
constructor(options) {
this.datasetCollection = {};
this.currentDataset = null;
this.setCanvas(options.canvas);
// check if a webgl context is requested and available and set up the shaders
if (defaultFor(options.useWebGL, true)) {
// Try to create a webgl context in a temporary canvas to see if webgl and
// required OES_texture_float is supported
if (create3DContext(new OffscreenCanvas(1, 1), {premultipliedAlpha: false}) !== null) {
const gl = create3DContext(this.canvas, {premultipliedAlpha: false});
this.gl = gl;
this.program = createProgram(gl, vertexShaderSource, fragmentShaderSource);
gl.useProgram(this.program);
// look up where the vertex data needs to go.
const texCoordLocation = gl.getAttribLocation(this.program, 'a_texCoord');
// provide texture coordinates for the rectangle.
this.texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texCoordLocation);
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
} else {
// Fall back to 2d context
this.ctx = this.canvas.getContext('2d');
}
} else {
this.ctx = this.canvas.getContext('2d');
}
if (options.colorScaleImage) {
this.setColorScaleImage(options.colorScaleImage);
} else {
this.setColorScale(defaultFor(options.colorScale, 'viridis'));
}
this.setDomain(defaultFor(options.domain, [0, 1]));
this.displayRange = defaultFor(options.displayRange, [0, 1]);
this.applyDisplayRange = defaultFor(options.applyDisplayRange, false);
this.setClamp(defaultFor(options.clampLow, true), options.clampHigh);
this.setNoDataValue(options.noDataValue);
if (options.data) {
const l = options.data.length;
this.setData(
options.data,
defaultFor(options.width, options.data[l - 2]),
defaultFor(options.height, options.data[l - 2])
);
}
if (options.datasets) {
for (let i = 0; i < options.datasets.length; ++i) {
const ds = options.datasets[i];
this.addDataset(ds.id, ds.data, ds.width, ds.height);
}
}
if (options.matrix) {
this.matrix = options.matrix;
} else { // if no matrix is provided, supply identity matrix
this.matrix = [
1, 0, 0,
0, 1, 0,
0, 0, 1,
];
}
}
/**
* Get the raw data from the currently selected dataset.
* @returns {TypedArray} the data of the currently selected dataset.
*/
getData() {
const dataset = this.currentDataset;
if (!dataset) {
throw new Error('No dataset available.');
}
return dataset.data;
}
/**
* Query the raw raster data at the specified coordinates.
* @param {Number} x the x coordinate
* @param {Number} y the y coordinate
* @returns {Number} the value at the specified coordinates
*/
atPoint(x, y) {
const dataset = this.currentDataset;
if (!dataset) {
throw new Error('No dataset available.');
} else if (x >= dataset.width || y >= dataset.height) {
throw new Error('Coordinates are outside of image bounds.');
}
return dataset.data[(y * dataset.width) + x];
}
/**
* Set the raw raster data to be rendered. This creates a new unnamed dataset.
* @param {TypedArray} data the raw raster data. This can be a typed array of
* any type, but will be coerced to Float32Array when
* beeing rendered.
* @param {int} width the width of the raster image
* @param {int} height the height of the data
*/
setData(data, width, height) {
if (this.currentDataset && this.currentDataset.id === null) {
destroyDataset(this.gl, this.currentDataset);
}
this.currentDataset = createDataset(this.gl, null, data, width, height);
}
/**
* Add a new named dataset. The semantics are the same as with @see setData.
* @param {string} id the identifier for the dataset.
* @param {TypedArray} data the raw raster data. This can be a typed array of
* any type, but will be coerced to Float32Array when
* beeing rendered.
* @param {int} width the width of the raster image
* @param {int} height the height of the data
*/
addDataset(id, data, width, height) {
if (this.datasetAvailable(id)) {
throw new Error(`There is already a dataset registered with id '${id}'`);
}
this.datasetCollection[id] = createDataset(this.gl, id, data, width, height);
if (!this.currentDataset) {
this.currentDataset = this.datasetCollection[id];
}
}
/**
* Set the current dataset to be rendered.
* @param {string} id the identifier of the dataset to be rendered.
*/
setCurrentDataset(id) {
if (!this.datasetAvailable(id)) {
throw new Error(`No such dataset registered: '${id}'`);
}
if (this.currentDataset && this.currentDataset.id === null) {
destroyDataset(this.gl, this.currentDataset);
}
this.currentDataset = this.datasetCollection[id];
}
/**
* Remove the dataset.
* @param {string} id the identifier of the dataset to be removed.
*/
removeDataset(id) {
const dataset = this.datasetCollection[id];
if (!dataset) {
throw new Error(`No such dataset registered: '${id}'`);
}
destroyDataset(this.gl, dataset);
if (this.currentDataset === dataset) {
this.currentDataset = null;
}
delete this.datasetCollection[id];
}
/**
* Check if the dataset is available.
* @param {string} id the identifier of the dataset to check.
* @returns {Boolean} whether or not a dataset with that identifier is defined
*/
datasetAvailable(id) {
return hasOwnProperty(this.datasetCollection, id);
}
/**
* Retrieve the rendered color scale image.
* @returns {(HTMLCanvasElement|HTMLImageElement)} the canvas or image element
* for the rendered color scale
*/
getColorScaleImage() {
return this.colorScaleImage;
}
/**
* Set the canvas to draw to. When no canvas is supplied, a new canvas element
* is created.
* @param {HTMLCanvasElement} [canvas] the canvas element to render to.
*/
setCanvas(canvas) {
this.canvas = canvas || new OffscreenCanvas(1, 1);
}
/**
* Set the new value domain for the rendering.
* @param {float[]} domain the value domain range in the form [low, high]
*/
setDomain(domain) {
if (!domain || domain.length !== 2) {
throw new Error('Invalid domain specified.');
}
this.domain = domain;
}
/**
* Set the display range that will be rendered, values outside of the range
* will not be rendered (transparent)
* @param {float[]} view range array in the form [min, max]
*/
setDisplayRange(displayRange) {
if (!displayRange || displayRange.length !== 2) {
throw new Error('Invalid view range specified.');
}
this.displayRange = displayRange;
// When setting view range automatically enable the apply flag
this.applyDisplayRange = true;
}
/**
* Get the canvas that is currently rendered to.
* @returns {HTMLCanvasElement} the canvas that is currently rendered to.
*/
getCanvas() {
return this.canvas;
}
/**
* Set the currently selected color scale.
* @param {string} name the name of the colorscale. Must be registered.
*/
setColorScale(name) {
if (!hasOwnProperty(colorscales, name)) {
throw new Error(`No such color scale '${name}'`);
}
if (!this.colorScaleCanvas) {
// Create single canvas to render colorscales
this.colorScaleCanvas = new OffscreenCanvas(256, 1);
this.colorScaleCanvas.width = 256;
this.colorScaleCanvas.height = 1;
}
renderColorScaleToCanvas(name, this.colorScaleCanvas);
this.name = name;
this.setColorScaleImage(this.colorScaleCanvas);
}
/**
* Set the clamping for the lower and the upper border of the values. When
* clamping is enabled for either side, the values below or above will be
* clamped to the minimum/maximum color.
* @param {Boolean} clampLow whether or not the minimum shall be clamped.
* @param {Boolean} clampHigh whether or not the maxmimum shall be clamped.
* defaults to clampMin.
*/
setClamp(clampLow, clampHigh) {
this.clampLow = clampLow;
this.clampHigh = (typeof clampHigh !== 'undefined') ? clampHigh : clampLow;
}
/**
* Set the currently selected color scale as an image or canvas.
* @param {(HTMLCanvasElement|HTMLImageElement)} colorScaleImage the new color
* scale image
*/
setColorScaleImage(colorScaleImage) {
this.colorScaleImage = colorScaleImage;
const gl = this.gl;
if (gl) {
if (this.textureScale) {
gl.deleteTexture(this.textureScale);
}
this.textureScale = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.textureScale);
// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, colorScaleImage);
}
}
/**
* Set the no-data-value: a special value that will be rendered transparent.
* @param {float} noDataValue the no-data-value. Use null to clear a
* previously set no-data-value.
*/
setNoDataValue(noDataValue) {
this.noDataValue = noDataValue;
}
/**
* Render the map to the specified canvas with the given settings.
*/
render() {
const canvas = this.canvas;
const dataset = this.currentDataset;
canvas.width = dataset.width;
canvas.height = dataset.height;
let ids = null;
if (this.expressionAst) {
const idsSet = new Set([]);
const getIds = (node) => {
if (typeof node === 'string') {
// ids should not contain unary operators
idsSet.add(node.replace(new RegExp(/[+-]/, 'g'), ''));
}
if (typeof node.lhs === 'string') {
idsSet.add(node.lhs.replace(new RegExp(/[+-]/, 'g'), ''));
} else if (typeof node.lhs === 'object') {
getIds(node.lhs);
}
if (typeof node.rhs === 'string') {
idsSet.add(node.rhs.replace(new RegExp(/[+-]/, 'g'), ''));
} else if (typeof node.rhs === 'object') {
getIds(node.rhs);
}
};
getIds(this.expressionAst);
ids = Array.from(idsSet);
}
let program = null;
if (this.gl) {
const gl = this.gl;
gl.viewport(0, 0, dataset.width, dataset.height);
if (this.expressionAst) {
const vertexShaderSourceExpressionTemplate = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 u_matrix;
uniform vec2 u_resolution;
varying vec2 v_texCoord;
void main() {
// apply transformation matrix
vec2 position = (u_matrix * vec3(a_position, 1)).xy;
// convert the rectangle from pixels to 0.0 to 1.0
vec2 zeroToOne = position / u_resolution;
// convert from 0->1 to 0->2
vec2 zeroToTwo = zeroToOne * 2.0;
// convert from 0->2 to -1->+1 (clipspace)
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
// pass the texCoord to the fragment shader
// The GPU will interpolate this value between points.
v_texCoord = a_texCoord;
}`;
const expressionReducer = (node) => {
if (typeof node === 'object') {
if (node.op === '**') {
// math power operator substitution
return `pow(${expressionReducer(node.lhs)}, ${expressionReducer(node.rhs)})`;
}
if (node.fn) {
return `(${node.fn}(${expressionReducer(node.lhs)}))`;
}
return `(${expressionReducer(node.lhs)} ${node.op} ${expressionReducer(node.rhs)})`;
} else if (typeof node === 'string') {
return `${node}_value`;
}
return `float(${node})`;
};
const compiledExpression = expressionReducer(this.expressionAst);
// Definition of fragment shader
const fragmentShaderSourceExpressionTemplate = `
precision mediump float;
// our texture
uniform sampler2D u_textureScale;
// add all required textures
${ids.map(id => ` uniform sampler2D u_texture_${id};`).join('\n')}
uniform vec2 u_textureSize;
uniform vec2 u_domain;
uniform float u_noDataValue;
uniform bool u_clampLow;
uniform bool u_clampHigh;
// the texCoords passed in from the vertex shader.
varying vec2 v_texCoord;
void main() {
${ids.map(id => ` float ${id}_value = texture2D(u_texture_${id}, v_texCoord)[0];`).join('\n')}
float value = ${compiledExpression};
if (value == u_noDataValue)
gl_FragColor = vec4(0.0, 0, 0, 0.0);
else if ((!u_clampLow && value < u_domain[0]) || (!u_clampHigh && value > u_domain[1]))
gl_FragColor = vec4(0, 0, 0, 0);
else {
float normalisedValue = (value - u_domain[0]) / (u_domain[1] - u_domain[0]);
gl_FragColor = texture2D(u_textureScale, vec2(normalisedValue, 0));
}
}`;
program = createProgram(gl, vertexShaderSource, fragmentShaderSourceExpressionTemplate);
gl.useProgram(program);
gl.uniform1i(gl.getUniformLocation(program, 'u_textureScale'), 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.textureScale);
for (let i = 0; i < ids.length; ++i) {
const location = i + 1;
const id = ids[i];
const ds = this.datasetCollection[id];
if (!ds) {
throw new Error(`No such dataset registered: '${id}'`);
}
gl.uniform1i(gl.getUniformLocation(program, `u_texture_${id}`), location);
gl.activeTexture(gl[`TEXTURE${location}`]);
gl.bindTexture(gl.TEXTURE_2D, ds.textureData);
}
} else {
program = this.program;
gl.useProgram(program);
// set the images
gl.uniform1i(gl.getUniformLocation(program, 'u_textureData'), 0);
gl.uniform1i(gl.getUniformLocation(program, 'u_textureScale'), 1);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, dataset.textureData);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, this.textureScale);
}
const positionLocation = gl.getAttribLocation(program, 'a_position');
const domainLocation = gl.getUniformLocation(program, 'u_domain');
const displayRangeLocation = gl.getUniformLocation(
program, 'u_display_range'
);
const applyDisplayRangeLocation = gl.getUniformLocation(
program, 'u_apply_display_range'
);
const resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
const noDataValueLocation = gl.getUniformLocation(program, 'u_noDataValue');
const clampLowLocation = gl.getUniformLocation(program, 'u_clampLow');
const clampHighLocation = gl.getUniformLocation(program, 'u_clampHigh');
const matrixLocation = gl.getUniformLocation(program, 'u_matrix');
gl.uniform2f(resolutionLocation, canvas.width, canvas.height);
gl.uniform2fv(domainLocation, this.domain);
gl.uniform2fv(displayRangeLocation, this.displayRange);
gl.uniform1i(applyDisplayRangeLocation, this.applyDisplayRange);
gl.uniform1i(clampLowLocation, this.clampLow);
gl.uniform1i(clampHighLocation, this.clampHigh);
gl.uniform1f(noDataValueLocation, this.noDataValue);
gl.uniformMatrix3fv(matrixLocation, false, this.matrix);
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
setRectangle(gl, 0, 0, canvas.width, canvas.height);
// Draw the rectangle.
gl.drawArrays(gl.TRIANGLES, 0, 6);
} else if (this.ctx) {
const ctx = this.ctx;
const w = canvas.width;
const h = canvas.height;
const imageData = ctx.createImageData(w, h);
const trange = this.domain[1] - this.domain[0];
const steps = this.colorScaleCanvas.width;
const csImageData = this.colorScaleCanvas.getContext('2d').getImageData(0, 0, steps, 1).data;
let alpha;
const data = dataset.data;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w) + x;
// TODO: Possible increase of performance through use of worker threads?
let c = Math.floor(((data[i] - this.domain[0]) / trange) * (steps - 1));
alpha = 255;
if (c < 0) {
c = 0;
if (!this.clampLow) {
alpha = 0;
}
} else if (c > 255) {
c = 255;
if (!this.clampHigh) {
alpha = 0;
}
}
// NaN values should be the only values that are not equal to itself
if (data[i] === this.noDataValue || data[i] !== data[i]) {
alpha = 0;
} else if (this.applyDisplayRange
&& (data[i] < this.displayRange[0] || data[i] >= this.displayRange[1])) {
alpha = 0;
}
const index = ((y * w) + x) * 4;
imageData.data[index + 0] = csImageData[c * 4];
imageData.data[index + 1] = csImageData[(c * 4) + 1];
imageData.data[index + 2] = csImageData[(c * 4) + 2];
imageData.data[index + 3] = Math.min(alpha, csImageData[(c * 4) + 3]);
}
}
ctx.putImageData(imageData, 0, 0); // at coords 0,0
}
}
/**
* Render the specified dataset with the current settings.
* @param {string} id the identifier of the dataset to render.
*/
renderDataset(id) {
this.setCurrentDataset(id);
return this.render();
}
/**
* Get the color for the specified value.
* @param {flaot} val the value to query the color for.
* @returns {Array} the 4-tuple: red, green, blue, alpha in the range 0-255.
*/
getColor(val) {
const steps = this.colorScaleCanvas.width;
const csImageData = this.colorScaleCanvas.getContext('2d')
.getImageData(0, 0, steps, 1).data;
const trange = this.domain[1] - this.domain[0];
let c = Math.round(((val - this.domain[0]) / trange) * steps);
let alpha = 255;
if (c < 0) {
c = 0;
if (!this.clampLow) {
alpha = 0;
}
}
if (c > 255) {
c = 255;
if (!this.clampHigh) {
alpha = 0;
}
}
return [
csImageData[c * 4],
csImageData[(c * 4) + 1],
csImageData[(c * 4) + 2],
alpha,
];
}
/**
* Sets a mathematical expression to be evaluated on the plot. Expression can contain mathematical operations with integer/float values, dataset identifiers or GLSL supported functions with a single parameter.
* Supported mathematical operations are: add '+', subtract '-', multiply '*', divide '/', power '**', unary plus '+a', unary minus '-a'.
* Useful GLSL functions are for example: radians, degrees, sin, asin, cos, acos, tan, atan, log2, log, sqrt, exp2, exp, abs, sign, floor, ceil, fract.
* @param {string} expression Mathematical expression. Example: '-2 * sin(3.1415 - dataset1) ** 2'
*/
setExpression(expression) {
if (!expression || !expression.length) {
this.expressionAst = null;
} else {
this.expressionAst = parseArithmetics(expression);
}
}
} |
JavaScript | class ChangeEventBuffer {
constructor(collection) {
this.collection = collection;
this.subs = [];
this.limit = 100;
/**
* array with changeEvents
* starts with oldest known event, ends with newest
* @type {RxChangeEvent[]}
*/
this.buffer = [];
this.counter = 0;
this.eventCounterMap = new WeakMap();
this.subs.push(
this.collection.$
.subscribe(cE => this._handleChangeEvent(cE))
);
}
_handleChangeEvent(changeEvent) {
this.counter++;
this.buffer.push(changeEvent);
this.eventCounterMap.set(changeEvent, this.counter);
while (this.buffer.length > this.limit)
this.buffer.shift();
}
getArrayIndexByPointer(pointer) {
const oldestEvent = this.buffer[0];
const oldestCounter = this.eventCounterMap.get(oldestEvent);
if (pointer < oldestCounter) {
throw new Error(`
pointer lower than lowest cache-pointer
- wanted: ${pointer}
- oldest: ${oldestCounter}
`);
}
const rest = pointer - oldestCounter;
return rest;
}
getFrom(pointer) {
let currentIndex = this.getArrayIndexByPointer(pointer);
const ret = [];
while (true) {
const nextEvent = this.buffer[currentIndex];
currentIndex++;
if (!nextEvent) return ret;
else ret.push(nextEvent);
}
}
runFrom(pointer, fn) {
this.getFrom(pointer).forEach(cE => fn(cE));
}
/**
* no matter how many operations are done on one document,
* only the last operation has to be checked to calculate the new state
* this function reduces the events to the last ChangeEvent of each doc
* @param {ChangeEvent[]} changeEvents
* @return {ChangeEvents[]}
*/
reduceByLastOfDoc(changeEvents) {
const docEventMap = {};
changeEvents.forEach(changeEvent => {
docEventMap[changeEvent.data.doc] = changeEvent;
});
return Object.values(docEventMap);
}
destroy() {
this.subs.forEach(sub => sub.unsubscribe());
}
} |
JavaScript | class AmpFormService {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const @private {!Promise} */
this.whenInitialized_ = this.installStyles_(ampdoc).then(() =>
this.installHandlers_(ampdoc)
);
// Dispatch a test-only event for integration tests.
if (getMode().test) {
this.whenInitialized_.then(() => {
const {win} = ampdoc;
const event = createCustomEvent(win, FormEvents.SERVICE_INIT, null, {
bubbles: true,
});
win.dispatchEvent(event);
});
}
}
/**
* Returns a promise that resolves when all form implementations (if any)
* have been upgraded.
* @return {!Promise}
*/
whenInitialized() {
return this.whenInitialized_;
}
/**
* Install the amp-form CSS
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {!Promise}
* @private
*/
installStyles_(ampdoc) {
const deferred = new Deferred();
installStylesForDoc(ampdoc, CSS, deferred.resolve, false, TAG);
return deferred.promise;
}
/**
* Install the event handlers
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {!Promise}
* @private
*/
installHandlers_(ampdoc) {
return ampdoc.whenReady().then(() => {
const root = ampdoc.getRootNode();
this.installSubmissionHandlers_(root.querySelectorAll('form'));
AmpFormTextarea.install(ampdoc);
this.installGlobalEventListener_(root);
});
}
/**
* Install submission handler on all forms in the document.
* @param {?IArrayLike<T>} forms
* @template T
* @private
*/
installSubmissionHandlers_(forms) {
if (!forms) {
return;
}
iterateCursor(forms, (form, index) => {
const existingAmpForm = formOrNullForElement(form);
if (!existingAmpForm) {
new AmpForm(form, `amp-form-${index}`);
}
});
}
/**
* Listen for DOM updated messages sent to the document.
* @param {!Document|!ShadowRoot} doc
* @private
*/
installGlobalEventListener_(doc) {
doc.addEventListener(AmpEvents.DOM_UPDATE, () => {
this.installSubmissionHandlers_(doc.querySelectorAll('form'));
});
}
} |
JavaScript | class HotPressTimeoutError extends Error {
/**
* @constructor
* @param {Number} ms The milliseconds that exceeded to cause the timeout
*/
constructor (ms) {
super(`Exceeded ${ms}ms`)
}
} |
JavaScript | class ListStyle extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ ListProperties ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'ListStyle';
}
constructor( editor ) {
super( editor );
logWarning( '`ListStyle` plugin is obsolete. Use `ListProperties` instead.' );
}
} |
JavaScript | class EditTramo extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
}
}
componentWillReceiveProps(nextProps) {
console.log("On receive props. Next props are", nextProps);
if(!nextProps.segmento) { return }
if(nextProps.segmento.id && nextProps.segmento.id!==this.state.id) {
const { id, name } = nextProps.segmento;
console.log("Inside willReceiveNextProps", name);
this.setState({
id,
name,
tramoLoaded: true
});
}
}
handleInputChange = (event, index, value) => {
const target = event.target;
const targetValue = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: targetValue
});
}
onSubmitForm = (evt) => {
evt.preventDefault();
const data = JSON.stringify(
{
"id": this.state.id,
"data" : {
"name":this.state.name,
}
}
);
const configuration = new Headers({
"Accept":"application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin":"*"
})
fetch("http://localhost:3000/api/tramo/update", {
method: "POST",
headers: configuration,
body: data
})
.then(res => res.json())
.then((value) => {
console.log("User created", value);
console.log("Data sent: ", data);
let parsedUser = JSON.parse(data)
let userId = this.state.id;
this.props.updateUser(userId, value);
this.props.handleClose();
return 'Tramo updated';
//ACTION TO CREATE A TRAMO
})
.catch((res) => {
console.log("Values sent", data);
console.log("ERROR!", res);
})
}
render() {
const actions = [
<FlatButton
backgroundColor={ 'red' }
style={ {color: 'white', width: '150px', height: '50px'} }
hoverColor={ 'red' }
label="ACTUALIZAR"
keyboardFocused={true}
primary={true}
onTouchTap={ this.onSubmitForm }
/>
];
return (
<Wrapper>
<Dialog
actions={actions}
modal={false}
open={this.props.open}
onRequestClose={this.props.handleClose}
actionsContainerStyle={ {textAlign: 'center'} }
bodyStyle={ {height: 'auto'} }
contentStyle={ {height: 'auto', width: '550px'} }
overlayStyle={ {background: 'gray', opacity: 0.80}}
style={ {fontSize: '18px'}}
>
<h2>Editar Tramo</h2>
<Form onSubmit={this.onSubmitForm}>
<TextField
floatingLabelFocusStyle= { {color: '#00BDA3'} }
floatingLabelStyle= { {color: '#707070'} }
hintText="nombre"
floatingLabelText="NOMBRE"
name="name"
value={this.state.name}
onChange={this.handleInputChange}
/><br />
</Form>
</Dialog>
</Wrapper>
);
}
} |
JavaScript | class ConfigManager {
/**
* Loads the configuration file.
*/
static load() {
if (configStore.data) {
WindowManager.emit('store-update', configStore.data);
}
fs.readFile(configFile, 'utf8', (err, data) => {
if (err) {
configStore.data = configStore.defaultConfig;
} else {
configStore.data = JSON.parse(data);
}
WindowManager.emit('store-update', configStore.data);
});
}
/**
* Retrieves the configuration data. When the renderer calls it, it will send
* a request to the main process synchronously, so that it will retrieve the
* data immediately instead of having to wait for it.
*/
static get() {
return configStore.data;
}
/**
* Sets a new configuration state. This is purely meant for the renderer.
*/
static set(state) {
configStore.data = {
...configStore.data,
...state,
};
const content = JSON.stringify(configStore.data);
fs.writeFile(configFile, content, (err) => {
if (err) {
console.log(err);
} else {
WindowManager.emit('store-update', configStore.data);
}
});
}
} |
JavaScript | class PointToPointConstraint extends Constraint {
constructor(bodyA, pivotA, bodyB, pivotB, maxForce) {
super(bodyA, bodyB)
maxForce = typeof maxForce !== 'undefined' ? maxForce : 1e6
/**
* Pivot, defined locally in bodyA.
* @property {Vec3} pivotA
*/
this.pivotA = pivotA ? pivotA.clone() : new Vec3()
/**
* Pivot, defined locally in bodyB.
* @property {Vec3} pivotB
*/
this.pivotB = pivotB ? pivotB.clone() : new Vec3()
/**
* @property {ContactEquation} equationX
*/
const x = (this.equationX = new ContactEquation(bodyA, bodyB))
/**
* @property {ContactEquation} equationY
*/
const y = (this.equationY = new ContactEquation(bodyA, bodyB))
/**
* @property {ContactEquation} equationZ
*/
const z = (this.equationZ = new ContactEquation(bodyA, bodyB))
// Equations to be fed to the solver
this.equations.push(x, y, z)
// Make the equations bidirectional
x.minForce = y.minForce = z.minForce = -maxForce
x.maxForce = y.maxForce = z.maxForce = maxForce
x.ni.set(1, 0, 0)
y.ni.set(0, 1, 0)
z.ni.set(0, 0, 1)
}
update() {
const bodyA = this.bodyA
const bodyB = this.bodyB
const x = this.equationX
const y = this.equationY
const z = this.equationZ
// Rotate the pivots to world space
bodyA.quaternion.vmult(this.pivotA, x.ri)
bodyB.quaternion.vmult(this.pivotB, x.rj)
y.ri.copy(x.ri)
y.rj.copy(x.rj)
z.ri.copy(x.ri)
z.rj.copy(x.rj)
}
} |
JavaScript | class Bullet {
constructor (scene, id, creator, x, y, angle, speed, polygonPoints, spawnToleranceRadius) {
this.sizeX = 9;
this.sizeY = 54;
this.creator = creator;
this.id = id;
this.speed = speed;
this.item = scene.physics.add.image(x, y, "bullet");
this.item.setDisplaySize(this.sizeX, this.sizeY);
this.item.setAngle(angle * 180 / Math.PI);
this.item.par_obj = this; // Just to associate this id with the image
this.colpoly = new PolygonShape(scene, x, y, 1, polygonPoints);
this.spawnToleranceShape = new CircleShape(scene, x, y, spawnToleranceRadius, {stroke: true, color: SPAWN_INFLUENCE_COLOR, alpha: 1});
}
update (data) {
this.colpoly.update(data.x, data.y);
this.spawnToleranceShape.update(data.x, data.y);
this.item.setPosition(data.x, data.y);
this.item.setVelocity(Math.sin(data.angle)*this.speed, -(Math.cos(data.angle)*this.speed));
this.item.setDepth(data.y);
}
destroy () {
this.item.destroy();
this.colpoly.destroy();
this.spawnToleranceShape.destroy();
}
} |
JavaScript | class Cell {
constructor (scene, id, x, y, polygonPoints, spawnToleranceRadius) {
this.sizeX = 32;
this.sizeY = 40;
this.id = id;
this.item = scene.add.image(x, y, "fuelcell");
this.item.setDisplaySize(this.sizeX, this.sizeY);
this.item.setSize(this.sizeX, this.sizeY);
this.item.setScale(0.9);
this.item.par_obj = this; // Just to associate this id with the image
this.colpoly = new PolygonShape(scene, x, y, this.scale, polygonPoints);
this.spawnToleranceShape = new CircleShape(scene, x, y, spawnToleranceRadius, {stroke: true, color: SPAWN_INFLUENCE_COLOR, alpha: 1});
}
destroy () {
this.item.destroy();
this.spawnToleranceShape.destroy();
this.colpoly.destroy();
}
} |
JavaScript | class Ammo {
constructor (scene, id, x, y, polygonPoints, spawnToleranceRadius) {
this.sizeX = 32;
this.sizeY = 40;
this.id = id;
this.item = scene.add.image(x, y, "ammopack");
this.item.setDisplaySize(this.sizeX, this.sizeY);
this.item.setSize(this.sizeX, this.sizeY);
this.item.setScale(0.9);
this.item.par_obj = this; // Just to associate this id with the image
this.colpoly = new PolygonShape(scene, x, y, this.scale, polygonPoints);
this.spawnToleranceShape = new CircleShape(scene, x, y, spawnToleranceRadius, {stroke: true, color: SPAWN_INFLUENCE_COLOR, alpha: 1});
}
destroy () {
this.item.destroy();
this.spawnToleranceShape.destroy();
this.colpoly.destroy();
}
} |
JavaScript | class Island {
constructor (scene, id, x, y, radius, spawnToleranceRadius) {
this.sizeX = 159;
this.sizeY = 159;
this.id = id;
this.island = scene.add.image(x, y, "station");
this.island.setDisplaySize(this.sizeX, this.sizeY);
this.island.setSize(this.sizeX, this.sizeY);
this.island.setScale(0.95);
this.island.par_obj = this; // Just to associate this id with the image
this.colShape = new CircleShape(scene, x, y, radius);
this.influenceShape = new CircleShape(scene, x, y, 3*radius, {stroke: true, color: 0x0000b2, alpha: 1})
this.spawnToleranceShape = new CircleShape(scene, x, y, spawnToleranceRadius, {stroke: true, color: SPAWN_INFLUENCE_COLOR, alpha: 1});
}
destroy () {
this.island.destroy();
this.colShape.destroy();
this.influenceShape.destroy();
this.spawnToleranceRadius.destroy();
}
} |
JavaScript | class Asteroid {
constructor (scene, id, x, y, polygonPoints, spawnToleranceRadius) {
this.sizeX = 151;
this.sizeY = 127;
this.scale = 0.7;
this.id = id;
this.asteroid = scene.add.image(x, y, "asteroid");
this.asteroid.setDisplaySize(this.sizeX, this.sizeY);
this.asteroid.setSize(this.sizeX, this.sizeY);
this.asteroid.setScale(this.scale);
this.asteroid.par_obj = this; // Just to associate this id with the image
this.colpoly = new PolygonShape(scene, x, y, this.scale, polygonPoints);
this.spawnToleranceShape = new CircleShape(scene, x, y, spawnToleranceRadius, {stroke: true, color: SPAWN_INFLUENCE_COLOR, alpha: 1});
}
destroy () {
this.colpoly.destroy();
this.asteroid.destroy();
this.spawnToleranceShape.destroy();
}
} |
JavaScript | class Explosion {
constructor (scene, x, y, scale, attack, decay) {
this.sizeX = 100*scale;
this.sizeY = 100*scale;
this.explosion = scene.add.image(x, y, "explosion").setAlpha(0);
this.explosion.setDepth(5100);
this.explosion.setDisplaySize(this.sizeX, this.sizeY);
this.explosion.setSize(this.sizeX, this.sizeY);
this.tween = scene.tweens.add({
targets: this.explosion,
paused: false,
delay: 0,
duration: attack,
ease: "Sine.easeInOut",
alpha: {
getStart: () => 0,
getEnd: () => 1
},
onComplete: () => {
scene.tweens.add({
targets: this.explosion,
paused: false,
delay: 0,
duration: decay,
ease: "Sine.easeInOut",
alpha: {
getStart: () => 1,
getEnd: () => 0
},
onComplete: () => {
this.destroy();
}
});
}
});
}
destroy () {
this.explosion.destroy();
}
} |
JavaScript | class Account{
constructor(pin, balance = 0){
this.pin = pin;
this.balance = balance;
}
getBalance(){
atm.clearInput("value");
return this.balance;
}
deposit(){
let amount = document.getElementById("value").value;
document.getElementById("msgBox").style = "color:red";
amount = parseInt(amount);
if(isNaN(amount)){
atm.displayMgs("msgBox", "Enter amount")
console.log(isNaN(amount));
}
else if(amount < 0 ){
atm.displayMgs("msgBox", "Amout cannot be less then 0")
}
else if( isNaN(amount)===false) {
this.balance += amount;
atm.displayMgs("msgBox", `Your new balance is: $${this.balance}`)
document.getElementById("msgBox").style = "color:#1e2749"
atm.updateLocalStor();
atm.clearInput("value");
}
}
withdrawal(){
let amount = document.getElementById("value").value;
document.getElementById("msgBox").style = "color:red"
amount = parseInt(amount)
if(isNaN(amount)){
atm.displayMgs("msgBox", "Enter amount")
}
else if(amount < 0 ){
atm.displayMgs("msgBox", "Amout cannot be less then 0")
}
else if(amount > this.balance){
atm.displayMgs("msgBox", "insufficent funds for this transaction")
}
else{
this.balance -= parseInt(amount);
atm.displayMgs("msgBox", `Your new balance is: $${this.balance}`)
document.getElementById("msgBox").style = "color:#1e2749"
atm.updateLocalStor();
atm.clearInput("value");
}
}
changePin(){
atm.account.exist = false;
let pin = document.getElementById("value").value;
document.getElementById("msgBox").style = "color:red"
atm.validate(pin)
if(isNaN(parseInt(pin))){
atm.displayMgs("msgBox", "Pin can only be numbers");
}
else if(atm.account.exist){
atm.displayMgs("msgBox", "invalid Pin!");
}
else if(atm.account.exist == false){
atm.updateLocalStor();
this.pin = pin
atm.displayMgs("msgBox", `Your New Pin is: ${this.pin}`);
document.getElementById("msgBox").style = "color:#1e2749"
atm.updateLocalStor();
}
}
} |
JavaScript | class ColumnTogglingExtension {
/**
* Extend grid
*
* @param {Grid} grid
*/
extend(grid) {
const $table = grid.getContainer().find('table.table');
$table.find('.ps-togglable-row').on('click', (e) => {
e.preventDefault();
this._toggleValue($(e.delegateTarget));
});
}
/**
* @param {jQuery} row
* @private
*/
_toggleValue(row) {
const toggleUrl = row.data('toggleUrl');
this._submitAsForm(toggleUrl);
}
/**
* Submits request url as form
*
* @param {string} toggleUrl
* @private
*/
_submitAsForm(toggleUrl) {
const $form = $('<form>', {
action: toggleUrl,
method: 'POST',
}).appendTo('body');
$form.submit();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.