language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class SignInProtocol {
/**
* @param {!Window} win
* @param {!Viewer} viewer
* @param {string} pubOrigin
* @param {!JSONObject} configJson
*/
constructor(win, viewer, pubOrigin, configJson) {
/** @const {!Window} */
this.win = win;
/** @private @const {!Viewer} */
this.viewer_ = viewer;
/** @private @const {string} */
this.pubOrigin_ = pubOrigin;
/** @private @const {boolean} */
this.isEnabled_ =
isExperimentOn(this.win, TAG) &&
this.viewer_.isEmbedded() &&
this.viewer_.getParam('signin') == '1';
if (this.isEnabled_) {
/** @private @const {boolean} */
this.acceptAccessToken_ = !!configJson['acceptAccessToken'];
const viewerSignInService = this.viewer_.getParam('signinService');
const configSignInServices = configJson['signinServices'];
if (configSignInServices) {
user().assert(isArray(configSignInServices),
'"signinServices" must be an array');
}
/** @private @const {boolean} */
this.supportsSignInService_ = configSignInServices &&
configSignInServices.indexOf(viewerSignInService) != -1;
} else {
/** @private @const {boolean} */
this.acceptAccessToken_ = false;
/** @private @const {boolean} */
this.supportsSignInService_ = false;
}
/** @private {?Promise<?string>} */
this.accessTokenPromise_ = null;
}
/**
* Whether this protocol has been enabled by the viewer.
* @return {boolean}
*/
isEnabled() {
return this.isEnabled_;
}
/**
* Starts up the sign-in protocol by passively pre-fetching the access token.
*/
start() {
this.getAccessTokenPassive();
}
/**
* Return the promise that will possibly yield the access token from the
* viewer.
*
* If viewer has not opted-in into signin protocol, this method returns
* `null`. If source origin has not opted-in into signin protocol via
* `acceptAccessToken: true` configration option, this method returns `null`.
*
* If an access token is not found or cannot be retrieved, this method
* returns a promise that will resolve `null`.
*
* @return {?Promise<?string>}
*/
getAccessTokenPassive() {
if (!this.acceptAccessToken_) {
return null;
}
if (!this.accessTokenPromise_) {
this.accessTokenPromise_ = this.viewer_.sendMessageAwaitResponse(
'getAccessTokenPassive', {
origin: this.pubOrigin_,
}).then(resp => {
return /** @type {?string} */ (resp);
}).catch(reason => {
user().error(TAG, 'Failed to retrieve access token: ', reason);
return null;
});
}
return this.accessTokenPromise_;
}
/**
* @param {?string} accessToken
* @private
*/
updateAccessToken_(accessToken) {
this.accessTokenPromise_ = Promise.resolve(accessToken);
}
/**
* Processes login dialog's result. And if `#code=` hash parameter
* is specified, will send this authorization code to the viewer to exchange
* for the access token. This method returns promise that will resolve the
* exchanged access token.
*
* If viewer has not opted-in into signin protocol, this method returns
* `null`. If source origin has not opted-in into signin protocol via
* `acceptAccessToken: true` configration option and by returning
* `#code=` response from the login dialog, this method returns
* `null`.
*
* The viewer is allowed to store the access token, but only when the user
* explicitly consents to it.
*
* @param {!Object<string, string>} query
* @return {?Promise<?string>}
*/
postLoginResult(query) {
if (!this.acceptAccessToken_) {
return null;
}
const authorizationCode = query['code'];
if (!authorizationCode) {
return null;
}
return this.viewer_.sendMessageAwaitResponse('storeAccessToken', {
origin: this.pubOrigin_,
authorizationCode,
}).then(resp => {
const accessToken = /** @type {?string} */ (resp);
this.updateAccessToken_(accessToken);
return accessToken;
}).catch(reason => {
user().error(TAG, 'Failed to retrieve access token: ', reason);
return null;
});
}
/**
* Requests the viewer to perform login on behalf of the source origin
* with the optional ID token. The result is the promise that will resolve
* with the dialog's response.
*
* If viewer has not opted-in into signin protocol, this method returns
* `null`. If source origin has not opted-in into signin protocol via
* `signinServices: []` configration option that includes this viewer's
* service, this method returns `null`.
*
* The viewer is only allowed to propagate ID token to the login dialog
* when the user explicitly consents to it.
*
* @param {string} url
* @return {?Promise<?string>}
*/
requestSignIn(url) {
if (!this.supportsSignInService_) {
return null;
}
return this.viewer_.sendMessageAwaitResponse('requestSignIn', {
origin: this.pubOrigin_,
url,
}).then(resp => {
const accessToken = /** @type {?string} */ (resp);
this.updateAccessToken_(accessToken);
// Return empty dialog result.
return '';
});
}
} |
JavaScript | class UseCases extends Component {
constructor(props) {
super(props)
this.state = {
activeUseCase: 1,
activeUseCaseTitle: useCasesData.filter(f => f.id === 1)[0].title,
activeUseCaseDescription: useCasesData.filter(f => f.id === 1)[0]
.description,
activeUseCaseVideo: useCasesData.filter(f => f.id === 1)[0].videoUrl,
videoPlaying: false,
isMobile: false,
}
this.onScroll = this.onScroll.bind(this)
this.updateActiveUseCaseMobile = this.updateActiveUseCaseMobile.bind(this)
}
componentDidMount() {
if (window) {
const isMobile = window.innerWidth <= 420 ? true : false
if (isMobile) {
this.setState({ isMobile: true })
}
window.addEventListener('scroll', this.onScroll, false)
}
}
componentWillUnmount() {
if (window) {
window.removeEventListener('scroll', this.onScroll, false)
}
}
onScroll() {
const scrollY = window.scrollY
if (scrollY > 1587 && !this.state.isMobile) {
this.setState({ videoPlaying: true })
}
}
autoPlayNextVideo() {
const nextId =
this.state.activeUseCase === 6 ? 1 : this.state.activeUseCase + 1
const nextIdFeature = useCasesData.filter(f => f.id === nextId)[0]
this.updateActiveUseCase(nextIdFeature)
this.setState({ activeUseCase: nextId })
}
toggleVideoPlaying() {
if (!this.state.isMobile) {
this.setState({ videoPlaying: !this.state.videoPlaying })
}
}
updateActiveUseCaseMobile(event) {
const useCaseTitle = event.target.value
const useCase = useCasesData.filter(f => f.title === useCaseTitle)[0]
this.updateActiveUseCase(useCase)
}
updateActiveUseCase(useCase) {
this.setState({
activeUseCase: useCase.id,
activeUseCaseTitle: useCase.title,
activeUseCaseDescription: useCase.description,
activeUseCaseVideo: useCase.videoUrl,
videoPlaying: true,
})
}
render() {
return (
<Flex mt={[92, 92, 52, 52, 122]}>
<Box width={[0, 0, 0, 0, 0.55]}>
<Box>
<div className='framework-video-player-wrapper'>
<ReactPlayer
url={this.state.activeUseCaseVideo}
controls={this.state.isMobile ? true : false}
onEnded={() => this.autoPlayNextVideo()}
className='react-player'
muted
loop={false}
playing={this.state.videoPlaying}
config={{
file: {
attributes: {
poster: videoPosterImage,
},
},
}}
/>
</div>
</Box>
</Box>
<Column width={[1, 1, 1, 1, 0.55]}>
<Box width={[1, 1, 1, 1, 1]}>
<Heading.h3 mb={46} align={['center', 'center', 'left']}>
The Serverless Application lifecycle
</Heading.h3>
<Box display={['none', 'none', 'block']}>
<Flex pb={'7px'} justifyContent={['space-between']}>
{useCasesData.map(useCase => (
<HoverableText
fontFamily={'SoleilBk'}
key={useCase.id}
fontSize={'18px'}
lineHeight={'30px'}
letterSpacing={['-0.28px']}
mr={[30, 30, 30, 30, '10px', 36]}
onEnded={() => this.autoPlayNextVideo()}
mb={['-9px']}
style={
useCase.id === this.state.activeUseCase
? { borderBottom: '2px solid black', color: '#000' }
: { color: '#8c8c8c' }
}
onClick={() => this.updateActiveUseCase(useCase)}
>
{useCase.title}
</HoverableText>
))}
</Flex>
<HR />
</Box>
<Box display={['block', 'block', 'none']}>
<StyledSelect onChange={this.updateActiveUseCaseMobile}>
{useCasesData.map(useCase => (
<option key={useCase.id} value={useCase.title}>
{useCase.title}
</option>
))}
</StyledSelect>
</Box>
</Box>
<Text
fontSize={'24px'}
lineHeight={'38px'}
letterSpacing={'-0.38px'}
fontFamily='Soleil'
mt={62}
>
{this.state.activeUseCaseTitle}
</Text>
<Flex flexDirection={['column', 'column', 'row']}>
<Column width={[1, 1, 0.5, 0.5, 0.8, 0.8]}>
<Box
minHeight={
this.state.activeUseCaseTitle === 'Intro'
? [0]
: [0, 0, 234, 182, 150]
}
>
<P mb={0} mt={'8px'}>
{this.state.activeUseCaseDescription}
</P>
</Box>
<Box display={['none', 'none', 'block']}>
<Actions />
</Box>
</Column>
</Flex>
<MobileCTA />
</Column>
</Flex>
)
}
} |
JavaScript | class FT_EEPROM_DATA {
constructor () {
this.vendorId = 0x0403
this.productId = 0x6001
this.manufacturer = 'FTDI'
this.manufacturerId = 'FT'
this.description = 'USB-Serial Converter'
this.serialNumber = ''
this.maxPower = 0x0090
this.selfPowered = false
this.remoteWakeup = false
}
} |
JavaScript | class Input extends Box {
constructor(options = {}) {
if (!options.sku) options.sku = 'input';
super(options);
this.type = 'input';
}
static build(options) {
return new Input(options);
}
} |
JavaScript | class Button extends Input {
constructor(options = {}) {
if (!options.sku) options.sku = 'button';
if (options.autoFocus == null) options.autoFocus = false;
super(options);
const self = this; // if (!(this instanceof Node)) return new Button(options)
this.on(KEYPRESS, (ch, key) => {
const name = key.name;
if (name === ENTER || name === SPACE || name === RETURN) return self.press();
});
if (this.options.mouse) {
this.on(CLICK, () => self.press());
}
this.type = 'button';
}
static build(options) {
return new Button(options);
}
press() {
this.focus();
this.value = true;
const result = this.emit(PRESS);
delete this.value;
return result;
}
} |
JavaScript | class Checkbox extends Input {
/**
* Checkbox
*/
constructor(options = {}) {
super(options);
const self = this; // if (!(this instanceof Node)) return new Checkbox(options)
this.text = options.content || options.text || '';
this.checked = this.value = options.checked || false;
this.on(KEYPRESS, (ch, key) => {
if (key.name === ENTER || key.name === SPACE) self.toggle(), self.screen.render();
});
if (options.mouse) this.on(CLICK, () => {
self.toggle(), self.screen.render();
});
this.on(FOCUS, function () {
const prevPos = self.prevPos;
if (!prevPos) return;
const program = self.screen.program;
program.lsaveCursor('checkbox');
program.cup(prevPos.yLo, prevPos.xLo + 1);
program.showCursor();
});
this.on(BLUR, () => self.screen.program.lrestoreCursor('checkbox', true));
this.type = 'checkbox'; // console.log(`>>> ${this.type} created, uid = ${this.uid}`)
}
static build(options) {
return new Checkbox(options);
}
render() {
// console.log('>>> checkbox rendered')
this.clearPos(true);
this.setContent('[' + (this.checked ? 'x' : ' ') + '] ' + this.text, true);
return this.renderElement();
}
check() {
if (this.checked) return;
this.checked = this.value = true;
this.emit(CHECK);
}
uncheck() {
if (!this.checked) return;
this.checked = this.value = false;
this.emit(UNCHECK);
}
toggle() {
return this.checked ? this.uncheck() : this.check();
}
} |
JavaScript | class FileManager extends List {
/**
* FileManager
*/
constructor(options = {}) {
options.parseTags = true;
super(options);
const self = this; // if (!(this instanceof Node)) return new FileManager(options)
// options.label = ' {blue-fg}%path{/blue-fg} ';
// List.call(this, options)
this.cwd = options.cwd || process.cwd();
this.file = this.cwd;
this.value = this.cwd;
if (options.label && ~options.label.indexOf('%path')) this._label.setContent(options.label.replace('%path', this.cwd));
this.on(SELECT, function (item) {
const value = item.content.replace(/\{[^{}]+\}/g, '').replace(/@$/, ''),
file = path.resolve(self.cwd, value);
return fs.stat(file, function (err, stat) {
if (err) return self.emit(ERROR, err, file);
self.file = file;
self.value = file;
if (stat.isDirectory()) {
self.emit(CD, file, self.cwd);
self.cwd = file;
if (options.label && ~options.label.indexOf('%path')) {
self._label.setContent(options.label.replace('%path', file));
}
self.refresh();
} else {
self.emit(FILE, file);
}
});
});
this.type = 'file-manager';
}
static build(options) {
return new FileManager(options);
}
refresh(cwd, callback) {
if (!callback) {
callback = cwd;
cwd = null;
}
const self = this;
if (cwd) this.cwd = cwd;else cwd = this.cwd;
return fs.readdir(cwd, function (err, list) {
if (err && err.code === 'ENOENT') {
self.cwd = cwd !== process.env.HOME ? process.env.HOME : '/';
return self.refresh(callback);
}
if (err) {
if (callback) return callback(err);
return self.emit(ERROR, err, cwd);
}
let dirs = [],
files = [];
list.unshift('..');
list.forEach(function (name) {
const f = path.resolve(cwd, name);
let stat;
try {
stat = fs.lstatSync(f);
} catch (e) {}
if (stat && stat.isDirectory() || name === '..') {
dirs.push({
name: name,
text: '{light-blue-fg}' + name + '{/light-blue-fg}/',
dir: true
});
} else if (stat && stat.isSymbolicLink()) {
files.push({
name: name,
text: '{light-cyan-fg}' + name + '{/light-cyan-fg}@',
dir: false
});
} else {
files.push({
name: name,
text: name,
dir: false
});
}
});
dirs = helpers.asort(dirs);
files = helpers.asort(files);
list = dirs.concat(files).map(function (data) {
return data.text;
});
self.setItems(list);
self.select(0);
self.screen.render();
self.emit(REFRESH);
if (callback) callback();
});
}
pick(cwd, callback) {
if (!callback) {
callback = cwd;
cwd = null;
}
const self = this,
focused = this.screen.focused === this,
hidden = this.hidden;
let onfile, oncancel;
function resume() {
self.removeListener(FILE, onfile);
self.removeListener(CANCEL, oncancel);
if (hidden) {
self.hide();
}
if (!focused) {
self.screen.restoreFocus();
}
self.screen.render();
}
this.on(FILE, onfile = function (file) {
resume();
return callback(null, file);
});
this.on(CANCEL, oncancel = function () {
resume();
return callback();
});
this.refresh(cwd, function (err) {
if (err) return callback(err);
if (hidden) {
self.show();
}
if (!focused) {
self.screen.saveFocus();
self.focus();
}
self.screen.render();
});
}
reset(cwd, callback) {
if (!callback) {
callback = cwd;
cwd = null;
}
this.cwd = cwd || this.options.cwd;
this.refresh(callback);
}
} |
JavaScript | class Form extends Box {
constructor(options = {}) {
if (!options.sku) options.sku = 'form';
options.ignoreKeys = true;
super(options);
const self = this; // if (!(this instanceof Node)) return new Form(options)
if (options.keys) {
this.screen._listenKeys(this);
this.on(ELEMENT_KEYPRESS, function (el, ch, key) {
if (key.name === TAB && !key.shift || el.type === 'textbox' && options.autoNext && key.name === ENTER || key.name === DOWN || options.vi && key.name === 'j') {
if (el.type === 'textbox' || el.type === 'textarea') {
if (key.name === 'j') return;
if (key.name === TAB) el.emit(KEYPRESS, null, {
name: BACKSPACE
}); // Workaround, since we can't stop the tab from being added.
el.emit(KEYPRESS, '\x1b', {
name: ESCAPE
});
}
self.focusNext();
return;
}
if (key.name === TAB && key.shift || key.name === UP || options.vi && key.name === 'k') {
if (el.type === 'textbox' || el.type === 'textarea') {
if (key.name === 'k') return;
el.emit(KEYPRESS, '\x1b', {
name: ESCAPE
});
}
self.focusPrevious();
return;
}
if (key.name === ESCAPE) self.focus();
});
}
this.type = 'form';
}
static build(options) {
return new Form(options);
}
_refresh() {
// XXX Possibly remove this if statement and refresh on every focus.
// Also potentially only include *visible* focusable elements.
// This would remove the need to check for _selected.visible in previous()
// and next().
if (!this._sub) {
const out = [];
this.sub.forEach(function refreshSub(el) {
if (el.keyable) out.push(el);
el.sub.forEach(refreshSub);
});
this._sub = out;
}
}
_visible() {
return !!this._sub.filter(el => el.visible).length;
}
next() {
this._refresh();
if (!this._visible()) return;
if (!this._selected) {
this._selected = this._sub[0];
if (!this._selected.visible) return this.next();
if (this.screen.focused !== this._selected) return this._selected;
}
const i = this._sub.indexOf(this._selected);
if (!~i || !this._sub[i + 1]) {
this._selected = this._sub[0];
if (!this._selected.visible) return this.next();
return this._selected;
}
this._selected = this._sub[i + 1];
if (!this._selected.visible) return this.next();
return this._selected;
}
previous() {
this._refresh();
if (!this._visible()) return;
if (!this._selected) {
this._selected = this._sub[this._sub.length - 1];
if (!this._selected.visible) return this.previous();
if (this.screen.focused !== this._selected) return this._selected;
}
const i = this._sub.indexOf(this._selected);
if (!~i || !this._sub[i - 1]) {
this._selected = this._sub[this._sub.length - 1];
if (!this._selected.visible) return this.previous();
return this._selected;
}
this._selected = this._sub[i - 1];
if (!this._selected.visible) return this.previous();
return this._selected;
}
focusNext() {
const next = this.next();
if (next) next.focus();
}
focusPrevious() {
const previous = this.previous();
if (previous) previous.focus();
}
resetSelected() {
this._selected = null;
}
focusFirst() {
this.resetSelected();
this.focusNext();
}
focusLast() {
this.resetSelected();
this.focusPrevious();
}
submit() {
const out = {};
this.sub.forEach(function submitSub(el) {
if (el.value != null) {
const name = el.name || el.type;
if (Array.isArray(out[name])) {
out[name].push(el.value);
} else if (out[name]) {
out[name] = [out[name], el.value];
} else {
out[name] = el.value;
}
}
el.sub.forEach(submitSub);
});
this.emit(SUBMIT, out);
return this.submission = out;
}
cancel() {
this.emit(CANCEL);
}
reset() {
this.sub.forEach(function resetSub(el) {
switch (el.type) {
case 'screen':
break;
case 'box':
break;
case 'text':
break;
case 'line':
break;
case 'scrollable-box':
break;
case 'list':
el.select(0);
return;
case 'form':
break;
case 'input':
break;
case 'textbox':
el.clearInput();
return;
case 'textarea':
el.clearInput();
return;
case 'button':
delete el.value;
break;
case 'progress-bar':
el.setProgress(0);
break;
case 'file-manager':
el.refresh(el.options.cwd);
return;
case 'checkbox':
el.uncheck();
return;
case 'radio-set':
break;
case 'radio-button':
el.uncheck();
return;
case 'prompt':
break;
case 'question':
break;
case 'message':
break;
case 'info':
break;
case 'loading':
break;
case 'list-bar':
//el.select(0);
break;
case 'dir-manager':
el.refresh(el.options.cwd);
return;
case 'terminal':
el.write('');
return;
case 'image':
//el.clearImage();
return;
}
el.sub.forEach(resetSub);
});
this.emit(RESET);
}
} |
JavaScript | class Textbox extends Textarea {
__olistener = super._listener;
constructor(options = {}) {
if (!options.sku) options.sku = 'textbox';
options.scrollable = false;
super(options); // if (!(this instanceof Node)) { return new Textbox(options) }
this.secret = options.secret;
this.censor = options.censor;
this.type = 'textbox'; // console.log(`>>> constructed ${this.type}`)
}
static build(options) {
return new Textbox(options);
}
_listener(ch, key) {
// console.log('>>> calling _listener in Textbox')
return key.name === ENTER ? void this._done(null, this.value) : this.__olistener(ch, key);
}
setValue(value) {
let visible, val;
if (value == null) value = this.value;
if (this._value !== value) {
value = value.replace(/\n/g, '');
this.value = value;
this._value = value;
if (this.secret) {
this.setContent('');
} else if (this.censor) {
this.setContent(Array(this.value.length + 1).join('*'));
} else {
visible = -(this.width - this.intW - 1);
val = this.value.replace(/\t/g, this.screen.tabc);
this.setContent(val.slice(visible));
}
this._updateCursor();
}
}
submit() {
return this.__listener ? this.__listener('\r', {
name: ENTER
}) : void 0;
}
} |
JavaScript | class Prompt extends Box {
input = this.readInput;
setInput = this.readInput;
/**
* Prompt
*/
constructor(options = {}) {
options.hidden = true;
super(options); // if (!(this instanceof Node)) return new Prompt(options)
this._.input = new Textbox({
sup: this,
top: 3,
height: 1,
left: 2,
right: 2,
bg: 'black'
});
this._.okay = new Button({
sup: this,
top: 5,
height: 1,
left: 2,
width: 6,
content: 'Okay',
align: 'center',
bg: 'black',
hoverBg: 'blue',
autoFocus: false,
mouse: true
});
this._.cancel = new Button({
sup: this,
top: 5,
height: 1,
shrink: true,
left: 10,
width: 8,
content: 'Cancel',
align: 'center',
bg: 'black',
hoverBg: 'blue',
autoFocus: false,
mouse: true
});
this.type = 'prompt';
}
static build(options) {
return new Prompt(options);
}
readInput(text, value, callback) {
const self = this;
let okay, cancel;
if (!callback) {
callback = value;
value = '';
} // Keep above:
// var sup = this.sup;
// this.detach();
// sup.append(this);
this.show();
this.setContent(' ' + text);
this._.input.value = value;
this.screen.saveFocus();
this._.okay.on(PRESS, okay = function () {
self._.input.submit();
});
this._.cancel.on(PRESS, cancel = function () {
self._.input.cancel();
});
this._.input.readInput(function (err, data) {
self.hide();
self.screen.restoreFocus();
self._.okay.removeListener(PRESS, okay);
self._.cancel.removeListener(PRESS, cancel);
return callback(err, data);
});
this.screen.render();
}
} |
JavaScript | class Question extends Box {
/**
* Question
*/
constructor(options = {}) {
options.hidden = true;
super(options); // if (!(this instanceof Node)) return new Question(options)
this._.okay = new Button({
screen: this.screen,
sup: this,
top: 2,
height: 1,
left: 2,
width: 6,
content: 'Okay',
align: 'center',
bg: 'black',
hoverBg: 'blue',
autoFocus: false,
mouse: true
});
this._.cancel = new Button({
screen: this.screen,
sup: this,
top: 2,
height: 1,
shrink: true,
left: 10,
width: 8,
content: 'Cancel',
align: 'center',
bg: 'black',
hoverBg: 'blue',
autoFocus: false,
mouse: true
});
this.type = 'question';
}
static build(options) {
return new Question(options);
}
ask(text, callback) {
const self = this;
let press, okay, cancel; // Keep above:
// var sup = this.sup;
// this.detach();
// sup.append(this);
this.show();
this.setContent(' ' + text);
this.onScreenEvent(KEYPRESS, press = function (ch, key) {
if (key.name === MOUSE) return;
if (key.name !== ENTER && key.name !== ESCAPE && key.name !== 'q' && key.name !== 'y' && key.name !== 'n') {
return;
}
done(null, key.name === ENTER || key.name === 'y');
});
this._.okay.on(PRESS, okay = function () {
done(null, true);
});
this._.cancel.on(PRESS, cancel = function () {
done(null, false);
});
this.screen.saveFocus();
this.focus();
function done(err, data) {
self.hide();
self.screen.restoreFocus();
self.removeScreenEvent(KEYPRESS, press);
self._.okay.removeListener(PRESS, okay);
self._.cancel.removeListener(PRESS, cancel);
return callback(err, data);
}
this.screen.render();
}
} |
JavaScript | class RadioSet extends Box {
/**
* RadioSet
*/
constructor(options = {}) {
super(options); // if (!(this instanceof Node)) return new RadioSet(options)
// Possibly inherit sup's style.
// options.style = this.sup.style;
this.type = 'radio-set';
}
static build(options) {
return new RadioSet(options);
}
} |
JavaScript | class LimitDialer {
/**
* Create a new dialer.
*
* @param {number} perPeerLimit
* @param {number} dialTimeout
*/
constructor (perPeerLimit, dialTimeout) {
log('create: %s peer limit, %s dial timeout', perPeerLimit, dialTimeout)
this.perPeerLimit = perPeerLimit
this.dialTimeout = dialTimeout
this.queues = new Map()
}
/**
* Dial a list of multiaddrs on the given transport.
*
* @param {PeerId} peer
* @param {SwarmTransport} transport
* @param {Array<Multiaddr>} addrs
* @param {function(Error, Connection)} callback
* @returns {void}
*/
dialMany (peer, transport, addrs, callback) {
log('dialMany:start')
// we use a token to track if we want to cancel following dials
const token = { cancel: false }
callback = once(callback) // only call callback once
map(addrs, (m, cb) => {
this.dialSingle(peer, transport, m, token, cb)
}, (err, results) => {
if (err) {
return callback(err)
}
const success = results.filter((res) => res.conn)
if (success.length > 0) {
log('dialMany:success')
return callback(null, success[0])
}
log('dialMany:error')
const error = new Error('Failed to dial any provided address')
error.errors = results
.filter((res) => res.error)
.map((res) => res.error)
return callback(error)
})
}
/**
* Dial a single multiaddr on the given transport.
*
* @param {PeerId} peer
* @param {SwarmTransport} transport
* @param {Multiaddr} addr
* @param {CancelToken} token
* @param {function(Error, Connection)} callback
* @returns {void}
*/
dialSingle (peer, transport, addr, token, callback) {
const ps = peer.toB58String()
log('dialSingle: %s:%s', ps, addr.toString())
let q
if (this.queues.has(ps)) {
q = this.queues.get(ps)
} else {
q = new DialQueue(this.perPeerLimit, this.dialTimeout)
this.queues.set(ps, q)
}
q.push(transport, addr, token, callback)
}
} |
JavaScript | class PagesSection extends Component {
static propTypes = {
user: PropTypes.instanceOf(User).isRequired
};
constructor(props) {
super(props);
this.state = {
startedloading: false,
fetchedPages: 0,
loadingBarStatus: {value: 0, message: "Waiting for facebook SDK", color: 'default'},
associationList: null
}
}
async componentDidMount() {
if (!this.state.startedLoading)
console.log("Ran loading page");
if (window.FB === undefined)
window.fbLoaded.push(this.loadingPages);
else
this.loadingPages();
}
updateBar(valueadd, message = this.state.loadingBarStatus.message, color = this.state.loadingBarStatus.color) {
console.log('bar length: ', this.state.loadingBarStatus.value + valueadd);
this.setState({
loadingBarStatus: {
value: this.state.loadingBarStatus.value + valueadd,
message: message,
color: color
}
});
}
loadingPages = async () => {
this.setState({startedLoading: true});
this.updateBar(20, "Getting login status (this step can be long)");
getAuthResponse().then(authResponse => {
this.updateBar(20, "Getting permissions");
getPermissions(this.props.user.fbId, authResponse.accessToken).then(permissionResponse => {
//If we already have the permission to see pages
if (permissionResponse.error) {
this.updateBar(0, permissionResponse.error.message, 'danger')
} else if (permissionResponse.data.some((e1) => {
return e1.permission === "manage_pages" && e1.status === "granted"
})) {
this.updateBar(20, "Getting pages");
//Getting page informations
getUserPages(this.props.user.fbId, authResponse.accessToken).then(r => {
this.updateBar(20, "Getting pages details");
this.setState({associationList: r.data});
const barlength = this.state.loadingBarStatus.value;
for (let i in this.state.associationList) {
let assocList = this.state.associationList;
getPagePicture(assocList[i].id).then((r) => {
assocList[i].picture = r.data.url;
console.log(r.data.url);
this.updateBar((100 - barlength) / assocList.length);
this.setState({fetchedPages: this.state.fetchedPages + 1, associationList: assocList});
})
}
}
)
} else {
//TODO: Ask for manage_pages permission
}
});
})
};
disabledButton = (page) => {
console.log(`${this.props.selectedPage} === ${page.id}: ${this.props.selectedPage === page.id}`);
return (this.props.selectedPage === page.id)
};
render() {
let associaitonRender = [];
if (this.state.associationList && this.state.fetchedPages === this.state.associationList.length) {
for (let i in this.state.associationList) {
// noinspection JSUnfilteredForInLoop
const page = this.state.associationList[i];
associaitonRender.push(
<div className={"Association"} key={page.id}>
<div className={"flexbox hcenter"} style={{width: '100%'}}>
<div className={"flexbox vcenter hcenter"}>
{/*TODO: prevent XSS throught img -> src*/}
<ImageLoader src={`${page.picture}`}>
<img alt={`${page.name} Cover`} className={"roundImage"}/>
<span>Error loading image</span>
<div className={"flexbox vcenter hcenter"}>
<Spinner
size={25}
spinnerColor={"#ddd"}
spinnerWidth={2}
visible={true}/>
</div>
</ImageLoader>
</div>
<div className={"flexbox vcenter"} style={{flexGrow: 1}}>
<span className={"associationName"}> {page.name} </span>
</div>
<div className={"flexbox vcenter hcenter"}>
<BigButton className={"greenBtn removeTextOnSmall"}
onClick={() => this.props.connect(page)}
disabled={this.disabledButton(page)}>
<Icon path={mdiRobot} size={1}
color={"#ffffff"}/>
<span>Connect bot to page</span>
</BigButton>
</div>
</div>
<hr className={"hSeparator"}/>
</div>)
}
}
return (
<div style={{margin: '2rem auto'}}>
<h2 style={{color: "#686868"}}>Your facebook pages</h2>
{!(this.state.associationList && this.state.fetchedPages === this.state.associationList.length) ?
<div style={{alignItems: 'center', textAlign: "center"}}>
<span style={{margin: 'auto'}}>{this.state.loadingBarStatus.message}</span>
<Progress animated={this.state.loadingBarStatus.color !== 'danger'}
value={this.state.loadingBarStatus.value}
color={this.state.loadingBarStatus.color}
style={{margin: "2em auto", width: "50%"}}/>
</div>
:
<div style={{marginBottom: "3em"}}>
{associaitonRender}
</div>
}
</div>
)
}
} |
JavaScript | class MuView extends MuEmitter {
constructor(mu, options) {
super('MuView');
this.mu = mu;
this.options = options;
this.loader = axios.create();
this._viewCache = new Map();
this._templatePattern = /\{\{([\w.:]+)\}\}/; // TODO, make option
}
virtual(html, selector) {
const parser = new DOMParser();
const virtual = parser.parseFromString(html || '', 'text/html');
return selector ? virtual.querySelector(selector) : virtual;
}
virtualContainer() {
return this.virtual('<div></div>', 'div');
}
load(path) {
const c = this._viewCache.get(path);
const p = Promise.resolve(c || this.loader.get(path).then(res => res.data))
if (!c) {
this._viewCache.set(path, p);
}
return p;
}
loadView(view) {
const { basePath } = this.options;
var path = (basePath || '') + '/' + view;
return this.load(path);
}
renderRemote(target, view, context) {
return this.loadView(view)
.then(template => this.render(target, template, context));
}
render(target, template, context) {
const output = this.interpolate(template, context);
// this.emit('rendered', target, data);
return Promise.resolve(this.apply(target, output, context));
}
interpolate(template, context) {
const pattern = this._templatePattern;
const regGlobal = new RegExp(pattern, 'g');
const renderCtx = MuContext.toContext(context);
const raw = template || '';
return Array.apply(null, raw.match(regGlobal) || [])
.reduce((out, ph) => {
const prop = ph.replace(pattern, '$1');
return out.replace(ph, renderCtx.get(prop) || '');
}, raw);
}
apply(target, html, context) {
this.dispose(target);
target.innerHTML = html;
return this.attach(target, context);
// const virtual = this.virtual(`<div>${html}</div>`, 'div');
// const bound = this.attach(virtual, context);
// target.innerHTML = '';
// Array.apply(null, bound.children)
// .forEach(node => target.appendChild(node));
}
attach(target, context) {
const { micro } = this.options;
const commonCtx = context && MuContext.toContext(context);
const _mus = [];
// bind mu to the anything with standard [mu] selector
Array.apply(null, target.querySelectorAll(attrToSelector(MUPROP.MU)))
.forEach(node => MuUtil.mergeProp(node, null, {
[MUPROP.MU]: this.mu, // direct access to mu
[MUPROP.CTX]: this.mu.root.context, // global context
}));
// keep mus array on target
MuUtil.defineProp(target, MUPROP.MUS, _mus);
const addPrebindings = parent => {
const any = micro.map(mod => mod.binding).join(',');
Array.apply(null, parent.querySelectorAll(any))
.filter(c => !c.muOriginal)
.forEach(child => {
const clone = child.cloneNode(true);
MuUtil.defineProp(child, 'muOriginal', () =>
addPrebindings(clone.cloneNode(true)));
});
return parent;
};
// assign getters on prebound objects
addPrebindings(target);
// bind micros
micro.forEach(mod => {
const nodes = target.querySelectorAll(mod.binding);
const list = [];
// instantiate per node
Array.apply(null, nodes).forEach(node => {
// determine context
const nodeCtx = MuUtil.resolveProp(node, MUPROP.CTX);
const ctx = nodeCtx || commonCtx ||
(!mod.ctor.CTX_INHERIT_ONLY && MuContext.toContext()); // context may be shared or uniquely scoped
if (ctx && target.contains(node)) {
const instance = MuUtil.initModule(mod, this.mu, this, ctx);
MuUtil.defineProp(instance, 'node', node); // assign the node to the instance
// MuUtil.defineProp(node, MUPROP.CTX, ctx); // assign sticky context to the node for persistence
// reference the instance in the target's mus
_mus.push(instance);
list.push(node);
return instance.onMount && instance.onMount();
}
});
if (list.length) {
this.emitOnce(mod.ctor, target, list);
}
});
// remove cloak
target.removeAttribute(MUPROP.CLOAK);
// emit that view was attached
this.emitOnce('attached', target);
return target;
}
dispose(target, andContext) {
const _mus = MuUtil.resolveProp(target, MUPROP.MUS);
const { context: rootCtx } = this.mu.root;
if (_mus) {
let m;
while (m = _mus.shift()) {
m.emit('dispose').dispose(); // dispose emitter
m.onDispose && m.onDispose(); // dispose hook
if (andContext && m.context !== rootCtx) { // dispose (non-root) context
m.context.dispose();
}
}
}
return target;
}
} |
JavaScript | class Mu extends MuEmitter {
constructor() {
super('Mu');
}
/**
* reset Mu
*/
static clean() {
this._core = this._core || [];
this._macro = []; // define static macro singleton modules on mu instance
this._micro = []; // define static micro components for view bindings
return this;
}
/**
* register a component to the mu namespace (macro)
* @param {string} name
* @param {Function} ctor
* @param {...any} args
*/
static macro(name, ctor, ...args) {
this._macro.push(MuUtil.defineModule(ctor, name, null, ...args));
return this;
}
/**
* register a view micro binding
* @param {Function} ctor
* @param {string} selector
* @param {...any} args
*/
static micro(ctor, selector, ...args) {
this._micro.push(MuUtil.defineModule(ctor, null, selector, ...args));
return this;
}
/**
* Create core micros
* @param {Function} ctor
* @param {string} selector
*/
static core(ctor, selector) {
this._core.push(MuUtil.defineModule(ctor, null, selector));
return this;
}
/**
* Main Mu Start point
* @param {HTMLElement} main
* @param {object} options
* @param {string} options.root - root node selector
* @param {string} options.baseViewUrl - base url for view loading
* @param {*} options.context - global context
*/
static run(main, options) {
const { mu, view } = this.init(main, options);
return this.start(mu, view);
}
/**
* Main Mu instance Initializer
* @param {HTMLElement} main
* @param {object} options
* @param {string} options.root - root node selector
* @param {string} options.baseViewUrl - base url for view loading
* @param {*} options.context - global context
*/
static init(main, options) {
const mu = new Mu();
// resolve options for this instance
const opts = Object.assign({
root: main.nodeName,
baseViewUrl: '/views',
context: {},
}, options || {});
// create singleton view engine with micro bindings
const micro = [].concat(this._core, this._micro);
const view = new MuView(mu, {
micro,
basePath: opts.baseViewUrl,
});
// create global context
const context = new MuContext(options.context);
// assign root object
MuUtil.defineProp(mu, 'root', {
context,
element: main,
selector: opts.root,
});
// init macros with global context
this._macro.forEach(mod => {
const instance = MuUtil.initModule(mod, mu, view, context);
// assign to the mu instance (as macro)
MuUtil.mergeProp(mu, mod.name, instance);
});
return { mu, view };
}
/**
* helper for testing
* @param {Mu} mu
* @param {MuView} view
*/
static start(mu, view) {
// attach main node to view (without any default context)
view.attach(mu.root.element, null);
// emit ready
mu.emit('ready');
return mu;
}
} |
JavaScript | class Boat
{
// object constructor, initializes velo and rot to 0
constructor(scene)
{
loader.load("/../myassets/models/watercraft/scene.gltf", (gltf) =>
{
scene.add(gltf.scene);
gltf.scene.scale.set(0.5, 0.5, 0.5);
gltf.scene.position.set(0, -5, 0);
this.boatobj = gltf.scene;
this.spatial = {
velocity: 0,
rot: 0,
};
});
}
// updating speed and velocity of the boat based on received inputs
update(time)
{
if (this.boatobj)
{
this.boatobj.rotation.y += this.spatial.rot;
this.boatobj.translateZ(this.spatial.velocity);
this.boatobj.position.y = 0.5*Math.sin(2*time)-3.5;
}
}
} |
JavaScript | class Wire extends Tile {
constructor(areaid, elemid, message_type, options) {
super(areaid, elemid, message_type)
this.options = deepExtend(DEFAULTS, options)
this.install()
}
/**
* installs the HTML code in the document
*/
install() {
super.install()
let hook = document.querySelector("#" + this.elemid)
let newel = document.createElement("ul")
hook.appendChild(newel)
this.listen(this.update.bind(this))
console.log("wire installed")
}
/**
* Wire message handler
*
* @param {String} msg The message"s type
* @param {Object} data The message
* {
source: "aodb",
type: "flightboard",
subject: move + " " + payload.flight + (payload.move == "departure" ? " to " : " from ") + payload.airport,
body: msgtype + " " + payload.time,
created_at: objcsv.timestamp,
priority: 2,
icon: "la-plane-" + payload.move,
"icon-color": msgcolor
}
*/
update(msg, data) {
// add wire
console.log("wire received", msg, data)
let hook = document.querySelector("#" + this.elemid + " ul")
let newel = document.createElement("li")
newel.innerHTML = data.subject
let first = document.querySelector("#" + this.elemid + " ul li:first-child")
if (!first) { // we insert the first elem
hook.appendChild(newel)
} else {
hook.insertBefore(newel, first)
}
let allwires = document.querySelectorAll("#" + this.elemid + " ul li")
while (allwires.length > this.options.maxentries) {
let last = document.querySelector("#" + this.elemid + " ul li:last-child")
hook.removeChild(last)
allwires = document.querySelector("#" + this.elemid + " ul li")
}
const formatter = showJson(data, newel)
formatter.openAtDepth(0) // all closed. See https://github.com/mohsen1/json-formatter-js
}
} |
JavaScript | class Content extends Component{
render(){
return (
<HashRouter history={history}>
<Switch>
<Route path={"/Home"}>
<TableContent/>
</Route>
<Route path="/Tutorial">
<Container>
<Tutorial/>
</Container>
</Route>
<Route path="/Manage">
<Container>
<Manage/>
</Container>
</Route>
<Route path="/Register">
<Container>
<Register/>
</Container>
</Route>
<Route path="/Login">
<Container>
<Login/>
</Container>
</Route>
<Route path="/Upload">
<Container fluid={true}>
<UploadDataset/>
</Container>
</Route>
<Redirect from={"/"} to={"/Home"}/>
</Switch>
</HashRouter>
);
}
} |
JavaScript | class Scryfall extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
card: null,
};
}
async componentDidMount() {
const SCRYFALLQUERY = "https://api.scryfall.com/cards/named?exact=";
const CARD = this.props.name;
const CARDCLEANED = CARD.toLowerCase()
.replace(/\s+/g, "-")
.replace(/&/g, "%26");
const response = await fetch(SCRYFALLQUERY + CARDCLEANED);
const data = await response.json();
this.setState({ card: data, loading: false });
}
render() {
return (
<div>
{this.state.loading ? (
<div>loading...</div>
) : (
<div>
<li>{this.state.card.name}</li>
<li>
<img src={this.state.card.image_uris.small} />
</li>
</div>
)}
</div>
);
}
} |
JavaScript | class App {
/**
* Created the whole application
* @constructor
*/
constructor() {
// noinspection JSIgnoredPromiseFromCall
this.createApp();
}
/**
* Create the app
*/
async createApp() {
document.title += ` ${version}`;
/** @private */
this.appUser_ = new AppUser();
await this.appUser_.requestAppUserData();
/** @private */
this.badgeManager_ = new BadgeManager();
/** @private */
this.emoteManager_ = new EmoteManager(this.appUser_);
/** @private */
this.messageParser_ =
new MessageParser(this.emoteManager_, this.badgeManager_);
/** @private */
this.chatManager_ = new ChatManager(this.emoteManager_, this.messageParser_);
/** @private */
new FavoritesList(this.badgeManager_, this.emoteManager_, this.chatManager_);
/** @private */
this.sendIrcConnection_ = new SendIRCConnection(this.appUser_);
/** @private */
this.receiveIrcConnection_ = new ReceiveIRCConnection(this.appUser_,
this.messageParser_, this.chatManager_);
this.chatManager_.setReceiveIrcConnection(this.receiveIrcConnection_);
this.chatManager_.setSendIrcConnection(this.sendIrcConnection_);
}
} |
JavaScript | class LStorage {
constructor() {
this.lsQueries = $.initNamespaceStorage("lsQueries").localStorage
this.lsNotes = $.initNamespaceStorage("lsNotes").localStorage
this.lsQueriesMuted = $.initNamespaceStorage("lsQueriesMuted").localStorage
this.lsNotesMuted = $.initNamespaceStorage("lsNotesMuted").localStorage
/* on the Queries and Notes pages the user can "mute" queries.
* Which items are muted,
* is stored as key value pairs in this local storage bucket.
* When shebanq shows relevant items next to a page, muting is taken into account.
*/
}
} |
JavaScript | class Autoresizer {
/**
* adds autoresize handler
* @param elements - elements that needs to expand
*/
constructor(elements) {
this.elements = elements || [];
for(let i = 0; i < this.elements.length; i++) {
this.addResizer(this.elements[i]);
}
}
/**
* autoresizer for textareas
* @param {Element} el - element we want to expand
*/
addResizer(el) {
if (el.value.trim()) {
el.style.height = el.scrollHeight + 'px';
} else {
el.style.height = 'auto';
}
el.addEventListener('keydown', this.enterKeyPressed, false);
el.addEventListener('input', this.resize.bind(this, el), false);
}
/**
* Prevent enter key pressing
* @param event
*/
enterKeyPressed(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
}
/**
* Resize input
* @param el
*/
resize(el) {
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
}
/**
* removes handlers from element
* @param {Element} el - element we want to clear from resizer
*/
removeResizer(el) {
el.removeEventListener('keydown', this.enterKeyPressed);
el.removeEventListener('input', this.resize);
}
/**
* Destroyer function. Clears all elements
*/
destroy() {
for(let i = 0; i < this.elements.length; i++) {
this.removeResizer(this.elements[i]);
this.elements[i].style.height = 'auto';
}
this.elements = [];
}
} |
JavaScript | class Data extends React.Component {
constructor(props) {
super(props);
this.state = {pivotState: {...props, vals: ['value']},
data: [['attribute', 'attribute2'], ['value1', 'value2']]
};
}
componentDidMount(){
const _this = this;
axios.get('http://localhost:8080/api/Demographies')
.then(function (response) {
const newData = _.map(response.data, (d)=>{ return {...d, value: parseInt(d.Valori)}})
_this.setState({data: newData});
})
.catch(function (error) {
console.error(error);
})
.finally(function () {
console.log('Data loaded');
});
}
render() {
return (
<PivotTableUI
data={this.state.data}
onChange={s => this.setState({pivotState:s})}
renderers={Object.assign({}, TableRenderers, PlotlyRenderers)}
{...this.state.pivotState}
/>
);
}
} |
JavaScript | class DevelopementScreen {
constructor() {
this.switchScreen = switchScreen;
this.player = new Player(GAME_WIDTH / 2, GAME_HEIGHT / 2);
this.map = new Map(MAIN_MAP);
this.timer = 1000;
this.all_mobs = [];
player = this.player;
this.mob_spawn_positions = [
[6, 45],
[49, 6]
]
this.x_pos = null;
this.y_pos = null;
this.rand = 0;
this.ui_items = [
["Coffee", this.player.coffee, 100],
["Food", this.player.food, 100],
["Satisfaction", this.player.satisfaction, 100]
]
this.ui = new UI(this.ui_items);
}
init(switchScreen) {
let map = {}; // You could also use an array
let onkeydown = function (e) {
map[e.keyCode] = e.type == 'keydown';
// Up and down
if (map[W_KEY]) {
this.player.vy = -PLAYER_SPEED;
this.player.direction = 270;
} else if (map[S_KEY]) {
this.player.vy = PLAYER_SPEED;
this.player.direction = 90;
} else this.player.vy = 0;
// Right and left
if (map[A_KEY]) {
this.player.vx = -PLAYER_SPEED;
this.player.direction = 180;
} else if (map[D_KEY]) {
this.player.vx = PLAYER_SPEED;
this.player.direction = 0;
} else this.player.vx = 0;
// Rotations
if (map[W_KEY] && map[D_KEY]) {
this.player.direction = 315;
}
if (map[S_KEY] && map[D_KEY]) {
this.player.direction = 45;
}
if (map[A_KEY] && map[S_KEY]) {
this.player.direction = 135;
}
if (map[W_KEY] && map[A_KEY]) {
this.player.direction = 225;
}
}.bind(this);
let onkeyup = onkeydown;
window.addEventListener('keydown', onkeydown);
window.addEventListener('keyup', onkeyup);
}
update() {
this.map.collisions(this.player);
this.player.update();
if (youLost()) {
alert("You lost");
switchScreen(MAIN_MENU_SCREEN);
} else if (youWon()) {
this.player.won = true;
}
for (const i of this.all_mobs) {
i.update();
}
if (this.timer >= 1000 && this.all_mobs.length < 10) {
this.rand = Math.round(Math.random());
this.x_pos = this.mob_spawn_positions[this.rand][0];
this.y_pos = this.mob_spawn_positions[this.rand][1];
this.mob = new mob(this.x_pos, this.y_pos);
current_registering.push(this.mob);
this.all_mobs.push(this.mob);
this.timer = 0;
}
if (this.all_mobs.length > 10) {
this.all_mobs.shift()
}
this.timer += 1;
}
redraw() {
this.ui_items = [
["Coffee", this.player.coffee, 100],
["Food", this.player.food, 100],
["Satisfaction", this.player.satisfaction, 100]
]
drawImage("map", 0, 0);
this.player.draw();
//drawGridOverlay();
for (const i of this.all_mobs) {
i.draw()
}
this.ui.draw(this.ui_items);
}
} |
JavaScript | class GroupMembershipsController extends PaginationController {
constructor(query = {}, additionalQuery = {}) {
super(
'groupmemberships',
query,
Query.merge(additionalQuery, {
embedded: { group: 1 },
})
);
}
/**
* Enroll the authenticated user to a group
*
* @param {String} groupId
* @return {Promise} exports for additional response handling
*/
enroll(groupId) {
return m
.request({
method: 'POST',
url: `${apiUrl}/groupmemberships`,
headers: getToken()
? {
Authorization: `Token ${getToken()}`,
}
: {},
body: { group: groupId, user: getUserId() },
})
.then(() => {
this.loadAll();
})
.catch(e => {
error(e.message);
});
}
/**
* Withdraw membership of the authenticated user from a group.
*
* @param {String} groupMembershipId groupmembership id
* @param {String} etag value given by AMIV API to be used as `If-Match` header.
* @return {Promise} exports for additional response handling
*/
withdraw(groupMembershipId, etag) {
return m
.request({
method: 'DELETE',
url: `${apiUrl}/groupmemberships/${groupMembershipId}`,
headers: getToken()
? {
Authorization: `Token ${getToken()}`,
'If-Match': etag,
}
: { 'If-Match': etag },
})
.then(() => {
this.loadAll();
})
.catch(e => {
error(e.message);
});
}
} |
JavaScript | class PoseIllustration {
constructor(scope) {
this.scope = scope;
this.frames = [];
}
updateSkeleton(pose, face) {
this.pose = pose;
this.face = face;
this.skeleton.update(pose, face);
if (!this.skeleton.isValid) {
return;
}
let getConfidenceScore = (p) => {
return Object.keys(p.skinning).reduce((totalScore, boneName) => {
let bt = p.skinning[boneName];
return totalScore + bt.bone.score * bt.weight;
}, 0);
}
this.skinnedPaths.forEach(skinnedPath => {
let confidenceScore = 0;
skinnedPath.segments.forEach(seg => {
// Compute confidence score.
confidenceScore += getConfidenceScore(seg.point);
// Compute new positions for curve point and handles.
seg.point.currentPosition = Skeleton.getCurrentPosition(seg.point);
if (seg.handleIn) {
seg.handleIn.currentPosition = Skeleton.getCurrentPosition(seg.handleIn);
}
if (seg.handleOut) {
seg.handleOut.currentPosition = Skeleton.getCurrentPosition(seg.handleOut);
}
});
skinnedPath.confidenceScore = confidenceScore / (skinnedPath.segments.length || 1);
});
}
draw() {
if (!this.skeleton.isValid) {
return;
}
let scope = this.scope;
// Add paths
this.skinnedPaths.forEach(skinnedPath => {
// Do not render paths with low confidence scores.
if (!skinnedPath.confidenceScore || skinnedPath.confidenceScore < MIN_CONFIDENCE_PATH_SCORE) {
return;
}
let path = new scope.Path({
fillColor: skinnedPath.fillColor,
strokeColor: skinnedPath.strokeColor,
strokeWidth: skinnedPath.strokeWidth,
closed: skinnedPath.closed,
});
skinnedPath.segments.forEach(seg => {
path.addSegment(seg.point.currentPosition,
seg.handleIn ? seg.handleIn.currentPosition.subtract(seg.point.currentPosition) : null,
seg.handleOut ? seg.handleOut.currentPosition.subtract(seg.point.currentPosition) : null);
});
if (skinnedPath.closed) {
path.closePath();
}
scope.project.activeLayer.addChild(path);
});
}
debugDraw() {
let scope = this.scope;
let group = new scope.Group();
scope.project.activeLayer.addChild(group);
let drawCircle = (p, opt = {}) => {
group.addChild(new scope.Path.Circle({
center: [p.x, p.y],
radius: opt.radius || 2,
fillColor: opt.fillColor || 'red',
}));
}
let drawLine = (p0, p1, opt = {}) => {
group.addChild(new scope.Path({
segments: [p0, p1],
strokeColor: opt.strokeColor || 'red',
strokeWidth: opt.strokeWidth || 1
}));
}
// Draw skeleton.
this.skeleton.debugDraw(scope);
// Draw curve and handles.
this.skinnedPaths.forEach(skinnedPath => {
skinnedPath.segments.forEach(seg => {
// Color represents weight influence from bones.
let color = new scope.Color(0);
Object.keys(seg.point.skinning).forEach((boneName) => {
let bt = seg.point.skinning[boneName];
ColorUtils.addRGB(color,
bt.weight * bt.bone.boneColor.red,
bt.weight * bt.bone.boneColor.green,
bt.weight * bt.bone.boneColor.blue);
let anchor = bt.bone.kp0.currentPosition.multiply(1 - bt.transform.anchorPerc).add(bt.bone.kp1.currentPosition.multiply(bt.transform.anchorPerc));
drawLine(anchor, seg.point.currentPosition, {strokeColor: 'blue', strokeWidth: bt.weight});
});
drawCircle(seg.point.currentPosition, {fillColor: color});
drawCircle(seg.handleIn.currentPosition, {fillColor: color});
drawLine(seg.point.currentPosition, seg.handleIn.currentPosition, {strokeColor: color});
drawCircle(seg.handleOut.currentPosition, {fillColor: color}, {strokeColor: color});
drawLine(seg.point.currentPosition, seg.handleOut.currentPosition);
});
});
}
debugDrawLabel(scope) {
this.skeleton.debugDrawLabels(scope);
}
bindSkeleton(skeleton, skeletonScope) {
let items = skeletonScope.project.getItems({ recursive: true });
items = items.filter(item => item.parent && item.parent.name && item.parent.name.startsWith('illustration'));
this.skeleton = skeleton;
this.skinnedPaths = [];
// Only support rendering path and shapes for now.
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (SVGUtils.isGroup(item)) {
this.bindGroup(item, skeleton);
} else if (SVGUtils.isPath(item)) {
this.bindPathToBones(item);
} else if (SVGUtils.isShape(item)) {
this.bindPathToBones(item.toPath());
}
}
}
bindGroup(group, skeleton) {
let paths = [];
let keypoints = {};
let items = group.getItems({recursive: true});
// Find all paths and included keypoints.
items.forEach(item => {
let partName = item.name ? allPartNames.find(partName => item.name.startsWith(partName)) : null;
if (partName) {
keypoints[partName] = {
position: item.bounds.center,
name: partName,
};
} else if (SVGUtils.isPath(item)) {
paths.push(item);
} else if (SVGUtils.isShape(item)) {
paths.push(item.toPath());
}
});
let secondaryBones = [];
// Find all parent bones of the included keypoints.
let parentBones = skeleton.bones.filter(bone => keypoints[bone.kp0.name] && keypoints[bone.kp1.name]);
let nosePos = skeleton.bNose3Nose4.kp1.position;
if (!parentBones.length) {
return;
}
// Crete secondary bones for the included keypoints.
parentBones.forEach(parentBone => {
let kp0 = keypoints[parentBone.kp0.name];
let kp1 = keypoints[parentBone.kp1.name];
let secondaryBone = new Bone().set(kp0, kp1, parentBone.skeleton, parentBone.type);
kp0.transformFunc = MathUtils.getTransformFunc(parentBone.kp0.position, nosePos, kp0.position);
kp1.transformFunc = MathUtils.getTransformFunc(parentBone.kp1.position, nosePos, kp1.position);
secondaryBone.parent = parentBone;
secondaryBones.push(secondaryBone);
});
skeleton.secondaryBones = skeleton.secondaryBones.concat(secondaryBones);
paths.forEach(path => {
this.bindPathToBones(path, secondaryBones);
});
}
// Assign weights from bones for point.
// Weight calculation is roughly based on linear blend skinning model.
getWeights(point, bones) {
let totalW = 0;
let weights = {};
bones.forEach(bone => {
let d = MathUtils.getClosestPointOnSegment(bone.kp0.position, bone.kp1.position, point)
.getDistance(point);
// Absolute weight = 1 / (distance * distance)
let w = 1 / (d * d);
weights[bone.name] = {
value: w,
bone: bone,
}
});
let values = Object.values(weights).sort((v0, v1) => {
return v1.value - v0.value;
});
weights = {};
totalW = 0;
values.forEach(v => {
weights[v.bone.name] = v;
totalW += v.value;
});
if (totalW === 0) {
// Point is outside of the influence zone of all bones. It will not be influence by any bone.
return {};
}
// Normalize weights to sum up to 1.
Object.values(weights).forEach(weight => {
weight.value /= totalW;
});
return weights;
}
// Binds a path to bones by compute weight contribution from each bones for each path segment.
// If selectedBones are set, bind directly to the selected bones. Otherwise auto select the bone group closest to each segment.
bindPathToBones(path, selectedBones) {
// Compute bone weights for each segment.
let segs = path.segments.map(s => {
// Check if control points are collinear.
// If so, use the middle point's weight for all three points (curve point, handleIn, handleOut).
// This makes sure smooth curves remain smooth after deformation.
let collinear = MathUtils.isCollinear(s.handleIn, s.handleOut);
let bones = selectedBones || this.skeleton.findBoneGroup(s.point);
let weightsP = this.getWeights(s.point, bones);
let segment = {
point: this.getSkinning(s.point, weightsP),
};
// For handles, compute transformation in world space.
if (s.handleIn) {
let pHandleIn = s.handleIn.add(s.point);
segment.handleIn = this.getSkinning(pHandleIn, collinear ? weightsP : this.getWeights(pHandleIn, bones));
}
if (s.handleOut) {
let pHandleOut = s.handleOut.add(s.point);
segment.handleOut = this.getSkinning(pHandleOut, collinear ? weightsP : this.getWeights(pHandleOut, bones));
}
return segment;
});
this.skinnedPaths.push({
segments: segs,
fillColor: path.fillColor,
strokeColor: path.strokeColor,
strokeWidth: path.strokeWidth,
closed: path.closed
});
}
getSkinning(point, weights) {
let skinning = {};
Object.keys(weights).forEach(boneName => {
skinning[boneName] = {
bone: weights[boneName].bone,
weight: weights[boneName].value,
transform: weights[boneName].bone.getPointTransform(point),
};
});
return {
skinning: skinning,
position: point,
currentPosition: new this.scope.Point(0, 0),
}
};
} |
JavaScript | class PluginActivity extends Plugin {
/**
* @param {AppBackground} app - The background application.
*/
constructor(app) {
super(app)
this.app.on('bg:calls:call_rejected', ({call}) => {
// Not answered.
let label
if (call.type === 'outgoing') label = 'unanswered'
else label = 'missed'
let activity = {
label,
status: 'warning',
type: `${call.type}-call`,
}
const contact = this.app.helpers.matchContact(call.number)
if (contact) Object.assign(activity, contact)
else activity.number = call.number
this.addActivity(activity)
})
this.app.on('bg:calls:call_ended', ({call}) => {
let activity = {
status: 'success',
type: `${call.type}-call`,
}
const contact = this.app.helpers.matchContact(call.number)
if (contact) Object.assign(activity, contact)
else activity.number = call.number
this.addActivity(activity)
})
}
/**
* Initializes the module's store.
* @returns {Object} The module's store properties.
*/
_initialState() {
return {
activity: [],
filters: {
missed: false,
reminders: false,
},
unread: false,
}
}
/**
* And an activity entry. Use an `endpointId` when the activity
* comes from an existing Contact Endpoint. Use a `number` when
* the activity is Callable. Use the title directly otherwise.
* @param {String} [contact] - Contact to link to the activity.
* @param {String} [endpoint] - Endpoint to link to the activity.
* @param {String} [label] - Label next to the activity.
* @param {String} [number] - Number in case of no existing endpoint.
* @param {String} type - Maps to a svgicon.
*/
addActivity({contact = null, endpoint = null, label = '', number = null, status = 'success', type = 'incoming'}) {
let activity = this.app.state.activity.activity
activity.unshift({
contact,
date: new Date().getTime(),
endpoint,
id: shortid.generate(),
label,
number,
remind: false,
status,
type,
})
if (activity.length > MAX_ACTIVITIES) {
// Check which discarded activities are reminders first.
let reminders = activity.slice(MAX_ACTIVITIES).filter((i) => i.remind)
// Slice the list of activities and add the reminders at the end.
activity = activity.slice(0, MAX_ACTIVITIES).concat(reminders)
}
// New activity is added. Mark it as unread when the current layer
// is not set on `activity`. The unread property is deactivated again
// when the activity component mounts.
this.app.setState({
activity: {
activity,
unread: this.app.state.ui.layer !== 'activity',
},
}, {persist: true})
}
/**
* Generate a representational name for this module. Used for logging.
* @returns {String} - An identifier for this module.
*/
toString() {
return `${this.app}[activity] `
}
} |
JavaScript | class HermodReactMicrophone extends HermodReactComponent {
constructor(props) {
super(props);
let that = this;
this.state={}
if (!props.siteId || props.siteId.length === 0) {
throw "Hermod Microphone must be configured with a siteId property";
}
this.state={recording:false,messages:[],lastIntent:'',lastTts:'',lastTranscript:'',showMessage:false,activated:false,speaking:false,showConfig:false,listening:false,sessionId : ""}
this.siteId = props.siteId ; //? props.siteId : 'browser'+parseInt(Math.random()*100000000,10);
this.clientId = props.clientId ? props.clientId : 'client'+parseInt(Math.random()*100000000,10);
this.hotwordId = props.hotwordId ? props.hotwordId : 'default';
this.context = null;
this.gainNode = null;
this.messageTimeout = null;
this.speakingTimeout = null;
this.speechEvents = null;
this.startRecording = this.startRecording.bind(this);
this.stopRecording = this.stopRecording.bind(this);
this.startRecorder = this.startRecorder.bind(this);
this.sendAudioBuffer = this.sendAudioBuffer.bind(this);
this.audioBufferToWav = this.audioBufferToWav.bind(this);
this.reSample = this.reSample.bind(this);
this.encodeWAV = this.encodeWAV.bind(this);
this.interleave = this.interleave.bind(this);
this.flashState = this.flashState.bind(this);
this.activate = this.activate.bind(this);
this.deactivate = this.deactivate.bind(this);
this.showConfig = this.showConfig.bind(this);
this.showConfigNow = this.showConfigNow.bind(this);
this.clearConfigTimer = this.clearConfigTimer.bind(this);
this.waitingForSession = null;
this.configTimeout = null;
let eventFunctions = {
// SESSION
'hermod/asr/textCaptured' : function(payload) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId && payload.text && payload.text.length > 0 ) {
that.flashState('lastTranscript',payload.text);
}
},
'hermod/tts/say' : function(payload) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId && payload.text && payload.text.length > 0 ) {
that.flashState('lastTts',payload.text);
}
},
'hermod/hotword/#/toggleOn' : function(payload) {
if (that.props.enableServerHotword) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId) {
that.setState({sending : true});
}
}
},
'hermod/hotword/#/toggleOff' : function(payload) {
if (that.props.enableServerHotword) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId) {
that.setState({sending : false});
}
}
},
'hermod/asr/startListening' : function(payload) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId ) {
that.setState({sending : true});
}
},
'hermod/asr/stopListening' : function(payload) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId ) {
that.setState({sending : false});
}
}
}
this.logger = this.connectToLogger(props.logger,eventFunctions);
}
/**
* Lifecycle functions
*/
/**
* Activate on mount if user has previously enabled.
*/
componentDidMount() {
this.startRecorder();
let that = this;
// FORCE START ASR ON THIS SITE BY TOGGLE ON SESSION, WAIT, THEN END SESSION AND RESET LOGS
that.queueOneOffCallbacks({
'hermod/dialogueManager/sessionStarted' : function(payload) {
if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId ) {
// clear log
//that.queueOneOffCallbacks({
//'hermod/feedback/sound/toggleOn' : function(payload) {
//if (payload.siteId && payload.siteId.length > 0 && payload.siteId === that.siteId ) {
//that.logger.reset();
//}
//}
//});
setTimeout(function() {
that.sendEndSession(payload.sessionId);
that.sendFeedbackToggleOn(that.props.siteId);
},500);
}
}
});
setTimeout(function() {
that.sendFeedbackToggleOff(that.props.siteId);
that.sendStartSession(that.props.siteId);
},900);
}
/**
* Functions to enable and disable configuration screen
* by default using a debounce to implement click and hold to enable config
**/
showConfig(e) {
let that = this;
this.configTimeout = setTimeout(function() {
// console.log('show now');
//that.setState({showConfig:true});
if (that.props.showConfig) that.props.showConfig();
else that.deactivate();
},1000);
};
showConfigNow(e) {
e.preventDefault();
e.stopPropagation();
//this.setState({showConfig:true});
if (this.props.showConfig) this.props.showConfig();
else this.deactivate();
};
clearConfigTimer() {
if (this.configTimeout) clearTimeout(this.configTimeout);
};
/**
* Connect to mqtt, start the recorder and optionally start listening
* Triggered by microphone click or hotword when the mic is deactivated
*/
activate(start = true) {
let that = this;
localStorage.setItem(this.appendUserId('Hermodmicrophone_enabled',this.props.user),'true');
if (start) {
setTimeout(function() {
that.startRecording();
},500);
}
that.setState({activated:true,sending:false});
};
/**
* Enable streaming of the audio input stream
*/
startRecording = function() {
this.setState({lastIntent:'',lastTts:'',lastTranscript:'',showMessage:false});
this.sendStartSession(this.siteId,{startedBy:'Hermodreactmicrophone',user:this.props.user ? this.props.user._id : ''});
}
/**
* Disable microphone and listeners
*/
deactivate() {
localStorage.setItem(this.appendUserId('Hermodmicrophone_enabled',this.props.user),'false');
this.setState({activated:false,sending:false});
};
/**
* Access the microphone and start streaming mqtt packets
*/
startRecorder() {
let that = this;
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
try {
if (navigator.getUserMedia) {
navigator.getUserMedia({audio:true}, success, function(e) {
console.log(['MIC Error capturing audio.',e]);
});
} else {
console.log('MIC getUserMedia not supported in this browser.');
}
} catch (e) {
console.log(e);
}
function success(e) {
let audioContext = window.AudioContext || window.webkitAudioContext;
let context = new audioContext();
that.setState({'activated':true});
that.gainNode = context.createGain();
// initial set volume
that.gainNode.gain.value = that.props.config.inputvolume > 0 ? that.props.config.inputvolume/100 : 0.5;
let audioInput = context.createMediaStreamSource(e);
var bufferSize = 256;
let recorder = context.createScriptProcessor(bufferSize, 1, 1);
recorder.onaudioprocess = function(e){
//!that.logger.connected ||
if(!that.state.sending) return;
var left = e.inputBuffer.getChannelData(0);
that.sendAudioBuffer(e.inputBuffer,context.sampleRate);
//console.log('MIC send audio'); //,buffer,that.audioBuffer]);
}
if (that.props.addInputGainNode) that.props.addInputGainNode(that.gainNode) ;
audioInput.connect(that.gainNode)
that.gainNode.connect(recorder);
recorder.connect(context.destination);
}
};
stopRecording = function() {
let session = this.logger.getSession(this.siteId,null);
if (session) this.sendEndSession(session.sessionId);
}
addInputGainNode(node) {
this.inputGainNodes.push(node);
};
appendUserId(text,user) {
if (user && user._id) {
return text+"_"+user._id;
} else {
return text;
}
};
///**
//* Bind silence recognition events to set speaking state
//*/
//bindSpeakingEvents(audioContext,e) {
//// console.log(['bindSpeakingEvents'])
//let that = this;
//var options = {audioContext:audioContext};
//options.threshhold = this.getThreshholdFromVolume(this.state.config.silencesensitivity);
//// bind speaking events care of hark
//this.speechEvents = hark(e, options);
//this.speechEvents.on('speaking', function() {
//if (that.state.config.silencedetection !== "no") {
////console.log('speaking');
//if (that.speakingTimeout) clearTimeout(that.speakingTimeout);
//that.setState({speaking:true});
//}
//});
//this.speechEvents.on('stopped_speaking', function() {
//if (that.state.config.silencedetection !== "no") {
//if (that.speakingTimeout) clearTimeout(that.speakingTimeout);
//that.speakingTimeout = setTimeout(function() {
//// console.log('stop speaking');
//that.setState({speaking:false});
//},1000);
//}
//});
//};
//getThreshholdFromVolume(volume) {
//return 10 * Math.log((101 - volume )/800);
//};
flashState(key,value) {
let that = this;
if (this.props.config.enablenotifications !== "no") {
if (key && key.length > 0 && value && value.length > 0) {
if (this.messageTimeOut) clearTimeout(this.messageTimeOut);
let newObj = {showMessage:true};
if (key === "lastTranscript") {
newObj.lastIntent='';
newObj.lastTts='';
}
newObj[key] = value;
this.setState(newObj);
setTimeout(function() {
that.setState({showMessage:false});
},that.props.messageTimeout > 0 ? that.props.messageTimeout : 10000);
}
}
};
/** WAV encoding functions */
sendAudioBuffer(buffer,sampleRate) {
let that = this;
if (buffer) {
this.reSample(buffer,16000,function(result) {
let wav = that.audioBufferToWav(result) ;
that.logger.sendAudioMqtt("hermod/audioServer/"+that.siteId+"/audioFrame",wav);
},sampleRate);
}
};
convertFloat32ToInt16(buffer) {
let l = buffer.length;
let buf = new Int16Array(l);
while (l--) {
buf[l] = Math.min(1, buffer[l])*0x7FFF;
}
return buf.buffer;
}
flattenArray(inChannelBuffer, recordingLength) {
let channelBuffer = this.convertFloat32ToInt16(inChannelBuffer);
var result = new Float32Array(recordingLength);
var offset = 0;
for (var i = 0; i < channelBuffer.length; i++) {
var buffer = channelBuffer[i];
result.set(buffer, offset);
offset += buffer.length;
}
return result;
}
reSample(audioBuffer, targetSampleRate, onComplete,sampleRateContext) {
let sampleRate = !isNaN(sampleRateContext) ? sampleRateContext : 44100;
var channel = audioBuffer && audioBuffer.numberOfChannels ? audioBuffer.numberOfChannels : 1;
var samples = audioBuffer.length * targetSampleRate / sampleRate;
var offlineContext = new OfflineAudioContext(channel, samples, targetSampleRate);
var bufferSource = offlineContext.createBufferSource();
bufferSource.buffer = audioBuffer;
bufferSource.connect(offlineContext.destination);
bufferSource.start(0);
offlineContext.startRendering().then(function(renderedBuffer){
onComplete(renderedBuffer);
}).catch(function(e) {
console.log(e);
})
}
audioBufferToWav (buffer, opt) {
opt = opt || {}
var numChannels = buffer.numberOfChannels
var sampleRate = buffer.sampleRate
var format = opt.float32 ? 3 : 1
var bitDepth = format === 3 ? 32 : 16
var result
if (numChannels === 2) {
result = this.interleave(buffer.getChannelData(0), buffer.getChannelData(1))
} else {
result = buffer.getChannelData(0)
}
return this.encodeWAV(result, format, sampleRate, numChannels, bitDepth)
}
encodeWAV (samples, format, sampleRate, numChannels, bitDepth) {
var bytesPerSample = bitDepth / 8
var blockAlign = numChannels * bytesPerSample
var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample)
var view = new DataView(buffer)
/* RIFF identifier */
this.writeString(view, 0, 'RIFF')
/* RIFF chunk length */
view.setUint32(4, 36 + samples.length * bytesPerSample, true)
/* RIFF type */
this.writeString(view, 8, 'WAVE')
/* format chunk identifier */
this.writeString(view, 12, 'fmt ')
/* format chunk length */
view.setUint32(16, 16, true)
/* sample format (raw) */
view.setUint16(20, format, true)
/* channel count */
view.setUint16(22, numChannels, true)
/* sample rate */
view.setUint32(24, sampleRate, true)
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * blockAlign, true)
/* block align (channel count * bytes per sample) */
view.setUint16(32, blockAlign, true)
/* bits per sample */
view.setUint16(34, bitDepth, true)
/* data chunk identifier */
this.writeString(view, 36, 'data')
/* data chunk length */
view.setUint32(40, samples.length * bytesPerSample, true)
if (format === 1) { // Raw PCM
this.floatTo16BitPCM(view, 44, samples)
} else {
this.writeFloat32(view, 44, samples)
}
return buffer
}
interleave (inputL, inputR) {
var length = inputL.length + inputR.length
var result = new Float32Array(length)
var index = 0
var inputIndex = 0
while (index < length) {
result[index++] = inputL[inputIndex]
result[index++] = inputR[inputIndex]
inputIndex++
}
return result
}
writeFloat32 (output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 4) {
output.setFloat32(offset, input[i], true)
}
}
floatTo16BitPCM (output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 2) {
var s = Math.max(-1, Math.min(1, input[i]))
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true)
}
}
writeString (view, offset, string) {
for (var i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
render() {
let that = this;
const {
text
} = this.props
let buttonStyle=this.props.buttonStyle ? this.props.buttonStyle : {};
let speechBubbleSettings= {};
let speechBubbleCSS= {};
let size= this.props.size && this.props.size.length > 0 ? this.props.size : '2em';
buttonStyle.width = size
buttonStyle.height = size
let position = this.props.position && this.props.position.length > 0 ? this.props.position : 'topright';
// set mic position and override bubble position
buttonStyle.position = 'fixed';
speechBubbleSettings.size ='20'
if (position === "topleft") {
buttonStyle.top = 0;
buttonStyle.left = 0;
speechBubbleSettings.triangle="top";
speechBubbleSettings.side="right";
} else if (position === "topright") {
buttonStyle.top = 0;
buttonStyle.right = 0;
speechBubbleSettings.triangle="bottom";
speechBubbleSettings.side="left";
} else if (position === "bottomleft") {
buttonStyle.bottom = 0;
buttonStyle.left = 0;
speechBubbleSettings.triangle="top";
speechBubbleSettings.side="right";
} else if (position === "bottomright") {
buttonStyle.bottom = 0;
buttonStyle.right = 0;
speechBubbleSettings.triangle="bottom";
speechBubbleSettings.side="left";
}
speechBubbleSettings.color="blue"
let status = 0;
if (this.state.activated) status = 2;
//if (this.state.connected) status = 2;
if (this.state.sending) status = 3;
//if (this.state.sending) status = 3;
// console.log(status);
let borderColor='black'
let borderWidth = 2;
if (status==3) {
borderColor = (this.state.speaking) ? 'darkgreen' : (this.props.borderColor ? this.props.borderColor : 'green');
buttonStyle.backgroundColor = 'lightgreen';
if (this.state.speaking) borderWidth = 3;
} else if (status==1) {
borderColor = (this.state.speaking) ? 'darkorange' : (this.props.borderColor ? this.props.borderColor : 'orange')
buttonStyle.backgroundColor = 'lightorange';
if (this.state.speaking) borderWidth = 3;
} else if (status==2) {
borderColor = (this.state.speaking) ? 'orangered' : (this.props.borderColor ? this.props.borderColor : 'red');
buttonStyle.backgroundColor = 'pink';
if (this.state.speaking) borderWidth = 3;
} else {
borderColor = this.props.borderColor ? this.props.borderColor : 'black';
buttonStyle.backgroundColor = 'lightgrey';
}
if (!buttonStyle.padding) buttonStyle.padding = '0.5em';
if (!buttonStyle.margin) buttonStyle.margin = '0.5em';
// console.log(borderColor);
//if (!buttonStyle.border)
buttonStyle.border = borderWidth + 'px solid '+borderColor;
if (!buttonStyle.borderRadius) buttonStyle.borderRadius = '100px';
// console.log(['BUTTON STYLE',buttonStyle]);
let micOffIcon = <svg style={buttonStyle} aria-hidden="true" data-prefix="fas" data-icon="microphone" className="svg-inline--fa fa-microphone fa-w-11" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512"><path fill="currentColor" d="M176 352c53.02 0 96-42.98 96-96V96c0-53.02-42.98-96-96-96S80 42.98 80 96v160c0 53.02 42.98 96 96 96zm160-160h-16c-8.84 0-16 7.16-16 16v48c0 74.8-64.49 134.82-140.79 127.38C96.71 376.89 48 317.11 48 250.3V208c0-8.84-7.16-16-16-16H16c-8.84 0-16 7.16-16 16v40.16c0 89.64 63.97 169.55 152 181.69V464H96c-8.84 0-16 7.16-16 16v16c0 8.84 7.16 16 16 16h160c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16h-56v-33.77C285.71 418.47 352 344.9 352 256v-48c0-8.84-7.16-16-16-16z"></path></svg>
let micOnIcon = <svg style={buttonStyle} aria-hidden="true" data-prefix="fas" data-icon="microphone-slash" className="svg-inline--fa fa-microphone-slash fa-w-20" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path fill="currentColor" d="M633.82 458.1l-157.8-121.96C488.61 312.13 496 285.01 496 256v-48c0-8.84-7.16-16-16-16h-16c-8.84 0-16 7.16-16 16v48c0 17.92-3.96 34.8-10.72 50.2l-26.55-20.52c3.1-9.4 5.28-19.22 5.28-29.67V96c0-53.02-42.98-96-96-96s-96 42.98-96 96v45.36L45.47 3.37C38.49-2.05 28.43-.8 23.01 6.18L3.37 31.45C-2.05 38.42-.8 48.47 6.18 53.9l588.36 454.73c6.98 5.43 17.03 4.17 22.46-2.81l19.64-25.27c5.41-6.97 4.16-17.02-2.82-22.45zM400 464h-56v-33.77c11.66-1.6 22.85-4.54 33.67-8.31l-50.11-38.73c-6.71.4-13.41.87-20.35.2-55.85-5.45-98.74-48.63-111.18-101.85L144 241.31v6.85c0 89.64 63.97 169.55 152 181.69V464h-56c-8.84 0-16 7.16-16 16v16c0 8.84 7.16 16 16 16h160c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16z"></path></svg>
let resetIcon =
<svg aria-hidden="true" style={{height:'1.1em'}} role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M500.333 0h-47.411c-6.853 0-12.314 5.729-11.986 12.574l3.966 82.759C399.416 41.899 331.672 8 256.001 8 119.34 8 7.899 119.526 8 256.187 8.101 393.068 119.096 504 256 504c63.926 0 122.202-24.187 166.178-63.908 5.113-4.618 5.354-12.561.482-17.433l-33.971-33.971c-4.466-4.466-11.64-4.717-16.38-.543C341.308 415.448 300.606 432 256 432c-97.267 0-176-78.716-176-176 0-97.267 78.716-176 176-176 60.892 0 114.506 30.858 146.099 77.8l-101.525-4.865c-6.845-.328-12.574 5.133-12.574 11.986v47.411c0 6.627 5.373 12 12 12h200.333c6.627 0 12-5.373 12-12V12c0-6.627-5.373-12-12-12z"></path></svg>
let stopIcon2=
<svg aria-hidden="true" style={{height:'1.4em'}} role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M440.5 88.5l-52 52L415 167c9.4 9.4 9.4 24.6 0 33.9l-17.4 17.4c11.8 26.1 18.4 55.1 18.4 85.6 0 114.9-93.1 208-208 208S0 418.9 0 304 93.1 96 208 96c30.5 0 59.5 6.6 85.6 18.4L311 97c9.4-9.4 24.6-9.4 33.9 0l26.5 26.5 52-52 17.1 17zM500 60h-24c-6.6 0-12 5.4-12 12s5.4 12 12 12h24c6.6 0 12-5.4 12-12s-5.4-12-12-12zM440 0c-6.6 0-12 5.4-12 12v24c0 6.6 5.4 12 12 12s12-5.4 12-12V12c0-6.6-5.4-12-12-12zm33.9 55l17-17c4.7-4.7 4.7-12.3 0-17-4.7-4.7-12.3-4.7-17 0l-17 17c-4.7 4.7-4.7 12.3 0 17 4.8 4.7 12.4 4.7 17 0zm-67.8 0c4.7 4.7 12.3 4.7 17 0 4.7-4.7 4.7-12.3 0-17l-17-17c-4.7-4.7-12.3-4.7-17 0-4.7 4.7-4.7 12.3 0 17l17 17zm67.8 34c-4.7-4.7-12.3-4.7-17 0-4.7 4.7-4.7 12.3 0 17l17 17c4.7 4.7 12.3 4.7 17 0 4.7-4.7 4.7-12.3 0-17l-17-17zM112 272c0-35.3 28.7-64 64-64 8.8 0 16-7.2 16-16s-7.2-16-16-16c-52.9 0-96 43.1-96 96 0 8.8 7.2 16 16 16s16-7.2 16-16z"></path></svg>
let inputStyle={marginBottom:'0.5em',fontSize:'0.9em'};
let config = this.props.config;
return <div id="hermodreactmicrophone" style={{zIndex:'9999'}}>
{(!this.state.activated) && <span onClick={this.activate}>{micOnIcon}</span>}
{(this.state.activated && this.state.sending) && <span onTouchStart={this.showConfig} onTouchEnd={this.clearConfigTimer} onMouseDown={this.showConfig} onMouseUp={this.clearConfigTimer} onContextMenu={this.showConfigNow} onClick={this.stopRecording}>{micOffIcon}</span>}
{(this.state.activated && !this.state.sending) && <span onTouchStart={this.showConfig} onTouchEnd={this.clearConfigTimer} onMouseDown={this.showConfig} onMouseUp={this.clearConfigTimer} onContextMenu={this.showConfigNow} onClick={this.startRecording}>{micOnIcon}</span>}
{(this.state.showMessage ) && <div style={{padding:'1em', borderRadius:'20px',backgroundColor:'skyblue',margin:'5%',width:'90%',top:'1.7em',color:'black',border:'2px solid blue',zIndex:'9999'}} >
{this.state.lastTranscript && <div style={{fontStyle:'italic'}}>{this.state.lastTranscript}</div>}
{false && this.state.lastIntent && <div>{this.state.lastIntent}</div>}
{this.state.lastTts && <div>{this.state.lastTts}</div>}
</div>}
<div id="audio"></div>
</div>
}
} |
JavaScript | class OrderbookUtils {
static calcFees(fees, totalCost) {
const feesTotal = totalCost.times(fees);
totalCost = totalCost.plus(feesTotal);
return { fees_total: feesTotal, total_cost: totalCost };
}
static extractOrders(orders) {
const len = orders.length;
const prices = new Array(len);
const sizes = new Array(len);
for (let i = 0; i < len; i++) {
prices[i] = orders[i].price;
sizes[i] = orders[i].totalSize;
}
const priceArray = new BigArray_1.default(prices);
const sizeArray = new BigArray_1.default(sizes);
const value = sizeArray.mult(priceArray);
return {
prices: priceArray,
sizes: sizeArray,
value: value
};
}
/**
* Find the index of the order that will fill size items starting at start_index
* @param cumSum {BigJS[]}
* @param startIndex {number} Optional optimisation argument, if it is known that the answer is above a certain index
* @param size {BigJS}
* @returns {number} the first index in order_data s.t. sum_to_i >= size
*/
static getIndexOf(cumSum, size, startIndex) {
let result = startIndex || 0;
while (result < cumSum.length - 1 && cumSum[result].lt(size)) {
result++;
}
return result;
}
constructor(book) {
if (!book || typeof book !== 'object') {
throw new Error('OrderbookUtils requires an order book object in the constructor');
}
const validBook = !!book.asks && !!book.bids;
if (!validBook) {
throw new Error('The order object must have both a bids and asks array');
}
this.book = book;
this.precalc = null;
}
get isCached() {
return this.precalc !== null;
}
get cache() {
if (!this.precalc) {
this.precache();
}
return this.precalc;
}
precache() {
const book = this.book;
this.precalc = {
asks: OrderbookUtils.extractOrders(book.asks),
bids: OrderbookUtils.extractOrders(book.bids)
};
}
bustCache() {
this.precalc = null;
}
state() {
return this.book;
}
/**
* Calculate stats for a market order. If a cached version is available, it will use that, which is much more
* efficient if multiple calculations on the same book are required. Otherwise for small, once-off calculations
* it's better to use the naive approach
* @param side {string} Must be 'buy' or 'sell'
* @param amount {string|number} The size of the trade
* @param fees {string|number} [] Optional. The fee rate charged (as a fraction, NOT a percentage)
* @returns {{ave_price: BigJS, total_size: BigJS, total_cost: BigJS, slippage: BigJS, fees: BigJS, unfilled: BigJS}}
*/
calculateMarketOrderStats(side, amount, fees = types_1.ZERO) {
if (+amount === 0) {
const orders = side === 'buy' ? this.book.asks : this.book.bids;
const firstOrder = orders[0];
return {
first_price: firstOrder.price,
last_price: firstOrder.price,
ave_price: firstOrder.price,
total_size: types_1.ZERO,
total_cost: types_1.ZERO,
slippage: types_1.ZERO,
fees: types_1.ZERO,
unfilled: types_1.ZERO
};
}
return this.isCached ? this.calculateStatsFromCache(side, amount, fees) : this.calculateStatsNoCache(side, amount, fees);
}
/**
* Return the index of the first order where the cumulative size is greater or equal to size
* @param size {BigJS}
* @param isBuy {boolean}
* @returns {number}
*/
getIndexOfTotalSize(size, isBuy) {
const orderData = isBuy ? this.cache.asks : this.cache.bids;
const sizes = orderData.sizes;
if (size.gt(sizes.sum())) {
return -1;
}
return OrderbookUtils.getIndexOf(sizes.cumsum().values, size, 0);
}
/**
* Return the index of the first order where the cumulative value is greater or equal to value
* @param value {BigJS}
* @param isBuy {boolean}
* @returns {number}
*/
getIndexOfTotalValue(value, isBuy) {
const orderData = isBuy ? this.cache.asks : this.cache.bids;
const cumsum = orderData.value.cumsum().values;
return OrderbookUtils.getIndexOf(cumsum, value, 0);
}
/**
* Calculate the marginal cost in buying from start_size to end_size, ie sum(price_i * size_i) i == start_size to end_size
* @param startSize {BigJS} the lower bound of the order
* @param endSize {BigJS} the upper bound of the order
* @param isBuy
* @param fees {BigJS}
* @param useValue {boolean} integrate using the value (quote currency) rather than base
*/
integrateBetween(startSize, endSize, isBuy, fees, useValue = false) {
endSize = types_1.Big(endSize);
const cache = this.cache;
const orderData = isBuy ? cache.asks : cache.bids;
// Cumulative sums for these arrays are cached, so multiple calls to this method is very efficient after the first one
// if calculating with values (quote currency) the 'size' vars actually refer to value. They'll be remapped later
const cumSize = useValue ? orderData.value.cumsum().values : orderData.sizes.cumsum().values;
const startIndex = OrderbookUtils.getIndexOf(cumSize, startSize, 0);
const partialStartSize = cumSize[startIndex].minus(startSize);
const firstPriceIndex = partialStartSize.eq(types_1.ZERO) ? startIndex + 1 : startIndex;
const firstPrice = types_1.Big(orderData.prices.values[firstPriceIndex]);
let endIndex = OrderbookUtils.getIndexOf(cumSize, endSize, startIndex);
let sizeNotIncluded = cumSize[endIndex].minus(endSize);
if (sizeNotIncluded.lt(types_1.ZERO)) {
sizeNotIncluded = types_1.ZERO;
}
let lastPrice = types_1.Big(orderData.prices.values[endIndex]);
let totalSize = cumSize[endIndex].minus(startSize).minus(sizeNotIncluded);
const remaining = endSize.minus(startSize).minus(totalSize);
let totalCost;
if (!useValue) {
const cumValues = orderData.value.cumsum().values;
totalCost = cumValues[endIndex].minus(cumValues[startIndex])
.plus(partialStartSize.times(firstPrice))
.minus(sizeNotIncluded.times(lastPrice));
}
else {
// We were summing over values, so 'cost' was actually size. Re-map that here
totalCost = totalSize;
const cumSizes = orderData.sizes.cumsum().values;
totalSize = cumSizes[endIndex].minus(cumSizes[startIndex])
.plus(partialStartSize.div(firstPrice))
.minus(sizeNotIncluded.div(lastPrice));
}
const feeCalc = OrderbookUtils.calcFees(fees, totalCost);
let avePrice;
if (totalSize.eq(types_1.ZERO)) {
avePrice = firstPrice;
lastPrice = firstPrice;
endIndex = firstPriceIndex;
}
else {
avePrice = feeCalc.total_cost.div(totalSize);
}
const slippage = avePrice.minus(firstPrice).div(firstPrice).abs();
return {
first_price: firstPrice,
last_price: lastPrice,
ave_price: avePrice,
total_size: totalSize,
total_cost: feeCalc.total_cost,
slippage: slippage,
fees: feeCalc.fees_total,
unfilled: remaining,
first_price_index: firstPriceIndex,
last_price_index: endIndex
};
}
/**
* Return the cumulative order size after filling until `index` orders
* @param index {number}
* @param isBuy {boolean}
*/
getCumulativeSize(index, isBuy) {
const orderData = isBuy ? this.cache.asks : this.cache.bids;
return orderData.sizes.sumTo(index);
}
/**
* Return the cumulative order cost after filling until `index` orders
* @param index {number}
* @param isBuy {boolean}
*/
getCumulativeCost(index, isBuy) {
const orderData = isBuy ? this.cache.asks : this.cache.bids;
return orderData.value.sumTo(index);
}
/**
* Calculate the base size that can be bought with total_cost, including fees
* @param startValue {BigJS} The total value that has already been traded
* @param totalFunds {BigJS} The quote amount to spend, including fees
* @param isBuy {boolean}
* @param fees {BigJS} fractional fee rate
*/
getSizeFromCost(startValue, totalFunds, isBuy, fees = types_1.ZERO) {
const onePlusFees = types_1.ONE.plus(fees);
const nonFeeValue = totalFunds.div(onePlusFees);
const endValue = startValue.plus(nonFeeValue);
const result = this.integrateBetween(startValue, endValue, isBuy, fees, true);
// When using quote currencies, we expect the unfilled amount to be inclusive of expected fees
result.unfilled = result.unfilled.times(onePlusFees);
return result;
}
calculateStatsFromCache(side, amount, fees) {
return this.integrateBetween(types_1.ZERO, amount, side === 'buy', fees);
}
calculateStatsNoCache(side, amount, fees = types_1.ZERO) {
amount = types_1.Big(amount);
let remaining = types_1.Big(amount);
let totalCost = types_1.ZERO;
const orders = side === 'buy' ? this.book.asks : this.book.bids;
if (!Array.isArray(orders[0])) {
throw new Error('Use pre-caching to calculate stats on object-format orderbooks');
}
let i = 0;
let size = null;
const firstPrice = types_1.Big(orders[0].price);
let lastPrice = types_1.Big(orders[0].price);
do {
lastPrice = orders[i].price;
size = orders[i].totalSize;
// We've filled the order
if (remaining.lte(size)) {
size = types_1.Big(remaining);
remaining = types_1.ZERO;
}
else {
remaining = remaining.minus(size);
}
totalCost = totalCost.plus(lastPrice.times(size));
i++;
} while (remaining.gt(0) && i < orders.length);
const feeCalc = OrderbookUtils.calcFees(fees, totalCost);
const fees_total = feeCalc.fees_total;
totalCost = feeCalc.total_cost;
const totalSize = amount.minus(remaining);
const avePrice = totalCost.div(totalSize);
const bestPrice = orders[0].price;
const slippage = avePrice.minus(bestPrice).div(bestPrice).abs();
return {
first_price: firstPrice,
last_price: lastPrice,
ave_price: avePrice,
total_size: totalSize,
total_cost: totalCost,
slippage: slippage,
fees: fees_total,
unfilled: remaining
};
}
} |
JavaScript | class AddDeleteDocElementCmd {
constructor(add, elementType, initialData, id, parentId, position, rb) {
this.add = add;
this.elementType = elementType;
this.initialData = initialData;
this.parentId = parentId;
this.position = position;
this.rb = rb;
this.id = id;
this.firstExecution = true;
}
getName() {
if (this.add) {
return 'Add element';
} else {
return 'Delete element';
}
}
do() {
if (this.add) {
this.addElement();
} else {
this.deleteElement();
}
this.firstExecution = false;
}
undo() {
if (this.add) {
this.deleteElement();
} else {
this.addElement();
}
}
addElement() {
let parent = this.rb.getDataObject(this.parentId);
if (parent !== null) {
let element = AddDeleteDocElementCmd.createElement(this.id, this.initialData, this.elementType, this.position, true, this.rb);
this.rb.notifyEvent(element, Command.operation.add);
this.rb.selectObject(this.id, true);
if (this.add && this.firstExecution) {
// in case of add command we serialize initialData on first execution so it contains all data
// created during setup (e.g. ids of table bands and table cells for a table)
this.initialData = element.toJS();
}
}
}
deleteElement() {
let element = this.rb.getDataObject(this.id);
if (element !== null) {
this.rb.deleteDocElement(element);
}
}
static createElement(id, data, elementType, panelPos, openPanelItem, rb) {
let element;
let properties = { draggable: true };
if (elementType === DocElement.type.text) {
element = new TextElement(id, data, rb);
} else if (elementType === DocElement.type.line) {
element = new LineElement(id, data, rb);
} else if (elementType === DocElement.type.image) {
element = new ImageElement(id, data, rb);
} else if (elementType === DocElement.type.pageBreak) {
element = new PageBreakElement(id, data, rb);
} else if (elementType === DocElement.type.table) {
element = new TableElement(id, data, rb);
properties.hasChildren = true;
} else if (elementType === DocElement.type.frame) {
element = new FrameElement(id, data, rb);
properties.hasChildren = true;
} else if (elementType === DocElement.type.section) {
element = new SectionElement(id, data, rb);
properties.hasChildren = true;
} else if (elementType === DocElement.type.barCode) {
element = new BarCodeElement(id, data, rb);
}
rb.addDocElement(element);
let parentPanel = element.getContainer().getPanelItem();
let panelItem = new MainPanelItem(elementType, parentPanel, element, properties, rb);
element.setPanelItem(panelItem);
parentPanel.insertChild(panelPos, panelItem);
element.setup(openPanelItem);
return element;
}
} |
JavaScript | class Entity {
/**
* Create new entity
* @param {string} type - What type of entity was found
* @param {string} value - What was the value of the entity type
*/
constructor (type, value) {
this.type = type;
this.value = value;
}
} |
JavaScript | class ModelBinder {
constructor(model, rootPath) {
this._model = model;
this._rootPath = rootPath;
}
get model() {
return this._model;
}
get rootPath() {
return this._rootPath;
}
setProperty(data, path = "", overrideRoot = false) {
let fullPath = `${this.rootPath}${path}`;
if (overrideRoot) {
fullPath = path;
}
this.model.setProperty(fullPath, data);
}
} |
JavaScript | class LegacyCluster {
constructor () {
}
init (config, context) {
context.log.warn('The cluster plugin is deprecated and can be safely removed: this plugin now only prevents breaking changes by adding the previously exposed API actions, and converts the old cluster configuration to the new version');
const clusterConfig = global.kuzzle.config.cluster;
if (config) {
if (config.minimumNodes) {
clusterConfig.minimumNodes = config.minimumNodes;
}
if (config.bindings) {
let family = 'ipv4';
if (config.bindings.pub) {
const { ipv6, port } = resolveBinding(
config.bindings.pub,
clusterConfig.ports.sync);
if (ipv6) {
family = 'ipv6';
}
clusterConfig.ports.sync = port;
}
if (config.bindings.router) {
const { ipv6, port } = resolveBinding(
config.bindings.router,
clusterConfig.ports.command);
if (family !== 'ipv6' && ipv6) {
family = 'ipv6';
}
clusterConfig.ports.command = port;
}
if (family === 'ipv6') {
clusterConfig.ipv6 = true;
}
}
}
this.controllers = {
cluster: {
health: 'clusterHealthAction',
reset: 'clusterResetAction',
status: 'clusterStatusAction'
}
};
this.routes = [
{action: 'health', controller: 'cluster', path: '/health', verb: 'get', },
{action: 'reset', controller: 'cluster', path: '/reset', verb: 'post', },
{action: 'status', controller: 'cluster', path: '/status', verb: 'get', },
];
}
/**
* @deprecated - added for backward compatibility only
*
* Returns "ok" if the cluster is able to respond. This route is obsolete
* because now, if there aren't enough nodes in the cluster, any API action
* returns a proper "api.process.not_enough_nodes" error (code 503) and
* Kuzzle refuses to process it.
*
* @return {string}
*/
clusterHealthAction () {
return 'ok';
}
/**
* @deprecated - added for backward compatibility only
*
* This action originally "resets" the cluster state
* This was only (somewhat) useful in development environments, or as a
* dirty workaround to desyncs, and this makes no sense with the new cluster
* architecture, since 1/ the state is guaranteed to be synchronized, and
* 2/ the state is now completely volatile: restarting the whole cluster at
* once (e.g. using "admin:shutdown" and then restarting nodes) will
* effectively force the cluster to have a blank state (the old cluster stored
* its state in redis, hence this API action).
*
* @return {string} deprecation notice
*/
clusterResetAction () {
return 'no-op: this route is deprecated and has been kept for backward-compatibility only. To reset a cluster, simply use "admin:shutdown" and then restart Kuzzle nodes';
}
/**
* @deprecated
*
* Reproduces the old "status" result from the new, more thorough one
* returned by the new cluster
*
* @return {[type]} [description]
*/
async clusterStatusAction () {
const status = await global.kuzzle.ask('cluster:status:get');
const result = {
count: status.activeNodes,
current: null,
pool: null,
};
result.current = convertToOldStatus(
status.nodes.find(node => node.id === global.kuzzle.id));
result.pool = status.nodes
.filter(node => node.id !== global.kuzzle.id)
.map(convertToOldStatus);
return result;
}
} |
JavaScript | class Client {
/**
* @param {Node} node
*/
constructor( node ) {
Object.defineProperties( this, {
node: { value: node },
options: { value: node.options },
} );
}
/**
* Forwards given command to peer node in cluster for processing remotely.
*
* @note This method is picking remote node automatically preferring current
* leader node if known or some randomly chosen peer. However, basic
* commands can be performed on leader node, only, thus request fails
* if leader is unknown.
*
* @param {object} command actual command to be performed
* @param {object<string,*>=} options
* @returns {Promise}
*/
command( command, options ) {
debug( 'command %j', command );
const self = this;
const node = this._pickNode();
if ( !node ) {
return Promise.reject( new NotLeaderError( this.node.leader() ) );
}
options.tries = ( options.tries || 0 ) + 1;
if ( node === this.node.id ) {
// local call
return this.node.command( command, options )
.catch( handleError );
}
// remote call
debug( 'forwarding command %j to %s via RPC', node, command );
const rpcOptions = Object.assign( {}, options, { remote: true } );
return this.node.rpc( {
from: this.node.id,
to: node,
action: 'Command',
params: { command, options: rpcOptions }
} )
.then( extractRemoteResult )
.catch( handleError );
function handleError( error ) {
debug( 'reply to command %j failed: %s, reply: %j', command, error && error.message );
switch ( error.message ) {
case 'not connected' :
maybeRetry();
break;
default :
switch ( error.code ) {
case 'ENOTLEADER' :
case 'ENOMAJORITY' :
case 'EOUTDATEDTERM' :
return maybeRetry( Boolean( error.leader ) );
default :
throw error;
}
}
}
function maybeRetry( immediate ) {
if ( options.tries < self.options.clientMaxRetries ) {
if ( immediate ) {
return self.node.command( command, options );
}
return new Promise( ( resolve, reject ) => {
setTimeout( () => {
self.node.command( command, options )
.then( resolve, reject );
}, self.options.clientRetryRPCTimeout );
} );
}
throw new NotLeaderError( self.node.leader() );
}
}
_pickNode() {
let node = this.node.leader();
if ( !node ) {
const peers = this.node.peers;
node = peers[Math.floor( Math.random() * peers.length )];
}
return node && node.toString();
}
} |
JavaScript | class Option extends OO.EventEmitter {
/**
* @param {Object} config
* @param {string} config.name Name of option. (required)
* @param {*} config.defaultValue The default value for the option. (required)
* @param {string} config.label Text displayed in settings. (required)
* @param {string} config.help Help text shown in settings.
* @param {boolean} config.hide Whether to hide the option.
* @param {boolean} config.helpInline Whether the help text should be inline or not.
* @param {Object} config.UIconfig Configuration that is passed into the underlying UI.
* @param {string} config.type
* Type of option. Should be same as name of subclass minus
* Option at the end (e.g "Color" for "ColorOption" class) (Defined by subclasses.)
* @param {...string} config.basetypes
* Type(s) to validate against (Defined by subclasses).
*/
constructor( config ) {
super();
this.name = config.name;
this.defaultValue = config.defaultValue;
this.label = config.label;
this.type = config.type;
this.UIconfig = config.UIconfig || {};
this.help = config.help;
this.hide = config.hide;
this.helpInline = config.helpInline;
const libSettingClass = [ `libSettings-${this.type}Option` ];
this.UIconfig.classes = this.UIconfig.classes ?
this.UIconfig.classes.push( libSettingClass ) :
libSettingClass;
this.validInput = true;
/**
* The name of the attribute the option's UI should display when generating the UI.
* Changed when e.g. showing the default value.
*/
this.propertyNameUI = 'value';
if ( this.name === undefined || this.defaultValue === undefined ) {
const varName = ( this.name === undefined ) ? 'name' : 'defaultValue';
throw Error( `[libSettings] "${varName}" of an Option is required to be defined but is not.` );
}
if ( this.type === undefined ) {
throw Error( '[libSettings] "config.type" is required to be defined by classes that extend Option.' );
}
}
/**
* Return either the configured saved user value if it exists or the default value.
* @return {*}
*/
get value() {
if ( this.customValue !== undefined ) {
return this.customValue;
} else {
return this.defaultValue;
}
}
/**
* @param {*} newValue
*/
set value( newValue ) {
this.customValue = newValue;
}
/**
* Return only the values the user has configured in the UI for each option
* where it is different from the default.
* This is called when saving settings.
* @return {*}
*/
get customUIValue() {
let UIValue;
if ( this.hasUI ) {
UIValue = this.UIvalue;
} else {
UIValue = this.value;
}
if ( UIValue !== this.defaultValue ) {
return UIValue;
} else {
return undefined;
}
}
/**
* Emit a change event. Called by {@link Option#UI}
* @fires Option#change
*/
change() {
/**
* Indicates that a user has changed the value of an option in the UI. Listened to by
* {@link SettingsDialog#changeHandler}.
* @event Option#change
*/
this.emit( 'change' );
}
/**
* @protected
* @return {OO.ui.Element}
*/
buildUI() {
if ( !this.hide ) {
this.hasUI = true;
return this.UI( this[ this.propertyNameUI ] );
}
}
/**
* Defines how to get the value inputed by the user in the UI.
* @return {*}
*/
get UIvalue() {
return mw.log.error( `Getter UIvalue not defined by extending class ${this.type}Option.` );
}
/**
* Create UI.
* @param {any} value
* @return {OO.ui.element}
*/
UI() {
return mw.log.error( `Function UI not defined by extending class ${this.type}Option.` );
}
} |
JavaScript | class ProductSwitch extends UI5Element {
constructor() {
super();
this.initItemNavigation();
}
initItemNavigation() {
this._itemNavigation = new ItemNavigation(this, { rowSize: 4 });
this._itemNavigation.getItemsCallback = () => this.items;
}
static get metadata() {
return metadata;
}
static get render() {
return litRender;
}
static get styles() {
return ProductSwitchCss;
}
static get template() {
return ProductSwitchTemplate;
}
static get ROW_MIN_WIDTH() {
return {
ONE_COLUMN: 600,
THREE_COLUMN: 900,
};
}
onEnterDOM() {
this._handleResizeBound = this._handleResize.bind(this);
ResizeHandler.register(document.body, this._handleResizeBound);
}
onExitDOM() {
ResizeHandler.deregister(document.body, this._handleResizeBound);
}
onBeforeRendering() {
this.desktopColumns = this.items.length > 6 ? 4 : 3;
}
_handleResize() {
const documentWidth = document.body.clientWidth;
if (documentWidth <= this.constructor.ROW_MIN_WIDTH.ONE_COLUMN) {
this._itemNavigation.rowSize = 1;
} else if (documentWidth <= this.constructor.ROW_MIN_WIDTH.THREE_COLUMN || this.items.length <= 6) {
this._itemNavigation.rowSize = 3;
} else {
this._itemNavigation.rowSize = 4;
}
}
_onfocusin(event) {
const target = event.target;
this._itemNavigation.update(target);
}
} |
JavaScript | class PageScroll {
/**
*
* @param {PageScrollOpts} options scrolling options
*/
constructor(
{
fnNext = (row) => row,
fnPrev = (row) => row,
vectorDefault = 50,
resultsDesc = true,
} = {},
) {
this._props = { fnNext, fnPrev, vectorDefault, resultsDesc };
}
/**
*
* @param {array} resultsArr array with data (can be empty [] on first call)
* @param {pageObj} pageObjLast pageObj from last call (can be empty {} on rowFirst call)
* @param {integer} vector (number of requested records signed by direction top to bottom if positive, bottom to top if negative)
* if omitted will be derived from last call class vectorDefault
* @param {*} overrideFirst conventionally first and last records are derived from results array still clients can override this
* by providing a valid record in special cases for efficiency when they for some reason wish to jump some records
* (for example if for some reason they know that query can't be fulfilled from next records in line)
* @param {*} overrideLast (see above)
* @returns {pageObj} a pageObj to be used and returned on next call
*/
async getPageObj(resultsArr, pageObjLast = {}, vector = undefined, { overrideFirst, overrideLast } = {}) {
vector = vector || pageObjLast.vector || this._props.vectorDefault || 1; // vector can't be 0
const direction = Math.sign(vector) || 1;
const limit = Math.abs(vector);
const pageSize = resultsArr.length;
const callCount = pageObjLast.callCount + 1 || 1;
const ts = Date.now();
let [dataFirst, dataLast] = arrFirstLast(resultsArr);
if (direction === -1 && this._props.resultsDesc === true) { [dataFirst, dataLast] = [dataLast, dataFirst]; }
dataFirst = overrideFirst || dataFirst; // override if provided (special case see documentation)
dataLast = overrideLast || dataLast; // override if provided (special case see documentation)
if (pageSize >= limit) {
return { next: this._props.fnNext(dataLast), prev: this._props.fnPrev(dataFirst), position: 0, vector, pageSize, callCount, ts };
}
if (pageSize === 0) {
if (direction === 1) {
return { next: pageObjLast.next, prev: pageObjLast.prev, position: 1, vector, pageSize, callCount, ts };
}
return { next: pageObjLast.next, prev: pageObjLast.prev, position: -1, vector, pageSize, callCount, ts };
}
if (pageSize < limit) { // this statement should be the LAST in if chain
if (direction === 1) {
return { next: pageObjLast.next, prev: this._props.fnPrev(dataFirst), position: 1, vector, pageSize, callCount, ts };
}
return { next: this._props.fnNext(dataLast), prev: pageObjLast.prev, position: -1, vector, pageSize, callCount, ts };
}
throw new ErrAcropolisND(5001, JSON.stringify({ vector, direction, limit, pageSize })); // should never get here;
}
} |
JavaScript | class CustomBlockquote extends HTMLBlockquoteElement {
constructor() {
this.custom = 42;
}
} |
JavaScript | class Rsa {
constructor() {
let signingSchemes = ['pkcs1', 'pss']
let signHashAlgorithms = {
'node': ['MD4', 'MD5', 'RIPEMD160', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'],
'browser': ['MD5', 'RIPEMD160', 'SHA1', 'SHA256', 'SHA512'],
}
this.RsaModule = new NodeRSA({b: 512, signingScheme: 'pkcs1-SHA512'})
}
/**
* Encrypt text with external key.
* @param plainText
*/
async encrypt3dKey(plainText, externalPublicKey) {
const RsaTmp = new Rsa()
await RsaTmp.importPublicKey(externalPublicKey)
return RsaTmp.encrypt(plainText)
}
/**
*
* @param plainText
* @return {*}
*/
encrypt(plainText) {
return this.RsaModule.encrypt(plainText, 'base64')
}
/**
*
* @param encryptText
* @return {*}
*/
decrypt(encryptText) {
return this.RsaModule.decrypt(encryptText, 'utf8')
}
/**
* Import external Rsa public key.
* @param {String} RsaPublicKey
*/
async importPublicKey(RsaPublicKey) {
await this.RsaModule.importKey(RsaPublicKey)
}
/**
*
* @param RsaPrivateKey
* @return {Promise<void>}
*/
async importPrivateKey(RsaPrivateKey) {
await this.RsaModule.importKey(RsaPrivateKey, 'pkcs1')
}
/**
* Retrieve Rsa public key.
* @returns {String}
*/
exportPublicKey() {
return this.RsaModule.exportKey('public')
}
/**
* Calculate max message size in bytes.
* @returns {Number}
*/
maxMessageSize() {
return this.RsaModule.getMaxMessageSize()
}
maxKeySize() {
return this.RsaModule.getKeySize()
}
getByteLen(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
c < (1 << 21) ? 4 :
c < (1 << 26) ? 5 :
c < (1 << 31) ? 6 : Number.NaN;
}
return byteLen;
}
} |
JavaScript | class ProxyWrapper {
_proxy = null;
_proxyPromise = null;
/**
* Creates a new `ProxyWrapper` from a layer proxy object and layer config.
*
* @param {Promise<LayerProxy>} proxyPromise a promise of a layer proxy object which will be coupled with a corresponding layer config object
* @param {LayerNode} layerConfig layer config defintion object from the config file; it may provide overrides and initial settings for the layer proxy object
*/
constructor(proxyPromise, layerConfig) {
this._initProxyPromise(proxyPromise);
this._layerConfig = layerConfig;
this.isControlVisible = ref.isControlVisible.bind(this);
this.isControlDisabled = ref.isControlDisabled.bind(this);
this.isControlSystemDisabled = ref.isControlSystemDisabled.bind(this);
this.isControlUserDisabled = ref.isControlUserDisabled.bind(this);
}
_initProxyPromise(proxyPromise) {
this._proxyPromise = proxyPromise;
// wait for the proxy to be resolved;
// for WFS layers proxy resolves when the layer record is made and "loaded"
// for other layer types proxy resolves when the layer record is made (layer is not necessarily loaded at this point)
this._proxyPromise
.then(proxy => {
this._proxy = proxy;
// This will apply initial state values from the layer config object to the layer proxy object.
// This is needed to apply state settings that are not set in geoApi (dynamic layers, for example, start up as fully invisible to prevent flicker on initial load).
this.opacity = this._layerConfig.state.opacity;
this.visibility = this._layerConfig.state.visibility;
this.query = this._layerConfig.state.query;
this._updateApiLayerVisibility(this);
this._updateApiLayerOpacity(this);
this._updateApiLayerQueryable(this);
})
.catch(error => {
console.error(`Layer proxy failed to resolve for "${this.layerConfig.id}"`, error);
// if the proxy fails to resolve (layer data failed to load, etc.), set status to `rv-error`
this._lastState = Geo.Layer.States.ERROR;
});
}
/**
* Checks if a proxy object is resolved or not, and throws error if not and no callback is provided.
*
* @param {*} [callback=null] a function to run later when the proxy is resolved
* @returns {Boolean} returns `true` if the proxy is resolved; `false` otherwise and a callback is provided;
* @memberof ProxyWrapper
*/
_proxyCheck(callback = null) {
if (this._proxy) {
return true;
} else if (callback) {
this.proxyPromise.then(callback);
return false;
} else {
throw new Error('Layer proxy is not yet resolved.');
}
}
get proxyPromise() {
return this._proxyPromise;
}
/**
* @return {Proxy} original gapi proxy object
*/
get proxy() {
this._proxyCheck();
return this._proxy;
}
/**
* @return {LayerNode} original typed layer config object
*/
get layerConfig() {
return this._layerConfig;
}
_stateTimeout = null;
_lastState = Geo.Layer.States.LOADING; // last valid state
/**
* A helper function to update state and cancel the state timeout.
*
* @memberof ProxyWrapper
*/
_updateState() {
common.$timeout.cancel(this._stateTimeout);
this._stateTimeout = null;
this._lastState = this._proxy.state;
}
get state() {
// if no proxy object is available, this is a config-added file-like layer with remote-data (aka WFS or a file-layer)
if (!this._proxy) {
return this._lastState;
}
if (this._proxy.state === this._lastState) {
return this._lastState;
}
// multiple error events are fired by ESRI code when some tiles are missing in a tile layer; this does not mean that the layer is broken, but it does trigger the error toast
// delay the state update to allow for a subsequent `rv-loaded` event to clear the delay; if `rv-loaded` is not fired before the delay is over, the layer is considered to have failed
// https://github.com/fgpv-vpgf/fgpv-vpgf/issues/2971
if (this._proxy.state !== Geo.Layer.States.ERROR) {
this._updateState();
} else if (this._lastState !== Geo.Layer.States.ERROR && !this._stateTimeout) {
this._stateTimeout = common.$timeout(() => this._updateState.apply(this), 2500);
}
return this._lastState;
}
get isActiveState() {
return this._proxy ? this._proxy.activeState : false;
}
get name() {
return this._proxy ? this._proxy.name : this._layerConfig.name;
}
get opacity() {
return this._proxy ? this._proxy.opacity : this._layerConfig.state.opacity;
}
get visibility() {
return this._proxy ? this._proxy.visibility : this._layerConfig.state.visibility;
}
get layerType() {
return this._proxy ? this._proxy.layerType : this._layerConfig.layerType;
}
get parentLayerType() {
this._proxyCheck();
return this._proxy.parentLayerType;
}
get featureCount() {
this._proxyCheck();
return this._proxy.featureCount;
}
get loadedFeatureCount() {
this._proxyCheck();
return this._proxy.loadedFeatureCount;
}
get geometryType() {
this._proxyCheck();
return this._proxy.geometryType;
}
get extent() {
this._proxyCheck();
return this._proxy.extent;
}
get symbology() {
this._proxyCheck();
return this._proxy.symbology;
}
get formattedAttributes() {
this._proxyCheck();
return this._proxy.formattedAttributes;
}
get itemIndex() {
this._proxyCheck();
return this._proxy.itemIndex;
}
get queryUrl() {
this._proxyCheck();
return this._proxy.queryUrl;
}
// TODO pick better name. using filterState due to current collision with other config-based .filter getter
get filterState() {
this._proxyCheck();
return this._proxy.filter;
}
get query() {
return this._proxy ? this._proxy.query : this._layerConfig.state.query;
}
get snapshot() {
return this._layerConfig.state.snapshot;
}
get boundingBox() {
return this._layerConfig.state.boundingBox;
}
set opacity(value) {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(() => (this.opacity = value))) {
return;
}
if (this.isControlSystemDisabled('opacity')) {
return;
}
this._proxy.setOpacity(value);
// store opacity value in the layer config; will be used by full state restore
this._layerConfig.state.opacity = value;
this._updateApiLayerOpacity(this);
}
set visibility(value) {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(() => (this.visibility = value))) {
return;
}
if (this.isControlSystemDisabled('visibility')) {
return;
}
this._proxy.setVisibility(value);
// store visibility value in the layer config; will be used by full state restore
this._layerConfig.state.visibility = value;
this._updateApiLayerVisibility(this);
}
set query(value) {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(() => (this.query = value))) {
return;
}
if (this.isControlSystemDisabled('query')) {
return;
}
// bounding box belongs to the LegendBlock, not ProxyWrapper;
// so, setting boundingBox value doesn't call the proxy object,
// it just stores the value in the layer config state for future bookmark use
this._proxy.setQuery(value);
// store query value in the layer config; will be used by full state restore
this._layerConfig.state.query = value;
this._updateApiLayerQueryable(this);
}
set boundingBox(value) {
if (this.isControlSystemDisabled('boundingBox')) {
return;
}
this._layerConfig.state.boundingBox = value;
}
/**
* Layer config object persists through layer reload (corresponding layer record and legend blocks are destroyed),
* the changed snapshot value will be processed in geoApi on the subsequent generation of layer records.
*
* @param {Boolean} value stores the snapshot value on the layer config object
*/
set snapshot(value) {
this._layerConfig.state.snapshot = value;
}
/**
* Checks if the layer is off scale by calling its proxy object with the current map scale value.
*
* @return {Object} of the form {offScale: <Boolean>, zoomIn: <Boolean> }
*/
isOffScale() {
this._proxyCheck();
return this._proxy.isOffScale(ref.map.instance.getScale());
}
zoomToBoundary() {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(this.zoomToBoundary)) {
return;
}
return this._proxy.zoomToBoundary(ref.map.instance);
}
zoomToScale() {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(this.zoomToScale)) {
return;
}
return this._proxy.zoomToScale(ref.map.instance, ref.map.selectedBasemap.lods, this.isOffScale().zoomIn);
}
/**
* Zooms to a graphic with the specified oid.
*
* @param {Number} oid object oid
* @param {Object} offsetFraction fractions of the current extent occupied by main and data panels in the form of { x: <Number>, y: <Number> }
* @return {Promise} a promise resolving when the extent change is comlete
*/
zoomToGraphic(oid, offsetFraction) {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(() => this.zoomToGraphic(oid, offsetFraction))) {
return;
}
return this._proxy.zoomToGraphic(oid, ref.map.instance, offsetFraction);
}
/**
* Retrieves a graphic with the id specified.
*
* @param {Number} oid the object id to be returned
* @param {Object} opts options object for the graphic
* @return {Promise} a promise resolving with a graphic object
*/
fetchGraphic(oid, opts) {
// the proxy has not resolved yet; retry when resolved;
if (!this._proxyCheck(() => this.fetchGraphic(oid, opts))) {
return;
}
return this._proxy.fetchGraphic(oid, opts);
}
abortAttribLoad() {
// the proxy has not resolved yet
this._proxyCheck();
this._proxy.abortAttribLoad();
}
/**
* Returns the value of the `userAdded` state flag.
*
* @return {Boolean} `true` is the layer was added by a user
*/
get userAdded() {
return this._layerConfig.state.userAdded;
}
// find whos calling this. determine if still relevant. attempt to port to new filter regime
// might want to use this.filterState.isActive() which returns boolean.
// See https://github.com/fgpv-vpgf/fgpv-vpgf/issues/3263#issuecomment-460794432 for further analysis on this
/**
* Returns the value of the `filter` state flag.
*
* @return {Boolean} `true` is the layer has filter
*/
get filter() {
return this._layerConfig.filter;
}
set filter(value) {
this._layerConfig.filter = value;
}
// if the projection is not valid, the layer cannot be displayed on the map
_validProjection = true;
get validProjection() {
return this._validProjection;
}
/**
* Checks if the spatial reference of the layer matches the spatial reference of the current basemap.
* If it doesn't, the layer cannot be displayed on the map.
*
* @function validateProjection
*/
validateProjection() {
// validate projection only for tile layers; although Aly said that wms, dynamic and image layers are potentially affected as well;
if (this.proxy.parentLayerType !== Geo.Layer.Types.ESRI_TILE) {
return;
}
this._validProjection = this.proxy.validateProjection(ref.map.selectedBasemap.spatialReference) !== false;
}
get metadataUrl() {
return this._layerConfig.metadataUrl;
}
set metadataUrl(url) {
this._layerConfig.metadataUrl = url;
}
get catalogueUrl() {
return this._layerConfig.catalogueUrl;
}
get enableStructuredDelete() {
return this._layerConfig.enableStructuredDelete;
}
get availableControls() {
return this._layerConfig.controls;
}
get disabledControls() {
return this._layerConfig.disabledControls;
}
get userDisabledControls() {
return this._layerConfig.userDisabledControls;
}
/**
* @function _updateApiLayerOpacity
* @private
* @param {LegendBlock} legendBlock legend block where opacity is being updated
*/
_updateApiLayerOpacity() {
let layer;
if (appInfo.mapi) {
if (this._layerConfig.layerType === Geo.Layer.Types.ESRI_DYNAMIC) {
// TODO: find a better way to find the dynamic ConfigLayer than directly comparing geoApi proxies
// potentially can add a 'layerId' to the proxy which will allow for an easy comparison
// of both the id and index to find the correct layer
layer = appInfo.mapi.layers.allLayers.find(l => l._layerProxy === this.proxy);
} else {
layer = appInfo.mapi.layers.getLayersById(this._layerConfig.id)[0];
}
if (layer && layer.opacity !== this._proxy.opacity) {
layer._opacityChanged.next(this._proxy.opacity);
}
}
}
/**
* @function _updateApiLayerVisibility
* @private
* @param {LegendBlock} legendBlock legend block where visibility is being updated
*/
_updateApiLayerVisibility() {
let layer;
if (appInfo.mapi) {
if (this._layerConfig.layerType === Geo.Layer.Types.ESRI_DYNAMIC) {
// TODO: find a better way to find the dynamic ConfigLayer than directly comparing geoApi proxies
// potentially can add a 'layerId' to the proxy which will allow for an easy comparison
// of both the id and index to find the correct layer
layer = appInfo.mapi.layers.allLayers.find(l => l._layerProxy === this.proxy);
} else {
layer = appInfo.mapi.layers.getLayersById(this._layerConfig.id)[0];
}
// push update into the observable
if (layer && layer.visibility !== this._proxy.visibility) {
layer._visibilityChanged.next(this._proxy.visibility);
}
}
}
/**
* @function _updateApiLayerQueryable
* @private
* @param {LegendBlock} legendBlock legend block where query value is being updated
*/
_updateApiLayerQueryable() {
let layer;
if (appInfo.mapi) {
if (this._layerConfig.layerType === Geo.Layer.Types.ESRI_DYNAMIC) {
// TODO: find a better way to find the dynamic ConfigLayer than directly comparing geoApi proxies
// potentially can add a 'layerId' to the proxy which will allow for an easy comparison
// of both the id and index to find the correct layer
layer = appInfo.mapi.layers.allLayers.find(l => l._layerProxy === this.proxy);
} else {
layer = appInfo.mapi.layers.getLayersById(this._layerConfig.id)[0];
}
if (layer && layer.queryable !== this._proxy.query) {
layer._queryableChanged.next(this._proxy.query);
}
}
}
} |
JavaScript | class LegendEntry extends LegendBlock {
constructor(blockConfig) {
super(blockConfig);
this.isControlVisible = ref.isControlVisible.bind(this);
this.isControlDisabled = ref.isControlDisabled.bind(this);
this.isControlSystemDisabled = ref.isControlSystemDisabled.bind(this);
this.isControlUserDisabled = ref.isControlUserDisabled.bind(this);
this._selectedChanged = new Subject();
}
get isInteractive() {
return true;
}
_isSelected = false;
_layerRecordId = null;
get isSelected() {
return this._isSelected;
}
set isSelected(value) {
this._isSelected = value;
this._selectedChanged.next(value);
}
get selectedChanged() {
return this._selectedChanged.asObservable();
}
/**
* Sets layer record id on legend entry.
*
* @param {String} value id of the layer bound to this legend block; this will be used in reordering and reloading
*/
set layerRecordId(value) {
this._layerRecordId = value;
}
/**
* @param {String} value id of the layer bound to this legend block; this will be used in reordering and reloading
*/
get layerRecordId() {
// layerRecordId is null until set in by the legend service;
return this._layerRecordId;
}
/**
* @return {Boolean} true if the LegendEntry's visual parent is a set; an child entry of a collapsed group which is a part of a set, is be considered a part of that set;
*/
get inSet() {
if (!this.parent) {
return false;
}
return this.visualParent.blockType === LegendBlock.SET;
}
} |
JavaScript | class LegendGroup extends LegendEntry {
/**
*
* @param {EntryGroup} blockConfig the entry group config object
* @param {ProxyWrapper} rootProxyWrapper the proxy wrapper containing the layer proxy object of a dynamic layer root
* @param {Boolean} [isDynamicRoot=false] specifying if this group is the root of a dynamic layer
*/
constructor(blockConfig, rootProxyWrapper = null, isDynamicRoot = false) {
super(blockConfig);
this._name = blockConfig.name;
this._expanded = blockConfig.expanded;
this._availableControls = blockConfig.controls;
this._disabledControls = blockConfig.disabledControls;
this._userDisabledControls = blockConfig.userDisabledControls;
this._rootProxyWrapper = rootProxyWrapper;
this._isDynamicRoot = isDynamicRoot;
this._sameOpacity = true;
this._toggled = false;
this._aggregateStates = ref.aggregateStates;
this._walk = ref.walkFunction.bind(this);
if (this._rootProxyWrapper) {
// Set LegendGroup's opacity to 1 to ensure opacity of children
// is calculated relative to fully opaque.
// The expected opacity is still applied to children values
this._rootProxyWrapper.opacity = 1;
}
}
get blockType() {
return TYPES.GROUP;
}
// collapsed value specifies if the group node will be hidden from UI
// in such a case, its children will appear to be on the same level as the legend group would have been
_collapsed = false;
get collapsed() {
return this._collapsed;
}
set collapsed(value) {
this._collapsed = value;
}
// TODO: this doesn't seem to be called from anywhere
applyInitialStateSettings() {
// this will ensure all the controlled layers settings in this group match settings of the observable entries
this.visibility = this.visibility;
this.opacity = this.opacity;
}
synchronizeControlledEntries() {
this._activeEntries.filter(entry => entry.controlled).forEach(controlledEntry => {
controlledEntry.visibility = this.visibility;
controlledEntry.opacity = this.opacity;
});
}
_entries = [];
get availableControls() {
return this._availableControls;
}
get disabledControls() {
return this._disabledControls;
}
get userDisabledControls() {
return this._userDisabledControls;
}
/**
* @return {Boolean} true if the group is part of the user-added dynamic layer
*/
get userAdded() {
if (this._rootProxyWrapper) {
return this._rootProxyWrapper.userAdded;
}
return false;
}
get state() {
if (this._isDynamicRoot) {
return this._rootProxyWrapper.state;
}
return Geo.Layer.States.LOADED;
}
get template() {
const availableControls = this._availableControls;
const collapsed = this.collapsed;
// only add `reload` control to the available controls when the dynamic layer is loading or already failed
// TODO would be nice if we could utilize the constants in Geo.Layer.States instead of hardcoding
const stateToTemplate = {
'rv-loading': () => 'placeholder',
'rv-loaded': () => {
// only remove reload if it is not the dynamic root or the top-most visible level of a dynamic layer (if root collapsed)
if (
!this._isDynamicRoot &&
!(this.parent.blockType === LegendBlock.GROUP && this.parent.collapsed)
) {
_removeReload();
} else {
_addReload();
}
return _collapsedCheck(super.template);
},
'rv-refresh': () => _collapsedCheck(super.template),
'rv-error': () => {
_addReload();
return 'error';
},
'rv-bad-projection': () => {
_removeReload();
return 'bad-projection';
}
};
return stateToTemplate[this.state]();
/**
* Adds a `reload` control to the list of available group controls.
*
* @function _addReload
* @private
*/
function _addReload() {
const index = availableControls.indexOf('reload');
if (index === -1) {
availableControls.push('reload');
}
}
/**
* Removes a `reload` control to the list of available group controls.
*
* @function _removeReload
* @private
*/
function _removeReload() {
const index = availableControls.indexOf('reload');
if (index !== -1) {
availableControls.splice(index, 1);
}
}
/**
* Checks if the group is collapsed. If so, return the name of the collapsed group template.
*
* @function _collapsedCheck
* @private
* @param {String} defaultValue the default tempalte name
* @return {String} template name
*/
function _collapsedCheck(defaultValue) {
return collapsed ? 'collapsed' : defaultValue;
}
}
get sortGroup() {
return Geo.Layer.SORT_GROUPS_[Geo.Layer.Types.ESRI_DYNAMIC];
}
get isRefreshing() {
return this.state === Geo.Layer.States.LOADING;
}
get name() {
return this._name || this._rootProxyWrapper.name;
}
get visibility() {
return this._observableEntries.some(entry => entry.visibility);
}
set visibility(value) {
if (this.isControlSystemDisabled('visibility')) {
return;
}
if (value) {
// Toggle each child entry's visibility on
this._activeEntries.forEach(entry => {
// If a child is a group propogate the toggled value
// This allows show all to effect all child groups
if (entry.blockType === 'group') {
entry._toggled = this._toggled;
}
if (entry.oldVisibility !== undefined && this._toggled) {
// Don't set the visibility if it doesn't change
// Prevents overwriting a past saved visibility state
if (entry.visibility !== entry.oldVisibility) {
entry.visibility = entry.oldVisibility;
}
} else {
// If there's no saved state or pressing show all set the visibility to true
entry.visibility = true;
}
});
this._toggled = false;
} else {
this._activeEntries.forEach(entry => {
entry.oldVisibility = entry.visibility;
if (entry.visibility) {
// Don't set the visibility if it doesn't change
// Prevents overwriting a past saved visibility state
entry.visibility = false;
}
});
this._toggled = true;
}
updateLegendElementVisibility(this);
return this;
}
/**
* @return {Boolean} `true` is all observed legend blocks are set to be queriable; `false` otherwise;
*/
get query() {
return this._observableEntries.some(entry => entry.query);
}
/**
* @param {Boolean} value zxxzcs
* @return {LegendGroup} this for chaining
*/
set query(value) {
if (this.isControlSystemDisabled('query')) {
return;
}
this._activeEntries.forEach(entry => (entry.query = value));
updateLegendElementQueryable(this);
return this;
}
/**
* @return {Number} returns opacity of the group;
* it's equal to the child opacity values if they are the same or 0.5 if not;
*/
get opacity() {
const defaultValue = 0.5;
const entries = this._observableEntries;
let isAllSame = this.sameOpacity;
let value = entries.length > 0 ? entries[0].opacity : undefined;
return isAllSame ? value : defaultValue;
}
/**
* Checks if all children have the same opacity
*
* @returns {Boolean} 'true' is all children have the same opacity; 'false otherwise;
*/
get sameOpacity() {
const entries = this._observableEntries;
let value;
if (entries.length > 0) {
value = entries[0].opacity;
// Check that they have the same opacity and if it has all the same opacity if it's a group
this._sameOpacity = entries.every(
entry =>
entry.opacity === value && (entry._sameOpacity === undefined || entry._sameOpacity === true)
);
}
return this._sameOpacity;
}
set opacity(value) {
if (this.isControlSystemDisabled('opacity')) {
return;
}
this._activeEntries.forEach(entry => (entry.opacity = value));
updateLegendElementOpacity(this);
return this;
}
get expanded() {
return this._expanded;
}
set expanded(value = !this.expanded) {
this._expanded = value;
$rootScope.$applyAsync();
}
get entries() {
return this._entries;
}
// active entries are legend blocks that directly or indirectly control map data, namely legend nodes, groups, and sets
// active entries do not include hidden nodes
get _activeEntries() {
return this.entries.filter(
entry =>
entry.blockType === TYPES.SET ||
entry.blockType === TYPES.GROUP ||
(entry.blockType === TYPES.NODE && !entry.hidden)
);
}
get _observableEntries() {
// observable entries are a subset of active entries which are not controlled blocks and are rendered in the UI
// when calculating group opacity or visibility, exclude controlled layers as they might have locked opacity specified in the config
return this._activeEntries.filter(entry => !entry.controlled);
}
addEntry(entry, position = this._entries.length) {
this._entries.splice(position, 0, entry);
entry.parent = this;
return this;
}
removeEntry(entry) {
const index = this._entries.indexOf(entry);
if (index !== -1) {
this._entries.splice(index, 1);
}
return index;
}
walk(...args) {
return this._walk(...args);
}
get isVisibleOnExport() {
return (
!this.hidden &&
this.opacity !== 0 &&
(this.state === Geo.Layer.States.REFRESH || this.state === Geo.Layer.States.LOADED) &&
this.entries.some(entry => entry.isVisibleOnExport)
);
}
} |
JavaScript | class CodeEditorTemplate extends Template {
/**
* Takes no parameters, adjust using the controller
*/
constructor() {
const container = <DocumentFragment/>;
super(container);
/** @type {CodeEditorViewController} */
this.controller = null;
return (async () => {
this.controller = await new CodeEditorViewController(container);
return this;
})();
}
/** @override */
didLoad() {
super.didLoad();
this.controller._editor.refresh();
}
/** @override */
async didInitialLoad() {
this.controller.setThemeType(CodeEditorThemeType.fromTheme(Theme.current));
}
// MARK: - InputInterface
/** @override */
observeValue() {
return this.controller.observeValue();
}
/** @override */
get userInput() { return null; }
} |
JavaScript | class Facet extends React.Component {
constructor() {
super();
// Set initial React commponent state.
this.state = {
initialState: true,
unsanitizedSearchTerm: '',
searchTerm: '',
};
// Bind `this` to non-React methods.
this.handleSearch = this.handleSearch.bind(this);
}
componentDidMount() {
this.setState({ initialState: false });
}
handleSearch(event) {
// Unsanitized search term entered by user for display
this.setState({ unsanitizedSearchTerm: event.target.value });
// Search term entered by the user
const filterVal = String(sanitizedString(event.target.value));
this.setState({ searchTerm: filterVal });
}
render() {
const { facet, filters, assayTerms, modifyFacetsFlag } = this.props;
const title = facet.title;
const field = facet.field;
const total = facet.total;
const typeahead = facet.type === 'typeahead';
// Filter facet terms to create list of those matching the search term entered by the user
// Note: this applies only to Typeahead facets
let filteredList = null;
if (typeahead && this.state.searchTerm !== '') {
filteredList = facet.terms.filter(
(term) => {
if (term.doc_count > 0) {
const termKey = sanitizedString(term.key);
if (termKey.match(this.state.searchTerm)) {
return term;
}
return null;
}
return null;
}
);
}
// Make a list of terms for this facet that should appear, by filtering out terms that
// shouldn't. Any terms with a zero doc_count get filtered out, unless the term appears in
// the search result filter list.
const unsortedTerms = facet.terms.filter((term) => {
if (term.key) {
// See if the facet term also exists in the search result filters (i.e. the term
// exists in the URL query string).
const found = filters.some(filter => ((filter.field === facet.field || filter.field === term.linkKey) && filter.term === term.key));
// If the term wasn't in the filters list, allow its display only if it has a non-
// zero doc_count. If the term *does* exist in the filters list, display it
// regardless of its doc_count.
return found || term.doc_count > 0;
}
// The term exists, but without a key, so don't allow its display.'
return false;
});
// Sort numerical terms by value not by frequency
// This should ultimately be accomplished in the back end, but the front end fix is much simpler so we are starting with that
// We have to check the full list for now (until schema change) because some lists contain both numerical and string terms ('Encyclopedia version' under Annotations) and we do not want to sort those by value
/* eslint-disable no-restricted-globals */
const numericalTest = a => !isNaN(a.key);
// For date facets, sort by date
let terms = [];
if (field.match('date')) {
terms = _.sortBy(unsortedTerms, obj => moment(obj.key, 'YYYY-MM-DD').toISOString()).reverse();
} else if (field.match('month')) {
terms = _.sortBy(unsortedTerms, obj => moment(obj.key, 'MMMM, YYYY').toISOString()).reverse();
} else if (field.match('year')) {
terms = _.sortBy(unsortedTerms, obj => moment(obj.key, 'YYYY').toISOString()).reverse();
// For straightforward numerical facets, just sort by value
} else if (unsortedTerms.every(numericalTest)) {
terms = _.sortBy(unsortedTerms, obj => obj.key);
} else {
terms = unsortedTerms;
}
const moreTerms = terms.slice(5);
const TermComponent = field === 'type' ? TypeTerm : Term;
const selectedTermCount = countSelectedTerms(moreTerms, facet, filters);
const canDeselect = (!facet.restrictions || selectedTermCount >= 2);
const statusFacet = field === 'status' || field === 'lot_reviews.status';
// Number of terms to show, the rest will be viewable on scroll
const displayedTermsCount = 5;
// Audit facet titles get mapped to a corresponding icon.
let titleComponent = title;
if (field.substr(0, 6) === 'audit.') {
// Get the human-readable part of the audit facet title.
const titleParts = title.split(': ');
// Get the non-human-readable part so we can generate a corresponding CSS class name.
const fieldParts = field.match(/^audit.(.+).category$/i);
if (fieldParts && fieldParts.length === 2 && titleParts) {
// We got something that looks like an audit title. Generate a CSS class name for
// the corresponding audit icon, and generate the title.
const iconClass = `icon audit-activeicon-${fieldParts[1].toLowerCase()}`;
titleComponent = <span>{titleParts[0]}: <i className={iconClass} /></span>;
} else {
// Something about the audit facet title doesn't match expectations, so just
// display the given non-human-readable audit title.
titleComponent = <span>{title}</span>;
}
}
// if ((terms.length && terms.some(term => term.doc_count))) {
if ((terms.length && terms.some(term => term.doc_count)) || (field.charAt(field.length - 1) === '!')) {
return (
<div className={`facet facet${facet.field.replace('/ /g', '')}`}>
{ ((field === 'annotation_type' || field === 'assay_term_name') && modifyFacetsFlag) ?
<React.Fragment>
{ (field === 'assay_term_name' || assayTerms === false) ?
<React.Fragment>
<h5 className="extra-padding-header">{titleComponent}</h5>
<FacetLabel label={field} />
</React.Fragment>
:
<FacetLabel label={field} />
}
</React.Fragment>
:
<h5>{titleComponent}</h5>
}
<ul className={`facet-list nav${statusFacet ? ' facet-status' : ''}`}>
{/* Display searchbar for typeahead facets if there are more than 5 terms */}
{typeahead ?
<div className="typeahead-entry" role="search">
<i className="icon icon-search" />
<div className="searchform">
<input type="search" aria-label={`search to filter list of terms for facet ${titleComponent}`} placeholder="Search" value={this.state.unsanitizedSearchTerm} onChange={this.handleSearch} name={`search${titleComponent.replace(/\s+/g, '')}`} />
</div>
</div>
: null}
{/* If user has searched using the typeahead, we will not display the full set of facet terms, just those matching the search */}
{(filteredList !== null) ?
<React.Fragment>
{/* Display error message if there is a search but no results found */}
{(filteredList.length === 0) ?
<div className="searcherror">
Try a different search term for results.
</div>
:
<div className="terms-block">
{/* List of results does not overflow top on initialization */}
<div className="top-shading hide-shading" />
{/* List of filtered terms */}
<div className={`term-list search${titleComponent.replace(/\s+/g, '')}`} onScroll={shadeOverflowOnScroll}>
{filteredList.map(term =>
<TermComponent {...this.props} key={term.key} term={term} filters={filters} total={total} canDeselect={canDeselect} statusFacet={statusFacet} />
)}
</div>
{/* Only show bottom shading when list of results overflows */}
<div className={`shading ${(filteredList.length < displayedTermsCount) ? 'hide-shading' : ''}`} />
</div>
}
</React.Fragment>
:
<React.Fragment>
{/* If the user has not searched, we will display the full set of facet terms */}
{(((terms.length > 0) && terms.some(term => term.doc_count)) || (field.charAt(field.length - 1) === '!')) ?
<div className="terms-block">
{/* List of results does not overflow top on initialization */}
<div className="top-shading hide-shading" />
{/* List of terms */}
<div className={`term-list${typeahead ? ` search${titleComponent.replace(/\s+/g, '')}` : ''}`} onScroll={shadeOverflowOnScroll}>
{/* To prevent long render time, wait for component to mount to display all typeahead terms and display 50 terms in the interim. */}
{(this.state.initialState && typeahead) ?
<React.Fragment>
{terms.slice(0, 50).map(term =>
<TermComponent {...this.props} key={term.key} term={term} filters={filters} total={total} canDeselect={canDeselect} statusFacet={statusFacet} />
)}
</React.Fragment>
:
<React.Fragment>
{terms.map(term =>
<TermComponent {...this.props} key={term.key} term={term} filters={filters} total={total} canDeselect={canDeselect} statusFacet={statusFacet} />
)}
</React.Fragment>
}
</div>
{/* Only show bottom shading when list of results overflows */}
<div className={`shading ${(terms.length < displayedTermsCount) ? 'hide-shading' : ''}`} />
</div>
: null}
</React.Fragment>
}
</ul>
</div>
);
}
// Facet had all zero terms and was not a "not" facet.
return null;
}
} |
JavaScript | class TextFilter extends React.Component {
constructor() {
super();
// Bind `this` to non-React component methods.
this.performSearch = this.performSearch.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
}
/**
* Keydown event handler
*
* @param {object} e Key down event
* @memberof TextFilter
* @private
*/
onKeyDown(e) {
if (e.keyCode === 13) {
this.performSearch(e);
e.preventDefault();
}
}
getValue() {
const filter = this.props.filters.filter(f => f.field === 'searchTerm');
return filter.length ? filter[0].term : '';
}
/**
* Makes call to do search
*
* @param {object} e Event
* @memberof TextFilter
* @private
*/
performSearch(e) {
let searchStr = this.props.searchBase.replace(/&?searchTerm=[^&]*/, '');
const value = e.target.value;
if (value) {
searchStr += `searchTerm=${e.target.value}`;
} else {
searchStr = searchStr.substring(0, searchStr.length - 1);
}
this.props.onChange(searchStr);
}
shouldUpdateComponent(nextProps) {
return (this.getValue(this.props) !== this.getValue(nextProps));
}
/**
* Provides view for @see {@link TextFilter}
*
* @returns {object} @see {@link TextFilter} React's JSX object
* @memberof TextFilter
* @public
*/
render() {
return (
<div className="facet">
<input
type="search"
className="form-control search-query"
placeholder="Enter search term(s)"
defaultValue={this.getValue(this.props)}
onKeyDown={this.onKeyDown}
data-test="filter-search-box"
/>
</div>
);
}
} |
JavaScript | class UcdlibBrandingBar extends Mixin(LitElement)
.with(NavElement) {
static get properties() {
return {
figure: {type: String},
siteName: {type: String, attribute: "site-name"},
slogan: {type: String},
siteUrl: {type: String, attribute: "site-url"},
navItems: {type: Array}
};
}
static get styles() {
return styles();
}
constructor() {
super();
this.render = render.bind(this);
this.mutationObserver = new MutationObserverController(
this,
{childList: true, characterData: true, attributes: true}
);
this.figure = "book";
this.siteName = "UC Davis Library";
this.slogan = "";
this.siteUrl = "/";
this.navItems = [];
}
/**
* @method willUpdate
* @description Lit lifecycle method called before an update
* @private
* @param {Map} props - Properties that have changed
*/
willUpdate(props){
if ( props.has("figure") && props.get("figure") !== undefined ){
const allowedKeywords = ['book', 'logo'];
if ( !allowedKeywords.includes(props.get('figure')) ){
console.warn(`${props.get('figure')} is not a recognized "figure" keyword.
Allowed values: ${JSON.stringify(allowedKeywords)}
`);
this.figure = allowedKeywords[0];
}
}
}
/**
* @method _renderFigure
* @description Renders an svg logo
* @private
* @returns {TemplateResult}
*/
_renderFigure(){
if ( this.figure === 'logo') return logo;
if ( this.figure === 'book' ) return bookLogo;
return svg``;
}
/**
* @method _onChildListMutation
* @private
* @description Fires when light dom child list changes. Called by MutationObserverController.
* Sets the 'navItems' property.
*/
_onChildListMutation(){
let navItems = this.parseNavChildren();
if ( navItems.length ) this.navItems = navItems;
}
} |
JavaScript | class SetGeometryCommand extends Command {
constructor( editor, object, newGeometry ) {
super( editor );
this.type = 'SetGeometryCommand';
this.name = 'Set Geometry';
this.updatable = true;
this.object = object;
this.oldGeometry = ( object !== undefined ) ? object.geometry : undefined;
this.newGeometry = newGeometry;
}
execute() {
this.object.geometry.dispose();
this.object.geometry = this.newGeometry;
this.object.geometry.computeBoundingSphere();
this.editor.signals.geometryChanged.dispatch( this.object );
this.editor.signals.sceneGraphChanged.dispatch();
}
undo() {
this.object.geometry.dispose();
this.object.geometry = this.oldGeometry;
this.object.geometry.computeBoundingSphere();
this.editor.signals.geometryChanged.dispatch( this.object );
this.editor.signals.sceneGraphChanged.dispatch();
}
update( cmd ) {
this.newGeometry = cmd.newGeometry;
}
toJSON() {
const output = super.toJSON( this );
output.objectUuid = this.object.uuid;
output.oldGeometry = this.object.geometry.toJSON();
output.newGeometry = this.newGeometry.toJSON();
return output;
}
fromJSON( json ) {
super.fromJSON( json );
this.object = this.editor.objectByUuid( json.objectUuid );
this.oldGeometry = parseGeometry( json.oldGeometry );
this.newGeometry = parseGeometry( json.newGeometry );
function parseGeometry( data ) {
const loader = new ObjectLoader();
return loader.parseGeometries( [ data ] )[ data.uuid ];
}
}
} |
JavaScript | class VecAny extends AbstractArray {
/**
* @description Returns the base runtime type name for this instance
*/
toRawType() {
// FIXME This is basically an any type, cannot instantiate via createType
return 'Vec<Codec>';
}
} |
JavaScript | class ExpandableListItem extends Component {
componentWillReceiveProps(nextProps) {
if (nextProps.selected && nextProps.scrollToSelected) {
// @material-ui/core encourages ReactDOM until React find better way
// https://@material-ui/core.com/getting-started/frequently-asked-questions/#how-can-i-access-the-dom-element-
ReactDOM.findDOMNode(this).scrollIntoView(nextProps.scrollOptions || { behavior: 'smooth', block: 'center' })
}
}
render() {
const {
classes,
details,
selected,
summary,
ExpansionPanelDetailsProps,
ExpansionPanelDetailsTypographyProps,
ExpansionPanelMoreIconProps,
ExpansionPanelProps,
ExpansionPanelSummaryProps,
ExpansionPanelSummaryTypographyProps,
SelectedExpansionPanelProps,
} = this.props;
const rootProps = selected
? { ...ExpansionPanelProps, ...SelectedExpansionPanelProps }
: ExpansionPanelProps;
return (
<ExpansionPanel {...rootProps} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon {...ExpansionPanelMoreIconProps} />}
{...ExpansionPanelSummaryProps}
>
<Typography
classes={{
root: classes.summaryText,
}}
gutterBottom
variant="subtitle1"
{...ExpansionPanelSummaryTypographyProps}
>
{summary}
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails {...ExpansionPanelDetailsProps}>
<Typography
classes={{
root: classes.detailsText,
}}
gutterBottom
component="div"
{...ExpansionPanelDetailsTypographyProps}
>
{details}
</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
)
}
} |
JavaScript | class WorldAndScenePoint {
/**
* This class allows for easy conversion between Three.js scene coordinates and Minecraft world coordinates.
* @param {THREE.Vector3 | object} point
* @param {boolean} isWorldPoint
*/
constructor(point, isWorldPoint) {
this.voxelSideLength = 50;
if (isWorldPoint) {
this.worldPoint = new THREE.Vector3(point.x, point.y, point.z);
this.scenePoint = new THREE.Vector3(
point.x * this.voxelSideLength,
point.y * this.voxelSideLength,
point.z * this.voxelSideLength
);
}
else {
this.scenePoint = new THREE.Vector3(point.x, point.y, point.z);
this.worldPoint = new THREE.Vector3(
Math.round(point.x / this.voxelSideLength),
Math.round(point.y / this.voxelSideLength),
Math.round(point.z / this.voxelSideLength)
);
}
}
/**
* The world point contains the coordinates of something in the Minecraft world.
* @returns {THREE.Vector3}
*/
world() {
return this.worldPoint;
}
/**
* The scene point contains coordinates used by three.js to render meshes.
* @returns {THREE.Vector3}
*/
scene() {
return this.scenePoint;
}
} |
JavaScript | class ToolRunner extends events.EventEmitter {
constructor(toolPath, args, options) {
super();
if (!toolPath) {
throw new Error("Parameter 'toolPath' cannot be null or empty.");
}
this.toolPath = toolPath;
this.args = args || [];
this.options = options || {};
}
_debug(message) {
if (this.options.listeners && this.options.listeners.debug) {
this.options.listeners.debug(message);
}
}
_getCommandString(options, noPrefix) {
const toolPath = this._getSpawnFileName();
const args = this._getSpawnArgs(options);
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
if (IS_WINDOWS) {
// Windows + cmd file
if (this._isCmdFile()) {
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows + verbatim
else if (options.windowsVerbatimArguments) {
cmd += `"${toolPath}"`;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows (regular)
else {
cmd += this._windowsQuoteCmdArg(toolPath);
for (const a of args) {
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
}
}
}
else {
// OSX/Linux - this can likely be improved with some form of quoting.
// creating processes on Unix is fundamentally different than Windows.
// on Unix, execvp() takes an arg array.
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
return cmd;
}
_processLineBuffer(data, strBuffer, onLine) {
try {
let s = strBuffer + data.toString();
let n = s.indexOf(os.EOL);
while (n > -1) {
const line = s.substring(0, n);
onLine(line);
// the rest of the string ...
s = s.substring(n + os.EOL.length);
n = s.indexOf(os.EOL);
}
strBuffer = s;
}
catch (err) {
// streaming lines to console is best effort. Don't fail a build.
this._debug(`error processing line. Failed with error ${err}`);
}
}
_getSpawnFileName() {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
return process.env['COMSPEC'] || 'cmd.exe';
}
}
return this.toolPath;
}
_getSpawnArgs(options) {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
for (const a of this.args) {
argline += ' ';
argline += options.windowsVerbatimArguments
? a
: this._windowsQuoteCmdArg(a);
}
argline += '"';
return [argline];
}
}
return this.args;
}
_endsWith(str, end) {
return str.endsWith(end);
}
_isCmdFile() {
const upperToolPath = this.toolPath.toUpperCase();
return (this._endsWith(upperToolPath, '.CMD') ||
this._endsWith(upperToolPath, '.BAT'));
}
_windowsQuoteCmdArg(arg) {
// for .exe, apply the normal quoting rules that libuv applies
if (!this._isCmdFile()) {
return this._uvQuoteCmdArg(arg);
}
// otherwise apply quoting rules specific to the cmd.exe command line parser.
// the libuv rules are generic and are not designed specifically for cmd.exe
// command line parser.
//
// for a detailed description of the cmd.exe command line parser, refer to
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
// need quotes for empty arg
if (!arg) {
return '""';
}
// determine whether the arg needs to be quoted
const cmdSpecialChars = [
' ',
'\t',
'&',
'(',
')',
'[',
']',
'{',
'}',
'^',
'=',
';',
'!',
"'",
'+',
',',
'`',
'~',
'|',
'<',
'>',
'"'
];
let needsQuotes = false;
for (const char of arg) {
if (cmdSpecialChars.some(x => x === char)) {
needsQuotes = true;
break;
}
}
// short-circuit if quotes not needed
if (!needsQuotes) {
return arg;
}
// the following quoting rules are very similar to the rules that by libuv applies.
//
// 1) wrap the string in quotes
//
// 2) double-up quotes - i.e. " => ""
//
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
// doesn't work well with a cmd.exe command line.
//
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
// for example, the command line:
// foo.exe "myarg:""my val"""
// is parsed by a .NET console app into an arg array:
// [ "myarg:\"my val\"" ]
// which is the same end result when applying libuv quoting rules. although the actual
// command line from libuv quoting rules would look like:
// foo.exe "myarg:\"my val\""
//
// 3) double-up slashes that precede a quote,
// e.g. hello \world => "hello \world"
// hello\"world => "hello\\""world"
// hello\\"world => "hello\\\\""world"
// hello world\ => "hello world\\"
//
// technically this is not required for a cmd.exe command line, or the batch argument parser.
// the reasons for including this as a .cmd quoting rule are:
//
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
//
// b) it's what we've been doing previously (by deferring to node default behavior) and we
// haven't heard any complaints about that aspect.
//
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
// by using %%.
//
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
//
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
// to an external program.
//
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
// % can be escaped within a .cmd file.
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\'; // double the slash
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '"'; // double the quote
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_uvQuoteCmdArg(arg) {
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
// is used.
//
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
// pasting copyright notice from Node within this function:
//
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
if (!arg) {
// Need double quotation for empty argument
return '""';
}
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
// No quotation needed
return arg;
}
if (!arg.includes('"') && !arg.includes('\\')) {
// No embedded double quotes or backslashes, so I can just wrap
// quote marks around the whole thing.
return `"${arg}"`;
}
// Expected input/output:
// input : hello"world
// output: "hello\"world"
// input : hello""world
// output: "hello\"\"world"
// input : hello\world
// output: hello\world
// input : hello\\world
// output: hello\\world
// input : hello\"world
// output: "hello\\\"world"
// input : hello\\"world
// output: "hello\\\\\"world"
// input : hello world\
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
// but it appears the comment is wrong, it should be "hello world\\"
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\';
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '\\';
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_cloneExecOptions(options) {
options = options || {};
const result = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: options.silent || false,
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
failOnStdErr: options.failOnStdErr || false,
ignoreReturnCode: options.ignoreReturnCode || false,
delay: options.delay || 10000
};
result.outStream = options.outStream || process.stdout;
result.errStream = options.errStream || process.stderr;
return result;
}
_getSpawnOptions(options, toolPath) {
options = options || {};
const result = {};
result.cwd = options.cwd;
result.env = options.env;
result['windowsVerbatimArguments'] =
options.windowsVerbatimArguments || this._isCmdFile();
if (options.windowsVerbatimArguments) {
result.argv0 = `"${toolPath}"`;
}
return result;
}
/**
* Exec a tool.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param tool path to tool to exec
* @param options optional exec options. See ExecOptions
* @returns number
*/
exec() {
return __awaiter(this, void 0, void 0, function* () {
// root the tool path if it is unrooted and contains relative pathing
if (!ioUtil.isRooted(this.toolPath) &&
(this.toolPath.includes('/') ||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
}
// if the tool is only a file name, then resolve it from the PATH
// otherwise verify it exists (add extension on Windows if necessary)
this.toolPath = yield io.which(this.toolPath, true);
return new Promise((resolve, reject) => {
this._debug(`exec tool: ${this.toolPath}`);
this._debug('arguments:');
for (const arg of this.args) {
this._debug(` ${arg}`);
}
const optionsNonNull = this._cloneExecOptions(this.options);
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
}
const state = new ExecState(optionsNonNull, this.toolPath);
state.on('debug', (message) => {
this._debug(message);
});
const fileName = this._getSpawnFileName();
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
const stdbuffer = '';
if (cp.stdout) {
cp.stdout.on('data', (data) => {
if (this.options.listeners && this.options.listeners.stdout) {
this.options.listeners.stdout(data);
}
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(data);
}
this._processLineBuffer(data, stdbuffer, (line) => {
if (this.options.listeners && this.options.listeners.stdline) {
this.options.listeners.stdline(line);
}
});
});
}
const errbuffer = '';
if (cp.stderr) {
cp.stderr.on('data', (data) => {
state.processStderr = true;
if (this.options.listeners && this.options.listeners.stderr) {
this.options.listeners.stderr(data);
}
if (!optionsNonNull.silent &&
optionsNonNull.errStream &&
optionsNonNull.outStream) {
const s = optionsNonNull.failOnStdErr
? optionsNonNull.errStream
: optionsNonNull.outStream;
s.write(data);
}
this._processLineBuffer(data, errbuffer, (line) => {
if (this.options.listeners && this.options.listeners.errline) {
this.options.listeners.errline(line);
}
});
});
}
cp.on('error', (err) => {
state.processError = err.message;
state.processExited = true;
state.processClosed = true;
state.CheckComplete();
});
cp.on('exit', (code) => {
state.processExitCode = code;
state.processExited = true;
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
state.CheckComplete();
});
cp.on('close', (code) => {
state.processExitCode = code;
state.processExited = true;
state.processClosed = true;
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
state.CheckComplete();
});
state.on('done', (error, exitCode) => {
if (stdbuffer.length > 0) {
this.emit('stdline', stdbuffer);
}
if (errbuffer.length > 0) {
this.emit('errline', errbuffer);
}
cp.removeAllListeners();
if (error) {
reject(error);
}
else {
resolve(exitCode);
}
});
if (this.options.input) {
if (!cp.stdin) {
throw new Error('child process missing stdin');
}
cp.stdin.end(this.options.input);
}
});
});
}
} |
JavaScript | class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
Object.defineProperty(this, "code", {
get() {
logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
this.headers = options.headers || {}; // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy;
}
} |
JavaScript | class ParseError extends core_1.RequestError {
constructor(error, response) {
const { options } = response.request;
super(`${error.message} in "${options.url.toString()}"`, error, response.request);
this.name = 'ParseError';
}
} |
JavaScript | class CancelError extends core_1.RequestError {
constructor(request) {
super('Promise was canceled', {}, request);
this.name = 'CancelError';
}
get isCanceled() {
return true;
}
} |
JavaScript | class RequestError extends Error {
constructor(message, error, self) {
var _a;
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'RequestError';
this.code = error.code;
if (self instanceof Request) {
Object.defineProperty(this, 'request', {
enumerable: false,
value: self
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: self[kResponse]
});
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self.options
});
}
else {
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self
});
}
this.timings = (_a = this.request) === null || _a === void 0 ? void 0 : _a.timings;
// Recover the original stacktrace
if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse();
// Remove duplicated traces
while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift();
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
} |
JavaScript | class MaxRedirectsError extends RequestError {
constructor(request) {
super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
this.name = 'MaxRedirectsError';
}
} |
JavaScript | class HTTPError extends RequestError {
constructor(response) {
super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);
this.name = 'HTTPError';
}
} |
JavaScript | class CacheError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'CacheError';
}
} |
JavaScript | class UploadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'UploadError';
}
} |
JavaScript | class TimeoutError extends RequestError {
constructor(error, timings, request) {
super(error.message, error, request);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
}
} |
JavaScript | class ReadError extends RequestError {
constructor(error, request) {
super(error.message, error, request);
this.name = 'ReadError';
}
} |
JavaScript | class UnsupportedProtocolError extends RequestError {
constructor(options) {
super(`Unsupported protocol "${options.url.protocol}"`, {}, options);
this.name = 'UnsupportedProtocolError';
}
} |
JavaScript | class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
} |
JavaScript | class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parse_url(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parse_url(`${input}`);
}
input = {};
} else {
parsedURL = parse_url(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has('Content-Type')) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
} |
JavaScript | class TwitchPS extends EventEmitter {
/**
* Constructor
* @constructor
* @param {Object} options - JSON object of required options
* @param {boolean} [options.reconnect=true] - True to try to reconnect, false to not
* @param {Object[]} options.init_topics - JSON Object array of initial topic
* @param {string} options.init_topics[].topic - Topic to listen too
* @param {string} options.init_topics[].token - Authentication token
* @param {boolean} [options.debug=false] - Turns debug console output on and off
* @param {string} [options.url='wss://pubsub-edge.twitch.tv'] - URL of WS to connect too. DEFAULT: Twitch {"wss://pubsub-edge.twitch.tv"}
*/
constructor(options = {
reconnect: true,
init_topics: {},
debug: false,
url: 'wss://pubsub-edge.twitch.tv'
}) {
super();
if (Object.prototype.toString.call(options.init_topics) != '[object Array]' || options.init_topics.length == 0) throw new Error('Missing initial topics');
this._recon = options.reconnect;
this._debug = options.debug;
this._url = (options.url) ? options.url : 'wss://pubsub-edge.twitch.tv';
this._init_topics = options.init_topics;
this._topics = [];
this._pending = [];
this._interval = null;
this._timeout = null;
this._tries = 0;
this._init_nonce = null;
this._ws = null;
this._connect();
}
/**
* Initial connection function -- Sets up connection, and websocket listeners
*/
_connect() {
this._ws = new WebSocket(this._url);
const self = this;
this._ws.on('open', () => {
self.addTopic(self._init_topics, true);
self.emit('connected');
});
/**
* MSG TYPES HANDLED:
* PONG - response to send type ping
* RECONNECT - sent when server restarting - reconnect to server
* MESSAGE - sent from server with message data - different topics - See topic handler section for emit details
* Types of topics:
* channel-bits-events-v1 - Bits - Sent on cheer events
* whispers - Whisper - Sent on whisper events
* video-playback - Sent on update to stream -
* stream-up - Sent when stream starts
* stream-down - Sent when stream ends
* viewcount - Sent on update to viewer count
* RESPONSE - sent from server after receiving listen message -- if error is empty string then it is good -
* Types of errors:
* ERR_BADMESSAGE
* ERR_BADAUTH
* ERR_SERVER
* ERR_BADTOPIC
*/
this._ws.on('message', (mess) => {
try {
let message = JSON.parse(mess);
// Emit 'raw' event on every message received
self.emit('raw', message);
self._sendDebug('_connect()', message);
if (message.type === 'RESPONSE') {
if (message.nonce === self._init_nonce) {
self._init_nonce = null;
if (message.error !== "") {
self._pending[message.nonce].reject(message.error);
self._handleError('MESSAGE RESPONSE - Error while listening to initial topics', message.error);
} else {
self._pending[message.nonce].resolve();
}
} else {
if (self._pending[message.nonce]) {
if (message.error !== "") {
self._pending[message.nonce].reject(message.error);
} else {
self._pending[message.nonce].resolve();
}
} else {
self._handleError('MESSAGE RESPONSE', 'Received message with unknown nonce');
}
}
} else if (message.type === 'MESSAGE') {
if (typeof message.data.message === 'string') message.data.message = JSON.parse(message.data.message);
let split = message.data.topic.split('.'),
channel = split[1];
switch (message.data.topic.substr(0, message.data.topic.indexOf('.'))) {
case 'channel-bits-events-v1':
self._onBits(message);
break;
case 'channel-subscribe-events-v1':
self._onSub(message);
break;
case 'whispers':
self._onWhisper(message);
break;
case 'video-playback':
self._onVideoPlayback(message, channel);
break;
case 'chat_moderator_actions':
self._onModeratorAction(message);
break;
}
} else if (message.type === 'RECONNECT') {
self._reconnect();
} else if (message.type === 'PONG') {
self._sendDebug('In messageType Pong', 'Received pong');
clearTimeout(self._timeout);
self._timeout = null;
} else {
self._handleError('MESSAGE RESPONSE - Unknown message type', message);
}
} catch (e) {
self._handleError('Error caught in _connect() on message', e);
}
});
this._ws.on('close', () => {
self._sendDebug('In websocket close', '');
self.emit('disconnected');
if (self._recon) {
self.emit('reconnect');
setTimeout(() => {
self._ws = new WebSocket(self._url);
}, 1000 * self._tries);
self._tries += 1;
}
clearTimeout(self._timeout);
clearInterval(self._interval);
self._timeout = null;
self._interval = null;
});
self._interval = setInterval(() => {
if (self._ws.readyState === 1) {
self._ws.send(JSON.stringify({
type: 'PING'
}));
self._sendDebug('In setInterval', 'Sent ping');
self._timeout = setTimeout(() => self._reconnect(), 15000);
}
}, 300000);
}
/**
* Reconnect function - Terminates current websocket connection and reconnects
*/
_reconnect() {
const self = this;
self._ws.terminate();
self._sendDebug('_reconnect()', 'Websocket has been terminated');
self.emit('reconnect');
setTimeout(() => {
self._connect();
}, 5000);
}
/*****
**** Message Handler Functions
****/
/**
* Handles Bits Message
* @param message - {object} - Message object received from pubsub-edge
* @param message.type - {string} - Type of message - Will always be 'MESSAGE' - Handled by _connect()
* @param message.data - {JSON} - JSON wrapper of topic/message fields
* @param message.data.topic - {string} - Topic that message pertains too - Will always be 'channel-bits-events-v1.<CHANNEL_ID>' - Handled by _connect()
* @param message.data.message - {JSON} - Parsed into JSON in _connect() - Originally received as string from Twitch
* @emits bits - {event} -
* JSON object -
* bits_used - {integer} - Number of bits used
* channel_id - {string} - User ID of the channel on which bits were used
* channel_name - {string} - Name of the channel on which bits were used
* chat_message - {string} - Chat message sent with the cheer
* context - {string} - Event type associated with this use of bits
* message_id - {string} - Message ID
* message_type - {string} - Message type
* time - {string} - Time when the bits were used. RFC 3339 format
* total_bits_used - {integer} - All-time total number of bits used on this channel by the specified user
* user_id - {string} - User ID of the person who used the bits
* user_name - {string} - Login name of the person who used the bits
* version - {string} - Message version
*/
_onBits(message) {
// TODO ADD VERSION CHECK/EMIT
this.emit('bits', {
"bits_used": message.data.message.data.bits_used,
"channel_id": message.data.message.data.channel_id,
"channel_name": message.data.message.data.channel_name,
"chat_message": message.data.message.data.chat_message,
"context": message.data.message.data.context,
"message_id": message.data.message.data.message_id,
"message_type": message.data.message.data.message_type,
"time": message.data.message.data.time,
"total_bits_used": message.data.message.data.total_bits_used,
"user_id": message.data.message.data.user_id,
"user_name": message.data.message.data.user_name,
"version": message.data.message.data.version
});
}
/**
* Handles Subscription Message
* @param message - {object} - Message object received from pubsub-edge
* @param message.type - {string} - Type of message - Will always be 'MESSAGE' - Handled by _connect()
* @param message.data - {JSON} - JSON wrapper of topic/message fields
* @param message.data.topic - {string} - Topic that message pertains too - Will always be 'channel-subscribe-events-v1.<CHANNEL_ID>' - Handled by _connect()
* @param message.data.message - {JSON} - Parsed into JSON in _connect() - Originally received as string from Twitch
* @emits bits - {event} -
* JSON object -
* user_name - {string} - Username of subscriber
* display_name - {string} - Display name of subscriber
* channel_name - {string} - Name of the channel subscribed too
* user_id - {string} - UserID of subscriber
* channel_id - {string} - Channel ID of channel subscribed too
* time - {string} - Time of subscription event RFC 3339 format
* sub_plan - {string} - Type of sub plan (ie. Prime, 1000, 2000, 3000)
* sub_plan_name - {string} - Name of subscription plan
* months - {integer} - Months subscribed to channel
* cumulative_months - {integer} - Cumulative months subscribed to channel
* context - {string} - Context of sub -- (ie. sub, resub)
* sub_message - {object} - Object containing message
* sub_message.message - {string} - Message sent in chat on resub
* sub_message.emotes - {array} - Array of emotes
*/
_onSub(message) {
// TODO ADD VERSION CHECK/EMIT
this.emit('subscribe', {
"user_name": message.data.message.user_name,
"display_name": message.data.message.display_name,
"channel_name": message.data.message.channel_name,
"user_id": message.data.message.user_id,
"channel_id": message.data.message.channel_id,
"time": message.data.message.time,
"sub_plan": message.data.message.sub_plan,
"sub_plan_name": message.data.message.sub_plan_name,
"months": message.data.message.months,
"cumulative_months": message.data.message.cumulative_months,
"context": message.data.message.context,
"sub_message": {
"message": message.data.message.sub_message.message,
"emotes": message.data.message.sub_message.emotes
},
"recipient_id": message.data.message.recipient_id,
"recipient_user_name": message.data.message.recipient_user_name,
"recipient_display_name": message.data.message.recipient_display_name
});
}
/**
* Handles Whisper Message
* @param message - {object} - Message object received from pubsub-edge
* @param message.type - {string} - Type of message - Will always be 'MESSAGE' - Handled by _connect()
* @param message.data - {JSON} - JSON wrapper of topic/message fields
* @param message.data.topic - {string} - Topic that message pertains too - Will always be 'whispers.<CHANNEL_ID>' - Handled by _connect()
* @param message.data.message - {JSON} - Parsed into JSON in _connect() - Originally received as string from Twitch
* @emits whisper_sent, whisper_received - {event} -
* JSON object -
* id - {integer} - Message ID
* body - {string} - Body of message sent
* thread_id - {string} - Thread ID
* sender - {JSON} - Object containing message sender's Information
* sender.id - {integer} - User ID of sender
* sender.username - {string} - Username of sender
* sender.display_name - {string} - Display name of sender (Usually only differs in letter case)
* sender.color - {string} - Color hex-code of sender username in chat
* sender.badges - {Array} - Array of sender badges
* sender.emotes - {Array} - Array of emotes usable by sender
* recipient - {JSON} - Object containing message recipient's Information
* recipient.id - {integer} - User ID of recipient
* recipient.username - {string} - Username of recipient
* recipient.display_name - {string} - Display name of recipient(Usually only differs in letter case)
* recipient.color - {string} - Color hex-code of recipient username in chat
* recipient.badges - {Array} - Array of recipient badges
* sent_ts - {integer} - Timestamp of when message was sent
* nonce - {string} - Nonce associated with whisper message
*/
_onWhisper(message) {
if (typeof message.data.message.tags === 'string') message.data.message.tags = JSON.parse(message.data.message.tags);
if (typeof message.data.message.recipient === 'string') message.data.message.recipient = JSON.parse(message.data.message.recipient);
switch (message.data.message.type) {
case 'whisper_sent':
this.emit('whisper_sent', {
id: message.data.message.data_object.id,
body: message.data.message.data_object.body,
thread_id: message.data.message.data_object.thread_id,
sender: {
id: message.data.message.data.from_id,
username: message.data.message.data_object.tags.login,
display_name: message.data.message.data_object.tags.display_name,
color: message.data.message.data_object.tags.color,
badges: message.data.message.data_object.tags.badges,
emotes: message.data.message.data_object.tags.emotes
},
recipient: {
id: message.data.message.data_object.recipient.id,
username: message.data.message.data_object.recipient.username,
display_name: message.data.message.data_object.recipient.display_name,
color: message.data.message.data_object.recipient.color,
badges: message.data.message.data_object.recipient.badges
},
sent_ts: message.data.message.data_object.sent_ts,
nonce: message.data.message.data_object.nonce
});
break;
case 'whisper_received':
this.emit('whisper_received', {
id: message.data.message.data_object.id,
body: message.data.message.data_object.body,
thread_id: message.data.message.data_object.thread_id,
sender: {
id: message.data.message.data.from_id,
username: message.data.message.data_object.tags.login,
display_name: message.data.message.data_object.tags.display_name,
color: message.data.message.data_object.tags.color,
badges: message.data.message.data_object.tags.badges,
emotes: message.data.message.data_object.tags.emotes
},
recipient: {
id: message.data.message.data_object.recipient.id,
username: message.data.message.data_object.recipient.username,
display_name: message.data.message.data_object.recipient.display_name,
color: message.data.message.data_object.recipient.color,
badges: message.data.message.data_object.recipient.badges
},
sent_ts: message.data.message.data_object.sent_ts,
nonce: message.data.message.data_object.nonce
});
break;
case 'thread':
this.emit('thread', {
thread_id: message.data.message.data_object.thread_id
});
break;
}
}
/**
* Handles Video-Playback Message
* @param message - {object} - Message object received from pubsub-edge
* @param message.type - {string} - Type of message - Will always be 'MESSAGE' - Handled by _connect()
* @param message.data - {JSON} - JSON wrapper of topic/message fields
* @param message.data.topic - {string} - Topic that message pertains too - Will always be 'whispers.<CHANNEL_ID>' - Handled by _connect()
* @param message.data.message - {JSON} - Parsed into JSON in _connect() - Originally received as string from Twitch
* @param channel - {string} - Channel name from
* @emits stream-up, stream-down, viewcount
* stream-up -
* JSON object -
* time - {integer} - Server time. RFC 3339 format
* channel_name - {string} - Channel name
* play_delay - {string} - Delay of stream
* stream-down -
* JSON object -
* time - {integer} - Server time. RFC 3339 format
* channel_name - {string} - Channel name
* viewcount -
* JSON object -
* time - {integer} - Server time. RFC 3339 format
* channel_name - {string} - Channel name
* viewers - {integer} - Number of viewers currently watching
*/
_onVideoPlayback(message, channel) {
if (message.data.message.type === 'stream-up') {
this.emit('stream-up', {
time: message.data.message.server_time,
channel_name: channel,
play_delay: message.data.message.play_delay
});
} else if (message.data.message.type === 'stream-down') {
this.emit('stream-down', {
time: message.data.message.server_time,
channel_name: channel
});
} else if (message.data.message.type === 'viewcount') {
this.emit('viewcount', {
time: message.data.message.server_time,
channel_name: channel,
viewers: message.data.message.viewers
});
}
}
/**
* Handles Moderator Actions (Ban/Unban/Timeout/Clear)
* @param message - {object} - Message object received from pubsub-edge
* @param message.type - {string} - Type of message - Will always be 'MESSAGE' - Handled by _connect()
* @param message.data - {JSON} - JSON wrapper of topic/message fields
* @param message.data.topic - {string} - Topic that message pertains too - Will always be 'chat_moderator_actions.<USER_ID><ROOM_ID>' - Handled by _connect()
* @param message.data.message - {JSON} - Parsed into JSON in _connect() - Originally received as string from Twitch
* @emits ban, unban, timeout, clear
* ban -
* JSON object -
* target - {string} - The banee's username
* target_user_id - {string} - The banee's user ID
* created_by - {string} - The banear's username
* created_by_user_id - {string} - The banear's user ID
* reason - {string} - The reason provided by the banear - Null if no reason was given
* unban -
* JSON object -
* target - {string} - The banee's username
* target_user_id - {string} - The banee's user ID
* created_by - {string} - The banear's username
* created_by_user_id - {string} - The banear's user ID
* timeout -
* JSON object -
* target - {string} - The timeout-ee's username
* target_user_id - {string} - The timeout-ee's user ID
* created_by - {string} - The timeout-ear's username
* created_by_user_id - {string} - The timeout-ear's user ID
* duration - {string} - The timeout duration in seconds
* clear -
* JSON object -
* created_by - {string} - The username of who cleared the chat
* created_by_user_id - {string} - The user ID of who cleared the chat
*/
_onModeratorAction(message) {
switch (message.data.message.data.moderation_action) {
case 'ban':
this.emit('ban', {
target: message.data.message.data.args[0],
target_user_id: message.data.message.data.target_user_id,
created_by: message.data.message.data.created_by,
created_by_user_id: message.data.message.data.created_by_user_id,
reason: message.data.message.data.args[1] || null,
});
break;
case 'unban':
this.emit('unban', {
target: message.data.message.data.args[0],
target_user_id: message.data.message.data.target_user_id,
created_by: message.data.message.data.created_by,
created_by_user_id: message.data.message.data.created_by_user_id,
});
break;
case 'timeout':
this.emit('timeout', {
target: message.data.message.data.args[0],
target_user_id: message.data.message.data.target_user_id,
created_by: message.data.message.data.created_by,
created_by_user_id: message.data.message.data.created_by_user_id,
duration: message.data.message.data.args[1],
});
break;
case 'clear':
this.emit('clear', {
created_by: message.data.message.data.created_by,
created_by_user_id: message.data.message.data.created_by_user_id,
});
break;
default:
// Do Nothing
}
}
/***** End Message Handler Functions *****/
/*****
**** Helper Functions
****/
/**
* Handles error
* @param {string} origin - Name of what callback function error originates from
* @param {string} error - Error message to emit
*/
_handleError(orig, error) {
let err_mess = 'Error found - ' + orig + ' - ';
console.error(err_mess, error);
}
/**
* Debug
* @param {string} origin - Name of what callback function error originates from
* @param {string} mess - Status message to emit
*/
_sendDebug(origin, mess) {
if (this._debug) {
let d = new Date();
console.log('TwitchPS -- ' + d.toLocaleString() + ' -- in ' + origin + ' -- ', mess);
}
}
/**
* Wait for websocket
*/
_wait(callback) {
setTimeout(() => {
if (this._ws.readyState === 1) {
this._sendDebug('_wait()', 'Connected');
if (callback != null) {
callback();
}
return;
}
this._sendDebug('_wait()', 'Waiting for connection');
this._wait(callback);
}, 5);
}
/***** End Helper Functions *****/
/*****
**** External Functions
****/
/**
* Add new topics to listen too
* @param {Object} topics - JSON Object array of topic(s)
* @param {string} topics[].topic - Topic to listen too
* @param {string} [token=Default Token] topics[].token - Authentication token
* @param {Boolean} init - Boolean for if first topics to listen
*/
addTopic(topics, init = false) {
return new Promise((resolve, reject) => {
this._wait(() => {
for (let i = 0; i < topics.length; i += 1) {
let top = topics[i].topic;
let tok = topics[i].token;
let nonce = shortid.generate();
if (init) {
this._init_nonce = nonce;
init = false;
}
this._pending[nonce] = {
resolve: () => {
this._topics.push(top);
delete this._pending[nonce];
resolve();
},
reject: (err) => {
reject(err);
this._handleError('Rejected addTopic() promise', err);
delete this._pending[nonce];
}
};
this._ws.send(JSON.stringify({
type: 'LISTEN',
nonce,
data: {
topics: [top],
auth_token: tok
}
}));
setTimeout(() => {
if (this._pending[nonce]) {
this._pending[nonce].reject('timeout');
}
}, 10000);
}
});
});
}
/**
* Remove topic(s) from list of topics and unlisten
* @param {Object} topics - JSON object array of topics
* @param {string} topics.topic - Topic to unlisten
*
*/
removeTopic(topics) {
return new Promise((resolve, reject) => {
this._wait(() => {
for (let i = 0; i < topics.length; i += 1) {
let top = topics[i].topic;
let nonce = shortid.generate();
this._pending[nonce] = {
resolve: () => {
let removeTopic = () => {
delete this._topics[nonce];
};
topics.map(removeTopic);
delete this._pending[nonce];
resolve();
},
reject: (err) => {
reject(err);
this._handleError('Rejected removeTopic() promise', err);
delete this._pending[nonce];
}
};
this._ws.send(JSON.stringify({
type: 'UNLISTEN',
nonce,
data: {
topics: [top]
}
}));
}
});
});
}
/***** End External Functions *****/
} |
JavaScript | class SearchableGroupEditor extends Component {
constructor(props) {
super(props)
this.state = {
itemStore: Store.create(),
assignedItemStore: Store.create(),
filterText: '',
fetchErrorMsg: null,
}
}
async componentDidMount() {
try {
const availableItems = await this.props.availableItemsQuery()
this.availableItemsReceivedHandler(availableItems)
} catch (error) {
const fetchErrorMsg = createHumanErrorMessage(
error,
i18n.t('Could not load available items')
)
this.setState({ fetchErrorMsg })
}
}
availableItemsReceivedHandler = response => {
// On update we want to be able to return an array of IDs or models
const { initiallyAssignedItems, returnModelsOnUpdate } = this.props
const { itemStore, assignedItemStore } = this.state
if (returnModelsOnUpdate) {
this.modelLookup = new Map()
}
const assignedItems = asArray(initiallyAssignedItems).map(
({ id }) => id
)
const availableItems = asArray(response).map(item => {
if (returnModelsOnUpdate) {
this.modelLookup.set(item.id, item)
}
const text = item.displayName || item.name
return {
value: item.id,
text: text,
}
})
itemStore.setState(availableItems)
assignedItemStore.setState(assignedItems)
}
onAssignItems = items => {
const { assignedItemStore } = this.state
const assigned = assignedItemStore.state.concat(items)
return this.update(assigned)
}
onRemoveItems = items => {
const { assignedItemStore } = this.state
const assigned = assignedItemStore.state.filter(
item => items.indexOf(item) === -1
)
return this.update(assigned)
}
update(assignedItemIds) {
const { onChange, returnModelsOnUpdate, onBlur } = this.props
const { assignedItemStore } = this.state
const assignedItems = returnModelsOnUpdate
? assignedItemIds.map(id => this.modelLookup.get(id))
: assignedItemIds
assignedItemStore.setState(assignedItemIds)
onChange(assignedItems)
// Also call onBlur if this is available. In a redux-form the component will be 'touched' by it
onBlur && onBlur()
return Promise.resolve()
}
updateFilterText = event => {
this.setState({ filterText: event.target.value })
}
renderHeader() {
const {
availableItemsHeader,
assignedItemsHeader,
errorText,
} = this.props
const assignedStyle = errorText
? { ...styles.header, ...styles.error }
: styles.header
return (
<div style={styles.headerWrap}>
<Heading level={4} style={styles.header}>
{availableItemsHeader}
</Heading>
<div style={styles.headerSpacer} />
<Heading level={4} style={assignedStyle}>
{assignedItemsHeader}
{errorText ? (
<span style={styles.errorText}>{errorText}</span>
) : null}
</Heading>
</div>
)
}
renderSearchInput() {
return (
<TextField
fullWidth={true}
type="search"
onChange={this.updateFilterText}
value={this.state.filterText}
floatingLabelText={i18n.t('Filter')}
hintText={i18n.t('Filter available and selected items')}
style={{ marginTop: '-16px' }}
/>
)
}
renderGroupEditor() {
const {
itemStore,
assignedItemStore,
filterText,
fetchErrorMsg,
} = this.state
if (fetchErrorMsg) {
const introText = i18n.t(
'There was a problem displaying the GroupEditor'
)
return (
<ErrorMessage
introText={introText}
errorMessage={fetchErrorMsg}
/>
)
}
return (
<GroupEditor
itemStore={itemStore}
assignedItemStore={assignedItemStore}
onAssignItems={this.onAssignItems}
onRemoveItems={this.onRemoveItems}
height={250}
filterText={filterText}
/>
)
}
render() {
return (
<div style={styles.outerWrap}>
{this.renderHeader()}
{this.renderSearchInput()}
{this.renderGroupEditor()}
</div>
)
}
} |
JavaScript | class KitchenSink extends React.Component {
constructor(props) {
super(props);
this.state = { step: 0, thread: [{crop: false, source: null, angle: 0}] };
['onFileChange',
'update',
'onRedo',
'onUndo',
'onRotateLeft',
'onCropStart',
'onCropConfirm',
'onCropCancel',
'onRotateRight'].forEach((method) => {
this[method] = this[method].bind(this);
});
}
componentDidUpdate() {
console.timeEnd('State changed');
}
update(action) {
const state = this.state;
let nextThread;
let nextStep = state.thread.length;
let newState;
let newThread;
switch (action.type) {
case "SET_FILE":
nextThread = fileController(state.thread[state.step], action);
break;
case "UNDO":
nextStep = state.step - 1;
break;
case "REDO":
nextStep = state.step + 1;
break;
case "ROTATE_LEFT":
case "ROTATE_RIGHT":
case "START_CROPPING":
case "STOP_CROPPING":
case "CONFIRM_CROP":
nextThread = imageController(state.thread[state.step], action);
break;
}
if ((action.type !== "UNDO" && action.type !== "REDO") &&
(state.step > 0 && state.step < state.thread.length - 1)) {
newThread = [
...state.thread.slice(0, state.step),
nextThread
];
nextStep = newThread.length - 1;
} else {
newThread = nextThread ? [...state.thread, nextThread ] : [].concat(state.thread);
}
newState = Object.assign({}, state, {
step: nextStep,
thread: newThread
});
console.time('State changed');
this.setState(newState);
}
onFileChange(e) {
readFile(e.target.files[0], file => {
this.update({type: 'SET_FILE', file });
});
}
onUndo() {
this.update({type: 'UNDO'});
}
onRedo() {
this.update({type: 'REDO'});
}
onRotateLeft() {
this.update({type: 'ROTATE_LEFT'});
}
onRotateRight() {
this.update({type: 'ROTATE_RIGHT'});
}
onCropStart() {
this.update({type: 'START_CROPPING'});
}
onCropCancel() {
this.update({type: 'STOP_CROPPING'});
}
onCropConfirm() {
let { source } = this.state.thread[this.state.step];
let { x, y, width, height } = this.refs.canvasWrapper.cropBox;
let newImage = Transform.cropImage(source, {x, y, width, height}, { width: canvasWidth, height: canvasHeight })
.then(image => this.update({ type: 'CONFIRM_CROP', image }));
}
render() {
let current = this.state.thread[this.state.step];
let { angle, source, crop } = current;
let hasFile = source !== null;
let selectFile = () => {
this.refs.fileselect.click();
};
return (
<div style={{padding: "0 1em"}}>
<header>
<h2>React Darkroom Kitchen Sink v0.3.5</h2>
<a href="https://github.com/MattMcFarland/react-darkroom">
https://github.com/MattMcFarland/react-darkroom
</a>
<hr/>
</header>
<div style={{padding: "1em"}}>
<Darkroom>
<Toolbar>
<button onClick={selectFile} data-tipsy="Select Image" className="tipsy tipsy--s">
<span className="icon icon-image"/>
<input type="file" ref="fileselect" onChange={this.onFileChange} style={{display: 'none'}}/>
</button>
<History step={this.state.step} length={this.state.thread.length - 1}>
<button
action="back"
onClick={this.onUndo}
data-ifEmpty="disable"
data-tipsy="Undo"
className="tipsy tipsy--sw">
<span className="icon icon-undo2"/>
</button>
<button
action="forward"
onClick={this.onRedo}
data-ifEmpty="disable"
data-tipsy="Redo"
className="tipsy tipsy--sw">
<span className="icon icon-redo2"/>
</button>
</History>
<button
disabled={!hasFile}
onClick={this.onRotateLeft}
data-tipsy="Rotate Left"
className="tipsy tipsy--sw">
<span className="icon icon-undo"/>
</button>
<button
disabled={!hasFile}
onClick={this.onRotateRight}
data-tipsy="Rotate Right"
className="tipsy tipsy--sw">
<span className="icon icon-redo"/>
</button>
<CropMenu isCropping={crop}>
<button
disabled={!hasFile}
data-showOnlyWhen='croppingIsOff'
onClick={this.onCropStart}
data-tipsy="Crop"
className="tipsy tipsy--sw">
<span className="icon icon-crop"/>
</button>
<button disabled={!hasFile} showOnlyWhen='croppingIsOn' style={{color: 'cyan'}}>
<span className="icon icon-crop"/>
</button>
<button
disabled={!hasFile}
data-showOnlyWhen='croppingIsOn'
onClick={this.onCropConfirm}
style={{color: 'green'}}
data-tipsy="Confirm"
className="tipsy tipsy--sw">
<span className="icon icon-checkmark"/>
</button>
<button
disabled={!hasFile}
data-showOnlyWhen='croppingIsOn'
onClick={this.onCropCancel}
style={{color: 'red'}}
data-tipsy="Cancel"
className="tipsy tipsy--sw">
<span className="icon icon-cross"/>
</button>
</CropMenu>
<button disabled={!hasFile} onClick={this.onSave} data-tipsy="Save" className="tipsy tipsy--sw">
<span className="icon icon-floppy-disk"/>
</button>
</Toolbar>
<Canvas
ref="canvasWrapper"
crop={crop}
source={source}
angle={angle}
width={canvasWidth}
height={canvasHeight}>
<FilePicker hasFile={hasFile} onChange={this.onFileChange}/>
</Canvas>
</Darkroom>
</div>
</div>
);
}
} |
JavaScript | class ContactRequestCompoundAllOf {
/**
* Constructs a new <code>ContactRequestCompoundAllOf</code>.
* @alias module:eZmaxAPI/model/ContactRequestCompoundAllOf
* @param objContactinformations {module:eZmaxAPI/model/ContactinformationsRequestCompound}
*/
constructor(objContactinformations) {
ContactRequestCompoundAllOf.initialize(this, objContactinformations);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, objContactinformations) {
obj['objContactinformations'] = objContactinformations;
}
/**
* Constructs a <code>ContactRequestCompoundAllOf</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:eZmaxAPI/model/ContactRequestCompoundAllOf} obj Optional instance to populate.
* @return {module:eZmaxAPI/model/ContactRequestCompoundAllOf} The populated <code>ContactRequestCompoundAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ContactRequestCompoundAllOf();
if (data.hasOwnProperty('objContactinformations')) {
obj['objContactinformations'] = ContactinformationsRequestCompound.constructFromObject(data['objContactinformations']);
}
}
return obj;
}
/**
* @return {module:eZmaxAPI/model/ContactinformationsRequestCompound}
*/
getObjContactinformations() {
return this.objContactinformations;
}
/**
* @param {module:eZmaxAPI/model/ContactinformationsRequestCompound} objContactinformations
*/
setObjContactinformations(objContactinformations) {
this['objContactinformations'] = objContactinformations;
}
} |
JavaScript | class CrcContext {
/**
* Factory method for generating a CrcContext object.
*
* @static
* @param {Result} result - An ESLint Rule Result.
* @param {Object} descriptorFactory - An object that identifies ASTNodes
* with ESQuery selectors.
* @returns {CrcContext} A CrcContext object.
*/
static create (result, descriptorFactory) {
// eslint-disable-next-line security/detect-non-literal-fs-filename
const src = fs.readFileSync(path.resolve(result.filePath)).toString();
const ast = espree.parse(src, astConfig);
return {
code: new SourceCode(src, ast),
filePath: result.filePath,
descriptor: descriptorFactory.descriptor
};
}
} |
JavaScript | class FileCollection extends EventEmitter {
/**
* @constructor FileCollection
* @param {String} name The name you want to use to refer to the FileCollection.
* Be sure to use the same name in Node and browser code.
* @param {Object} options options for collection
* @param {Function} options.allowGet A function that returns `true` if a GET request for a file should be allowed
* @param {StorageAdapter[]} options.stores An array of instances of classes that extend StorageAdapter
* @param {TempFileStore} options.tempStore A temporary store to support chunked file uploads from browsers.
*/
constructor(name, options) {
super();
this.name = name;
this.storesLookup = {};
this.options = {
allowGet: () => false,
stores: [],
tempStore: null,
...(options || {})
};
const { stores } = this.options;
// Make sure at least one store has been supplied if we're not in a browser
if (isNode && (!Array.isArray(stores) || stores.length === 0)) {
throw new Error("You must specify at least one store in the stores array.");
}
stores.forEach((store) => {
// Check for duplicates
const { name: storeName } = store;
if (this.storesLookup[storeName]) {
throw new Error(`FileCollection store names must be unique. Two stores are named "${storeName}"`);
}
this.storesLookup[storeName] = store;
store.on("stored", this.getStoreSuccessHandler(storeName));
store.on("error", this.getStoreErrorHandler(storeName));
});
}
/**
* @method getStoreSuccessHandler
* @private
* @param {String} storeName name of the store
* @return {Function} A function to use as the handler for a "stored" event emitted by a StorageAdapter instance
*
* Whenever a store emits "stored" and the passed FileRecord instance is linked with this FileCollection,
* this will emit "stored" on the FileCollection instance as well.
*/
getStoreSuccessHandler(storeName) {
return (fileRecord) => {
// When a file is successfully stored into the store, we emit a "stored" event on the FileCollection only if the file belongs to this collection
if (fileRecord.collectionName === this.name) {
this.emit("stored", fileRecord, storeName);
}
};
}
/**
* @method getStoreErrorHandler
* @private
* @param {String} storeName name of the store
* @return {Function} A function to use as the handler for a "error" event emitted by a StorageAdapter instance
*
* Whenever a store emits "error" and the passed FileRecord instance is linked with this FileCollection,
* this will emit "error" on the FileCollection instance as well.
*/
getStoreErrorHandler(storeName) {
return (error, fileRecord) => {
// When a file has an error while being stored into the temp store, we emit an "error" event on the FS.Collection only if the file belongs to this collection
if (fileRecord.collectionName === this.name) {
const storeError = new Error(`Error from ${storeName} store: ${error.message}`);
this.emit("error", storeError, fileRecord, storeName);
}
};
}
/**
* @method insert
* @param {FileRecord} fileRecord fileRecord object
* @param {Object} options options for insert
* @param {Boolean} [options.raw] True to get back the raw inserted document rather than a FileRecord
* @returns {Promise<FileRecord|Object>} The inserted FileRecord or a plain object if `raw` option was `true`
*
* The actual behavior depends on how the specific class implements the _insert
* method, which will also vary in browser code vs. Node. In general, the document
* attached to the FileRecord will be inserted into a database somehow.
*
* Options are passed along to _insert
*/
async insert(fileRecord, options = {}) {
if (!(fileRecord instanceof FileRecord)) throw new Error("Argument to FileCollection.insert must be a FileRecord instance");
if (!fileRecord.collection) {
fileRecord.attachCollection(this);
} else if (fileRecord.collectionName !== this.name) {
throw new Error(`You are trying to insert FileRecord for ${fileRecord.name()} into the "${this.name}" FileCollection but it is attached to the ` +
`"${fileRecord.collectionName}" FileCollection`);
}
const insertedDoc = await this._insert(fileRecord.document, options);
if (!insertedDoc || options.raw) return insertedDoc || undefined;
return new FileRecord(insertedDoc, { collection: this });
}
/**
* @method update
* @param {String} id FileRecord ID
* @param {Object} doc Updated document, modifier, or whatever _update expects
* @param {Object} options options for update
* @param {Boolean} [options.raw] True to get back the raw updated document rather than a FileRecord
* @returns {Promise<FileRecord|Object>} The updated FileRecord or a plain object if `raw` option was `true`
*
* The actual behavior depends on how the specific class implements the _update
* method, which will also vary in browser code vs. Node. In general, the doc argument
* will be used to update what is stored in a database somehow.
*
* Options are passed along to _update
*/
async update(id, doc, options = {}) {
if (!id) throw new Error("FileCollection update requires a FileRecord ID.");
if (typeof id !== "string") throw new Error(`FileCollection update requires a single ID and updated document. Multiple not supported. Received: ${id}`);
const updatedDoc = await this._update(id, doc, options);
if (!updatedDoc || options.raw) return updatedDoc || undefined;
return new FileRecord(updatedDoc, { collection: this });
}
/**
* @method remove
* @param {String|FileRecord} id FileRecord ID or a FileRecord instance
* @param {Object} options options for remove
* @returns {Promise<Boolean>} True if removed
*
* The actual behavior depends on how the specific class implements the _remove
* method, which will also vary in browser code vs. Node. In general, the FileRecord
* with the given ID will be removed from a database somehow.
*
* In Node (whenever `stores` array was passed), the FileRecord will first
* be removed from all stores as well.
*
* Options are passed along to _remove
*/
async remove(id, options = {}) {
let fileRecord;
let ID;
if (id instanceof FileRecord) {
fileRecord = id;
ID = fileRecord._id;
} else {
fileRecord = await this.findOne(id);
ID = id;
}
// Remove all copies from all stores first. Stores won't be defined in browser code
// so this will run on Node only.
const { stores } = this.options;
if (Array.isArray(stores)) {
await Promise.all(stores.map((store) => store.remove(fileRecord)));
}
// Then remove the FileRecord from the database
return this._remove(ID, options);
}
/**
* @method findOne
* @param {Object|String} selector FileRecord ID or query selector of some sort
* @param {Object} options options for _findOne
* @param {Boolean} [options.raw] True to get back the raw document rather than a FileRecord
* @returns {Promise<FileRecord|Object>} The document or FileRecord instance
*
* The actual behavior depends on how the specific class implements the _findOne
* method, which will also vary in browser code vs. Node. In general, the FileRecord
* with the given ID will be returned.
*
* Options are passed along to _findOne
*/
async findOne(selector, options = {}) {
const doc = await this._findOne(selector, options);
if (!doc || options.raw) return doc || undefined;
return new FileRecord(doc, { collection: this });
}
/**
* @method find
* @param {Object} selector A selector understood by the specific subclass
* @param {Object} options options for _find
* @param {Boolean} [options.raw] True to get back the raw document rather than a FileRecord
* @returns {Promise<FileRecord[]|any>} An array of FileRecords, or whatever _find returns if raw option is `true`
*
* The actual behavior depends on how the specific class implements the _find
* method, which will also vary in browser code vs. Node. In general, an array of
* FileRecords that match the given selector will be returned.
*
* Options are passed along to _find
*/
async find(selector, options = {}) {
const docs = await this._find(selector, options);
if (options.raw) return docs;
return docs.map((doc) => new FileRecord(doc, { collection: this }));
}
/**
* @method findOneLocal
* @param {Object} selector A selector understood by the specific subclass
* @param {Object} options options for _find
* @returns {FileRecord} File record found
* Similar to findOne, except that it calls _findOneLocal and
* synchronously return a FileRecord or raw document.
*/
findOneLocal(selector, options = {}) {
const doc = this._findOneLocal(selector, options);
if (!doc || options.raw) return doc || undefined;
return new FileRecord(doc, { collection: this });
}
/**
* @method findLocal
* @param {Object} selector A selector understood by the specific subclass
* @param {Object} options options for _find
* @returns {FileRecord} File record found
* Similar to find, except that it calls _findLocal and
* synchronously returns an array of FileRecords or the result.
*/
findLocal(selector, options = {}) {
const docs = this._findLocal(selector, options);
if (options.raw) return docs;
return docs.map((doc) => new FileRecord(doc, { collection: this }));
}
/**
* @method shouldAllowGet
* @param {FileRecord} fileRecord file record to be found
* @param {Request} req An incoming request
* @param {String} storeName The store from which a file in this collection is being requested.
* @returns {Promise<Boolean>} Returns whatever the allowGet function passed as a constructor option
* returns, which should be `true` to allow or `false` to send a Forbidden response.
*/
async shouldAllowGet(fileRecord, req, storeName) {
return this.options.allowGet(fileRecord, req, storeName);
}
/**
* @method getStore
* @param {String} storeName name of store
* @returns {StorageAdapter} Returns a store instance from its name
*/
getStore(storeName) {
return this.storesLookup[storeName];
}
/**
* The remaining methods must be overridden when subclassing
*/
// Must insert doc into a database and then return a Promise that resolves with the inserted doc
_insert() {
throw new Error(`${this.constructor.name} does not properly override the _insert method`);
}
// Must update doc in the database and then return a Promise that resolves with the full updated doc
_update() {
throw new Error(`${this.constructor.name} does not properly override the _update method`);
}
// Must remove doc by ID from database and then return a Promise that resolves if successful
_remove() {
throw new Error(`${this.constructor.name} does not properly override the _remove method`);
}
// Must return a Promise that resolves with the file document with the given ID
_findOne() {
throw new Error(`${this.constructor.name} does not properly override the _findOne method`);
}
// Must return a Promise that resolves with an array of file documents that match the selector
_find() {
throw new Error(`${this.constructor.name} does not properly override the _find method`);
}
// May provide a function that returns the document from a local store
_findOneLocal() {
throw new Error(`${this.constructor.name} does not properly override the _findOne method`);
}
// May provide a function that returns an array of documents or cursor from a local store
_findLocal() {
throw new Error(`${this.constructor.name} does not properly override the _find method`);
}
} |
JavaScript | class CategoryProvider extends Provider {
constructor() {
super();
}
/**
* Get Categories - Retrieves all Categories
* @return {Promise} Promise of Resolution
*/
getCategories() {
let url = window.location.origin;
url = url + "/api/categories";
return this.http.get(url);
}
} |
JavaScript | class Asset extends EventEmitter {
static registerRelation(Class) {
this.relations.add(Class);
AssetGraph.registerRelation(Class);
}
/**
* Create a new Asset instance.
*
* Most of the time it's unnecessary to create asset objects
* directly. When you need to manipulate assets that already exist on
* disc or on a web server, the `loadAssets` and `populate` transforms
* are the easiest way to get the objects created. See the section about
* transforms below.
*
* Note that the Asset base class is only intended to be used to
* represent assets for which there's no specific subclass.
*
* @constructor
* @param {AssetConfig} config Configuration for instantiating an asset
* @param {AssetGraph} assetGraph Mandatory AssetGraph instance references
*/
constructor(config, assetGraph) {
super();
if (!assetGraph) {
throw new Error('2nd argument (assetGraph) is mandatory');
}
this.assetGraph = assetGraph;
if (config.id) {
this.id = config.id;
} else {
this.id = `${_.uniqueId()}`;
}
this.init(config);
}
init(config = {}) {
if (typeof config.lastKnownByteLength === 'number') {
this._lastKnownByteLength = config.lastKnownByteLength;
}
if (config.type) {
this._type = config.type;
}
if (config.rawSrc) {
this._rawSrc = config.rawSrc;
this._consumer = undefined; // SourceMap
this._updateRawSrcAndLastKnownByteLength(config.rawSrc);
} else if (config.parseTree !== undefined || config.text !== undefined) {
this._rawSrc = undefined;
}
if (typeof config.text === 'string') {
this._text = config.text;
this._consumer = undefined; // SourceMap
} else if (config.parseTree !== undefined || config.rawSrc !== undefined) {
this._text = undefined;
}
if (config.parseTree) {
this._parseTree = config.parseTree;
this._consumer = undefined; // SourceMap
} else if (config.text !== undefined || config.rawSrc !== undefined) {
this._parseTree = undefined;
}
if (config.encoding) {
this._encoding = config.encoding;
}
if (config.sourceMap) {
this._sourceMap = config.sourceMap;
}
if (config.url) {
this._url = config.url.trim();
this._updateUrlIndex(this._url);
if (!urlEndsWithSlashRegExp.test(this._url)) {
const urlObj = urlTools.parse(this._url);
// Guard against mailto: and the like
if (/^(?:https?|file):/.test(urlObj.protocol)) {
const pathname = urlTools.parse(this._url).pathname;
this._extension = pathModule.extname(pathname);
this._fileName = pathModule.basename(pathname);
this._baseName = pathModule.basename(pathname, this._extension);
}
}
extendDefined(
this,
_.omit(config, [
'rawSrc',
'parseTree',
'text',
'encoding',
'sourceMap',
'lastKnownByteLength',
'url',
'fileName',
'extension',
])
);
} else {
if (
typeof config.fileName === 'string' &&
typeof this._fileName !== 'string'
) {
this._fileName = config.fileName;
this._extension = pathModule.extname(this._fileName);
}
for (const propertyName of [
'baseName',
'extension',
'protocol',
'username',
'password',
'hostname',
'port',
]) {
if (
typeof config[propertyName] !== 'undefined' &&
typeof this[`_${propertyName}`] === 'undefined'
) {
this[`_${propertyName}`] = config[propertyName];
}
}
if (
typeof config.path !== 'undefined' &&
typeof this._path === 'undefined'
) {
this._path = config.path;
}
extendDefined(
this,
_.omit(config, [
'rawSrc',
'parseTree',
'text',
'encoding',
'sourceMap',
'lastKnownByteLength',
'url',
'fileName',
'extension',
'protocol',
'username',
'password',
'hostname',
'port',
'path',
'id',
])
);
}
}
_inferType(incomingRelation) {
if (!this._inferredType) {
let typeFromContentType;
if (Object.prototype.hasOwnProperty.call(this, 'contentType')) {
typeFromContentType = AssetGraph.lookupContentType(this.contentType);
if (typeFromContentType) {
this._inferredType = typeFromContentType;
}
}
if (
!this._inferredType ||
this._inferredType === 'Image' ||
this._inferredType === 'Font'
) {
let firstFoundTargetType;
const incomingRelations = this.incomingRelations;
if (incomingRelation) {
incomingRelations.push(incomingRelation);
}
for (const incomingRelation of incomingRelations) {
if (incomingRelation.targetType) {
firstFoundTargetType = incomingRelation.targetType;
break;
}
}
if (firstFoundTargetType) {
if (
!this._inferredType ||
AssetGraph[firstFoundTargetType].prototype[
`is${this._inferredType}`
]
) {
this._inferredType = firstFoundTargetType;
}
}
}
const typeFromExtension =
this.url &&
AssetGraph.typeByExtension[
pathModule.extname(this.url.replace(/[?#].*$/, '')).toLowerCase()
];
if (
typeFromExtension &&
// avoid upgrading from explicit Content-Type: text/plain to eg. JavaScript based on the file extension
(!this._inferredType ||
(AssetGraph[typeFromExtension].prototype[`is${this._inferredType}`] &&
typeFromContentType !== 'Text'))
) {
this._inferredType = typeFromExtension;
}
}
return this._inferredType;
}
_upgrade(Class) {
Object.setPrototypeOf(this, Class.prototype);
this.init();
// This is a smell: Maybe we should find a way to avoid populating non-upgraded Asset instances,
// but what about HttpRedirect and FileRedirect, then?
this.isPopulated = false;
this._outgoingRelations = undefined;
}
_tryUpgrade(type, incomingRelation) {
type = type || this._inferType(incomingRelation);
if (type === this.constructor.name) {
return;
}
if (
/^https?:/.test(this.protocol) &&
!Object.prototype.hasOwnProperty.call(this, 'contentType') &&
!this._type
) {
return;
}
const Class = AssetGraph[type];
if (Class) {
// Allow upgrading from Image to Svg, or from Font to Svg:
if (
Class.prototype.type !== this.type &&
Class.prototype[`is${this.type}`]
) {
this._upgrade(Class);
} else {
// Only allow upgrading from a superclass:
let superclass = Object.getPrototypeOf(Class);
while (superclass) {
if (superclass === this.constructor) {
this._upgrade(Class);
break;
}
superclass = Object.getPrototypeOf(superclass);
}
}
}
}
/**
* The assets defined or inferred type
*
* @type {String}
*/
get type() {
if (this._type) {
return this._type;
} else {
return this._inferType();
}
}
/**
* The default extension for the asset type, prepended with a dot, eg. `.html`, `.js` or `.png`
*
* @type {String}
*/
get defaultExtension() {
return (this.supportedExtensions && this.supportedExtensions[0]) || '';
}
/**
* Some asset classes support inspection and manipulation using a high
* level interface. If you modify the parse tree, you have to call
* `asset.markDirty()` so any cached serializations of the asset are
* invalidated.
*
* These are the formats you'll get:
*
* `Html` and `Xml`:
* jsdom document object (https://github.com/tmpvar/jsdom).
*
* `Css`
* CSSOM CSSStyleSheet object (https://github.com/NV/CSSOM).
*
* `JavaScript`
* estree AST object (via acorn).
*
* `Json`
* Regular JavaScript object (the result of JSON.parse on the decoded source).
*
* `CacheManifest`
* A JavaScript object with a key for each section present in the
* manifest (`CACHE`, `NETWORK`, `REMOTE`). The value is an array with
* an item for each entry in the section. Refer to the source for
* details.
*
* @member {Oject} Asset#parseTree
*/
/**
* Load the Asset
*
* Returns a promise that is resolved when the asset is loaded.
* This is Asset's only async method, as soon as it is
* loaded, everything can happen synchronously.
*
* Usually you'll want to use `transforms.loadAssets`, which will
* handle this automatically.
*
* @async
* @return {Promise<Asset>} The loaded Asset
*/
async load({ metadataOnly = false } = {}) {
try {
if (!this.isLoaded) {
if (!this.url) {
throw new Error('Asset.load: No url, cannot load');
}
const url = this.url;
const protocol = url.substr(0, url.indexOf(':')).toLowerCase();
if (protocol === 'file') {
const pathname = urlTools.fileUrlToFsPath(url);
if (metadataOnly) {
const stats = await stat(pathname);
if (stats.isDirectory()) {
this.fileRedirectTargetUrl = urlTools.fsFilePathToFileUrl(
pathname.replace(/(\/)?$/, '/index.html')
);
// Make believe it's loaded:
this._rawSrc = Buffer.from([]);
}
} else {
try {
this._rawSrc = await readFile(pathname);
this._updateRawSrcAndLastKnownByteLength(this._rawSrc);
} catch (err) {
if (err.code === 'EISDIR' || err.code === 'EINVAL') {
this.fileRedirectTargetUrl = urlTools.fsFilePathToFileUrl(
pathname.replace(/(\/)?$/, '/index.html')
);
this.isRedirect = true;
} else {
throw err;
}
}
}
} else if (protocol === 'http' || protocol === 'https') {
const { headers = {}, ...requestOptions } =
this.assetGraph.requestOptions || {};
const firstIncomingRelation = this.incomingRelations[0];
let Referer;
if (
firstIncomingRelation &&
firstIncomingRelation.from.protocol &&
firstIncomingRelation.from.protocol.startsWith('http')
) {
Referer = firstIncomingRelation.from.url;
}
const response = await this.assetGraph.teepee.request({
...requestOptions,
headers: {
...headers,
Referer,
},
method: metadataOnly ? 'HEAD' : 'GET',
url,
json: false,
});
this.statusCode = response.statusCode;
if (!metadataOnly) {
this._rawSrc = response.body;
this._updateRawSrcAndLastKnownByteLength(this._rawSrc);
}
if (
response.headers.location &&
this.statusCode >= 301 &&
this.statusCode <= 303
) {
this.location = response.headers.location;
this.isRedirect = true;
}
const contentTypeHeaderValue = response.headers['content-type'];
if (contentTypeHeaderValue) {
const matchContentType = contentTypeHeaderValue.match(
/^\s*([\w\-+.]+\/[\w-+.]+)(?:\s|;|$)/i
);
if (matchContentType) {
this.contentType = matchContentType[1].toLowerCase();
const matchCharset = contentTypeHeaderValue.match(
/;\s*charset\s*=\s*(['"]|)\s*([\w-]+)\s*\1(?:\s|;|$)/i
);
if (matchCharset) {
this._encoding = matchCharset[2].toLowerCase();
}
} else {
const err = new Error(
`Invalid Content-Type response header received: ${contentTypeHeaderValue}`
);
err.asset = this;
this.assetGraph.warn(err);
}
} else if (response.statusCode >= 200 && response.statusCode < 300) {
const err = new Error('No Content-Type response header received');
err.asset = this;
this.assetGraph.warn(err);
}
if (response.headers.etag) {
this.etag = response.headers.etag;
}
if (response.headers['cache-control']) {
this.cacheControl = response.headers['cache-control'];
}
if (response.headers['content-security-policy']) {
this.contentSecurityPolicy =
response.headers['content-security-policy'];
}
if (response.headers['content-security-policy-report-only']) {
this.contentSecurityPolicyReportOnly =
response.headers['content-security-policy-report-only'];
}
for (const headerName of ['date', 'last-modified']) {
if (response.headers[headerName]) {
this[
headerName.replace(/-([a-z])/, ($0, ch) => ch.toUpperCase())
] = new Date(response.headers[headerName]);
}
}
} else if (!knownAndUnsupportedProtocols[protocol]) {
const err = new Error(
`No resolver found for protocol: ${protocol}\n\tIf you think this protocol should exist, please contribute it here:\n\thttps://github.com/Munter/schemes#contributing`
);
if (this.assetGraph) {
this.assetGraph.warn(err);
} else {
throw err;
}
}
}
// Try to upgrade to a subclass based on the currently available type information:
this._inferredType = undefined;
let type = this._inferType();
if (
(!type || type === 'Image') &&
(this._rawSrc || typeof this._text === 'string') &&
!Object.prototype.hasOwnProperty.call(this, 'contentType')
) {
const detectedContentType = await determineFileType(
this._rawSrc || this._text
);
if (detectedContentType) {
if (detectedContentType !== 'text/plain') {
// Setting text/plain explicitly here would fool _inferType later
this.contentType = detectedContentType;
}
const typeFromDetectedContentType =
AssetGraph.typeByContentType[this.contentType];
if (typeFromDetectedContentType) {
if (
!type ||
(type === 'Image' &&
AssetGraph[typeFromDetectedContentType].prototype.isImage) ||
(type === 'Font' &&
AssetGraph[typeFromDetectedContentType].prototype.isFont)
) {
type = typeFromDetectedContentType;
}
}
}
}
this._tryUpgrade(type);
this.emit('load', this);
if (this.assetGraph) {
this.populate(true);
}
return this;
} catch (err) {
if (!err.message) {
err.message = err.code || err.name;
}
err.asset = this;
throw err;
}
}
/**
* The loaded state of the Asset
*
* @type {Boolean}
*/
get isLoaded() {
return (
this._rawSrc !== undefined ||
this._parseTree !== undefined ||
this.isRedirect ||
typeof this._text === 'string'
);
}
/**
* Get the first non-inline ancestor asset by following the
* incoming relations, ie. the first asset that has a
* url. Returns the asset itself if it's not inline, and null if
* the asset is inline, but not in an AssetGraph.
*
* @type {?Asset}
*/
get nonInlineAncestor() {
if (!this.isInline) {
return this;
}
if (
this.incomingInlineRelation &&
this.incomingInlineRelation.from !== this
) {
return this.incomingInlineRelation.from.nonInlineAncestor;
} else if (this.assetGraph) {
const incomingRelations = this.incomingRelations.filter(
(r) => r.from !== r._to
);
if (incomingRelations.length > 0) {
return incomingRelations[0].from.nonInlineAncestor;
}
}
return null;
}
get baseUrl() {
if (this.isInline) {
const nonInlineAncestor = this.nonInlineAncestor;
if (nonInlineAncestor) {
return this.nonInlineAncestor.baseUrl;
}
} else {
return this.url;
}
}
/**
* The file name extension for the asset (String). It is
* automatically kept in sync with the url, but preserved if the
* asset is inlined or set to a value that ends with a slash.
*
* If updated, the url of the asset will also be updated.
*
* The extension includes the leading dot and is thus kept in the
* same format as `require('path').extname` and the `basename`
* command line utility use.
*
* @type {String}
*/
get extension() {
if (typeof this._extension === 'string') {
return this._extension;
} else {
return this.defaultExtension;
}
}
set extension(extension) {
if (!this.isInline) {
this.url = this.url.replace(/(?:\.\w+)?([?#]|$)/, `${extension}$1`);
} else if (typeof this._fileName === 'string') {
this._fileName =
pathModule.basename(this._fileName, this._extension) + extension;
}
this._extension = extension;
}
/**
* The file name for the asset. It is automatically kept
* in sync with the url, but preserved if the asset is inlined or
* set to a value that ends with a slash.
*
* If updated, the url of the asset will also be updated.
*
* @type {String}
*/
get fileName() {
if (typeof this._fileName === 'string') {
return this._fileName;
}
}
set fileName(fileName) {
if (!this.isInline) {
this.url = this.url.replace(/[^/?#]*([?#]|$)/, `${fileName}$1`);
}
this._extension = pathModule.extname(fileName);
this._baseName = pathModule.basename(fileName, this._extension);
this._fileName = fileName;
}
/**
* The file name for the asset, excluding the extension. It is automatically
* kept in sync with the url, but preserved if the asset is inlined or
* set to a value that ends with a slash.
*
* If updated, the url of the asset will also be updated.
*
* @type {String}
*/
get baseName() {
if (typeof this._baseName === 'string') {
return this._baseName;
}
}
set baseName(baseName) {
if (!this.isInline) {
this.url = this.url.replace(
/[^/?#]*([?#]|$)/,
`${baseName + this.extension}$1`
);
}
this._fileName = baseName + this.extension;
}
/**
* The path of the asset relative to the AssetGraph root.
* Corresponds to a `new URL(...).pathName`
*
* If updated, the url of the asset will also be updated.
*
* @type {String}
*/
get path() {
const currentValue = this._path;
if (typeof currentValue !== 'undefined') {
return currentValue;
}
const url = this.url;
if (url) {
let value;
if (url.startsWith(this.assetGraph.root)) {
value = url.substr(this.assetGraph.root.length - 1);
} else {
value = new urlModule.URL(url).pathname;
}
return value.replace(/\/+[^/]+$/, '/') || '/';
}
}
set path(value) {
const url = this.url;
if (url) {
if (url.startsWith(this.assetGraph.root)) {
this.url =
this.assetGraph.root +
value.replace(/^\//, '').replace(/\/?$/, '/') +
(this.fileName || '');
} else {
const urlObj = new urlModule.URL(url);
urlObj.pathname = value.replace(/\/?$/, '/') + (this.fileName || '');
this.url = urlObj.toString();
}
} else if (this.isInline) {
throw new Error('Cannot update the path of an inline asset');
}
}
/**
* The origin of the asset, `protocol://host`
* Corresponds to `new URL(...).origin`
*
* For inlined assets, this will contain the origin
* of the first non-inlined ancestor
*
* @type {String}
*/
get origin() {
const nonInlineAncestor = this.nonInlineAncestor;
if (nonInlineAncestor) {
const urlObj = new urlModule.URL(nonInlineAncestor.url);
const slashes = nonInlineAncestor.url.startsWith(`${urlObj.protocol}//`);
if (urlObj) {
return urlObj.protocol + (slashes ? '//' : '') + (urlObj.host || '');
}
}
}
/**
* Get or set the raw source of the asset.
*
* If the internal state has been changed since the asset was
* initialized, it will automatically be reserialized when this
* property is retrieved.
*
* @example
* const htmlAsset = new AssetGraph().addAsset({
* type: 'Html',
* rawSrc: new Buffer('<html><body>Hello!</body></html>')
* });
* htmlAsset.parseTree.body.innerHTML = "Bye!";
* htmlAsset.markDirty();
* htmlAsset.rawSrc.toString(); // "<html><body>Bye!</body></html>"
*
* @type {Buffer}
*/
get rawSrc() {
if (this._rawSrc) {
return this._rawSrc;
}
const err = new Error(`Asset.rawSrc getter: Asset isn't loaded: ${this}`);
if (this.assetGraph) {
this.assetGraph.warn(err);
} else {
throw err;
}
}
set rawSrc(rawSrc) {
this.unload();
this._updateRawSrcAndLastKnownByteLength(rawSrc);
if (this.assetGraph) {
this.populate();
}
this.markDirty();
}
/**
* The `data:`-url of the asset for inlining
*
* @type {String}
*/
get dataUrl() {
if (this.isText) {
const text = this.text;
const urlEncodedText = encodeURIComponent(text).replace(/%2C/g, ',');
const isUsAscii = !/[\x80-\uffff]/.test(text);
const charsetParam = isUsAscii ? '' : ';charset=UTF-8';
if (
urlEncodedText.length + charsetParam.length <
';base64'.length + this.rawSrc.length * 1.37
) {
return `data:${this.contentType}${
isUsAscii ? '' : ';charset=UTF-8'
},${urlEncodedText}`;
}
}
// Default to base64 encoding:
return `data:${this.contentType};base64,${this.rawSrc.toString('base64')}`;
}
_updateRawSrcAndLastKnownByteLength(rawSrc) {
this._rawSrc = rawSrc;
this._lastKnownByteLength = rawSrc.length;
}
/**
* Get the last known byt length of the Asset
*
* Doesn't force a serialization of the asset if a value has previously been recorded.
*
* @type {Number}
*/
get lastKnownByteLength() {
if (this._rawSrc) {
return this._rawSrc.length;
} else if (typeof this._lastKnownByteLength === 'number') {
return this._lastKnownByteLength;
} else {
return this.rawSrc.length; // Force the rawSrc to be computed
}
}
/**
* Externalize an inlined Asset.
*
* This will create an URL from as many available URL parts as possible and
* auto generate the rest, then assign the URL to the Asset
*/
externalize() {
let urlObj;
if (typeof this._path === 'string') {
urlObj = new urlModule.URL(
this.assetGraph.root + this._path.replace(/^\//, '')
);
} else {
urlObj = new urlModule.URL(this.assetGraph.root);
}
for (const urlPropertyName of [
'username',
'password',
'hostname',
'port',
'protocol',
]) {
const value = this[`_${urlPropertyName}`];
if (typeof value !== 'undefined') {
urlObj[urlPropertyName] = value;
}
}
let baseName;
let extension;
if (typeof this._fileName === 'string') {
extension = pathModule.extname(this._fileName);
baseName = pathModule.basename(this._fileName, extension);
} else {
baseName = this.baseName || this.id;
extension = this.extension;
if (typeof extension === 'undefined') {
extension = this.defaultExtension;
}
}
if (this._query) {
urlObj.search = this._query;
}
const pathnamePrefix = urlObj.pathname.replace(/\/+[^/]+$/, '/') || '/';
urlObj.pathname = pathnamePrefix + baseName + extension;
this.url = urlObj.toString();
}
/**
* Unload the asset body. If the asset is in a graph, also
* remove the relations from the graph along with any inline
* assets.
* Also used internally to clean up before overwriting
* .rawSrc or .text.
*/
unload() {
this._unpopulate();
this._rawSrc = undefined;
this._text = undefined;
this._parseTree = undefined;
}
/**
* Get the current md5 hex of the asset.
*
* @type {String}
*/
get md5Hex() {
if (!this._md5Hex) {
this._md5Hex = crypto.createHash('md5').update(this.rawSrc).digest('hex');
}
return this._md5Hex;
}
/**
* Get or set the absolute url of the asset.
*
* The url will use the `file:` schema if loaded from disc. Will be
* falsy for inline assets.
*
* @type {String}
*/
get url() {
return this._url;
}
_updateUrlIndex(newUrl, oldUrl) {
if (this.assetGraph) {
if (oldUrl) {
if (this.assetGraph._urlIndex[oldUrl] !== this) {
throw new Error(`${oldUrl} was not in the _urlIndex`);
}
delete this.assetGraph._urlIndex[oldUrl];
}
if (newUrl) {
if (this.assetGraph._urlIndex[newUrl]) {
if (this.assetGraph._urlIndex[newUrl] !== this) {
throw new Error(
`${newUrl} already exists in the graph, cannot update url`
);
}
} else {
this.assetGraph._urlIndex[newUrl] = this;
}
}
}
}
set url(url) {
if (!this.isExternalizable) {
throw new Error(
`${this.toString()} cannot set url of non-externalizable asset`
);
}
const oldUrl = this._url;
if (url && !/^[a-z+]+:/.test(url)) {
// Non-absolute
const baseUrl =
oldUrl ||
(this.assetGraph && this.baseAsset && this.baseUrl) ||
(this.assetGraph && this.assetGraph.root);
if (!baseUrl) {
throw new Error(
`Cannot find base url for resolving new url of ${this.urlOrDescription} to non-absolute: ${url}`
);
}
if (/^\/\//.test(url)) {
// Protocol-relative
url = urlTools.resolveUrl(baseUrl, url);
} else if (/^\//.test(url)) {
// Root-relative
if (/^file:/.test(baseUrl) && /^file:/.test(this.assetGraph.root)) {
url = urlTools.resolveUrl(this.assetGraph.root, url.substr(1));
} else {
url = urlTools.resolveUrl(baseUrl, url);
}
} else {
// Relative
url = urlTools.resolveUrl(baseUrl, url);
}
}
if (url !== oldUrl) {
const existingAsset = this.assetGraph._urlIndex[url];
if (existingAsset) {
// Move the existing asset at that location out of the way
let nextSuffixToTry = 1;
let newUrlForExistingAsset;
do {
const urlObj = new URL(url);
urlObj.pathname = urlObj.pathname.replace(
/([^/]*?)(\.[^/]*)?$/,
($0, $1, $2) => `${$1}-${nextSuffixToTry}${$2 || ''}`
);
newUrlForExistingAsset = urlObj.toString();
nextSuffixToTry += 1;
} while (this.assetGraph._urlIndex[newUrlForExistingAsset]);
existingAsset.url = newUrlForExistingAsset;
}
this._url = url;
this._query = undefined;
this._updateUrlIndex(url, oldUrl);
if (url) {
this.incomingInlineRelation = undefined;
if (!urlEndsWithSlashRegExp.test(url)) {
const pathname = urlTools.parse(url).pathname;
this._extension = pathModule.extname(pathname);
this._fileName = pathModule.basename(pathname);
this._baseName = pathModule.basename(pathname, this._extension);
}
}
if (this.assetGraph) {
for (const incomingRelation of this.assetGraph.findRelations({
to: this,
})) {
incomingRelation.refreshHref();
}
for (const relation of this.externalRelations) {
relation.refreshHref();
}
}
}
}
/**
* Determine whether the asset is inline (shorthand for checking
* whether it has a url).
*
* @type {Boolean}
*/
get isInline() {
return !this.url;
}
/**
* Sets the `dirty` flag of the asset, which is the way to say
* that the asset has been manipulated since it was first loaded
* (read from disc or loaded via http). For inline assets the flag
* is set if the asset has been manipulated since it was last
* synchronized with (copied into) its containing asset.
*
* For assets that support a `text` or `parseTree` property, calling
* `markDirty()` will invalidate any cached serializations of the
* asset.
*
* @return {Asset} The asset itself (chaining-friendly)
*/
markDirty() {
this.isDirty = true;
if (typeof this._text === 'string' || this._parseTree !== undefined) {
this._rawSrc = undefined;
}
this._md5Hex = undefined;
if (this.isInline && this.assetGraph && this.incomingInlineRelation) {
// Cascade dirtiness to containing asset and re-inline
if (this.incomingInlineRelation.from !== this) {
this.incomingInlineRelation.inline();
}
}
return this;
}
_vivifyRelation(outgoingRelation) {
outgoingRelation.from = this;
if (!outgoingRelation.isRelation) {
const originalHref = outgoingRelation.href;
if (typeof originalHref === 'string') {
outgoingRelation.to = { url: originalHref };
delete outgoingRelation.href;
}
const type = outgoingRelation.type;
delete outgoingRelation.type;
outgoingRelation = new AssetGraph[type](outgoingRelation);
// Make sure that we preserve the href of relations that maintain it as a direct property
// rather than a getter/setter:
if (typeof originalHref === 'string' && !('href' in outgoingRelation)) {
outgoingRelation.href = originalHref;
}
if (outgoingRelation.to && this.assetGraph) {
if (/^#/.test(outgoingRelation.to.url)) {
// Self-reference, only fragment
// Might need refinement for eg. url(#foo) in SvgStyle in inline Svg
outgoingRelation._to = this;
} else {
// Implicitly create the target asset:
outgoingRelation._to = this.assetGraph.addAsset(
outgoingRelation.to,
outgoingRelation
);
}
}
}
return outgoingRelation;
}
/**
* Get/set the outgoing relations of the asset.
*
* @type {Relation[]}
*/
get outgoingRelations() {
if (!this._outgoingRelations) {
this._outgoingRelations = this.findOutgoingRelationsInParseTree().map(
(outgoingRelation) => this._vivifyRelation(outgoingRelation)
);
}
return this._outgoingRelations;
}
set outgoingRelations(outgoingRelations) {
this._outgoingRelations = outgoingRelations.map((outgoingRelation) =>
this._vivifyRelation(outgoingRelation)
);
}
/**
* Attaches a Relation to the Asset.
*
* The ordering of certain relation types is significant
* (`HtmlScript`, for instance), so it's important that the order
* isn't scrambled in the indices. Therefore the caller must
* explicitly specify a position at which to insert the object.
*
* @param {Relation} relation The Relation to attach to the Asset
* @param {String} [position='last'] `"first"`, `"last"`, `"before"`, or `"after"`
* @param {Relation} [adjacentRelation] The adjacent relation, mandatory if the position is `"before"` or `"after"`
*/
addRelation(relation, position, adjacentRelation) {
relation = this._vivifyRelation(relation);
position = position || 'last';
if (typeof relation.node === 'undefined' && relation.attach) {
relation.attach(position, adjacentRelation);
} else {
relation.addToOutgoingRelations(position, adjacentRelation);
relation.refreshHref();
}
// Smells funny, could be moved to Asset#_vivifyRelation?
if (relation._hrefType === 'inline' || !relation.to.url) {
relation._hrefType = undefined;
relation.inline();
}
this.assetGraph.emit('addRelation', relation); // Consider getting rid of this
return relation;
}
/**
* Remove an outgoing Relation from the Asset by reference
*
* @param {Relation} relation Outgoing Relation
* @return {Asset} The Asset itself
*/
removeRelation(relation) {
if (this._outgoingRelations) {
const outgoingRelations = this.outgoingRelations;
const i = outgoingRelations.indexOf(relation);
if (i !== -1) {
outgoingRelations.splice(i, 1);
}
}
return this;
}
/**
* The subset of outgoing Relations that point to external (non-inlined) Assets
*
* @type {Relation[]}
*/
get externalRelations() {
const externalRelations = [];
const seenAssets = new Set();
(function gatherExternalRelations(asset) {
if (asset.keepUnpopulated || seenAssets.has(asset)) {
return;
}
seenAssets.add(asset);
for (const outgoingRelation of asset.outgoingRelations) {
if (outgoingRelation.to.isInline) {
gatherExternalRelations(outgoingRelation.to);
} else {
externalRelations.push(outgoingRelation);
}
}
})(this);
return externalRelations;
}
/**
* Parse the Asset for outgoing relations and return them.
*
* @return {Relation[]} The Assets outgoing Relations
*/
findOutgoingRelationsInParseTree() {
const outgoingRelations = [];
if (
typeof this.statusCode === 'number' &&
this.statusCode >= 301 &&
this.statusCode <= 303 &&
this.location !== undefined
) {
outgoingRelations.push({
type: 'HttpRedirect',
statusCode: this.statusCode,
href: this.location,
});
} else if (this.fileRedirectTargetUrl) {
outgoingRelations.push({
type: 'FileRedirect',
href: this.fileRedirectTargetUrl,
});
}
return outgoingRelations;
}
/**
* Get/set the relations pointing to this asset
*
* **Caveat**: Setting Does not remove/detach other relations already pointing at the
* asset, but not included in the array, so it's not strictly symmetric
* with the incomingRelations getter.
*
* @type {Relation[]}
*/
get incomingRelations() {
if (!this.assetGraph) {
throw new Error(
'Asset.incomingRelations getter: Asset is not part of an AssetGraph'
);
}
if (this.incomingInlineRelation) {
return [this.incomingInlineRelation];
} else {
return this.assetGraph.findRelations({ to: this });
}
}
set incomingRelations(incomingRelations) {
for (const relation of incomingRelations) {
relation.to = this;
}
}
_updateQueryString(obj) {
const url = this.url;
const queryString = qs.stringify(obj);
if (url) {
const urlObj = new urlModule.URL(url);
if (queryString.length > 0) {
urlObj.search = `?${queryString}`;
} else {
urlObj.search = '';
}
this.url = urlObj.toString();
} else {
this._query = queryString;
}
}
/**
* The query parameters part of the Assets URL.
*
* Can be set with a `String` or `Object`, but always returns `String` in the getters
*
* @type {String}
*/
get query() {
if (!this._query && !this.isInline) {
this._query = new Proxy(
qs.parse(new urlModule.URL(this.url).search.slice(1)),
{
get(target, parameterName) {
return target[parameterName];
},
set: (target, parameterName, value) => {
target[parameterName] = String(value);
this._updateQueryString(target);
},
deleteProperty: (target, parameterName) => {
delete target[parameterName];
this._updateQueryString(target);
},
}
);
}
return this._query;
}
set query(query) {
if (typeof query === 'string') {
query = qs.parse(query.replace(/^\?/, ''));
}
this._updateQueryString(query);
}
/**
* The username part of a URL `protocol://<username>:password@hostname:port/`
*
* @member {String} Asset#username
*/
/**
* The password part of a URL `protocol://username:<password>@hostname:port/`
*
* @member {String} Asset#password
*/
/**
* The hostname part of a URL `protocol://username:password@<hostname>:port/`
*
* @member {String} Asset#hostname
*/
/**
* The port part of a URL `protocol://username:password@hostname:<port>/`
*
* @member {Number} Asset#port
*/
/**
* The protocol part of a URL `<protocol:>//username:password@hostname:port/`.
* Includes trailing `:`
*
* @member {String} Asset#protocol
*/
/**
* Go through the outgoing relations of the asset and add the ones
* that refer to assets that are already part of the
* graph. Recurses into inline assets.
*
* You shouldn't need to call this manually.
*/
populate(force = false) {
if (!this.assetGraph) {
throw new Error('Asset.populate: Asset is not part of an AssetGraph');
}
if (
(force || this.isLoaded) &&
!this.keepUnpopulated &&
!this.isPopulated
) {
// eslint-disable-next-line no-unused-expressions
this.outgoingRelations; // For the side effects
this.isPopulated = true;
}
}
_unpopulate() {
if (this._outgoingRelations) {
// Remove inline assets and outgoing relations:
if (this.assetGraph && this.isPopulated) {
const outgoingRelations = [...this._outgoingRelations];
for (const outgoingRelation of outgoingRelations) {
if (outgoingRelation.hrefType === 'inline') {
// Remove inline asset
this.assetGraph.removeAsset(outgoingRelation.to);
}
}
}
this._outgoingRelations = undefined;
}
this.isPopulated = false;
}
/**
* Replace the asset in the graph with another asset, then remove
* it from the graph.
*
* Updates the incoming relations of the old asset to point at the
* new one and preserves the url of the old asset if it's not
* inline.
*
* @param {Asset} newAsset The asset to put replace this one with.
* @return {Asset} The new asset.
*/
replaceWith(newAsset) {
const thisUrl = this.url;
if (thisUrl && (!newAsset.url || newAsset.isAsset)) {
this._updateUrlIndex(undefined, thisUrl);
this._url = undefined;
newAsset.url = thisUrl;
}
newAsset = this.assetGraph.addAsset(newAsset);
for (const incomingRelation of this.incomingRelations) {
incomingRelation.to = newAsset;
}
if (!thisUrl && newAsset.url) {
newAsset.url = null;
}
this.assetGraph.removeAsset(this);
return newAsset;
}
/**
* Clone this asset instance and add the clone to the graph if
* this instance is part of a graph. As an extra service,
* optionally update some caller-specified relations to point at
* the clone.
*
* If this instance isn't inline, a url is made up for the clone.
*
* @param {Relation[]|Relation} incomingRelations (optional) Some incoming relations that should be pointed at the clone.
* @return {Asset} The cloned asset.
*/
clone(incomingRelations) {
if (incomingRelations && !this.assetGraph) {
throw new Error(
"asset.clone(): incomingRelations not supported because asset isn't in a graph"
);
}
// TODO: Clone more metadata
const constructorOptions = {
isInitial: this.isInitial,
_toBeMinified: this._toBeMinified,
isPretty: this.isPretty,
isDirty: this.isDirty,
extension: this.extension,
lastKnownByteLength: this.lastKnownByteLength,
serializationOptions: this.serializationOptions && {
...this.serializationOptions,
},
};
if (this.type === 'JavaScript' || this.type === 'Css') {
if (this._parseTree) {
constructorOptions.parseTree = this._cloneParseTree();
if (typeof this._text === 'string') {
constructorOptions.text = this._text;
}
if (this._rawSrc) {
constructorOptions.rawSrc = this._rawSrc;
}
} else {
const sourceMap = this.sourceMap;
if (sourceMap) {
constructorOptions.sourceMap = sourceMap;
}
}
} else if (this.isText) {
// Cheaper than encoding + decoding
constructorOptions.text = this.text;
} else {
constructorOptions.rawSrc = this.rawSrc;
}
if (this._isFragment !== undefined) {
// FIXME: Belongs in the subclass
constructorOptions._isFragment = this._isFragment;
}
if (this.type === 'JavaScript') {
// FIXME: Belongs in the subclass
if (this.initialComments) {
constructorOptions.initialComments = this.initialComments;
}
constructorOptions.isRequired = this.isRequired;
}
if (!this.isInline) {
let nextSuffixToTry = 0;
const baseName = this.baseName || this.id;
const extension = this.extension || this.defaultExtension;
do {
constructorOptions.url = this.assetGraph.resolveUrl(
this.url,
baseName + (nextSuffixToTry ? `-${nextSuffixToTry}` : '') + extension
);
nextSuffixToTry += 1;
} while (this.assetGraph._urlIndex[constructorOptions.url]);
}
const clone = new this.constructor(constructorOptions, this.assetGraph);
this.assetGraph.addAsset(clone);
if (!this.isInline) {
clone.externalize(this.url);
}
if (incomingRelations) {
if (!Array.isArray(incomingRelations)) {
incomingRelations = [incomingRelations];
}
for (const incomingRelation of incomingRelations) {
if (!incomingRelation || !incomingRelation.isRelation) {
throw new Error(
`asset.clone(): Incoming relation is not a relation: ${incomingRelation.toString()}`
);
}
incomingRelation.to = clone;
}
}
return clone;
}
/**
* Get a brief text containing the type, id, and url (if not inline) of the asset.
*
* @return {String} The string, eg. "[JavaScript/141 file:///the/thing.js]"
*/
toString() {
return `[${this.type}/${this.id} ${this.urlOrDescription}]`;
}
/**
* A Human readable URL or Asset description if inline.
* Paths for `file://` URL's are kept relative to the current
* working directory for easier copy/paste if needed.
*
* @type {String}
*/
get urlOrDescription() {
function makeRelativeToCwdIfPossible(url) {
if (/^file:\/\//.test(url)) {
try {
return pathModule.relative(
process.cwd(),
urlTools.fileUrlToFsPath(url)
);
} catch (err) {
err.message = `Error while attempting to resolve working directory relative path for ${url}: ${err.message}`;
this.assetGraph.emit('warn', err);
return url;
}
} else {
return url;
}
}
return this.url
? makeRelativeToCwdIfPossible(this.url)
: `inline ${this.type}${
this.nonInlineAncestor
? ` in ${makeRelativeToCwdIfPossible(this.nonInlineAncestor.url)}`
: ''
}`;
}
} |
JavaScript | class ConnectionStatusBar extends PureComponent {
static displayName = 'ConnectionStatusBar';
static defaultProps = DEFAULT_PROPS;
static registerGlobalOnConnectionLost(callback) {
ConnectionStatusBar.onConnectionLost = callback;
}
static unregisterGlobalOnConnectionLost() {
delete ConnectionStatusBar.onConnectionLost;
}
constructor(props) {
super(props);
this.onConnectionChange = this.onConnectionChange.bind(this);
this.state = {
isConnected: true,
isCancelled: false
};
if (NetInfo) {
this.getInitialConnectionState();
} else {
console.error(`RNUILib ConnectionStatusBar component requires installing "@react-native-community/netinfo" dependency`);
}
}
generateStyles() {
this.styles = createStyles();
}
componentDidMount() {
this.unsubscribe = NetInfo?.addEventListener(this.onConnectionChange);
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
onConnectionChange(state) {
const isConnected = this.isStateConnected(state);
if (isConnected !== this.state.isConnected) {
this.setState({
isConnected,
isCancelled: false
});
if (this.props.onConnectionChange) {
this.props.onConnectionChange(isConnected, false);
}
if (!isConnected) {
setTimeout(() => {
this.getInitialConnectionState();
}, 3000);
}
if (!isConnected && _.isFunction(ConnectionStatusBar.onConnectionLost)) {
ConnectionStatusBar.onConnectionLost();
}
}
}
async getInitialConnectionState() {
const isConnected = (await NetInfo?.fetch()).isConnected;
this.setState({
isConnected
});
if (this.props.onConnectionChange) {
this.props.onConnectionChange(isConnected, true);
}
}
isStateConnected(state) {
const lowerCaseState = _.lowerCase(state.type);
const isConnected = lowerCaseState !== 'none';
return isConnected;
}
render() {
if (this.state.isConnected || this.state.isCancelled) {
return false;
}
const containerStyle = [this.styles.topContainer, this.props.useAbsolutePosition ? this.styles.absolutePosition : null];
return <View useSafeArea style={containerStyle}>
<View style={this.styles.container}>
<View style={{
flex: 1,
flexDirection: 'row'
}}>
<Text style={this.styles.text}>{this.props.label}</Text>
{this.props.allowDismiss && <TouchableOpacity style={this.styles.xContainer} onPress={() => this.setState({
isCancelled: true
})}>
<Text style={this.styles.x}>✕</Text>
</TouchableOpacity>}
</View>
</View>
</View>;
}
} |
JavaScript | class SixFlagsFiestaTexas extends SixFlagsPark {
static parkName = 'Six Flags Fiesta Texas';
static timezone = 'America/Chicago';
static location = new GeoLocation({
latitude: 29.599801,
longitude: -98.609028,
});
/**
* The identifier for the park
* @name SixFlagsFiestaTexas.parkId
* @type {String}
*/
static parkId = '8';
} |
JavaScript | class ImptTestHelper {
static get TIMEOUT() {
return TIMEOUT_MS;
}
static get TESTS_EXECUTION_FOLDER() {
return TESTS_EXECUTION_FOLDER;
}
static get ATTR_NAME() {
return 'name';
}
static get ATTR_DESCRIPTION() {
return 'description';
}
static get ATTR_ID() {
return 'id';
}
static get ATTR_TYPE() {
return 'type';
}
static get OUTPUT_MODES() {
const VALID_MODES = ['minimal', 'json', 'debug'];
// default output mode present always
let modes = [''];
config.outputModes.forEach((item) => { if (VALID_MODES.includes(item)) modes.push(`-z ${item}`) });
return modes;
}
static get KEY_ANSWER() {
return KEY_ANSWER;
}
// Initializes testing environment: creates test execution folder, sets default jasmine test timeout.
// Optionally executes 'impt auth login --local' command in the test execution folder.
// Should be called from any test suite beforeAll method.
static init(login = true) {
jasmine.DEFAULT_TIMEOUT_INTERVAL = TIMEOUT_MS;
Utils.removeDirSync(TESTS_EXECUTION_FOLDER);
FS.mkdirSync(TESTS_EXECUTION_FOLDER);
if (!config.username || !config.password) {
console.log("Error! Environment variable IMPT_USER_NAME and/or IMPT_USER_PASSWORD not set");
return;
}
if (login) {
const endpoint = config.apiEndpoint ? `--endpoint ${config.apiEndpoint}` : '';
return ImptTestHelper.runCommand(
`impt auth login --local --user ${config.username} --pwd "${config.password}" ${endpoint}`,
ImptTestHelper.checkSuccessStatus);
}
return Promise.resolve();
}
// Cleans up testing environment.
// Should be called from any test suite afterAll method.
static cleanUp() {
Shell.cd(__dirname);
Utils.removeDirSync(TESTS_EXECUTION_FOLDER);
return Promise.resolve();
}
// Executes impt command and calls outputChecker function to check the command output
static runCommand(command, outputChecker, env = {}) {
return new Promise((resolve, reject) => {
if (config.debug) {
console.log('Running command: ' + command);
}
Shell.cd(TESTS_EXECUTION_FOLDER);
ENV_VARS.forEach(function (val) {
if (env[val] === undefined) delete Shell.env[val];
else Shell.env[val] = env[val];
});
Shell.exec(`node ${__dirname}/../bin/${command}`,
{ silent: !config.debug },
(code, stdout, stderr) => {
resolve({ code: code, output: stdout.replace(/((\u001b\[2K.*\u001b\[1G)|(\u001b\[[0-9]{2}m))/g, '') });
}
);
}).then(outputChecker);
}
static runCommandInteractive(command, outputChecker, env = {}) {
return new Promise((resolve, reject) => {
if (config.debug) {
console.log('Running command: ' + command);
}
ENV_VARS.forEach(function (val) {
if (env[val] === undefined) delete Shell.env[val];
else Shell.env[val] = env[val];
});
let child = Shell.exec(`node ${__dirname}/../bin/${command}`,
{ silent: !config.debug },
(code, stdout, stderr) => {
resolve({ code: code, output: stdout.replace(/((\u001b\[2K.*\u001b\[1G)|(\u001b\[[0-9]{2}m))/g, '') });
});
child.stdin.end();
}).then(outputChecker);
}
static delayMs(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
static retrieveDeviceInfo(product, deviceGroup) {
return ImptTestHelper.createDeviceGroup(product, deviceGroup).
then(() => ImptTestHelper.runCommand(`impt device info -d ${config.devices[config.deviceidx]} -z json`, (commandOut) => {
let _json = JSON.parse(commandOut.output);
this.deviceInfo.originalName = _json.Device.name;
this.deviceInfo.deviceName = `${config.devices[config.deviceidx]}${config.suffix}`;
this.deviceInfo.deviceMac = _json.Device.mac_address;
this.deviceInfo.deviceGroup = _json.Device["Device Group"] ? _json.Device["Device Group"].id : null;
this.deviceInfo.deviceAgentId = _json.Device.agent_id;
ImptTestHelper.emptyCheck(commandOut);
})).
then(() => ImptTestHelper.runCommand(`impt device assign -d ${config.devices[config.deviceidx]} -g "${deviceGroup}" -q`, ImptTestHelper.emptyCheck)).
then(() => ImptTestHelper.runCommand(`impt device info -d ${config.devices[config.deviceidx]} -z json`, (commandOut) => {
let _json = JSON.parse(commandOut.output);
this.deviceInfo.deviceAgentId = _json.Device.agent_id;
ImptTestHelper.emptyCheck(commandOut);
})).
then(() => ImptTestHelper.runCommand(`impt device update -d ${config.devices[config.deviceidx]} --name "${this.deviceInfo.deviceName}"`, ImptTestHelper.emptyCheck));
}
static restoreDeviceInfo() {
return ImptTestHelper.runCommand(`impt device update -d ${config.devices[config.deviceidx]} --name "${this.deviceInfo.originalName ? this.deviceInfo.originalName : ''}"`, ImptTestHelper.emptyCheck).
then(() => {
if (this.deviceInfo.deviceGroup) {
return this.deviceAssign(this.deviceInfo.deviceGroup);
} else {
return Promise.resolve();
}
});
}
static getAccountAttrs(owner = 'me') {
return ImptTestHelper.runCommand(`impt account info -u ${owner} -z json`, (commandOut) => {
let json = JSON.parse(commandOut.output);
if (json.Account) {
return Promise.resolve({ email: json.Account.email, id: json.Account.id });
} else {
return Promise.reject("Failed to create device group");
}
});
}
// Checks if file exist in the TESTS_EXECUTION_FOLDER
static checkFileExist(fileName) {
expect(Shell.test('-e', `${TESTS_EXECUTION_FOLDER}/${fileName}`)).toBe(true);
}
// Checks if file not exist in the TESTS_EXECUTION_FOLDER
static checkFileNotExist(fileName) {
expect(Shell.test('-e', `${TESTS_EXECUTION_FOLDER}/${fileName}`)).not.toBe(true);
}
static checkFileEqual(fileName, fileName2) {
expect(Shell.test('-e', `${TESTS_EXECUTION_FOLDER}/${fileName}`)).toBe(true);
expect(Shell.test('-e', `${TESTS_EXECUTION_FOLDER}/${fileName2}`)).toBe(true);
let file = Shell.cat(`${TESTS_EXECUTION_FOLDER}/${fileName}`).trim();
let file2 = Shell.cat(`${TESTS_EXECUTION_FOLDER}/${fileName2}`).trim();
expect(file).toEqual(file2);
}
static checkFileContainsString(fileName, string) {
expect(Shell.test('-e', `${TESTS_EXECUTION_FOLDER}/${fileName}`)).toBe(true);
let file = Shell.cat(`${TESTS_EXECUTION_FOLDER}/${fileName}`);
expect(file).toMatch(string);
}
static projectCreate(dg, dfile = 'device.nut', afile = 'agent.nut') {
return ImptTestHelper.runCommand(`impt project link -g ${dg} -x ${dfile} -y ${afile} -q`, ImptTestHelper.emptyCheck);
}
static projectDelete() {
return ImptTestHelper.runCommand(`impt project delete -f -q`, ImptTestHelper.emptyCheck);
}
static createDeviceGroup(productName, dgName) {
let product_id = null;
return ImptTestHelper.runCommand(`impt product delete -p "${productName}" -f -b -q`, ImptTestHelper.emptyCheck).
then(() => ImptTestHelper.runCommand(`impt product create -n "${productName}"`, (commandOut) => {
product_id = ImptTestHelper.parseId(commandOut);
})).
then(() => ImptTestHelper.runCommand(`impt dg create -n "${dgName}" -p "${productName}"`, (commandOut) => {
let dg_id = ImptTestHelper.parseId(commandOut);
if (dg_id) {
return Promise.resolve({ productId: product_id, dgId: dg_id });
} else {
return Promise.reject("Failed to create device group");
}
}));
}
static productDelete(productName) {
return ImptTestHelper.runCommand(`impt product delete -p "${productName}" -f -b -q`, ImptTestHelper.emptyCheck);
}
static deviceAssign(dg) {
return ImptTestHelper.runCommand(`impt device assign -d ${config.devices[config.deviceidx]} -g ${dg} -q`, ImptTestHelper.emptyCheck);
}
static deviceRestart() {
return ImptTestHelper.runCommand(`impt device restart -d ${config.devices[config.deviceidx]}`, ImptTestHelper.emptyCheck);
}
static deviceUnassign(dg) {
return ImptTestHelper.runCommand(`impt dg unassign -g "${dg}"`, ImptTestHelper.emptyCheck);
}
// Checks success return code of the command
static checkSuccessStatus(commandOut) {
expect(commandOut.output).not.toMatch(UserInteractor.ERRORS.ACCESS_FAILED);
expect(commandOut.code).toEqual(0);
}
// Checks fail return code of the command
static checkFailStatus(commandOut) {
expect(commandOut.output).not.toMatch(UserInteractor.ERRORS.ACCESS_FAILED);
expect(commandOut.code).not.toEqual(0);
}
// Does not check command status, just check 'Access to impCentral failed or timed out' error doesn't occur.
static emptyCheck(commandOut) {
expect(commandOut.output).not.toMatch(UserInteractor.ERRORS.ACCESS_FAILED);
}
// Checks if the command output contains the specified attribute name and value
static checkAttribute(commandOut, attrName, attrValue) {
expect(commandOut.output).toMatch(new RegExp(`${attrName}"?:\\s+"?${attrValue.replace(new RegExp(/([\^\[\.\$\{\*\(\\\+\)\|\?\<\>])/g), '\\$&').replace(new RegExp(/"/g), '\\\\?"')}"?`));
}
// Checks if the command output contains the specified message for default or debug output mode
static checkOutputMessage(outputMode, commandOut, message) {
const matcher = outputMode.match('-(z|-output)\\s+(json|minimal)');
if (matcher && matcher.length) expect(true).toBeTrue;
else expect(commandOut.output).toMatch(new RegExp(message.replace(new RegExp(/[()\\]/g), `\\$&`).replace(new RegExp(/"/g), '\\\\?"')));
}
// parse ID from command output and return id value if success, otherwise return null
static parseId(commandOut) {
const idMatcher = commandOut.output.match(new RegExp(`${ImptTestHelper.ATTR_ID}"?:\\s+"?([A-Za-z0-9-]+)`));
if (idMatcher && idMatcher.length > 1) {
return idMatcher[1];
}
else return null;
}
// parse sha from command output and return sha value if success, otherwise return null
static parseSha(commandOut) {
const idMatcher = commandOut.output.match(new RegExp(`sha"?:\\s+"?([A-Za-z0-9]{64})`));
if (idMatcher && idMatcher.length > 1) {
return idMatcher[1];
}
else return null;
}
// parse loginkey id from command output and return id value if success, otherwise return null
static parseLoginkey(commandOut) {
if (commandOut.output.match('Account Limit Reached')) {
console.log('Error: No free loginkey slot');
return null;
}
const idMatcher = commandOut.output.match(new RegExp(`[0-9a-z]{16}`));
if (idMatcher && idMatcher.length > 0) {
return idMatcher[0];
}
else return null;
}
static checkDeviceStatus(device) {
return ImptTestHelper.runCommand(`impt device info --device ${device} `, (commandOut) => {
if (commandOut.output.match('not found')) console.log(`Error: Device id:${device} not found`);
if (commandOut.output.match(/device_online:\\s+false/)) console.log(`Error: Device id:${device} is offline`);
});
}
} |
JavaScript | class AnnotationsOverlay extends Component {
/**
* annotationsMatch - compares previous annotations to current to determine
* whether to add a new updateCanvas method to draw annotations
* @param {Array} currentAnnotations
* @param {Array} prevAnnotations
* @return {Boolean}
*/
static annotationsMatch(currentAnnotations, prevAnnotations) {
if (!currentAnnotations && !prevAnnotations) return true;
if (
(currentAnnotations && !prevAnnotations)
|| (!currentAnnotations && prevAnnotations)
) return false;
if (currentAnnotations.length === 0 && prevAnnotations.length === 0) return true;
if (currentAnnotations.length !== prevAnnotations.length) return false;
return currentAnnotations.every((annotation, index) => {
const newIds = annotation.resources.map(r => r.id);
const prevIds = prevAnnotations[index].resources.map(r => r.id);
if (newIds.length === 0 && prevIds.length === 0) return true;
if (newIds.length !== prevIds.length) return false;
if ((annotation.id === prevAnnotations[index].id) && (isEqual(newIds, prevIds))) {
return true;
}
return false;
});
}
/**
* @param {Object} props
*/
constructor(props) {
super(props);
this.ref = React.createRef();
this.osdCanvasOverlay = null;
// An initial value for the updateCanvas method
this.updateCanvas = () => {};
this.onUpdateViewport = this.onUpdateViewport.bind(this);
this.onCanvasClick = this.onCanvasClick.bind(this);
this.onCanvasMouseMove = debounce(this.onCanvasMouseMove.bind(this), 10);
this.onCanvasExit = this.onCanvasExit.bind(this);
}
/**
* React lifecycle event
*/
componentDidMount() {
this.initializeViewer();
}
/**
* When the tileSources change, make sure to close the OSD viewer.
* When the annotations change, reset the updateCanvas method to make sure
* they are added.
* When the viewport state changes, pan or zoom the OSD viewer as appropriate
*/
componentDidUpdate(prevProps) {
const {
drawAnnotations,
drawSearchAnnotations,
annotations, searchAnnotations,
hoveredAnnotationIds, selectedAnnotationId,
highlightAllAnnotations,
viewer,
} = this.props;
this.initializeViewer();
const annotationsUpdated = !AnnotationsOverlay.annotationsMatch(
annotations, prevProps.annotations,
);
const searchAnnotationsUpdated = !AnnotationsOverlay.annotationsMatch(
searchAnnotations, prevProps.searchAnnotations,
);
const hoveredAnnotationsUpdated = (
xor(hoveredAnnotationIds, prevProps.hoveredAnnotationIds).length > 0
);
if (this.osdCanvasOverlay && hoveredAnnotationsUpdated) {
if (hoveredAnnotationIds.length > 0) {
this.osdCanvasOverlay.canvasDiv.style.cursor = 'pointer';
} else {
this.osdCanvasOverlay.canvasDiv.style.cursor = '';
}
}
const selectedAnnotationsUpdated = selectedAnnotationId !== prevProps.selectedAnnotationId;
const redrawAnnotations = drawAnnotations !== prevProps.drawAnnotations
|| drawSearchAnnotations !== prevProps.drawSearchAnnotations
|| highlightAllAnnotations !== prevProps.highlightAllAnnotations;
if (
searchAnnotationsUpdated
|| annotationsUpdated
|| selectedAnnotationsUpdated
|| hoveredAnnotationsUpdated
|| redrawAnnotations
) {
this.updateCanvas = this.canvasUpdateCallback();
viewer.forceRedraw();
}
}
/**
*/
componentWillUnmount() {
const { viewer } = this.props;
viewer.removeHandler('canvas-click', this.onCanvasClick);
viewer.removeHandler('canvas-exit', this.onCanvasExit);
viewer.removeHandler('update-viewport', this.onUpdateViewport);
viewer.removeHandler('mouse-move', this.onCanvasMouseMove);
}
/** */
onCanvasClick(event) {
const {
canvasWorld,
} = this.props;
const { position: webPosition, eventSource: { viewport } } = event;
const point = viewport.pointFromPixel(webPosition);
const canvas = canvasWorld.canvasAtPoint(point);
if (!canvas) return;
const [
_canvasX, _canvasY, canvasWidth, canvasHeight, // eslint-disable-line no-unused-vars
] = canvasWorld.canvasToWorldCoordinates(canvas.id);
// get all the annotations that contain the click
const annos = this.annotationsAtPoint(canvas, point);
if (annos.length > 0) {
event.preventDefaultAction = true; // eslint-disable-line no-param-reassign
}
if (annos.length === 1) {
this.toggleAnnotation(annos[0].id);
} else if (annos.length > 0) {
/**
* Try to find the "right" annotation to select after a click.
*
* This is perhaps a naive method, but seems to deal with rectangles and SVG shapes:
*
* - figure out how many points around a circle are inside the annotation shape
* - if there's a shape with the fewest interior points, it's probably the one
* with the closest boundary?
* - if there's a tie, make the circle bigger and try again.
*/
const annosWithClickScore = (radius) => {
const degreesToRadians = Math.PI / 180;
return (anno) => {
let score = 0;
for (let degrees = 0; degrees < 360; degrees += 1) {
const x = Math.cos(degrees * degreesToRadians) * radius + point.x;
const y = Math.sin(degrees * degreesToRadians) * radius + point.y;
if (this.isAnnotationAtPoint(anno, canvas, { x, y })) score += 1;
}
return { anno, score };
};
};
let annosWithScore = [];
let radius = 1;
annosWithScore = sortBy(annos.map(annosWithClickScore(radius)), 'score');
while (radius < Math.max(canvasWidth, canvasHeight)
&& annosWithScore[0].score === annosWithScore[1].score) {
radius *= 2;
annosWithScore = sortBy(annos.map(annosWithClickScore(radius)), 'score');
}
this.toggleAnnotation(annosWithScore[0].anno.id);
}
}
/** */
onCanvasMouseMove(event) {
const {
annotations,
canvasWorld,
hoverAnnotation,
hoveredAnnotationIds,
searchAnnotations,
viewer,
windowId,
} = this.props;
if (annotations.length === 0 && searchAnnotations.length === 0) return;
const { position: webPosition } = event;
const point = viewer.viewport.pointFromPixel(webPosition);
const canvas = canvasWorld.canvasAtPoint(point);
if (!canvas) {
hoverAnnotation(windowId, []);
return;
}
const annos = this.annotationsAtPoint(canvas, point);
if (xor(hoveredAnnotationIds, annos.map(a => a.id)).length > 0) {
hoverAnnotation(windowId, annos.map(a => a.id));
}
}
/** If the cursor leaves the canvas, wipe out highlights */
onCanvasExit(event) {
const {
hoverAnnotation,
windowId,
} = this.props;
// a move event may be queued up by the debouncer
this.onCanvasMouseMove.cancel();
hoverAnnotation(windowId, []);
}
/**
* onUpdateViewport - fires during OpenSeadragon render method.
*/
onUpdateViewport(event) {
this.updateCanvas();
}
/** @private */
initializeViewer() {
const { viewer } = this.props;
if (!viewer) return;
if (this.osdCanvasOverlay) return;
this.osdCanvasOverlay = new OpenSeadragonCanvasOverlay(viewer, this.ref);
viewer.addHandler('canvas-click', this.onCanvasClick);
viewer.addHandler('canvas-exit', this.onCanvasExit);
viewer.addHandler('update-viewport', this.onUpdateViewport);
viewer.addHandler('mouse-move', this.onCanvasMouseMove);
this.updateCanvas = this.canvasUpdateCallback();
}
/** */
canvasUpdateCallback() {
return () => {
this.osdCanvasOverlay.clear();
this.osdCanvasOverlay.resize();
this.osdCanvasOverlay.canvasUpdate(this.renderAnnotations.bind(this));
};
}
/** @private */
isAnnotationAtPoint(resource, canvas, point) {
const {
canvasWorld,
} = this.props;
const [canvasX, canvasY] = canvasWorld.canvasToWorldCoordinates(canvas.id);
const relativeX = point.x - canvasX;
const relativeY = point.y - canvasY;
if (resource.svgSelector) {
const context = this.osdCanvasOverlay.context2d;
const { svgPaths } = new CanvasAnnotationDisplay({ resource });
return [...svgPaths].some(path => (
context.isPointInPath(new Path2D(path.attributes.d.nodeValue), relativeX, relativeY)
));
}
if (resource.fragmentSelector) {
const [x, y, w, h] = resource.fragmentSelector;
return x <= relativeX && relativeX <= (x + w)
&& y <= relativeY && relativeY <= (y + h);
}
return false;
}
/** @private */
annotationsAtPoint(canvas, point) {
const {
annotations, searchAnnotations,
} = this.props;
const lists = [...annotations, ...searchAnnotations];
const annos = flatten(lists.map(l => l.resources)).filter((resource) => {
if (canvas.id !== resource.targetId) return false;
return this.isAnnotationAtPoint(resource, canvas, point);
});
return annos;
}
/** */
toggleAnnotation(id) {
const {
selectedAnnotationId,
selectAnnotation,
deselectAnnotation,
windowId,
} = this.props;
if (selectedAnnotationId === id) {
deselectAnnotation(windowId, id);
} else {
selectAnnotation(windowId, id);
}
}
/**
* annotationsToContext - converts anontations to a canvas context
*/
annotationsToContext(annotations, palette) {
const {
highlightAllAnnotations, hoveredAnnotationIds, selectedAnnotationId, canvasWorld,
viewer,
} = this.props;
const context = this.osdCanvasOverlay.context2d;
const zoomRatio = viewer.viewport.getZoom(true) / viewer.viewport.getMaxZoom();
annotations.forEach((annotation) => {
annotation.resources.forEach((resource) => {
if (!canvasWorld.canvasIds.includes(resource.targetId)) return;
const offset = canvasWorld.offsetByCanvas(resource.targetId);
const canvasAnnotationDisplay = new CanvasAnnotationDisplay({
hovered: hoveredAnnotationIds.includes(resource.id),
offset,
palette: {
...palette,
default: {
...palette.default,
...(!highlightAllAnnotations && palette.hidden),
},
},
resource,
selected: selectedAnnotationId === resource.id,
zoomRatio,
});
canvasAnnotationDisplay.toContext(context);
});
});
}
/** */
renderAnnotations() {
const {
annotations,
drawAnnotations,
drawSearchAnnotations,
searchAnnotations,
palette,
} = this.props;
if (drawSearchAnnotations) {
this.annotationsToContext(searchAnnotations, palette.search);
}
if (drawAnnotations) {
this.annotationsToContext(annotations, palette.annotations);
}
}
/**
* Renders things
*/
render() {
const { viewer } = this.props;
if (!viewer) return <></>;
return ReactDOM.createPortal(
(
<div
ref={this.ref}
style={{
height: '100%', left: 0, position: 'absolute', top: 0, width: '100%',
}}
>
<canvas />
</div>
),
viewer.canvas,
);
}
} |
JavaScript | class Contato {
constructor(name, lastname, email) {
this.name = name
this.lastname = lastname
this.email = email
}
validarDados() {
for (let i in this) {
if (this[i] == undefined || this[i] == null || this[i] == '') {
return false
}
}
return true
}
} |
JavaScript | class WglTexture {
/**
* @param {!int} width
* @param {!int} height
* @param {!int} pixelType FLOAT or UNSIGNED_BYTE
*/
constructor(width, height, pixelType = WebGLRenderingContext.FLOAT) {
if (width === 0 && height === 0) {
this.width = 0;
this.height = 0;
this.pixelType = pixelType;
this._hasBeenRenderedTo = true;
this._textureAndFrameBufferSlot = new WglMortalValueSlot(
() => { throw new DetailedError("Touched a zero-size texture.", this); },
() => { throw new DetailedError("Touched a zero-size texture.", this); });
return;
}
if (!Util.isPowerOf2(width) || !Util.isPowerOf2(height)) {
throw new DetailedError("Sizes must be a power of 2.", {width, height, pixelType});
}
/** @type {!int} */
this.width = width;
/** @type {!int} */
this.height = height;
/** @type {!number} */
this.pixelType = pixelType;
/**
* @type {!boolean}
* @private
*/
this._hasBeenRenderedTo = false;
/**
* @type {!WglMortalValueSlot.<!{texture: !WebGLTexture, framebuffer: !WebGLFramebuffer}>}
* @private
*/
this._textureAndFrameBufferSlot = new WglMortalValueSlot(
() => this._textureAndFramebufferInitializer(),
e => WglTexture._deinitialize(e));
}
/**
* @param {!int} sizePower
* @returns {{w: !int, h: !int}}
*/
static preferredWidthHeightForSizePower(sizePower) {
let w = 1 << Math.ceil(sizePower / 2);
let h = 1 << Math.floor(sizePower / 2);
if (w === 2 && h === 2) {
w = 4;
h = 1;
}
return {w, h};
}
/**
* Returns the base-2 logarithm of the texture's area.
* @returns {!int}
*/
sizePower() {
if (this.width === 0) {
return -Infinity;
}
return Math.round(Math.log2(this.width * this.height));
}
/**
* @returns {!string}
*/
toString() {
return 'Texture(' + [
this.width + 'x' + this.height,
this.pixelType === WebGLRenderingContext.FLOAT ? 'FLOAT' :
this.pixelType === WebGLRenderingContext.UNSIGNED_BYTE ? 'UNSIGNED_BYTE' :
this.pixelType,
this._hasBeenRenderedTo ? 'rendered' : 'not rendered'].join(', ') + ')';
}
markRendered() {
this._hasBeenRenderedTo = true;
}
/**
* For catching use-after-free bugs, despite texture pooling.
* Moves the underlying WebGLTexture to a new instance, and marks this instance as invalidated.
* @param {*} details
* @returns {!WglTexture}
*/
invalidateButMoveToNewInstance(details) {
let result = new WglTexture(this.width, this.height, this.pixelType);
result._textureAndFrameBufferSlot = this._textureAndFrameBufferSlot;
let invalidated = () => { throw new DetailedError("WglTexture's value accessed after invalidation.", details) };
this._textureAndFrameBufferSlot = new WglMortalValueSlot(invalidated, invalidated);
return result;
}
/**
* @returns {!WebGLTexture}
*/
initializedTexture() {
if (!this._hasBeenRenderedTo) {
throw new Error("Called initializedTexture on a texture that hasn't been rendered to.");
}
return this._textureAndFrameBufferSlot.initializedValue(initializedWglContext().lifetimeCounter).texture;
}
/**
* @returns {!WebGLFramebuffer}
*/
initializedFramebuffer() {
return this._textureAndFrameBufferSlot.initializedValue(initializedWglContext().lifetimeCounter).framebuffer;
}
/**
* @private
*/
static _deinitialize({texture, framebuffer}) {
let gl = initializedWglContext().gl;
gl.deleteTexture(texture);
gl.deleteFramebuffer(framebuffer);
}
ensureDeinitialized() {
this._textureAndFrameBufferSlot.ensureDeinitialized();
}
/**
* @returns {!{texture: !WebGLTexture, framebuffer: !WebGLFramebuffer}}
* @private
*/
_textureAndFramebufferInitializer() {
const GL = WebGLRenderingContext;
let gl = initializedWglContext().gl;
let result = {
texture: gl.createTexture(),
framebuffer: gl.createFramebuffer()
};
gl.bindTexture(GL.TEXTURE_2D, result.texture);
gl.bindFramebuffer(GL.FRAMEBUFFER, result.framebuffer);
try {
gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
gl.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
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.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, this.width, this.height, 0, GL.RGBA, this.pixelType, null);
checkGetErrorResult(gl, "texImage2D");
gl.framebufferTexture2D(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, result.texture, 0);
checkGetErrorResult(gl, "framebufferTexture2D");
checkFrameBufferStatusResult(gl);
} finally {
gl.bindTexture(GL.TEXTURE_2D, null);
gl.bindFramebuffer(GL.FRAMEBUFFER, null);
}
return result;
}
/**
* Performs a blocking read of the pixel color data in this texture.
* @param {!boolean} isOnHotPath
* @returns {!Uint8Array|!Float32Array}
*/
readPixels(isOnHotPath=true) {
const GL = WebGLRenderingContext;
if (!this._hasBeenRenderedTo) {
throw new Error("Called readPixels on a texture that hasn't been rendered to.");
}
let outputBuffer;
switch (this.pixelType) {
case GL.UNSIGNED_BYTE:
outputBuffer = new Uint8Array(this.width * this.height * 4);
break;
case GL.FLOAT:
outputBuffer = new Float32Array(this.width * this.height * 4);
break;
default:
throw new Error("Unrecognized pixel type.");
}
if (this.width === 0 || this.height === 0) {
return outputBuffer;
}
let gl = initializedWglContext().gl;
gl.bindFramebuffer(GL.FRAMEBUFFER, this.initializedFramebuffer());
checkGetErrorResult(gl, "framebufferTexture2D", isOnHotPath);
checkFrameBufferStatusResult(gl, isOnHotPath);
gl.readPixels(0, 0, this.width, this.height, GL.RGBA, this.pixelType, outputBuffer);
checkGetErrorResult(gl, `readPixels(..., RGBA, ${this.pixelType}, ...)`, isOnHotPath);
return outputBuffer;
}
} |
JavaScript | class Stock {
/**
* The amount of money that has to paid whenever stocks
* is bought or sold.
* @type {number}
*/
static commission = 100000;
/**
* Create an instance of a tradeable stock.
* @param {import("../..").NS} ns
* @param {string} sym - The symbol of the stock.
*/
constructor(ns, sym) {
/**
* The position of the stock.
* @type {number[]}
*/
let position = ns.stock.getPosition(sym);
/**
* The symbol of the stock (unique ID).
* @type {string}
*/
this.sym = sym;
/**
* The current price of a share.
* @type {number}
*/
this.price = ns.stock.getPrice(sym);
/**
* The number of shares owned by the player.
* @type {number}
*/
this.shares = position[0];
/**
* The maximum available shares.
* @type {number}
*/
this.sharesMax = ns.stock.getMaxShares(sym);
/**
* The shares that are available to buy.
* @type {number}
*/
this.sharesAvailable = this.sharesMax - this.shares;
/**
* The average price the player payed for the shares.
* @type {number}
*/
this.buyPrice = position[1];
/**
* The percentage that the stock's price can change per cycle.
* @type {number}
*/
this.volatility = ns.stock.getVolatility(sym);
/**
* The probability that the stocks price will increase in the next cycle.
* @type {number}
*/
this.probability = 2 * (ns.stock.getForecast(sym) - 0.5);
/**
* The expected return of the stock extrapolated from change probability and
* volatility.
* @type {number}
*/
this.expectedReturn = this.volatility * this.probability * 0.5;
}
/**
* Update the data of the stock.
* @param {import("..").NS} ns
*/
update(ns) {
/**
* The position of the stock.
* @type {number[]}
*/
let position = ns.stock.getPosition(this.sym);
this.price = ns.stock.getPrice(this.sym);
this.shares = position[0];
this.sharesMax = ns.stock.getMaxShares(this.sym);
this.sharesAvailable = this.sharesMax - this.shares;
this.buyPrice = position[1];
this.volatility = ns.stock.getVolatility(this.sym);
this.probability = 2 * (ns.stock.getForecast(this.sym) - 0.5);
this.expectedReturn = this.volatility * this.probability * 0.5;
}
/**
* Sell a defined number of shares.
* @param {import("..").NS} ns
* @param {number} numShares - The numbe rof shares that shall be sold.
*/
buy(ns, numShares) {
/**
* The actual number of shares that will be bought. If more shares are
* requested than available the number will be limited to what
* is available.
* @type {number}
*/
var num = Math.min(numShares, this.sharesAvailable);
let price = ns.stock.buy(this.sym, num);
if (price) {
ns.print(`Bought ${this.sym} for ${formatMoney(num * price)}`);
} else {
ns.print(`Failed to buy ${num} of ${this.sym}`);
}
}
/**
* Sell a number of shares.
* @param {import("..").NS} ns
* @param {number} numShares - The number of shares that shall be sold.
*/
sell(ns, numShares) {
/**
* The actual number of shares that will be bought. If more shares are
* requested than owned the number will be limited to what
* is owned.
* @type {number}
*/
var num = Math.min(numShares, this.shares);
/**
* The amount of money the player earns when selling the stock.
* The original price for buying the stock and the commission
* for buying and selling are already subtracted.
* @type {number}
*/
var profit = num * (this.price - this.buyPrice) - 2 * Stock.commission;
ns.stock.sell(this.sym, num);
ns.print(`Sold ${this.sym} for profit of ${formatMoney(profit)}`);
}
} |
JavaScript | class MatrixRenderer {
constructor (initOptions = {}, isDebugEnabled = false) {
this.debug = new Proxy({
_consoleLog: null,
_consoleInfo: null,
_consoleWarn: null,
_consoleError: null,
enabled: false,
fps: {
add: (entry) => {
if (this.debug.fps._n >= 30) {
this.debug.fps._n = 0;
}
this.debug.fps._dataset[this.debug.fps._n++] = entry;
let sum = this.debug.fps._dataset.reduce((acc, cur) => acc + cur);
this.debug.fps.average = Math.round(sum / this.debug.fps._dataset.length);
return entry;
},
average: 0,
_dataset: [],
_n: 0
},
gui: Object.freeze({
customConsole: document.getElementById("debug__custom-console"),
fpsCounter: document.getElementById("debug__fps"),
fpsCounterAvg: document.getElementById("debug__fps-avg"),
windowFrame: document.getElementById("debug"),
}),
switchToCustomConsole: () => {
if (this.debug._consoleLog !== null) {
return;
}
this.debug._consoleLog = console.log;
this.debug._consoleInfo = console.info;
this.debug._consoleWarn = console.warn;
this.debug._consoleError = console.error;
let msgHandler = (type) => {
return (msg) => {
let entry = document.createElement("div");
entry.classList.add("entry");
entry.classList.add(type);
entry.innerHTML = msg;
this.debug.gui.customConsole.appendChild(entry);
}
}
window["console"]["log"] = msgHandler("log");
window["console"]["info"] = msgHandler("info");
window["console"]["warn"] = msgHandler("warn");
window["console"]["error"] = msgHandler("error");
this.debug.gui.customConsole.dataset.visible = true;
},
switchToDefaultConsole: () => {
if (this.debug._consoleLog !== null) {
window["console"]["log"] = this.debug._consoleLog;
window["console"]["info"] = this.debug._consoleInfo;
window["console"]["warn"] = this.debug._consoleWarn;
window["console"]["error"] = this.debug._consoleError;
this.debug._consoleLog = null;
this.debug._consoleInfo = null;
this.debug._consoleWarn = null;
this.debug._consoleError = null;
this.debug.gui.customConsole.dataset.visible = false;
}
}
}, {
set: (obj, prop, value) => {
if (prop === "enabled") {
if (typeof value !== "boolean") {
throw new TypeError("Only boolean allowed!");
} else {
this.debug.gui.windowFrame.dataset.visible = value;
}
}
obj[prop] = value;
return true;
}
});
this.debug.enabled = isDebugEnabled;
let optionHandler = (prefix = "") => {
return {
set: (obj, prop, value) => {
obj[prop] = value;
this.applyOption(prefix + prop);
return true;
}
}
};
this.options = new Proxy(Object.assign({
backgroundColor: 0x000000,
canvasElement: null,
changeCharactersRandomly: true,
columnAlphaFade: true,
font: new Proxy({
family: "'Courier New'",
size: 12,
}, optionHandler("font.")),
fps: 30,
screen: new Proxy({
height: 1080,
rainDropFactor: 0.75,
width: 1920,
}, optionHandler("screen.")),
style: {
column: {
color: 0x33FF22,
color1: 0xFFFFFF,
color2: 0xFFFFFF,
// possible modes:
// 1 - Single color
// 2 - Gradient (horizontal)
// 3 - Gradient (vertical)
// 4 - Random
mode: 1,
},
highlight: {
color: 0xFFFFFF,
enabled: true,
},
tail: {
color: 0x777777,
enabled: true,
},
},
textRange: new Proxy({
binary: false,
chinese: false,
cyrillic: true,
hex: false,
japanese: false,
lettersLowerCase: true,
lettersUpperCase: true,
numbers: true,
octal: false,
specialCharacters: true,
}, {
set: (obj, prop, value) => {
obj[prop] = value;
this._buildTextRange();
return true;
}
}),
}, initOptions), {
set: (obj, prop, value) => {
obj[prop] = value;
if (prop == "backgroundColor" && this.render.pixi.app !== null) {
this.render.pixi.app.renderer.backgroundColor = value;
document.body.style.backgroundColor = PIXI.utils.hex2string(value);
} else if (prop == "fps" && this.render.pixi.app !== null) {
this.render.pixi.app.ticker.maxFPS = value;
}
return true;
}
});
this.render = {
count: {
rows: 0,
cols: 0
},
isCreatingLetterTextures: false,
isPaused: false,
pixi: {
app: null,
resources: null,
},
shouldCreateLetterTexturesNextFrame: false,
shouldRestartNextFrame: false,
textcols: [],
textRange: "?",
textRangeAll: "?",
};
}
/**
* Gets a unicode range from start to end.
* @param {number} start The beginning of the range (inclusive)
* @param {number} end The end of the range (exclusive)
* @param {Array.<number>} [exclude] Characters to exclude from the output
* @returns {string}
*/
_getUnicodeRange(start, end, exclude = []) {
let ret = "";
for (let c = start; c < end; c++) {
if (exclude.includes(c)) {
continue;
}
ret += String.fromCharCode(c);
}
return ret;
}
_buildTextRange() {
const textSets = {
binary: "01",
chinese: this._getUnicodeRange(0x2E80, 0x2EF3) + this._getUnicodeRange(0x2F00, 0x2FD5),
cyrillic: "аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ",
hex: "0123456789ABCDEF",
japanese: this._getUnicodeRange(0x3040, 0x31F0, [0x3040, 0x3097, 0x3098, 0x3099, 0x309A, 0x309B, 0x309C, 0x30FB, 0x30FC, 0x30FD, 0x30FE]),
lettersLowerCase: "abcdefghijklmnopqrstuvwxyz",
lettersUpperCase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
numbers: "0123456789",
octal: "01234567",
specialCharacters: ",;.:-_+*~#'^°!\"§$%&/()=?{[]}\\@€"
};
let tmpRange = "";
let tmpRangeAll = "";
for (let k in this.options.textRange) {
if (this.options.textRange.hasOwnProperty(k)) {
tmpRangeAll += textSets[k];
if (this.options.textRange[k] == true) {
tmpRange += textSets[k];
}
}
}
this.render.textRange = [...new Set((tmpRange == "" ? "?" : tmpRange).split(""))].join("");
this.render.textRangeAll = [...new Set((tmpRangeAll == "" ? "?" : tmpRangeAll).split(""))].join("");
}
_randomTextFromRange(count, textRange) {
let retText = "";
for (let i = 0; i < count; i++)
retText += textRange.charAt(Math.floor(Math.random() * textRange.length));
return retText;
}
_randomTextCol(c, isInit = false) {
let color = this.options.style.column.color;
if (this.options.style.column.mode == 2) {
// Horizontal Gradient
let c1 = PIXI.utils.hex2rgb(this.options.style.column.color1);
let c2 = PIXI.utils.hex2rgb(this.options.style.column.color2);
let ctmp = [
c1[0] + (c / this.render.count.cols) * (c2[0] - c1[0]), // red
c1[1] + (c / this.render.count.cols) * (c2[1] - c1[1]), // green
c1[2] + (c / this.render.count.cols) * (c2[2] - c1[2]), // blue
];
color = PIXI.utils.rgb2hex(ctmp);
} else if (this.options.style.column.mode == 4) {
// Random
color = Math.random() * 0xFFFFFF;
}
return {
color: color,
data: this._randomTextFromRange(this.render.count.rows, this.render.textRange),
delayedLoops: Math.floor(Math.random() * 140) % (isInit ? 135 : 40),
dropLength: Math.floor(this.render.count.rows * this.options.screen.rainDropFactor),
loops: 0
};
}
_buildTextCols(isInit = false) {
for (let c = 0; c < this.render.count.cols; c++) {
this.render.textcols[c] = this._randomTextCol(c, isInit);
}
}
_changeTextFromTextCols() {
let c, cc, ccMax = Math.floor(Math.random() * 100) % Math.floor(this.render.count.rows / 8), rpos;
for (c = 0; c < this.render.count.cols; c++) {
let txtcTmp = this.render.textcols[c].data.split("");
let txtRangeTmp = this._randomTextFromRange(this.render.count.rows, this.render.textRange);
for (cc = 0; cc < ccMax; cc++) {
rpos = Math.floor(Math.random() * 100) % (this.render.count.rows);
txtcTmp[rpos] = txtRangeTmp[rpos];
}
this.render.textcols[c].data = txtcTmp.join("");
}
}
_createLetterTextures(loadCallback = () => {}) {
if (this.render.isCreatingLetterTextures) {
return;
}
this.render.isCreatingLetterTextures = true;
if (this.debug.enabled) {
console.info("Creating Letter Textures.");
}
this.render.pixi.app.loader.reset();
this.render.pixi.app.loader.destroy();
PIXI.utils.clearTextureCache();
PIXI.utils.destroyTextureCache();
let canvas = document.createElement("canvas");
canvas.width = this.options.font.size;
canvas.height = this.options.font.size;
let ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = PIXI.utils.hex2string(0xFFFFFF);
ctx.font = this.options.font.size + "px " + this.options.font.family;
// Create fallback
this.render.pixi.app.loader.add("l_blank", canvas.toDataURL());
// Create textRange + fallback letter (?) if not included in textRange
for (let l = 0; l < this.render.textRangeAll.length; l++) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(
this.render.textRangeAll.charAt(l),
this.options.font.size / 2,
this.options.font.size / 2,
);
this.render.pixi.app.loader.add("l_" + this.render.textRangeAll.charCodeAt(l), canvas.toDataURL());
}
// Quickndirty: disable console.warn globally
let oldConsoleWarn = console.warn;
window["console"]["warn"] = () => {};
this.render.pixi.app.loader.load((loader, resources) => {
// enable it as soon as loader callback is called.
// WHY? bc pixi.js does not provide any option to disable duplicate
// texture warnings on load and it's annoying.
window["console"]["warn"] = oldConsoleWarn;
this.render.pixi.resources = resources;
loadCallback();
this.render.isCreatingLetterTextures = false;
});
}
// setup render environment and canvas
_initializeRender() {
if (this.debug.enabled) {
console.info("Initializing Renderer with following options:", this.options);
}
this.render.pixi.app = new PIXI.Application({
autoStart: false,
backgroundColor: this.options.backgroundColor,
clearBeforeRender: true,
height: this.options.screen.height,
sharedLoader: false,
sharedTicker: false,
view: this.options.canvasElement,
width: this.options.screen.width,
});
this.render.pixi.app.stage.interactiveChildren = false;
this.render.pixi.app.stage.removeChildren();
this.render.pixi.app.ticker.minFPS = 1;
this.render.pixi.app.ticker.maxFPS = this.options.fps;
document.body.style.backgroundColor = PIXI.utils.hex2string(this.options.backgroundColor);
this.render.count.cols = Math.floor(this.options.screen.width / this.options.font.size);
this.render.count.rows = Math.floor(this.options.screen.height / this.options.font.size);
this._buildTextRange();
this._buildTextCols(true);
this._createLetterTextures(() => {
for (let c = 0; c < this.render.count.cols; c++) {
for (let r = 0; r < this.render.count.rows; r++) {
let sprite = new PIXI.Sprite(this.render.pixi.resources['l_blank'].texture);
sprite.x = c * this.options.font.size;
sprite.y = r * this.options.font.size;
sprite.interactiveChildren = false;
this.render.pixi.app.stage.addChild(sprite);
}
}
this.render.pixi.app.start();
this.render.pixi.app.ticker.add(() => {
if (this.render.shouldRestartNextFrame) {
this.render.shouldRestartNextFrame = false;
this.restart();
} else if (this.render.shouldCreateLetterTexturesNextFrame && !this.render.isCreatingLetterTextures) {
this.render.shouldCreateLetterTexturesNextFrame = false;
let isPausedCache = this.render.isPaused;
this.render.isPaused = true;
this._createLetterTextures(() => {
this.render.isPaused = isPausedCache;
});
} else if (this.render.isPaused) {
return;
} else {
if (this.debug.enabled) {
this.debug.gui.fpsCounter.innerHTML = Math.round(this.debug.fps.add(this.render.pixi.app.ticker.FPS));
this.debug.gui.fpsCounterAvg.innerHTML = this.debug.fps.average;
}
this._updateMatrix();
}
});
});
}
// draw matrix
_updateMatrix() {
let r, c, txtc;
let mode3enabled = this.options.style.column.mode == 3, mode3colors = [];
if (mode3enabled) {
// Calculate Vertical Gradient only once per row per column to save frame time.
for (r = 0; r < this.render.count.rows; r++) {
let c1 = PIXI.utils.hex2rgb(this.options.style.column.color1);
let c2 = PIXI.utils.hex2rgb(this.options.style.column.color2);
let ctmp = [
c1[0] + (r / this.render.count.rows) * (c2[0] - c1[0]), // red
c1[1] + (r / this.render.count.rows) * (c2[1] - c1[1]), // green
c1[2] + (r / this.render.count.rows) * (c2[2] - c1[2]), // blue
];
mode3colors.push(PIXI.utils.rgb2hex(ctmp));
}
}
for (c = 0; c < this.render.count.cols; c++) {
txtc = this.render.textcols[c];
if (txtc.delayedLoops > 0) {
txtc.delayedLoops--;
} else if (txtc.loops > txtc.dropLength + this.render.count.rows + 4) {
this.render.textcols[c] = this._randomTextCol(c, false);
} else {
for (r = 0; r < this.render.count.rows; r++) {
let sprite = this.render.pixi.app.stage.getChildAt(c * this.render.count.rows + r);
let color = txtc.color;
if (mode3enabled) {
color = mode3colors[r];
}
let alpha = 1.0;
if (txtc.loops % this.render.count.rows == r && txtc.loops < this.render.count.rows && this.options.style.highlight.enabled) {
// highlight character
color = this.options.style.highlight.color;
} else if (txtc.loops > txtc.dropLength + 4 + r) {
// if dropLength + 4 + row < loops happened
sprite.texture = this.render.pixi.resources["l_blank"].texture;
continue;
} else if (txtc.loops > txtc.dropLength + r && txtc.loops <= txtc.dropLength + 4 + r && this.options.style.tail.enabled) {
color = this.options.style.tail.color;
}
if (this.options.columnAlphaFade) {
alpha = 1 - (txtc.loops - r) / (txtc.dropLength + 4);
}
sprite.alpha = alpha;
sprite.tint = color;
sprite.texture = this.render.pixi.resources["l_" + txtc.data.charCodeAt(r)].texture;
if (txtc.loops % this.render.count.rows == r && txtc.loops < this.render.count.rows) {
break;
}
}
txtc.loops++;
}
}
if (this.options.changeCharactersRandomly) {
this._changeTextFromTextCols();
}
}
/**
* Starts the MatrixRenderer.
*/
start() {
if (this.render.pixi.app !== null) {
if (this.debug.enabled) {
console.error("Cannot start MatrixRenderer: Process is already running!");
}
return false;
} else if (this.render.isPaused) {
return this.togglePause();
} else {
if (this.debug.enabled) {
console.info("Starting MatrixRenderer process.");
}
this._initializeRender();
return true;
}
}
/**
* Restarts the MatrixRenderer.
*/
restart() {
if (this.render.pixi.app === null) {
if (this.debug.enabled) {
console.error("Cannot restart MatrixRenderer: Process not initialized!");
}
return false;
} else if (!this.stop()) {
return false;
}
return this.start();
}
/**
* Tries to apply settings instantly on renderer, else restarts
* MatrixRenderer.
* @param {string} opt The name of the option
*/
applyOption(opt) {
if (this.render.pixi.app === null) {
return;
}
if ([
"font.size",
"screen.width",
"screen.height",
"screen.rainDropFactor",
].includes(opt)) {
this.render.shouldRestartNextFrame = true;
} else if ([
"font.family",
].includes(opt)) {
this.render.shouldCreateLetterTexturesNextFrame = true;
}
}
/**
* Pauses the MatrixRenderer, if possible.
*/
togglePause() {
if (this.render.pixi.app === null) {
if (this.debug.enabled) {
console.error("Cannot pause MatrixRenderer: Process not initialized!");
}
return false;
} else if (this.render.isPaused) {
if (this.debug.enabled) {
console.info("Unpausing MatrixRenderer process.");
}
this.render.isPaused = false;
return true;
} else {
if (this.debug.enabled) {
console.info("Pausing MatrixRenderer process.");
}
this.render.isPaused = true;
return true;
}
}
/**
* Stops the MatrixRenderer, if possible.
*/
stop() {
if (this.render.pixi.app === null) {
if (this.debug.enabled) {
console.error("Cannot stop MatrixRenderer: Process not initialized!");
}
return false;
} else {
if (this.debug.enabled) {
console.log("Stopping MatrixRenderer process.");
}
this.render.pixi.app.ticker.stop();
this.render.pixi.app.stop();
this.render.pixi.app.loader.reset();
this.render.pixi.app.loader.destroy();
this.render.pixi.app.stage.removeChildren();
this.render.pixi.app.render();
this.render.pixi.app.destroy(false, true);
PIXI.utils.clearTextureCache();
PIXI.utils.destroyTextureCache();
this.render.pixi.app = null;
this.render.isCreatingLetterTextures = false;
this.render.isPaused = false;
this.render.shouldCreateLetterTexturesNextFrame = false;
this.render.shouldRestartNextFrame = false;
return true;
}
}
} |
JavaScript | class Dates extends Doc {
constructor(list, from, w) {
super(list, from, w)
this.context = opts
}
} |
JavaScript | class DeviceDriver {
constructor(hardware) {
this.hardware = hardware;
}
read(address) {
return this.hardware.read(address);
}
write(address, data) {
const start = nanoTime();
this.hardware.write(INIT_ADDRESS, PROGRAM_COMMAND);
this.hardware.write(address, data);
let readyByte;
while (((readyByte = this.read(INIT_ADDRESS)) & READY_MASK) === 0) {
if (readyByte !== READY_NO_ERROR) {
this.hardware.write(INIT_ADDRESS, RESET_COMMAND);
if ((readyByte & VPP_MASK) > 0) {
throw new VppException();
}
if ((readyByte & INTERNAL_ERROR_MASK) > 0) {
throw new InternalErrorException();
}
if ((readyByte & PROTECTED_BLOCK_ERROR_MASK) > 0) {
throw new ProtectedBlockException();
}
}
if (nanoTime() - start > TIMEOUT_THRESHOLD) {
throw new TimeoutException('Timeout when trying to read data from memory');
}
}
const actual = this.read(address);
if (data !== actual) {
throw new ReadFailureException('Failed to read data from memory');
}
}
} |
JavaScript | class FuroFileDialog extends FBP(LitElement) {
constructor() {
super();
this.multiple = false;
this.capture = '';
}
/**
* flow is ready lifecycle method
*/
_FBPReady() {
super._FBPReady();
// this._FBPTraceWires();
/**
* Is fired if native input change event is fired
* @event input-changed Payload: target element
*/
this._FBPAddWireHook('--changed', e => {
this.dispatchEvent(
new CustomEvent('input-changed', {
detail: e.target,
bubbles: true,
composed: true,
}),
);
});
}
static get properties() {
return {
/**
* A FileList listing the chosen files
* readonly
*/
files: {
type: Array,
},
/**
* Hint for expected file type in file upload controls
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
* e.g. .doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document
*/
accept: {
type: String,
reflect: true,
},
/**
* Whether to allow multiple values
*/
multiple: {
type: Boolean,
reflect: true,
},
/**
* What source to use for capturing image or video data
* The capture attribute value is a string that specifies which camera to use for capture of
* image or video data, if the accept attribute indicates that the input should be of one of those types.
* A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment
* specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing,
* the user agent is free to decide on its own what to do. If the requested facing mode isn't available,
* the user agent may fall back to its preferred default mode.
*/
capture: {
type: String,
reflect: true,
},
};
}
static get styles() {
// language=CSS
return css`
:host {
display: block;
}
:host([hidden]) {
display: none;
}
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
label {
display: none;
}
`;
}
/**
* Updater for the accept attr, the prop alone with accept="${this.accept}" wont work,
* becaue it set "undefined" (as a Sting!)
*
* @param value
*/
set accept(value) {
Helper.UpdateInputAttribute(this, 'accept', value);
}
set multiple(value) {
Helper.UpdateInputAttribute(this, 'multiple', value);
}
set capture(value) {
Helper.UpdateInputAttribute(this, 'capture', value);
}
/**
* Opens the file dialog
*/
open() {
this._FBPTriggerWire('--open', null);
}
/**
* @private
* @returns {TemplateResult|TemplateResult}
*/
render() {
// language=HTML
return html`
<input
type="file"
class="inputfile"
tabindex="-1"
?accept=${this.accept}
?multiple=${this.multiple}
?capture="${this.capture}"
id="input"
name="input"
@-change="--changed(*)"
/>
<label for="input" ƒ-click="--open"></label>
`;
}
} |
JavaScript | class App extends Component {
static async getInitialProps({ query }) {
return query
}
state = {
leaderboardList: [],
currentDonationAddress:
verifyAddress(this.props.address) ||
"0x5adf43dd006c6c36506e2b2dfa352e60002d22dc",
web3: null,
showMetaMaskModal: false,
amount: "",
message: "",
}
async componentDidMount() {
const web3 = new Web3Local(window.web3.currentProvider)
if (web3) {
this.setState({ web3 })
} else {
return alert("Please install MetaMask")
}
const networkId = await web3.eth.net.getId()
if (networkId !== 1) {
return alert("Please switch to Mainnet")
}
const leaderboardList = await getLeaderboardList(
this.state.currentDonationAddress,
)
if (leaderboardList) {
this.setState({
leaderboardList,
})
}
}
handleAddressSubmit = async e => {
if (e.keyCode === 13) {
const value = e.target.value
if (verifyAddress(value)) {
this.setState({ loading: true })
const leaderboardList = await getLeaderboardList(value)
if (leaderboardList) {
this.setState({
leaderboardList,
loading: false,
currentDonationAddress: value,
})
// clear input field
}
}
// Check if e.target.value is an address
}
}
handleMetaMask = async () => {
const { amount, message, currentDonationAddress, web3 } = this.state
let donateWei = new web3.utils.BN(web3.utils.toWei(amount, "ether"))
let extraGas = message.length * 68
const accounts = await web3.eth.getAccounts()
if (!accounts.length) {
return alert("Please unlock MetaMask")
}
try {
alert("Pending transaction..")
await web3.eth.sendTransaction({
from: accounts[0],
to: currentDonationAddress,
value: donateWei,
gas: 150000 + extraGas,
data: web3.utils.toHex(message),
})
alert("Transaction is successful!")
this.setState({ showMetaMaskModal: false })
} catch (e) {
alert("An error occurred - Try again")
}
}
render() {
const {
currentDonationAddress,
leaderboardList,
loading,
amount,
message,
showMetaMaskModal,
} = this.state
return (
<div>
{/* <MainImage>PICTURE</MainImage>
<Field>
<FieldTitle>Title</FieldTitle>
<FieldText>Donation Leaderboard</FieldText>
</Field>
<Field>
<FieldTitle>About</FieldTitle>
<FieldText>
This leaderboard project is a way for people to generate their own
donation leaderboards so they can easily share their generated
donation page and get people to donate.
</FieldText>
</Field>
<Field>
<FieldTitle>Extra</FieldTitle>
<FieldText>
You should be able to generate as many fields as you like. (title,
about and extra are all fields)
</FieldText>
</Field> */}
{showMetaMaskModal && (
<Overlay
onClick={() => this.setState({ showMetaMaskModal: false })}
/>
)}
<ContainerTest>
<DonateSection>
<LeaderboadTitle>
Ways to Donate to {trimAddress(currentDonationAddress)}
</LeaderboadTitle>
<DonationItemContainer>
<DonationItem
onClick={() => this.setState({ showMetaMaskModal: true })}
>
<DonationItemImg src="/static/images/metamask.svg" />
<FieldTitleCenter>MetaMask</FieldTitleCenter>
</DonationItem>
<DonationItem>
<DonationItemImg src="/static/images/giveth-qr.svg" />
<FieldTitleCenter>Scan QR Code</FieldTitleCenter>
</DonationItem>
</DonationItemContainer>
<AddressInputContainer>
<AddressInput
placeholder="Enter address.."
onKeyUp={this.handleAddressSubmit}
/>
</AddressInputContainer>
</DonateSection>
<LeaderboadSection>
{(!leaderboardList.length || loading) && (
<LeaderboardCardLoading>Loading...</LeaderboardCardLoading>
)}
{leaderboardList
.sort((a, b) => b.amount - a.amount)
.map(({ amount, address, message }, idx) => (
<LeaderboardCard>
<FirstHalf>
<div>
<FirstHalfText>Rank #{idx + 1}</FirstHalfText>
<FirstHalfText>{formatAmount(amount)} ETH</FirstHalfText>
</div>
</FirstHalf>
<SecondHalf>
<CardField>
<CardText>Address</CardText>
<Address
target="_blank"
href={"https://etherscan.io/address/" + address}
>
{address}
</Address>
</CardField>
<CardField>
<CardText>Message</CardText>
<Address>
<Emojify>{message || "-"}</Emojify>
</Address>
</CardField>
</SecondHalf>
</LeaderboardCard>
))}
</LeaderboadSection>
</ContainerTest>
{showMetaMaskModal && (
<Modal>
<ModalInput
placeholder="Enter amount.."
onChange={e => this.setState({ amount: e.target.value })}
value={amount}
/>
<ModalInput
placeholder="Enter message.."
onChange={e => this.setState({ message: e.target.value })}
value={message}
/>
<Submit onClick={this.handleMetaMask}>Submit</Submit>
</Modal>
)}
</div>
)
}
} |
JavaScript | class JWKSKeyProvider {
/**
* Create new provider.
*
* @param {string} jwksUri The JWKS URI.
*/
constructor(jwksUri) {
const jwksUrl = new url.URL(jwksUri);
switch (jwksUrl.protocol) {
case 'https:':
this._client = require('https');
break;
case 'http:':
this._client = require('http');
break;
default:
throw new common.X2UsageError('The JWKS URI must be http or https.');
}
this._requestOptions = {
_href: jwksUrl.href,
method: 'GET',
hostname: jwksUrl.hostname,
port: jwksUrl.port,
path: jwksUrl.pathname,
headers: {
'Accept': 'application/json'
}
};
if (jwksUrl.username)
this._requestOptions.auth =
`${jwksUrl.username}:${jwksUrl.password}`;
this._keysPromise = null;
this._keysPending = false;
this._keysExp = 0;
}
/**
* Get the keys using cached JWKS or load the JWKS.
*
* @returns {Promise} Promise of an object with keys being the key ids and
* values being the certificates used to verify signatures.
*/
getKeys() {
if (!this._keysPending && (Date.now() >= this._keysExp)) {
this._keysPending = true;
this._keysPromise = new Promise((resolve, reject) => {
log(`loading keys from ${this._requestOptions._href}`);
const request = this._client.request(
this._requestOptions, response => {
const chunks = [];
response.on('data', chunk => {
chunks.push(chunk);
}).on('end', () => {
let jwks;
const contentType = response.headers['content-type'];
if (/^application\/json/.test(contentType)) {
try {
jwks = JSON.parse(
Buffer.concat(chunks).toString('utf8'));
} catch (e) {
return reject(new common.X2DataError(
'Could not parse JWKS response: ' +
e.message));
}
}
const statusCode = response.statusCode;
if ((statusCode < 200) || (statusCode >= 300))
return reject(new common.X2DataError(
`Error ${statusCode} response from JWKS.`));
if (!jwks || !Array.isArray(jwks.keys))
return reject(new common.X2DataError(
'Invalid JWKS response.'));
const expiresHeader = response.headers['expires'];
jwks.expiresAt = (
expiresHeader ?
(new Date(expiresHeader)).getTime() :
Date.now() + 24*3600*1000
);
resolve(jwks);
});
});
request.on('error', err => {
reject(err);
});
request.end();
}).then(
jwks => {
this._keysPending = false;
this._keysExp = jwks.expiresAt;
return jwks.keys.reduce((res, jwk) => {
if (jwk.use === 'sig') {
if (Array.isArray(jwk.x5c) && (jwk.x5c.length > 0)) {
res[`${jwk.kid}:${jwk.alg}`] = (
'-----BEGIN CERTIFICATE-----\n' +
jwk.x5c[0].match(/.{1,64}/g).join('\n') +
'\n-----END CERTIFICATE-----\n'
);
} else if (jwk.n && jwk.e) {
res[`${jwk.kid}:${jwk.alg}`] =
getPem(jwk.n, jwk.e);
}
}
return res;
}, new Object());
},
err => {
this._keysPending = false;
this._keysExp = 0;
return Promise.reject(err);
}
);
}
return this._keysPromise;
}
/**
* Get the key for the specified token.
*
* @param {Object} jwt Decoded JWT.
* @returns {Promise.<string>} Promise of the key.
*/
getKey(jwt) {
if (!jwt.header || !jwt.header.kid || !jwt.header.alg) {
log('no kid or alg in the token header');
return null;
}
return this.getKeys().then(
keys => keys[`${jwt.header.kid}:${jwt.header.alg}`]);
}
} |
JavaScript | class $Settings extends Category{
constructor(){
super();
this._name = "$Settings";
}
save(){
if($EventHandler.trigger("save:pre", s, {})){
var dirname = require("path").dirname(path);
if(!fs.existsSync(dirname)){
fs.mkdir(dirname);
}
console.log(this.getString());
fs.writeFile(path, this.getString(), function(error) {
if(error){
console.error("Settings weren't able to be saved: ", error);
}else{
console.info("Settings saved succesfully");
}
var d = {success:!error};
if(error) d.errorMessage = error;
$EventHandler.trigger("save:post", s, d);
});
}
}
load(){
if($EventHandler.trigger("load:pre", s, {})){
var error;
try {
var data = fs.readFileSync(path, 'utf8');
this.setString(data);
console.info("Settings loaded succesfully");
}catch(e){
error = e;
console.error("Settings weren't able to load: ", e);
}
var d = {success:!error};
if(error) d.errorMessage = error;
$EventHandler.trigger("load:post", s, d);
}
}
fromString(path){
return getObject(path);
}
} |
JavaScript | class CheckFlagFor {
constructor(flag = 0b00000000) {
this.flag = flag;
}
subtraction() {
this.setSubtraction(true);
return this;
}
notSubtraction() {
this.setSubtraction(false);
return this;
}
setSubtraction(isSub) {
if (isSub) this.flag |= 0x40;
else this.flag &= 0b10111111;
return this;
}
// TODO: depricated
carry(val) {
this.setCarry(val > 255);
return this;
}
carry16(val) {
this.setCarry(val > 0xFFFF);
return this;
}
zero(val) {
this.setZero(!(val & 255));
return this;
}
setZero(isZero) {
if (isZero) this.flag |= 0x80;
else this.flag &= 0b01111111;
return this;
}
setHalfCarry(isHalfCarry) {
if (isHalfCarry) this.flag |= 0x20;
else this.flag &= 0b11011111;
return this;
}
// TODO: depricated
setCarry(isCarry) {
if (isCarry) this.flag |= 0x10;
else this.flag &= 0b11101111;
return this;
}
// If carry occured from lower nibble (4 bit of reg) 3.2.2 GBCPUman
setH(val, a, b) {
this.setHalfCarry(((val & 0xFF) ^ b ^ a) & 0x10);
return this;
}
setC(isCarry) {
this.setCarry(isCarry);
return this;
}
setH16(val, a, b) {
this.setHalfCarry(((val & 0xFFFF) ^ b ^ a) & 0x1000);
return this;
}
get() { return this.flag; }
isCarry() { return (this.flag & 0b00010000) === 0b00010000; }
isHalfCarry() { return (this.flag & 0b00100000) === 0b00100000; }
isZero() { return (this.flag & 0b10000000) === 0b10000000; }
isSubtraction() { return (this.flag & 0b01000000) === 0b01000000; }
} |
JavaScript | class ImageRenderer extends Base
{
/**
* @param {Object} options
* @param {Boolean} options.useCache
* @param {String} options.sourcePath
* @param {String} options.cachePath
*/
constructor(imagesRepository, moduleConfiguration, options)
{
super(options);
// Check params
assertParameter(this, 'moduleConfiguration', moduleConfiguration, true, ImageConfiguration);
assertParameter(this, 'imagesRepository', imagesRepository, true, ImagesRepository);
// Assign
const opts = options || {};
this._useCache = (typeof opts.useCache !== 'undefined') ? opts.useCache : true;
this._resizableFileExtensions = opts.resizableFileExtensions || ['.png', '.jpg'];
this._imagesRepository = imagesRepository;
}
/**
* @inheritDoc
*/
static get injections()
{
return { 'parameters': [ImagesRepository, ImageConfiguration, 'renderer/ImageResizer.useCache'] };
}
/**
* @inheritDoc
*/
static get className()
{
return 'renderer/ImageRenderer';
}
/**
* @type {Boolean}
*/
get useCache()
{
return this._useCache;
}
/**
* @type {model.image.ImagesRepository}
*/
get imagesRepository()
{
return this._imagesRepository;
}
/**
* @type {Array<String>}
*/
get resizableFileExtensions()
{
return this._resizableFileExtensions;
}
/**
* Reads the image settings when available
*
* @protected
* @param {string} filename
* @returns {Promise<Object>}
*/
getImageSettings(filename)
{
if (!filename)
{
return Promise.resolve(false);
}
const scope = this;
const promise = co(function*()
{
const result = {};
// Get settings
const settingsFile = filename.substr(0, filename.length - 3) + 'json';
const settingsFileExists = yield fs.exists(settingsFile);
// Parse & return settings
if (settingsFileExists)
{
const settingsFileContent = yield fs.readFile(settingsFile, { encoding: 'utf8' });
result.focal = JSON.parse(settingsFileContent).focal;
}
// Create default settings
else
{
result.focal =
{
x: 0,
y: 0,
width: 0,
height: 0
};
}
// Done
return result;
}).catch(ErrorHandler.handler(scope));
return promise;
}
/**
* Calculates the area that will be cropped prior to resizing honoring the focal point.
*
* @protected
* @param {number} width
* @param {number} height
* @param {bool} forced
* @param {Object} settings
* @returns {Promise<Object>}
*/
calculateCropArea(width, height, forced, settings)
{
const result =
{
x: 0,
y: 0,
width: settings.width,
height: settings.height,
aspect: 0
};
if (forced === '0')
{
return Promise.resolve(result);
}
//Get maximum enclosing size
if (width >= height)
{
result.aspect = height / width;
if (settings.width >= settings.height)
{
result.height = settings.height;
result.width = Math.round(result.height / result.aspect);
}
else
{
result.width = settings.width;
result.height = Math.round(result.width * result.aspect);
}
if (result.height > settings.height)
{
result.height = settings.height;
result.width = Math.round(result.height / result.aspect);
}
else if (result.width > settings.width)
{
result.width = settings.width;
result.height = Math.round(result.width * result.aspect);
}
}
else
{
result.aspect = width / height;
if (settings.width >= settings.height)
{
result.height = settings.height;
result.width = Math.round(result.height * result.aspect);
}
else
{
result.width = settings.width;
result.height = Math.round(result.width / result.aspect);
}
if (result.height > settings.height)
{
result.height = settings.height;
result.width = Math.round(result.height * result.aspect);
}
else if (result.width > settings.width)
{
result.width = settings.width;
result.height = Math.round(result.width / result.aspect);
}
}
//Get enclosing area
if (forced === '1')
{
result.x = Math.round(settings.focal.x + ((settings.focal.width - result.width) / 2));
result.y = Math.round(settings.focal.y + ((settings.focal.height - result.height) / 2));
result.x = Math.max(0, Math.min(result.x, settings.width - result.width));
result.y = Math.max(0, Math.min(result.y, settings.height - result.height));
}
if (forced === 'tl')
{
result.x = 0;
result.y = 0;
}
if (forced === 'tr')
{
result.x = settings.width - result.width;
result.y = 0;
}
if (forced === 'bl')
{
result.x = Math.round(settings.focal.x + ((settings.focal.width - result.width) / 2));
result.y = Math.round(settings.focal.y + ((settings.focal.height - result.height) / 2));
result.x = Math.max(0, Math.min(result.x, settings.width - result.width));
result.y = Math.max(0, Math.min(result.y, settings.height - result.height));
result.x = 0;
result.y = settings.height - result.height;
}
if (forced === 'br')
{
result.x = settings.width - result.width;
result.y = settings.height - result.height;
}
return Promise.resolve(result);
}
/**
* Create a resized image and store it at cacheFilename
*
* @param {string} imageFilename
* @param {string} cacheFilename
* @param {number} width
* @param {number} height
* @param {string} forced
* @returns {Promise<string>}
*/
renderImage(imageFilename, cacheFilename, width, height, forced)
{
return Promise.resolve(false);
}
/**
* Get cached image
*
* @param {string} filename
* @param {number} width
* @param {number} height
* @param {string} forced
* @returns {Promise<string>}
*/
resize(name, width, height, forced)
{
const scope = this;
const promise = co(function*()
{
// Cleanup options
const w = (typeof width === 'number')
? width
: parseInt(width, 10);
const h = (typeof height === 'number')
? height
: parseInt(height, 10);
const f = (['1', '0', 'tl', 'bl', 'tr', 'br'].indexOf(forced) !== -1)
? forced
: '0';
// See if image needs to be resized
const imageName = yield scope.imagesRepository.getPathByName(name);
if (!imageName)
{
scope.logger.warn('Image ' + name + ' does not exist.');
return false;
}
const imageFilename = yield scope.imagesRepository.getFileByName(imageName);
if (scope.resizableFileExtensions.indexOf(path.extname(imageFilename)) === -1)
{
return imageFilename;
}
// Check cache
const cacheFilename = yield scope.imagesRepository.getCacheFileByName(imageName, w, h, f);
if (scope.useCache)
{
const cacheFilenameExists = yield fs.exists(cacheFilename);
if (cacheFilenameExists)
{
return cacheFilename;
}
}
// Render
yield fs.mkdirp(path.dirname(cacheFilename));
const rendered = yield scope.renderImage(imageFilename, cacheFilename, w, h, f);
if (!rendered)
{
return imageFilename;
}
return cacheFilename;
}).catch(ErrorHandler.handler(scope));
return promise;
}
} |
JavaScript | class Character {
constructor(x, y, sprite) {
// Variables applied to each of our instances go here,
// we've provided one for you to get started
// Actual position
this.x = x;
this.y = y;
// The image/sprite for our enemies, this uses
// a helper we've provided to easily load images
this.sprite = sprite;
}
// Draw the enemy on the screen, required method for game
render() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
} |
JavaScript | class Enemy extends Character {
constructor(x, y, speed) {
super(x, y, ENEMY_SPRITE);
// Number of pixels (x) to move in each update
this.speed = speed;
}
// To see if this enemy crashes with the player.
checkCollision() {
if (
this.x < player.x + COLISION_LIMIT &&
this.x + COLISION_LIMIT > player.x &&
this.y < player.y + COLISION_LIMIT &&
this.y + COLISION_LIMIT > player.y
) {
score = 0;
scoreDiv.innerHTML = score;
player.reset();
}
}
// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
update(dt) {
// You should multiply any movement by the dt parameter
// which will ensure the game runs at the same speed for
// all computers.
this.x += this.speed * dt;
// When a bug reached the end, comes back to the init
if (this.x > 400) {
this.x = -100;
}
this.checkCollision();
}
} |
JavaScript | class Player extends Character {
constructor(x, y) {
super(PLAYER_POS_X, PLAYER_POS_Y, PLAYER_SPRITE);
}
// To move back the player to default position
reset() {
this.x = PLAYER_POS_X;
this.y = PLAYER_POS_Y;
};
// Update the player's position
update() {
// If the player reaches the end (water)
if (this.y < 1) {
this.reset();
score++;
scoreDiv.innerHTML = score;
}
};
// Action depending the direction chosen by the user
handleInput(direction) {
if (direction == 'left' && this.x > 0) {
this.x -= TILE_WIDTH;
}
if (direction == 'right' && this.x < 400) {
this.x += TILE_WIDTH;
}
if (direction == 'up' && this.y > 0) {
this.y -= TILE_HEIGHT;
}
if (direction == 'down' && this.y < 430) {
this.y += TILE_HEIGHT;
}
};
} |
JavaScript | class ReloadTimer extends Component {
/**
* ReloadTimer component's property types.
*
* @static
*/
static propTypes = {
/**
* The end of the timer. When this.state.current reaches this value the
* timer will stop and call onFinish function.
*
* @public
* @type {number}
*/
end: React.PropTypes.number,
/**
* The interval in sec for adding this.state.step to this.state.current.
*
* @public
* @type {number}
*/
interval: React.PropTypes.number,
/**
* The function that will be executed when timer finish (when
* this.state.current === this.props.end)
*/
onFinish: React.PropTypes.func,
/**
* The start of the timer. The initial value for this.state.current.
*
* @public
* @type {number}
*/
start: React.PropTypes.number,
/**
* The value which will be added to this.state.current on every step.
*
* @public
* @type {number}
*/
step: React.PropTypes.number,
/**
* The function to translate human-readable text.
*
* @public
* @type {Function}
*/
t: React.PropTypes.func
}
/**
* Initializes a new ReloadTimer instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
* @public
*/
constructor(props) {
super(props);
this.state = {
/**
* Current value(time) of the timer.
*
* @type {number}
*/
current: this.props.start,
/**
* The absolute value of the time from the start of the timer until
* the end of the timer.
*
* @type {number}
*/
time: Math.abs(this.props.end - this.props.start)
};
}
/**
* React Component method that executes once component is mounted.
*
* @inheritdoc
* @returns {void}
* @protected
*/
componentDidMount() {
AJS.progressBars.update('#reloadProgressBar', 0);
const intervalId
= setInterval(
() => {
if (this.state.current === this.props.end) {
clearInterval(intervalId);
this.props.onFinish();
} else {
this.setState((prevState, props) => {
return {
current: prevState.current + props.step
};
});
}
},
Math.abs(this.props.interval) * 1000);
}
/**
* React Component method that executes once component is updated.
*
* @inheritdoc
* @returns {void}
* @protected
*/
componentDidUpdate() {
AJS.progressBars.update(
'#reloadProgressBar',
Math.abs(this.state.current - this.props.start)
/ this.state.time);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement|null}
* @public
*/
render() {
const { t } = this.props;
return (
<div>
<div
className = 'aui-progress-indicator'
id = 'reloadProgressBar'>
<span className = 'aui-progress-indicator-value' />
</div>
<span className = 'reload_overlay_text'>
{
this.state.current
}
<span>
{ t('dialog.conferenceReloadTimeLeft') }
</span>
</span>
</div>
);
}
} |
JavaScript | class display {
/**
* @param {object} sharedIO - socketIO
* @param {object} dispatcher - dispatcher
* @param {object} meta - reads from config.displays
* @param {number} displayId - this display instances id
* @param {module:infoscreen3/bundleManager} bundleManager
*/
constructor(sharedIO, dispatcher, meta, displayId, bundleManager) {
cli.info("Starting display with id " + displayId + " ...");
/**
* @property {number} displayId - this display id
* @property {number} currentId - index number @see getBundle()
* @property {string} currentBundle - current bundle directory name at ./data/
* @property {string} currentFile - current filename at bundle
* @property {string} currentJSON - current slides json data
* @property {boolean} loop - runs main loop
* @property {number} loopIndex - index number used to calculate slide at enabledSlides @see getBundle()
* @property {boolean} blackout - should the blackout be enabled
* @property {boolean} isStreaming - is media server stream enabled at client
* @property {string} streamSource - URL for FLV media stream
* @property {bool} isAnnounce - if the next slide is announce one
* @property {bool} announceMeta - all data needed for announces
* @property {string} transition values
*/
this.serverOptions = {
displayId: displayId,
currentId: -1,
currentBundle: "default",
currentMeta: {},
currentFile: null,
slideDuration: 10,
loop: true,
loopIndex: 0,
blackout: false,
isStreaming: false,
streamSource: "",
isAnnounce: false,
announceMeta: {},
transition: "fade",
displayTime: true,
statusMessage: "",
};
/** @property {Array} timeoutId - holds setTimeout id's for mainLoop */
this.timeoutId = null;
/**
* @type {bundleManager|module:infoscreen3/bundleManager}
*/
this.bundleManager = bundleManager;
let io = sharedIO.of("/display-" + displayId.toString());
this.io = io;
this.name = meta.name;
this.dispatcher = dispatcher;
this.id = displayId;
let self = this;
/**
* helper callback for global announce
* @listens event:announce
*
*/
dispatcher.on("all.override", function (data) {
self.overrideSlide(data.json, data.png, data.duration);
self.displayCurrentSlide();
});
dispatcher.on("display.recalcBundleData", function (bundleName) {
if (self.serverOptions.currentBundle === bundleName) {
for (let slide of self.getBundle().allSlides) {
// calculate new index for next slide;
if (slide.uuid === self.serverOptions.currentFile) {
self.serverOptions.loopIndex = slide.index + 1;
}
}
}
});
dispatcher.on("announce", function (obj) {
// if global announce, ie screens is null
if (obj.screens === null) {
io.emit(obj.event, obj.data);
} else {
// screens is array
for (let screen of obj.screens) {
// so if match, emit data from here
if (screen === displayId) {
io.emit(obj.event, obj.data);
}
}
}
});
io.on("connection",
/**
* @param socket
*/
function (socket) {
cli.info("WS display" + displayId + ":" + socket.conn.remoteAddress + " connect");
socket.on('error', function (error) {
cli.info("WS display" + displayId + ": error");
cli.error(error);
});
socket.on('disconnect', function (reason) {
cli.info("WS display" + displayId + ": disconnect " + reason + " " + socket.conn.remoteAddress);
});
socket.on('sync', function () {
cli.info("request sync " + self.name);
socket.emit("callback.load", self.getSlideData());
});
}); // io
this.init(meta);
cli.success(meta.name + " started with '" + meta.bundle + "'");
} // display
init(meta) {
this.io.emit("callback.reload");
this.changeBundle(meta.bundle);
}
/**
* change displayed bundle
* @param {string} bundleName
*/
changeBundle(bundleName) {
this.serverOptions.currentBundle = bundleName;
let bundle = this.getBundle();
this.serverOptions.loopIndex = 0;
this.serverOptions.currentFile = bundle.enabledSlides[0] || "";
this.serverOptions.currentMeta = bundle.findSlideByUuid(bundle.enabledSlides[0]);
this.serverOptions.slideDuration = bundle.getBundleData().duration;
this.serverOptions.currentId = bundle.enabledSlides.indexOf(this.serverOptions.currentFile);
this.serverOptions.transition = bundle.getBundleData().transition;
this.serverOptions.loop = true;
this.io.emit("callback.load", this.getSlideData());
bundle = null;
this.mainLoop();
}
getSlideData() {
let bundle = this.getBundle();
return { bundleData: bundle.getBundleData(), slides: bundle.allSlides, serverOptions: this.serverOptions };
}
/**
* clears timers
*/
clearTimers() {
clearTimeout(this.timeoutId);
}
/**
* @return {bundle}
*/
getBundle() {
return this.bundleManager.getBundle(this.serverOptions.currentBundle);
}
toggleBlackout() {
this.serverOptions.blackout = this.serverOptions.blackout === false;
this.io.emit("callback.blackout", { serverOptions: this.serverOptions });
}
/**
* emits custom event for screens
* @fires event:announce
* @param screens list of screenId's use "admin" for admin interface
* @param event string event to io.emit on the selected screens
* @param data object object to send
*/
announce(screens, event, data) {
/**
* @event event:announce
*/
this.dispatcher.emit("announce", { screens: screens, event: event, data: data });
}
/**
* display main loop, which updates the display periodically
*/
mainLoop() {
if (this.serverOptions.loop) {
this.clearTimers();
}
this.serverOptions.isAnnounce = false;
this.serverOptions.announceMeta = {};
let bundle = this.getBundle();
let slides = bundle.enabledSlides;
if (slides.length >= 0) {
let lIndex = this.serverOptions.loopIndex;
if (lIndex < 0) lIndex = slides.length - Math.abs(lIndex); // negative values should shift from end
let idx = (lIndex % slides.length); // make sure id is normalized to slide count
this.serverOptions.loopIndex = idx;
this.serverOptions.currentFile = slides[idx];
this.serverOptions.slideDuration = bundle.findSlideByUuid(slides[idx]).duration || bundle.getBundleData().duration;
this.serverOptions.currentId = bundle.enabledSlides.indexOf(this.serverOptions.currentFile);
this.serverOptions.currentMeta = bundle.findSlideByUuid(slides[idx]);
this.serverOptions.displayTime = bundle.bundleData.displayTime;
}
if (this.serverOptions.loop) {
// override slide timeout if set by slide
let slideTimeout = this.serverOptions.slideDuration * 1000;
if (this.serverOptions.currentMeta.duration > 5) {
slideTimeout = parseFloat(this.serverOptions.currentMeta.duration) * 1000;
}
if (slideTimeout >= 5000) {
this.timeoutId = setTimeout(this.mainLoop.bind(this), slideTimeout);
} else {
this.serverOptions.loop = false;
}
}
if (!this.serverOptions.isStreaming) {
this.displayCurrentSlide();
this.serverOptions.loopIndex += 1;
}
bundle = null;
}
overrideSlide(json, pngData, duration, transition) {
this.clearTimers();
let _transition = this.serverOptions.transition;
this.serverOptions.transition = transition;
this.serverOptions.loop = false;
this.serverOptions.isAnnounce = true;
this.serverOptions.announceMeta = json;
// save temporarily png data...
if (json.type === "image") {
fs.writeFileSync("./tmp/display_" + this.serverOptions.displayId + ".png", pngData.replace(/^data:image\/png;base64,/, ""), "base64");
}
if (duration && duration >= 5 &&
(json.type === "video" && json.loop === false)
) {
this.serverOptions.loop = true;
this.timeoutId = setTimeout(this.mainLoop.bind(this), duration * 1000);
}
this.displayCurrentSlide();
this.serverOptions.transition = _transition;
}
updateUI() {
this.io.emit("callback.updateUI", this.getSlideData());
}
displayCurrentSlide() {
this.announce([this.id, "admin"], "callback.update", this.getSlideData());
}
} |
JavaScript | class ImageDiff
{
/**
* @constructor
* @param {int} width Width of the canvas
* @param {int} height Height of the canvas
* @param {Number} tolerance Tolerance for difference
*/
constructor(width, height, tolerance)
{
this.width = width;
this.height = height;
this.tolerance = tolerance;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
this.context = canvas.getContext('2d', {
antialias: false,
preserveDrawingBuffer: true,
});
}
/**
* Compare two base64 images
* @method compare
* @param {string} src1 Canvas source
* @param {string} src2 Canvas source
* @return {Boolean} If images are within tolerance
*/
compare(src1, src2)
{
const a = this.getImageData(src1);
const b = this.getImageData(src2);
const len = a.length;
const tolerance = this.tolerance;
const diff = a.filter(function (val, i)
{
return Math.abs(val - b[i]) / 255 > tolerance;
});
if (diff.length / len > tolerance)
{
return false;
}
return true;
}
/**
* Get an array of pixels
* @method getImageData
* @param {string} src Source of the image
* @return {Uint8ClampedArray} Data for image of pixels
*/
getImageData(src)
{
const image = new Image();
image.src = src;
this.context.clearRect(0, 0, this.width, this.height);
this.context.drawImage(image, 0, 0, this.width, this.height);
const imageData = this.context.getImageData(0, 0, this.width, this.height);
return imageData.data;
}
} |
JavaScript | class XMIComposition {
constructor (shm, irim, xmiasoc) {
this.componentsCounter = 1;
this.components = [];
this.labels = new Map();
this.xmiats = null;
this.shm = shm;
this.irim = irim;
this.XMIAux = XMIAux;
this.xmiasoc = xmiasoc;
}
/**
* Genera componente dependientes en XMI.
* @returns {string} XMI de componentes
*/
createDependentComponents() {
let classXMI = "";
for(let i = 0; i < this.components.length; i++) {
let shape = this.shm.findShape(this.components[i].name);
classXMI += this.XMIAux.createPackEl("uml:Class", shape.id, 'name="' + this.components[i].name + '"',
this.xmiats.createXMIAttributes(this.components[i].expr, shape.name));
classXMI += this.xmiasoc.createDependentAssociations(shape.id);
}
//Crear shapes pendientes de realización
let pendingShapes = this.shm.getPendingShapes();
for(let i = 0; i < pendingShapes.length; i++) {
let ps = pendingShapes[i];
classXMI += this.XMIAux.createPackEl("uml:Class", ps.id, 'name="' + this.irim.getPrefixedTermOfIRI(ps.name)+ '"',
"");
}
this.shm.clearPendingShapes();
this.components = [];
return classXMI;
}
/**
* Obtiene el número pertinente para un componente
* @returns {string} Nombre de la clase con número
*/
getComponentNumber() {
return "_Blank" + this.componentsCounter++;
}
/**
* Guarda un componente en el registro
* @param sub componente
*/
saveComponent(sub) {
this.components.push(sub);
}
/**
* Crea una subclase que contiene parte de la clase actual.
* Esto puede ser necesario si hemos de asignar cardinalidad a un oonjunto de elementos,
* o aplicar operaciones como OneOf.
* @param asocName Nombre de la asociación
* @param subClassName Nombre de la subclase
* @param expr Expresión
* @param min Cardinalidad mínima
* @param max Cardinalidad máxima
* @returns {*} Subclase XMI
*/
createComponent(asocName, subClassName, expr, min, max) {
let subClass = {
name: subClassName,
expr: expr
};
if(subClass.expr && subClass.expr.type !== "TripleConstraint") {
subClass.expr.min = undefined;
subClass.expr.max = undefined;
}
this.saveComponent(subClass);
return this.xmiasoc.createXMICompAsocAttribute(asocName, subClassName, min, max);
}
/**
* Guarda una referencia a expresión etiquetada
* @param labelRef Referencia
* @param comp Componente referenciado
*/
saveLabel(labelRef, comp) {
this.labels.set(labelRef, comp);
}
/**
* Retorna un componente etiquetado según referencia
* @param labelRef Etiqueta
* @returns {any}
*/
getLabelled(labelRef) {
return this.labels.get(labelRef);
}
/**
* Resetea los registros
*/
clear() {
this.componentsCounter = 1;
this.components = [];
this.labels = new Map();
}
} |
JavaScript | class FIPrepay {
/**
* Constructs a new <code>FIPrepay</code>.
* @alias module:model/FIPrepay
*/
constructor() {
FIPrepay.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>FIPrepay</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/FIPrepay} obj Optional instance to populate.
* @return {module:model/FIPrepay} The populated <code>FIPrepay</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new FIPrepay();
if (data.hasOwnProperty('prepayName')) {
obj['prepayName'] = ApiClient.convertToType(data['prepayName'], 'String');
}
}
return obj;
}
} |
JavaScript | class PackagesContainer extends Component {
constructor(props) {
super(props);
//sets the initial state so neither of the modals are showing, and feeds them a package to make them happy
this.state = {
modalShow: false,
modalPackage: this.props.packages[0],
deleteModalShow: false,
deleteModalPackage: this.props.packages[0]
}
}
//used by Package to toggle a modal on and off.
setModalShow = (value, pkg) => {
this.setState({
modalShow: value,
modalPackage: pkg
})
}
//used by Package to toggle the delete confirmation on and off.
deleteModalShow = (value, pkg) => {
this.setState({
deleteModalShow: value,
deleteModalPackage: pkg
})
}
//Loads all packages after initial mounting of component
componentDidMount() {
this.props.fetchPackages()
}
render() {
// Does further routing to 3 urls - /packages, /packages/new/, & /packages/:id
/*
first Route
/packages - render Loading if doing API work (i.e. loadingPackages, deletingPackages, or creatingPackages is set to true)
otherwise, render out a Packages component
second Route
/packages/new - render the PackageForm for creating a new package
third Route
/packages/id - render Loading if doing API work (i.e. loadingPackages, deletingPackages, or creatingPackages is set to true)
otherwise, first find the specific package from the packages array,
then only pass down that specific package as the packages prop to Packages component, thus only rendering the 1 package
This is a package's "show" page, but is only used after the creation of a new package to show the new one.
otherwise, the PackageDetails modal acts as a show page for a package.
After the routes comes the two modal components (that are hidden initially)
*/
const { loadingPackages, deletingPackage, creatingPackage } = this.props
return (
<React.Fragment>
<Switch>
<Route exact path={this.props.match.url} render={() => {
if (loadingPackages || deletingPackage || creatingPackage) {
return (
<Loading />
)
} else {
return (
<React.Fragment>
<br/>
<Packages
packages={this.props.packages}
createPackage={this.props.createPackage}
deleteModalShow={this.deleteModalShow}
setModalShow={this.setModalShow}
modalShow={this.state.modalShow}
history={this.props.history}
/>
</React.Fragment>
)}}
}
/>
<Route exact path={`${this.props.match.url}/new`} render={() => {
return (
<PackageForm
createPackage={this.props.createPackage}
serviceProviders={serviceProviders}
history={this.props.history}
/>
)}}
/>
<Route path={`${this.props.match.url}/:packageId`} render={routerProps => {
if (loadingPackages || deletingPackage || creatingPackage) {
return (
<Loading />
)
} else {
//grab just the specific package and pass it down to the packages prop... I suppose this logic could be passed down to the Packages component eventually instead of having it here. REFACTOR
const pkg = this.props.packages.filter(pack => pack.id === parseInt(routerProps.match.params.packageId))
return (
<React.Fragment>
<br/>
<Packages
{...routerProps}
createPackage={this.props.createPackage}
packages={pkg}
deleteModalShow={this.deleteModalShow}
setModalShow={this.setModalShow}
modalshow={this.modalShow}
history={this.props.history}
/>
<div className="text-center">
<Link
to="/packages"
className="btn btn-secondary"
>Back to All Packages
</Link>
</div>
</React.Fragment>
)}}
}
/>
</Switch>
<PackageDetail
package={this.state.modalPackage}
show={this.state.modalShow}
onHide={() => this.setModalShow(false)}
/>
<DeletePackageModal
package={this.state.deleteModalPackage}
show={this.state.deleteModalShow}
onHide={() => this.deleteModalShow(false)}
deletePackage={this.props.deletePackage}
history={this.props.history}
/>
</React.Fragment>
)
}
} |
JavaScript | class Credentials {
constructor(apiKey, apiSecret, privateKey, applicationId, signatureSecret, signatureMethod) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.privateKey = null;
this.applicationId = applicationId;
this.signatureSecret = signatureSecret;
this.signatureMethod = signatureMethod;
if (privateKey instanceof Buffer) {
// it is already a buffer, use it as-is
this.privateKey = privateKey;
} else if (typeof privateKey === "string" && privateKey.startsWith("-----BEGIN PRIVATE KEY-----")) {
// It's a key string. Check for \n, replace with newlines
privateKey = privateKey.replace(/\\n/g, "\n");
this.privateKey = Buffer.from(privateKey, "utf-8");
} else if (privateKey !== undefined) {
if (!_fs.default.existsSync(privateKey)) {
throw new Error("File \"".concat(privateKey, "\" not found."));
}
this.privateKey = _fs.default.readFileSync(privateKey);
}
/** @private */
this._jwtGenerator = new _JwtGenerator.default();
this._hashGenerator = new _HashGenerator.default();
}
/**
* Generate a Jwt using the Private Key in the Credentials.
* By default the credentials.applicationId will be used when creating the token.
* However, this can be overwritten.
*
* @param {string} [applicationId] an application ID to be used instead of the
* default Credentials.applicationId value.
*
* @returns {string} The generated JWT
*/
generateJwt() {
var applicationId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.applicationId;
var privateKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.privateKey;
var claims = {
application_id: applicationId
};
var token = this._jwtGenerator.generate(privateKey, claims);
return token;
}
generateSignature(params) {
var signatureSecret = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.signatureSecret;
var signatureMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.signatureMethod;
return this._hashGenerator.generate(signatureMethod, signatureSecret, params);
}
/**
* @private
* Used for testing purposes only.
*/
_setJwtGenerator(generator) {
this._jwtGenerator = generator;
}
/**
* @private
* Used for testing purposes only.
*/
_setHashGenerator(generator) {
this._hashGenerator = generator;
}
/**
* Ensures a credentials instance is used.
*
* Key/Secret credentials are only supported at present.
*/
static parse(obj) {
if (obj instanceof Credentials) {
return obj;
} else {
return new Credentials(obj.apiKey, obj.apiSecret, obj.privateKey, obj.applicationId, obj.signatureSecret, obj.signatureMethod);
}
}
} |
JavaScript | class BindingTargetIsNotBasedOnFunction extends Exception
{
/**
* Initializes a new instance of {BindingTargetIsNotBasedOnFunction}
*/
constructor(type) {
super(`Binding target ´${type}´ is not a function at its core`);
this.type = type;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.