language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Phonebook extends Component {
state = {
showContacts: false,
};
componentDidMount() {
this.props.onFetchContacts();
}
componentDidUpdate(prevProps, nextProps) {
console.log("prevProps", prevProps);
console.log("nextProps", nextProps);
}
// componentDidMount() {
// const persistedContacts = localStorage.getItem("contacts");
// if (persistedContacts) {
// console.log("persistedContacts", persistedContacts);
// this.props.saveInStorage(JSON.parse(persistedContacts));
// }
// }
// componentDidUpdate(prevProps, prevState) {
// if (prevProps.contacts !== this.props.contacts) {
// console.log("this.props.contacts", this.props.contacts);
// localStorage.setItem("contacts", JSON.stringify(this.props.contacts));
// }
// }
// addContact = (name, number) => {
// const contact = {
// name: name,
// number: number,
// id: uuidv4(),
// };
// this.setState((prevState) => {
// return {
// contacts: [...prevState.contacts, contact],
// showContacts: true,
// };
// });
// };
// changeFilter = (filter) => {
// this.setState({ filter });
// };
// getFilteredContacts = () => {
// const { contacts, filter } = this.state;
// return contacts.filter((contact) =>
// contact.name.toLowerCase().includes(filter.toLowerCase())
// );
// };
// handleDelete = (id) => {
// this.setState((prevState) => ({
// contacts: prevState.contacts.filter((contact) => contact.id !== id),
// }));
// };
render() {
//const { filter, contacts } = this.state;
//const filteredContacts = this.getFilteredContacts();
// const { IsLoadingContacts } = this.props;
return (
<div className="container ">
<CSSTransition
in={true}
appear={true}
classNames="mainTitle-slideIn"
timeout={5000}
unmountOnExit
>
<MainTitle />
</CSSTransition>
<ContactForm
// addContact={this.addContact}
// contacts={this.state.contacts}
/>
{/* {this.props.filteredContacts && ( */}
<CSSTransition
in={
this.props.filteredContacts.length > 1 ||
this.props.contacts.length > 1
}
timeout={250}
classNames="findContact"
unmountOnExit
>
{/* {this.props.contacts > 0 && ( */}
<FindContactInput
// value={this.props.filter}
// onChangeFilter={this.changeFilter}
/>
{/* )} */}
</CSSTransition>
{/* )} */}
{/* <CSSTransition in={showContacts} inmountOnExit> */}
{/* {this.state.contacts && ( */}
{/* {this.props.filteredContacts === [] ? (
<h4>...There is no result</h4>
) : ( */}
<ContactsList
// deleteContact={this.handleDelete} contacts={contacts}
/>
{/* )} */}
{this.props.IsLoadingContacts && (
<Loader
style={{ display: "flex ", justifyContent: "center" }}
type="ThreeDots"
color="#00BFFF"
height={80}
width={80}
/>
)}
{/* )} */}
{/* </CSSTransition> */}
</div>
);
}
} |
JavaScript | class Cella {
/**
* Initializes a new instance of Cella
* @example
* const cella = new Cella(config);
* @param {Object} [config=null] - Implements {@link #CellaInterface|`CellaInterface`}
* This object parameter specifies the configuration for initialiszing
* the `Cella` class instance. You may specify encryption, storage engine or transforms.
*
* <blockquote>See {@link #CellaInterface|`CellaInterface`} for more details</blockquote>
*/
constructor() { } // eslint-disable-line
/**
* Method used to store data.
* @param {Object} storeParams - Specification for the item to be stored.
* @return {void}
* <blockquote>See {@link #StorageItem|`StorageItem`} for more details</blockquote>
* @example
* cella.store(storeParams);
*/
store() { } // eslint-disable-line
/**
* Method used to retrieve stored data.
* @param {Object} getParams - Specification for the item to be retrieved.
* @return {unknown} - The initial data type of the data that was stored. i.e: store an array, retrieve an array!
* See {@link #RetrievedStorageItem|`RetrievedStorageItem`} for more details
* @example
* cella.get(getParams);
*/
get() { } // eslint-disable-line
/**
* Method used to delete data.
* @param {Object} ejectParams - Specification for the item to be deleted.
* @return {void}
* See {@link #DeletedStorageItem|`DeletedStorageItem`} for more details
* @example
* cella.eject(ejectParams);
*/
eject() { } // eslint-disable-line
} |
JavaScript | class RangeSlider extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
}
componentWillMount() {
if (this.props.initialValue) {
this.setState({
value: this.props.initialValue
});
}
}
componentWillReceiveProps(nextProps) {
const { initialValue } = this.props;
if (nextProps.initialValue && !_.isEqual(nextProps.initialValue, initialValue)) {
this.setState({
value: nextProps.initialValue
});
}
}
setValue = (value) => {
this.setState({ value }, () => {
this.props.onRangeUpdate(value);
});
}
render() {
return (
<RangeSliderWrap className={this.props.className}>
{this.props.label &&
<Label>{this.props.label}</Label>
}
<InputRange
formatLabel={this.props.formatLabel}
maxValue={this.props.maxValue}
minValue={this.props.minValue}
onChange={this.setValue}
className="pb-test__ranger-slider"
step={this.props.step}
value={this.state.value} />
</RangeSliderWrap>
);
}
} |
JavaScript | class V1Plan {
/**
* Constructs a new <code>V1Plan</code>.
* @alias module:model/V1Plan
*/
constructor() {
V1Plan.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>V1Plan</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/V1Plan} obj Optional instance to populate.
* @return {module:model/V1Plan} The populated <code>V1Plan</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new V1Plan();
if (data.hasOwnProperty('apiVersion')) {
obj['apiVersion'] = ApiClient.convertToType(data['apiVersion'], 'String');
}
if (data.hasOwnProperty('kind')) {
obj['kind'] = ApiClient.convertToType(data['kind'], 'String');
}
if (data.hasOwnProperty('metadata')) {
obj['metadata'] = V1ObjectMeta.constructFromObject(data['metadata']);
}
if (data.hasOwnProperty('spec')) {
obj['spec'] = V1PlanSpec.constructFromObject(data['spec']);
}
if (data.hasOwnProperty('status')) {
obj['status'] = V1PlanStatus.constructFromObject(data['status']);
}
}
return obj;
}
/**
* Returns APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
* @return {String}
*/
getApiVersion() {
return this.apiVersion;
}
/**
* Sets APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
* @param {String} apiVersion APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
*/
setApiVersion(apiVersion) {
this['apiVersion'] = apiVersion;
}
/**
* Returns Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
* @return {String}
*/
getKind() {
return this.kind;
}
/**
* Sets Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
* @param {String} kind Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
*/
setKind(kind) {
this['kind'] = kind;
}
/**
* @return {module:model/V1ObjectMeta}
*/
getMetadata() {
return this.metadata;
}
/**
* @param {module:model/V1ObjectMeta} metadata
*/
setMetadata(metadata) {
this['metadata'] = metadata;
}
/**
* @return {module:model/V1PlanSpec}
*/
getSpec() {
return this.spec;
}
/**
* @param {module:model/V1PlanSpec} spec
*/
setSpec(spec) {
this['spec'] = spec;
}
/**
* @return {module:model/V1PlanStatus}
*/
getStatus() {
return this.status;
}
/**
* @param {module:model/V1PlanStatus} status
*/
setStatus(status) {
this['status'] = status;
}
} |
JavaScript | class Messenger extends EventEmitter {
constructor(egg) {
super();
this.egg = egg;
}
/**
* Send message to all agent and app
* @param {String} action - message key
* @param {Object} data - message value
* @return {Messenger} this
*/
broadcast(action, data) {
debug('[%s] broadcast %s with %j', this.pid, action, data);
this.send(action, data, 'both');
return this;
}
/**
* send message to the specified process
* Notice: in single process mode, it only can send to self process,
* and it will send to both agent and app's messengers.
* @param {String} pid - the process id of the receiver
* @param {String} action - message key
* @param {Object} data - message value
* @return {Messenger} this
*/
sendTo(pid, action, data) {
debug('[%s] send %s with %j to %s', this.pid, action, data, pid);
if (pid !== process.pid) return;
this.send(action, data, 'both');
return this;
}
/**
* send message to one worker by random
* Notice: in single process mode, we only start one agent worker and one app worker
* - if it's running in agent, it will send to one of app workers
* - if it's running in app, it will send to agent
* @param {String} action - message key
* @param {Object} data - message value
* @return {Messenger} this
*/
sendRandom(action, data) {
debug('[%s] send %s with %j to opposite', this.pid, action, data);
this.send(action, data, 'opposite');
return this;
}
/**
* send message to app
* @param {String} action - message key
* @param {Object} data - message value
* @return {Messenger} this
*/
sendToApp(action, data) {
debug('[%s] send %s with %j to all app', this.pid, action, data);
this.send(action, data, 'application');
return this;
}
/**
* send message to agent
* @param {String} action - message key
* @param {Object} data - message value
* @return {Messenger} this
*/
sendToAgent(action, data) {
debug('[%s] send %s with %j to all agent', this.pid, action, data);
this.send(action, data, 'agent');
return this;
}
/**
* @param {String} action - message key
* @param {Object} data - message value
* @param {String} to - let master know how to send message
* @return {Messenger} this
*/
send(action, data, to) {
// use nextTick to keep it async as IPC messenger
process.nextTick(() => {
const { egg } = this;
let application;
let agent;
let opposite;
if (egg.type === 'application') {
application = egg;
agent = egg.agent;
opposite = agent;
} else {
agent = egg;
application = egg.application;
opposite = application;
}
if (!to) to = egg.type === 'application' ? 'agent' : 'application';
if (application && application.messenger && (to === 'application' || to === 'both')) {
application.messenger._onMessage({ action, data });
}
if (agent && agent.messenger && (to === 'agent' || to === 'both')) {
agent.messenger._onMessage({ action, data });
}
if (opposite && opposite.messenger && to === 'opposite') {
opposite.messenger._onMessage({ action, data });
}
});
return this;
}
_onMessage(message) {
if (message && is.string(message.action)) {
debug('[%s] got message %s with %j', this.pid, message.action, message.data);
this.emit(message.action, message.data);
}
}
close() {
this.removeAllListeners();
}
/**
* @method Messenger#on
* @param {String} action - message key
* @param {Object} data - message value
*/
} |
JavaScript | class DateTime extends Date {
constructor() {
super(...arguments);
/**
* Used with Intl.DateTimeFormat
*/
this.locale = 'default';
this.nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
this.leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
}
/**
* Chainable way to set the {@link locale}
* @param value
*/
setLocale(value) {
this.locale = value;
return this;
}
/**
* Converts a plain JS date object to a DateTime object.
* Doing this allows access to format, etc.
* @param date
*/
static convert(date, locale = 'default') {
if (!date)
throw `A date is required`;
return new DateTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()).setLocale(locale);
}
/**
* Native date manipulations are not pure functions. This function creates a duplicate of the DateTime object.
*/
get clone() {
return new DateTime(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.getMilliseconds()).setLocale(this.locale);
}
/**
* Sets the current date to the start of the {@link unit} provided
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).startOf('month')
* would return April 1, 2021, 12:00:00.000 AM (midnight)
* @param unit
* @param startOfTheWeek Allows for the changing the start of the week.
*/
startOf(unit, startOfTheWeek = 0) {
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
switch (unit) {
case 'seconds':
this.setMilliseconds(0);
break;
case 'minutes':
this.setSeconds(0, 0);
break;
case 'hours':
this.setMinutes(0, 0, 0);
break;
case 'date':
this.setHours(0, 0, 0, 0);
break;
case 'weekDay':
this.startOf(exports.Unit.date);
this.manipulate(startOfTheWeek - this.weekDay, exports.Unit.date);
break;
case 'month':
this.startOf(exports.Unit.date);
this.setDate(1);
break;
case 'year':
this.startOf(exports.Unit.date);
this.setMonth(0, 1);
break;
}
return this;
}
/**
* Sets the current date to the end of the {@link unit} provided
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).endOf('month')
* would return April 30, 2021, 11:59:59.999 PM
* @param unit
*/
endOf(unit) {
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
switch (unit) {
case 'seconds':
this.setMilliseconds(999);
break;
case 'minutes':
this.setSeconds(59, 999);
break;
case 'hours':
this.setMinutes(59, 59, 999);
break;
case 'date':
this.setHours(23, 59, 59, 999);
break;
case 'weekDay':
this.startOf(exports.Unit.date);
this.manipulate(6 - this.weekDay, exports.Unit.date);
break;
case 'month':
this.endOf(exports.Unit.date);
this.manipulate(1, exports.Unit.month);
this.setDate(0);
break;
case 'year':
this.endOf(exports.Unit.date);
this.manipulate(1, exports.Unit.year);
this.setDate(0);
break;
}
return this;
}
/**
* Change a {@link unit} value. Value can be positive or negative
* Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).manipulate(1, 'month')
* would return May 30, 2021, 11:45:32.984 AM
* @param value A positive or negative number
* @param unit
*/
manipulate(value, unit) {
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
this[unit] += value;
return this;
}
/**
* Returns a string format.
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
* for valid templates and locale objects
* @param template An object. Uses browser defaults otherwise.
* @param locale Can be a string or an array of strings. Uses browser defaults otherwise.
*/
format(template, locale = this.locale) {
return new Intl.DateTimeFormat(locale, template).format(this);
}
/**
* Return true if {@link compare} is before this date
* @param compare The Date/DateTime to compare
* @param unit If provided, uses {@link startOf} for
* comparision.
*/
isBefore(compare, unit) {
if (!unit)
return this.valueOf() < compare.valueOf();
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
return (this.clone.startOf(unit).valueOf() < compare.clone.startOf(unit).valueOf());
}
/**
* Return true if {@link compare} is after this date
* @param compare The Date/DateTime to compare
* @param unit If provided, uses {@link startOf} for
* comparision.
*/
isAfter(compare, unit) {
if (!unit)
return this.valueOf() > compare.valueOf();
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
return (this.clone.startOf(unit).valueOf() > compare.clone.startOf(unit).valueOf());
}
/**
* Return true if {@link compare} is same this date
* @param compare The Date/DateTime to compare
* @param unit If provided, uses {@link startOf} for
* comparision.
*/
isSame(compare, unit) {
if (!unit)
return this.valueOf() === compare.valueOf();
if (this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
compare = DateTime.convert(compare);
return (this.clone.startOf(unit).valueOf() === compare.startOf(unit).valueOf());
}
/**
* Check if this is between two other DateTimes, optionally looking at unit scale. The match is exclusive.
* @param left
* @param right
* @param unit.
* @param inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion.
* If the inclusivity parameter is used, both indicators must be passed.
*/
isBetween(left, right, unit, inclusivity = '()') {
if (unit && this[unit] === undefined)
throw `Unit '${unit}' is not valid`;
const leftInclusivity = inclusivity[0] === '(';
const rightInclusivity = inclusivity[1] === ')';
return (((leftInclusivity
? this.isAfter(left, unit)
: !this.isBefore(left, unit)) &&
(rightInclusivity
? this.isBefore(right, unit)
: !this.isAfter(right, unit))) ||
((leftInclusivity
? this.isBefore(left, unit)
: !this.isAfter(left, unit)) &&
(rightInclusivity
? this.isAfter(right, unit)
: !this.isBefore(right, unit))));
}
/**
* Returns flattened object of the date. Does not include literals
* @param locale
* @param template
*/
parts(locale = this.locale, template = { dateStyle: 'full', timeStyle: 'long' }) {
const parts = {};
new Intl.DateTimeFormat(locale, template)
.formatToParts(this)
.filter((x) => x.type !== 'literal')
.forEach((x) => (parts[x.type] = x.value));
return parts;
}
/**
* Shortcut to Date.getSeconds()
*/
get seconds() {
return this.getSeconds();
}
/**
* Shortcut to Date.setSeconds()
*/
set seconds(value) {
this.setSeconds(value);
}
/**
* Returns two digit hours
*/
get secondsFormatted() {
return this.seconds < 10 ? `0${this.seconds}` : `${this.seconds}`;
}
/**
* Shortcut to Date.getMinutes()
*/
get minutes() {
return this.getMinutes();
}
/**
* Shortcut to Date.setMinutes()
*/
set minutes(value) {
this.setMinutes(value);
}
/**
* Returns two digit minutes
*/
get minutesFormatted() {
return this.minutes < 10 ? `0${this.minutes}` : `${this.minutes}`;
}
/**
* Shortcut to Date.getHours()
*/
get hours() {
return this.getHours();
}
/**
* Shortcut to Date.setHours()
*/
set hours(value) {
this.setHours(value);
}
/**
* Returns two digit hours
*/
get hoursFormatted() {
let formatted = this.format({ hour: '2-digit', hour12: false });
if (formatted === '24')
formatted = '00';
return formatted;
}
/**
* Returns two digit hours but in twelve hour mode e.g. 13 -> 1
*/
get twelveHoursFormatted() {
let hour = this.parts().hour;
if (hour.length === 1)
hour = `0${hour}`;
return hour;
}
/**
* Get the meridiem of the date. E.g. AM or PM.
* If the {@link locale} provides a "dayPeriod" then this will be returned,
* otherwise it will return AM or PM.
* @param locale
*/
meridiem(locale = this.locale) {
var _a;
return (_a = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
hour12: true,
})
.formatToParts(this)
.find((p) => p.type === 'dayPeriod')) === null || _a === void 0 ? void 0 : _a.value;
}
/**
* Shortcut to Date.getDate()
*/
get date() {
return this.getDate();
}
/**
* Shortcut to Date.setDate()
*/
set date(value) {
this.setDate(value);
}
/**
* Return two digit date
*/
get dateFormatted() {
return this.date < 10 ? `0${this.date}` : `${this.date}`;
}
/**
* Shortcut to Date.getDay()
*/
get weekDay() {
return this.getDay();
}
/**
* Shortcut to Date.getMonth()
*/
get month() {
return this.getMonth();
}
/**
* Shortcut to Date.setMonth()
*/
set month(value) {
this.setMonth(value);
}
/**
* Return two digit, human expected month. E.g. January = 1, December = 12
*/
get monthFormatted() {
return this.month + 1 < 10 ? `0${this.month}` : `${this.month}`;
}
/**
* Shortcut to Date.getFullYear()
*/
get year() {
return this.getFullYear();
}
/**
* Shortcut to Date.setFullYear()
*/
set year(value) {
this.setFullYear(value);
}
// borrowed a bunch of stuff from Luxon
/**
* Gets the week of the year
*/
get week() {
const ordinal = this.computeOrdinal(), weekday = this.getUTCDay();
let weekNumber = Math.floor((ordinal - weekday + 10) / 7);
if (weekNumber < 1) {
weekNumber = this.weeksInWeekYear(this.year - 1);
}
else if (weekNumber > this.weeksInWeekYear(this.year)) {
weekNumber = 1;
}
return weekNumber;
}
weeksInWeekYear(weekYear) {
const p1 = (weekYear +
Math.floor(weekYear / 4) -
Math.floor(weekYear / 100) +
Math.floor(weekYear / 400)) %
7, last = weekYear - 1, p2 = (last +
Math.floor(last / 4) -
Math.floor(last / 100) +
Math.floor(last / 400)) %
7;
return p1 === 4 || p2 === 3 ? 53 : 52;
}
get isLeapYear() {
return this.year % 4 === 0 && (this.year % 100 !== 0 || this.year % 400 === 0);
}
computeOrdinal() {
return this.date + (this.isLeapYear ? this.leapLadder : this.nonLeapLadder)[this.month];
}
} |
JavaScript | class Collapse {
/**
* Flips the show/hide state of `target`
* @param target html element to affect.
*/
static toggle(target) {
if (target.classList.contains(Namespace.css.show)) {
this.hide(target);
}
else {
this.show(target);
}
}
/**
* If `target` is not already showing, then show after the animation.
* @param target
*/
static show(target) {
if (target.classList.contains(Namespace.css.collapsing) ||
target.classList.contains(Namespace.css.show))
return;
const complete = () => {
target.classList.remove(Namespace.css.collapsing);
target.classList.add(Namespace.css.collapse, Namespace.css.show);
target.style.height = '';
};
target.style.height = '0';
target.classList.remove(Namespace.css.collapse);
target.classList.add(Namespace.css.collapsing);
setTimeout(complete, this.getTransitionDurationFromElement(target));
target.style.height = `${target.scrollHeight}px`;
}
/**
* If `target` is not already hidden, then hide after the animation.
* @param target HTML Element
*/
static hide(target) {
if (target.classList.contains(Namespace.css.collapsing) ||
!target.classList.contains(Namespace.css.show))
return;
const complete = () => {
target.classList.remove(Namespace.css.collapsing);
target.classList.add(Namespace.css.collapse);
};
target.style.height = `${target.getBoundingClientRect()['height']}px`;
const reflow = (element) => element.offsetHeight;
reflow(target);
target.classList.remove(Namespace.css.collapse, Namespace.css.show);
target.classList.add(Namespace.css.collapsing);
target.style.height = '';
setTimeout(complete, this.getTransitionDurationFromElement(target));
}
} |
JavaScript | class DateDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.daysContainer);
container.append(...this._daysOfTheWeek());
if (this._context._options.display.calendarWeeks) {
const div = document.createElement('div');
div.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
container.appendChild(div);
}
for (let i = 0; i < 42; i++) {
if (i !== 0 && i % 7 === 0) {
if (this._context._options.display.calendarWeeks) {
const div = document.createElement('div');
div.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
container.appendChild(div);
}
}
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectDay);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const container = this._context._display.widget.getElementsByClassName(Namespace.css.daysContainer)[0];
const [previous, switcher, next] = container.parentElement
.getElementsByClassName(Namespace.css.calendarHeader)[0]
.getElementsByTagName('div');
switcher.setAttribute(Namespace.css.daysContainer, this._context._viewDate.format(this._context._options.localization.dayViewHeaderFormat));
this._context._validation.isValid(this._context._viewDate.clone.manipulate(-1, exports.Unit.month), exports.Unit.month)
? previous.classList.remove(Namespace.css.disabled)
: previous.classList.add(Namespace.css.disabled);
this._context._validation.isValid(this._context._viewDate.clone.manipulate(1, exports.Unit.month), exports.Unit.month)
? next.classList.remove(Namespace.css.disabled)
: next.classList.add(Namespace.css.disabled);
let innerDate = this._context._viewDate.clone
.startOf(exports.Unit.month)
.startOf('weekDay', this._context._options.localization.startOfTheWeek)
.manipulate(12, exports.Unit.hours);
container
.querySelectorAll(`[data-action="${ActionTypes.selectDay}"], .${Namespace.css.calendarWeeks}`)
.forEach((containerClone, index) => {
if (this._context._options.display.calendarWeeks &&
containerClone.classList.contains(Namespace.css.calendarWeeks)) {
if (containerClone.innerText === '#')
return;
containerClone.innerText = `${innerDate.week}`;
return;
}
let classes = [];
classes.push(Namespace.css.day);
if (innerDate.isBefore(this._context._viewDate, exports.Unit.month)) {
classes.push(Namespace.css.old);
}
if (innerDate.isAfter(this._context._viewDate, exports.Unit.month)) {
classes.push(Namespace.css.new);
}
if (!this._context._unset &&
this._context.dates.isPicked(innerDate, exports.Unit.date)) {
classes.push(Namespace.css.active);
}
if (!this._context._validation.isValid(innerDate, exports.Unit.date)) {
classes.push(Namespace.css.disabled);
}
if (innerDate.isSame(new DateTime(), exports.Unit.date)) {
classes.push(Namespace.css.today);
}
if (innerDate.weekDay === 0 || innerDate.weekDay === 6) {
classes.push(Namespace.css.weekend);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${innerDate.year}-${innerDate.monthFormatted}-${innerDate.dateFormatted}`);
containerClone.setAttribute('data-day', `${innerDate.date}`);
containerClone.innerText = innerDate.format({ day: 'numeric' });
innerDate.manipulate(1, exports.Unit.date);
});
}
/***
* Generates an html row that contains the days of the week.
* @private
*/
_daysOfTheWeek() {
let innerDate = this._context._viewDate.clone
.startOf('weekDay', this._context._options.localization.startOfTheWeek)
.startOf(exports.Unit.date);
const row = [];
document.createElement('div');
if (this._context._options.display.calendarWeeks) {
const htmlDivElement = document.createElement('div');
htmlDivElement.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
htmlDivElement.innerText = '#';
row.push(htmlDivElement);
}
for (let i = 0; i < 7; i++) {
const htmlDivElement = document.createElement('div');
htmlDivElement.classList.add(Namespace.css.dayOfTheWeek, Namespace.css.noHighlight);
htmlDivElement.innerText = innerDate.format({ weekday: 'short' });
innerDate.manipulate(1, exports.Unit.date);
row.push(htmlDivElement);
}
return row;
}
} |
JavaScript | class MonthDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.monthsContainer);
for (let i = 0; i < 12; i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectMonth);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const container = this._context._display.widget.getElementsByClassName(Namespace.css.monthsContainer)[0];
const [previous, switcher, next] = container.parentElement
.getElementsByClassName(Namespace.css.calendarHeader)[0]
.getElementsByTagName('div');
switcher.setAttribute(Namespace.css.monthsContainer, this._context._viewDate.format({ year: 'numeric' }));
this._context._validation.isValid(this._context._viewDate.clone.manipulate(-1, exports.Unit.year), exports.Unit.year)
? previous.classList.remove(Namespace.css.disabled)
: previous.classList.add(Namespace.css.disabled);
this._context._validation.isValid(this._context._viewDate.clone.manipulate(1, exports.Unit.year), exports.Unit.year)
? next.classList.remove(Namespace.css.disabled)
: next.classList.add(Namespace.css.disabled);
let innerDate = this._context._viewDate.clone.startOf(exports.Unit.year);
container
.querySelectorAll(`[data-action="${ActionTypes.selectMonth}"]`)
.forEach((containerClone, index) => {
let classes = [];
classes.push(Namespace.css.month);
if (!this._context._unset &&
this._context.dates.isPicked(innerDate, exports.Unit.month)) {
classes.push(Namespace.css.active);
}
if (!this._context._validation.isValid(innerDate, exports.Unit.month)) {
classes.push(Namespace.css.disabled);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${index}`);
containerClone.innerText = `${innerDate.format({ month: 'short' })}`;
innerDate.manipulate(1, exports.Unit.month);
});
}
} |
JavaScript | class YearDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.yearsContainer);
for (let i = 0; i < 12; i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectYear);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
Dates.getStartEndYear(10, this._context._viewDate.year);
this._startYear = this._context._viewDate.clone.manipulate(-1, exports.Unit.year);
this._endYear = this._context._viewDate.clone.manipulate(10, exports.Unit.year);
const container = this._context._display.widget.getElementsByClassName(Namespace.css.yearsContainer)[0];
const [previous, switcher, next] = container.parentElement
.getElementsByClassName(Namespace.css.calendarHeader)[0]
.getElementsByTagName('div');
switcher.setAttribute(Namespace.css.yearsContainer, `${this._startYear.format({ year: 'numeric' })}-${this._endYear.format({ year: 'numeric' })}`);
this._context._validation.isValid(this._startYear, exports.Unit.year)
? previous.classList.remove(Namespace.css.disabled)
: previous.classList.add(Namespace.css.disabled);
this._context._validation.isValid(this._endYear, exports.Unit.year)
? next.classList.remove(Namespace.css.disabled)
: next.classList.add(Namespace.css.disabled);
let innerDate = this._context._viewDate.clone
.startOf(exports.Unit.year)
.manipulate(-1, exports.Unit.year);
container
.querySelectorAll(`[data-action="${ActionTypes.selectYear}"]`)
.forEach((containerClone, index) => {
let classes = [];
classes.push(Namespace.css.year);
if (!this._context._unset &&
this._context.dates.isPicked(innerDate, exports.Unit.year)) {
classes.push(Namespace.css.active);
}
if (!this._context._validation.isValid(innerDate, exports.Unit.year)) {
classes.push(Namespace.css.disabled);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${innerDate.year}`);
containerClone.innerText = innerDate.format({ year: "numeric" });
innerDate.manipulate(1, exports.Unit.year);
});
}
} |
JavaScript | class DecadeDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.decadesContainer);
for (let i = 0; i < 12; i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectDecade);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const [start, end] = Dates.getStartEndYear(100, this._context._viewDate.year);
this._startDecade = this._context._viewDate.clone.startOf(exports.Unit.year);
this._startDecade.year = start;
this._endDecade = this._context._viewDate.clone.startOf(exports.Unit.year);
this._endDecade.year = end;
const container = this._context._display.widget.getElementsByClassName(Namespace.css.decadesContainer)[0];
const [previous, switcher, next] = container.parentElement
.getElementsByClassName(Namespace.css.calendarHeader)[0]
.getElementsByTagName('div');
switcher.setAttribute(Namespace.css.decadesContainer, `${this._startDecade.format({ year: 'numeric' })}-${this._endDecade.format({ year: 'numeric' })}`);
this._context._validation.isValid(this._startDecade, exports.Unit.year)
? previous.classList.remove(Namespace.css.disabled)
: previous.classList.add(Namespace.css.disabled);
this._context._validation.isValid(this._endDecade, exports.Unit.year)
? next.classList.remove(Namespace.css.disabled)
: next.classList.add(Namespace.css.disabled);
const pickedYears = this._context.dates.picked.map((x) => x.year);
container
.querySelectorAll(`[data-action="${ActionTypes.selectDecade}"]`)
.forEach((containerClone, index) => {
if (index === 0) {
containerClone.classList.add(Namespace.css.old);
if (this._startDecade.year - 10 < 0) {
containerClone.textContent = ' ';
previous.classList.add(Namespace.css.disabled);
containerClone.classList.add(Namespace.css.disabled);
containerClone.setAttribute('data-value', ``);
return;
}
else {
containerClone.innerText = this._startDecade.clone.manipulate(-10, exports.Unit.year).format({ year: 'numeric' });
containerClone.setAttribute('data-value', `${this._startDecade.year}`);
return;
}
}
let classes = [];
classes.push(Namespace.css.decade);
const startDecadeYear = this._startDecade.year;
const endDecadeYear = this._startDecade.year + 9;
if (!this._context._unset &&
pickedYears.filter((x) => x >= startDecadeYear && x <= endDecadeYear)
.length > 0) {
classes.push(Namespace.css.active);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${this._startDecade.year}`);
containerClone.innerText = `${this._startDecade.format({ year: 'numeric' })}`;
this._startDecade.manipulate(10, exports.Unit.year);
});
}
} |
JavaScript | class TimeDisplay {
constructor(context) {
this._gridColumns = '';
this._context = context;
}
/**
* Build the container html for the clock display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.clockContainer);
container.append(...this._grid());
return container;
}
/**
* Populates the various elements with in the clock display
* like the current hour and if the manipulation icons are enabled.
* @private
*/
_update() {
if (!this._context._display._hasTime)
return;
const timesDiv = (this._context._display.widget.getElementsByClassName(Namespace.css.clockContainer)[0]);
const lastPicked = (this._context.dates.lastPicked || this._context._viewDate).clone;
timesDiv
.querySelectorAll('.disabled')
.forEach((element) => element.classList.remove(Namespace.css.disabled));
if (this._context._options.display.components.hours) {
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(1, exports.Unit.hours), exports.Unit.hours)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.incrementHours}]`)
.classList.add(Namespace.css.disabled);
}
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(-1, exports.Unit.hours), exports.Unit.hours)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.decrementHours}]`)
.classList.add(Namespace.css.disabled);
}
timesDiv.querySelector(`[data-time-component=${exports.Unit.hours}]`).innerText = this._context._options.display.components.useTwentyfourHour
? lastPicked.hoursFormatted
: lastPicked.twelveHoursFormatted;
}
if (this._context._options.display.components.minutes) {
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(1, exports.Unit.minutes), exports.Unit.minutes)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.incrementMinutes}]`)
.classList.add(Namespace.css.disabled);
}
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(-1, exports.Unit.minutes), exports.Unit.minutes)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.decrementMinutes}]`)
.classList.add(Namespace.css.disabled);
}
timesDiv.querySelector(`[data-time-component=${exports.Unit.minutes}]`).innerText = lastPicked.minutesFormatted;
}
if (this._context._options.display.components.seconds) {
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(1, exports.Unit.seconds), exports.Unit.seconds)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.incrementSeconds}]`)
.classList.add(Namespace.css.disabled);
}
if (!this._context._validation.isValid(this._context._viewDate.clone.manipulate(-1, exports.Unit.seconds), exports.Unit.seconds)) {
timesDiv
.querySelector(`[data-action=${ActionTypes.decrementSeconds}]`)
.classList.add(Namespace.css.disabled);
}
timesDiv.querySelector(`[data-time-component=${exports.Unit.seconds}]`).innerText = lastPicked.secondsFormatted;
}
if (!this._context._options.display.components.useTwentyfourHour) {
const toggle = timesDiv.querySelector(`[data-action=${ActionTypes.toggleMeridiem}]`);
toggle.innerText = lastPicked.meridiem();
if (!this._context._validation.isValid(lastPicked.clone.manipulate(lastPicked.hours >= 12 ? -12 : 12, exports.Unit.hours))) {
toggle.classList.add(Namespace.css.disabled);
}
else {
toggle.classList.remove(Namespace.css.disabled);
}
}
timesDiv.style.gridTemplateAreas = `"${this._gridColumns}"`;
}
/**
* Creates the table for the clock display depending on what options are selected.
* @private
*/
_grid() {
this._gridColumns = '';
const top = [], middle = [], bottom = [], separator = document.createElement('div'), upIcon = this._context._display._iconTag(this._context._options.display.icons.up), downIcon = this._context._display._iconTag(this._context._options.display.icons.down);
separator.classList.add(Namespace.css.separator, Namespace.css.noHighlight);
const separatorColon = separator.cloneNode(true);
separatorColon.innerHTML = ':';
const getSeparator = (colon = false) => {
return colon
? separatorColon.cloneNode(true)
: separator.cloneNode(true);
};
if (this._context._options.display.components.hours) {
let divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.incrementHour);
divElement.setAttribute('data-action', ActionTypes.incrementHours);
divElement.appendChild(upIcon.cloneNode(true));
top.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.pickHour);
divElement.setAttribute('data-action', ActionTypes.showHours);
divElement.setAttribute('data-time-component', exports.Unit.hours);
middle.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.decrementHour);
divElement.setAttribute('data-action', ActionTypes.decrementHours);
divElement.appendChild(downIcon.cloneNode(true));
bottom.push(divElement);
this._gridColumns += 'a';
}
if (this._context._options.display.components.minutes) {
this._gridColumns += ' a';
if (this._context._options.display.components.hours) {
top.push(getSeparator());
middle.push(getSeparator(true));
bottom.push(getSeparator());
this._gridColumns += ' a';
}
let divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.incrementMinute);
divElement.setAttribute('data-action', ActionTypes.incrementMinutes);
divElement.appendChild(upIcon.cloneNode(true));
top.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.pickMinute);
divElement.setAttribute('data-action', ActionTypes.showMinutes);
divElement.setAttribute('data-time-component', exports.Unit.minutes);
middle.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.decrementMinute);
divElement.setAttribute('data-action', ActionTypes.decrementMinutes);
divElement.appendChild(downIcon.cloneNode(true));
bottom.push(divElement);
}
if (this._context._options.display.components.seconds) {
this._gridColumns += ' a';
if (this._context._options.display.components.minutes) {
top.push(getSeparator());
middle.push(getSeparator(true));
bottom.push(getSeparator());
this._gridColumns += ' a';
}
let divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.incrementSecond);
divElement.setAttribute('data-action', ActionTypes.incrementSeconds);
divElement.appendChild(upIcon.cloneNode(true));
top.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.pickSecond);
divElement.setAttribute('data-action', ActionTypes.showSeconds);
divElement.setAttribute('data-time-component', exports.Unit.seconds);
middle.push(divElement);
divElement = document.createElement('div');
divElement.setAttribute('title', this._context._options.localization.decrementSecond);
divElement.setAttribute('data-action', ActionTypes.decrementSeconds);
divElement.appendChild(downIcon.cloneNode(true));
bottom.push(divElement);
}
if (!this._context._options.display.components.useTwentyfourHour) {
this._gridColumns += ' a';
let divElement = getSeparator();
top.push(divElement);
let button = document.createElement('button');
button.setAttribute('title', this._context._options.localization.toggleMeridiem);
button.setAttribute('data-action', ActionTypes.toggleMeridiem);
button.setAttribute('tabindex', '-1');
button.classList.add(Namespace.css.toggleMeridiem);
divElement = document.createElement('div');
divElement.classList.add(Namespace.css.noHighlight);
divElement.appendChild(button);
middle.push(divElement);
divElement = getSeparator();
bottom.push(divElement);
}
this._gridColumns = this._gridColumns.trim();
return [...top, ...middle, ...bottom];
}
} |
JavaScript | class HourDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.hourContainer);
for (let i = 0; i <
(this._context._options.display.components.useTwentyfourHour ? 24 : 12); i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectHour);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const container = this._context._display.widget.getElementsByClassName(Namespace.css.hourContainer)[0];
let innerDate = this._context._viewDate.clone.startOf(exports.Unit.date);
container
.querySelectorAll(`[data-action="${ActionTypes.selectHour}"]`)
.forEach((containerClone, index) => {
let classes = [];
classes.push(Namespace.css.hour);
if (!this._context._validation.isValid(innerDate, exports.Unit.hours)) {
classes.push(Namespace.css.disabled);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${innerDate.hours}`);
containerClone.innerText = this._context._options.display.components
.useTwentyfourHour
? innerDate.hoursFormatted
: innerDate.twelveHoursFormatted;
innerDate.manipulate(1, exports.Unit.hours);
});
}
} |
JavaScript | class MinuteDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.minuteContainer);
let step = this._context._options.stepping === 1
? 5
: this._context._options.stepping;
for (let i = 0; i < 60 / step; i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectMinute);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const container = this._context._display.widget.getElementsByClassName(Namespace.css.minuteContainer)[0];
let innerDate = this._context._viewDate.clone.startOf(exports.Unit.hours);
let step = this._context._options.stepping === 1
? 5
: this._context._options.stepping;
container
.querySelectorAll(`[data-action="${ActionTypes.selectMinute}"]`)
.forEach((containerClone, index) => {
let classes = [];
classes.push(Namespace.css.minute);
if (!this._context._validation.isValid(innerDate, exports.Unit.minutes)) {
classes.push(Namespace.css.disabled);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${innerDate.minutesFormatted}`);
containerClone.innerText = innerDate.minutesFormatted;
innerDate.manipulate(step, exports.Unit.minutes);
});
}
} |
JavaScript | class secondDisplay {
constructor(context) {
this._context = context;
}
/**
* Build the container html for the display
* @private
*/
get _picker() {
const container = document.createElement('div');
container.classList.add(Namespace.css.secondContainer);
for (let i = 0; i < 12; i++) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.selectSecond);
container.appendChild(div);
}
return container;
}
/**
* Populates the grid and updates enabled states
* @private
*/
_update() {
const container = this._context._display.widget.getElementsByClassName(Namespace.css.secondContainer)[0];
let innerDate = this._context._viewDate.clone.startOf(exports.Unit.minutes);
container
.querySelectorAll(`[data-action="${ActionTypes.selectSecond}"]`)
.forEach((containerClone, index) => {
let classes = [];
classes.push(Namespace.css.second);
if (!this._context._validation.isValid(innerDate, exports.Unit.seconds)) {
classes.push(Namespace.css.disabled);
}
containerClone.classList.remove(...containerClone.classList);
containerClone.classList.add(...classes);
containerClone.setAttribute('data-value', `${innerDate.seconds}`);
containerClone.innerText = innerDate.secondsFormatted;
innerDate.manipulate(5, exports.Unit.seconds);
});
}
} |
JavaScript | class Display {
constructor(context) {
this._isVisible = false;
/**
* A document click event to hide the widget if click is outside
* @private
* @param e MouseEvent
*/
this._documentClickEvent = (e) => {
var _a;
if (this._context._options.debug || window.debug)
return;
if (this._isVisible &&
!e.composedPath().includes(this.widget) && // click inside the widget
!((_a = e.composedPath()) === null || _a === void 0 ? void 0 : _a.includes(this._context._element)) // click on the element
) {
this.hide();
}
};
/**
* Click event for any action like selecting a date
* @param e MouseEvent
* @private
*/
this._actionsClickEvent = (e) => {
this._context._action.do(e);
};
this._context = context;
this._dateDisplay = new DateDisplay(context);
this._monthDisplay = new MonthDisplay(context);
this._yearDisplay = new YearDisplay(context);
this._decadeDisplay = new DecadeDisplay(context);
this._timeDisplay = new TimeDisplay(context);
this._hourDisplay = new HourDisplay(context);
this._minuteDisplay = new MinuteDisplay(context);
this._secondDisplay = new secondDisplay(context);
this._widget = undefined;
}
/**
* Returns the widget body or undefined
* @private
*/
get widget() {
return this._widget;
}
/**
* Returns this visible state of the picker (shown)
*/
get isVisible() {
return this._isVisible;
}
/**
* Updates the table for a particular unit. Used when an option as changed or
* whenever the class list might need to be refreshed.
* @param unit
* @private
*/
_update(unit) {
if (!this.widget)
return;
//todo do I want some kind of error catching or other guards here?
switch (unit) {
case exports.Unit.seconds:
this._secondDisplay._update();
break;
case exports.Unit.minutes:
this._minuteDisplay._update();
break;
case exports.Unit.hours:
this._hourDisplay._update();
break;
case exports.Unit.date:
this._dateDisplay._update();
break;
case exports.Unit.month:
this._monthDisplay._update();
break;
case exports.Unit.year:
this._yearDisplay._update();
break;
case 'clock':
if (!this._hasTime)
break;
this._timeDisplay._update();
this._update(exports.Unit.hours);
this._update(exports.Unit.minutes);
this._update(exports.Unit.seconds);
break;
case 'calendar':
this._update(exports.Unit.date);
this._update(exports.Unit.year);
this._update(exports.Unit.month);
this._decadeDisplay._update();
this._updateCalendarHeader();
break;
case 'all':
if (this._hasTime) {
this._update('clock');
}
if (this._hasDate) {
this._update('calendar');
}
}
}
/**
* Shows the picker and creates a Popper instance if needed.
* Add document click event to hide when clicking outside the picker.
* @fires Events#show
*/
show() {
var _a, _b;
if (this.widget == undefined) {
if (this._context._options.useCurrent &&
!this._context._options.defaultDate &&
!((_a = this._context._input) === null || _a === void 0 ? void 0 : _a.value)) {
//todo in the td4 branch a pr changed this to allow granularity
const date = new DateTime().setLocale(this._context._options.localization.locale);
if (!this._context._options.keepInvalid) {
let tries = 0;
let direction = 1;
if ((_b = this._context._options.restrictions.maxDate) === null || _b === void 0 ? void 0 : _b.isBefore(date)) {
direction = -1;
}
while (!this._context._validation.isValid(date)) {
date.manipulate(direction, exports.Unit.date);
if (tries > 31)
break;
tries++;
}
}
this._context.dates._setValue(date);
}
if (this._context._options.defaultDate) {
this._context.dates._setValue(this._context._options.defaultDate);
}
this._buildWidget();
// reset the view to the clock if there's no date components
if (this._hasTime && !this._hasDate) {
this._context._action.do(null, ActionTypes.showClock);
return;
}
// otherwise return to the calendar view
this._context._currentViewMode = this._context._minViewModeNumber;
if (this._hasTime)
Collapse.hide(this._context._display.widget
.getElementsByClassName(Namespace.css.timeContainer)[0]);
Collapse.show(this._context._display.widget
.getElementsByClassName(Namespace.css.dateContainer)[0]);
if (this._hasDate) {
this._showMode();
}
if (!this._context._options.display.inline) {
document.body.appendChild(this.widget);
this._popperInstance = core.createPopper(this._context._element, this.widget, {
modifiers: [{ name: 'eventListeners', enabled: true }],
//#2400
placement: document.documentElement.dir === 'rtl'
? 'bottom-end'
: 'bottom-start'
});
}
else {
this._context._element.appendChild(this.widget);
}
if (this._context._options.display.viewMode == 'clock') {
this._context._action.do(null, ActionTypes.showClock);
}
this.widget
.querySelectorAll('[data-action]')
.forEach((element) => element.addEventListener('click', this._actionsClickEvent));
// show the clock when using sideBySide
if (this._context._options.display.sideBySide) {
this._timeDisplay._update();
this.widget.getElementsByClassName(Namespace.css.clockContainer)[0].style.display = 'grid';
}
}
this.widget.classList.add(Namespace.css.show);
if (!this._context._options.display.inline) {
this._popperInstance.update();
document.addEventListener('click', this._documentClickEvent);
}
this._context._triggerEvent({ type: Namespace.events.show });
this._isVisible = true;
}
/**
* Changes the calendar view mode. E.g. month <-> year
* @param direction -/+ number to move currentViewMode
* @private
*/
_showMode(direction) {
if (!this.widget) {
return;
}
if (direction) {
const max = Math.max(this._context._minViewModeNumber, Math.min(3, this._context._currentViewMode + direction));
if (this._context._currentViewMode == max)
return;
this._context._currentViewMode = max;
}
this.widget
.querySelectorAll(`.${Namespace.css.dateContainer} > div:not(.${Namespace.css.calendarHeader}), .${Namespace.css.timeContainer} > div:not(.${Namespace.css.clockContainer})`)
.forEach((e) => (e.style.display = 'none'));
const datePickerMode = DatePickerModes[this._context._currentViewMode];
let picker = this.widget.querySelector(`.${datePickerMode.className}`);
switch (datePickerMode.className) {
case Namespace.css.decadesContainer:
this._decadeDisplay._update();
break;
case Namespace.css.yearsContainer:
this._yearDisplay._update();
break;
case Namespace.css.monthsContainer:
this._monthDisplay._update();
break;
case Namespace.css.daysContainer:
this._dateDisplay._update();
break;
}
picker.style.display = 'grid';
this._updateCalendarHeader();
}
_updateCalendarHeader() {
const showing = [
...this.widget.querySelector(`.${Namespace.css.dateContainer} div[style*="display: grid"]`).classList
].find((x) => x.startsWith(Namespace.css.dateContainer));
const [previous, switcher, next] = this._context._display.widget
.getElementsByClassName(Namespace.css.calendarHeader)[0]
.getElementsByTagName('div');
switch (showing) {
case Namespace.css.decadesContainer:
previous.setAttribute('title', this._context._options.localization.previousCentury);
switcher.setAttribute('title', '');
next.setAttribute('title', this._context._options.localization.nextCentury);
break;
case Namespace.css.yearsContainer:
previous.setAttribute('title', this._context._options.localization.previousDecade);
switcher.setAttribute('title', this._context._options.localization.selectDecade);
next.setAttribute('title', this._context._options.localization.nextDecade);
break;
case Namespace.css.monthsContainer:
previous.setAttribute('title', this._context._options.localization.previousYear);
switcher.setAttribute('title', this._context._options.localization.selectYear);
next.setAttribute('title', this._context._options.localization.nextYear);
break;
case Namespace.css.daysContainer:
previous.setAttribute('title', this._context._options.localization.previousMonth);
switcher.setAttribute('title', this._context._options.localization.selectMonth);
next.setAttribute('title', this._context._options.localization.nextMonth);
switcher.innerText = this._context._viewDate.format(this._context._options.localization.dayViewHeaderFormat);
break;
}
switcher.innerText = switcher.getAttribute(showing);
}
/**
* Hides the picker if needed.
* Remove document click event to hide when clicking outside the picker.
* @fires Events#hide
*/
hide() {
if (!this.widget || !this._isVisible)
return;
this.widget.classList.remove(Namespace.css.show);
if (this._isVisible) {
this._context._triggerEvent({
type: Namespace.events.hide,
date: this._context._unset
? null
: this._context.dates.lastPicked
? this._context.dates.lastPicked.clone
: void 0
});
this._isVisible = false;
}
document.removeEventListener('click', this._documentClickEvent);
}
/**
* Toggles the picker's open state. Fires a show/hide event depending.
*/
toggle() {
return this._isVisible ? this.hide() : this.show();
}
/**
* Removes document and data-action click listener and reset the widget
* @private
*/
_dispose() {
document.removeEventListener('click', this._documentClickEvent);
if (!this.widget)
return;
this.widget
.querySelectorAll('[data-action]')
.forEach((element) => element.removeEventListener('click', this._actionsClickEvent));
this.widget.parentNode.removeChild(this.widget);
this._widget = undefined;
}
/**
* Builds the widgets html template.
* @private
*/
_buildWidget() {
const template = document.createElement('div');
template.classList.add(Namespace.css.widget);
const dateView = document.createElement('div');
dateView.classList.add(Namespace.css.dateContainer);
dateView.append(this._headTemplate, this._decadeDisplay._picker, this._yearDisplay._picker, this._monthDisplay._picker, this._dateDisplay._picker);
const timeView = document.createElement('div');
timeView.classList.add(Namespace.css.timeContainer);
timeView.appendChild(this._timeDisplay._picker);
timeView.appendChild(this._hourDisplay._picker);
timeView.appendChild(this._minuteDisplay._picker);
timeView.appendChild(this._secondDisplay._picker);
const toolbar = document.createElement('div');
toolbar.classList.add(Namespace.css.toolbar);
toolbar.append(...this._toolbar);
if (this._context._options.display.inline) {
template.classList.add(Namespace.css.inline);
}
if (this._context._options.display.calendarWeeks) {
template.classList.add('calendarWeeks');
}
if (this._context._options.display.sideBySide &&
this._hasDate &&
this._hasTime) {
template.classList.add(Namespace.css.sideBySide);
if (this._context._options.display.toolbarPlacement === 'top') {
template.appendChild(toolbar);
}
const row = document.createElement('div');
row.classList.add('td-row');
dateView.classList.add('td-half');
timeView.classList.add('td-half');
row.appendChild(dateView);
row.appendChild(timeView);
template.appendChild(row);
if (this._context._options.display.toolbarPlacement === 'bottom') {
template.appendChild(toolbar);
}
this._widget = template;
return;
}
if (this._context._options.display.toolbarPlacement === 'top') {
template.appendChild(toolbar);
}
if (this._hasDate) {
if (this._hasTime) {
dateView.classList.add(Namespace.css.collapse);
if (this._context._options.display.viewMode !== 'clock')
dateView.classList.add(Namespace.css.show);
}
template.appendChild(dateView);
}
if (this._hasTime) {
if (this._hasDate) {
timeView.classList.add(Namespace.css.collapse);
if (this._context._options.display.viewMode === 'clock')
timeView.classList.add(Namespace.css.show);
}
template.appendChild(timeView);
}
if (this._context._options.display.toolbarPlacement === 'bottom') {
template.appendChild(toolbar);
}
const arrow = document.createElement('div');
arrow.classList.add('arrow');
arrow.setAttribute('data-popper-arrow', '');
template.appendChild(arrow);
this._widget = template;
}
/**
* Returns true if the hours, minutes, or seconds component is turned on
*/
get _hasTime() {
return (this._context._options.display.components.clock &&
(this._context._options.display.components.hours ||
this._context._options.display.components.minutes ||
this._context._options.display.components.seconds));
}
/**
* Returns true if the year, month, or date component is turned on
*/
get _hasDate() {
return (this._context._options.display.components.calendar &&
(this._context._options.display.components.year ||
this._context._options.display.components.month ||
this._context._options.display.components.date));
}
/**
* Get the toolbar html based on options like buttons.today
* @private
*/
get _toolbar() {
const toolbar = [];
if (this._context._options.display.buttons.today) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.today);
div.setAttribute('title', this._context._options.localization.today);
div.appendChild(this._iconTag(this._context._options.display.icons.today));
toolbar.push(div);
}
if (!this._context._options.display.sideBySide &&
this._hasDate &&
this._hasTime) {
let title, icon;
if (this._context._options.display.viewMode === 'clock') {
title = this._context._options.localization.selectDate;
icon = this._context._options.display.icons.date;
}
else {
title = this._context._options.localization.selectTime;
icon = this._context._options.display.icons.time;
}
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.togglePicker);
div.setAttribute('title', title);
div.appendChild(this._iconTag(icon));
toolbar.push(div);
}
if (this._context._options.display.buttons.clear) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.clear);
div.setAttribute('title', this._context._options.localization.clear);
div.appendChild(this._iconTag(this._context._options.display.icons.clear));
toolbar.push(div);
}
if (this._context._options.display.buttons.close) {
const div = document.createElement('div');
div.setAttribute('data-action', ActionTypes.close);
div.setAttribute('title', this._context._options.localization.close);
div.appendChild(this._iconTag(this._context._options.display.icons.close));
toolbar.push(div);
}
return toolbar;
}
/***
* Builds the base header template with next and previous icons
* @private
*/
get _headTemplate() {
const calendarHeader = document.createElement('div');
calendarHeader.classList.add(Namespace.css.calendarHeader);
const previous = document.createElement('div');
previous.classList.add(Namespace.css.previous);
previous.setAttribute('data-action', ActionTypes.previous);
previous.appendChild(this._iconTag(this._context._options.display.icons.previous));
const switcher = document.createElement('div');
switcher.classList.add(Namespace.css.switch);
switcher.setAttribute('data-action', ActionTypes.pickerSwitch);
const next = document.createElement('div');
next.classList.add(Namespace.css.next);
next.setAttribute('data-action', ActionTypes.next);
next.appendChild(this._iconTag(this._context._options.display.icons.next));
calendarHeader.append(previous, switcher, next);
return calendarHeader;
}
/**
* Builds an icon tag as either an `<i>`
* or with icons.type is `sprites` then an svg tag instead
* @param iconClass
* @private
*/
_iconTag(iconClass) {
if (this._context._options.display.icons.type === 'sprites') {
const svg = document.createElement('svg');
svg.innerHTML = `<use xlink:href='${iconClass}'></use>`;
return svg;
}
const icon = document.createElement('i');
DOMTokenList.prototype.add.apply(icon.classList, iconClass.split(' '));
return icon;
}
/**
* Causes the widget to get rebuilt on next show. If the picker is already open
* then hide and reshow it.
* @private
*/
_rebuild() {
const wasVisible = this._isVisible;
if (wasVisible)
this.hide();
this._dispose();
if (wasVisible) {
this.show();
}
}
} |
JavaScript | class Validation {
constructor(context) {
this._context = context;
}
/**
* Checks to see if the target date is valid based on the rules provided in the options.
* Granularity can be provide to chek portions of the date instead of the whole.
* @param targetDate
* @param granularity
*/
isValid(targetDate, granularity) {
var _a;
if (this._context._options.restrictions.disabledDates.length > 0 &&
this._isInDisabledDates(targetDate)) {
return false;
}
if (this._context._options.restrictions.enabledDates.length > 0 &&
!this._isInEnabledDates(targetDate)) {
return false;
}
if (granularity !== exports.Unit.month &&
granularity !== exports.Unit.year &&
((_a = this._context._options.restrictions.daysOfWeekDisabled) === null || _a === void 0 ? void 0 : _a.length) > 0 &&
this._context._options.restrictions.daysOfWeekDisabled.indexOf(targetDate.weekDay) !== -1) {
return false;
}
if (this._context._options.restrictions.minDate &&
targetDate.isBefore(this._context._options.restrictions.minDate, granularity)) {
return false;
}
if (this._context._options.restrictions.maxDate &&
targetDate.isAfter(this._context._options.restrictions.maxDate, granularity)) {
return false;
}
if (granularity === exports.Unit.hours ||
granularity === exports.Unit.minutes ||
granularity === exports.Unit.seconds) {
if (this._context._options.restrictions.disabledHours.length > 0 &&
this._isInDisabledHours(targetDate)) {
return false;
}
if (this._context._options.restrictions.enabledHours.length > 0 &&
!this._isInEnabledHours(targetDate)) {
return false;
}
if (this._context._options.restrictions.disabledTimeIntervals.length > 0) {
for (let i = 0; i < this._context._options.restrictions.disabledTimeIntervals.length; i++) {
if (targetDate.isBetween(this._context._options.restrictions.disabledTimeIntervals[i].from, this._context._options.restrictions.disabledTimeIntervals[i].to))
return false;
}
}
}
return true;
}
/**
* Checks to see if the disabledDates option is in use and returns true (meaning invalid)
* if the `testDate` is with in the array. Granularity is by date.
* @param testDate
* @private
*/
_isInDisabledDates(testDate) {
if (!this._context._options.restrictions.disabledDates ||
this._context._options.restrictions.disabledDates.length === 0)
return false;
const formattedDate = testDate.format(Dates.getFormatByUnit(exports.Unit.date));
return this._context._options.restrictions.disabledDates
.map((x) => x.format(Dates.getFormatByUnit(exports.Unit.date)))
.find((x) => x === formattedDate);
}
/**
* Checks to see if the enabledDates option is in use and returns true (meaning valid)
* if the `testDate` is with in the array. Granularity is by date.
* @param testDate
* @private
*/
_isInEnabledDates(testDate) {
if (!this._context._options.restrictions.enabledDates ||
this._context._options.restrictions.enabledDates.length === 0)
return true;
const formattedDate = testDate.format(Dates.getFormatByUnit(exports.Unit.date));
return this._context._options.restrictions.enabledDates
.map((x) => x.format(Dates.getFormatByUnit(exports.Unit.date)))
.find((x) => x === formattedDate);
}
/**
* Checks to see if the disabledHours option is in use and returns true (meaning invalid)
* if the `testDate` is with in the array. Granularity is by hours.
* @param testDate
* @private
*/
_isInDisabledHours(testDate) {
if (!this._context._options.restrictions.disabledHours ||
this._context._options.restrictions.disabledHours.length === 0)
return false;
const formattedDate = testDate.hours;
return this._context._options.restrictions.disabledHours.find((x) => x === formattedDate);
}
/**
* Checks to see if the enabledHours option is in use and returns true (meaning valid)
* if the `testDate` is with in the array. Granularity is by hours.
* @param testDate
* @private
*/
_isInEnabledHours(testDate) {
if (!this._context._options.restrictions.enabledHours ||
this._context._options.restrictions.enabledHours.length === 0)
return true;
const formattedDate = testDate.hours;
return this._context._options.restrictions.enabledHours.find((x) => x === formattedDate);
}
} |
JavaScript | class TempusDominus {
constructor(element, options = {}) {
this._currentViewMode = 0;
this._subscribers = {};
this._minViewModeNumber = 0;
this._isDisabled = false;
this._notifyChangeEventContext = 0;
this._viewDate = new DateTime();
/**
* Event for when the input field changes. This is a class level method so there's
* something for the remove listener function.
* @private
*/
this._inputChangeEvent = () => {
const setViewDate = () => {
if (this.dates.lastPicked)
this._viewDate = this.dates.lastPicked;
};
const value = this._input.value;
if (this._options.multipleDates) {
try {
const valueSplit = value.split(this._options.multipleDatesSeparator);
for (let i = 0; i < valueSplit.length; i++) {
if (this._options.hooks.inputParse) {
this.dates.set(this._options.hooks.inputParse(this, valueSplit[i]), i, 'input');
}
else {
this.dates.set(valueSplit[i], i, 'input');
}
}
setViewDate();
}
catch (_a) {
console.warn('TD: Something went wrong trying to set the multidate values from the input field.');
}
}
else {
if (this._options.hooks.inputParse) {
this.dates.set(this._options.hooks.inputParse(this, value), 0, 'input');
}
else {
this.dates.set(value, 0, 'input');
}
setViewDate();
}
};
/**
* Event for when the toggle is clicked. This is a class level method so there's
* something for the remove listener function.
* @private
*/
this._toggleClickEvent = () => {
this.toggle();
};
if (!element) {
Namespace.errorMessages.mustProvideElement;
}
this._element = element;
this._options = this._initializeOptions(options, DefaultOptions, true);
this._viewDate.setLocale(this._options.localization.locale);
this._unset = true;
this._display = new Display(this);
this._validation = new Validation(this);
this.dates = new Dates(this);
this._action = new Actions(this);
this._initializeInput();
this._initializeToggle();
if (this._options.display.inline)
this._display.show();
}
get viewDate() {
return this._viewDate;
}
// noinspection JSUnusedGlobalSymbols
/**
* Update the picker options. If `reset` is provide `options` will be merged with DefaultOptions instead.
* @param options
* @param reset
* @public
*/
updateOptions(options, reset = false) {
if (reset)
this._options = this._initializeOptions(options, DefaultOptions);
else
this._options = this._initializeOptions(options, this._options);
this._display._rebuild();
}
// noinspection JSUnusedGlobalSymbols
/**
* Toggles the picker open or closed. If the picker is disabled, nothing will happen.
* @public
*/
toggle() {
if (this._isDisabled)
return;
this._display.toggle();
}
// noinspection JSUnusedGlobalSymbols
/**
* Shows the picker unless the picker is disabled.
* @public
*/
show() {
if (this._isDisabled)
return;
this._display.show();
}
// noinspection JSUnusedGlobalSymbols
/**
* Hides the picker unless the picker is disabled.
* @public
*/
hide() {
this._display.hide();
}
// noinspection JSUnusedGlobalSymbols
/**
* Disables the picker and the target input field.
* @public
*/
disable() {
var _a;
this._isDisabled = true;
// todo this might be undesired. If a dev disables the input field to
// only allow using the picker, this will break that.
(_a = this._input) === null || _a === void 0 ? void 0 : _a.setAttribute('disabled', 'disabled');
this._display.hide();
}
// noinspection JSUnusedGlobalSymbols
/**
* Enables the picker and the target input field.
* @public
*/
enable() {
var _a;
this._isDisabled = false;
(_a = this._input) === null || _a === void 0 ? void 0 : _a.removeAttribute('disabled');
}
// noinspection JSUnusedGlobalSymbols
/**
* Clears all the selected dates
* @public
*/
clear() {
this.dates.clear();
}
// noinspection JSUnusedGlobalSymbols
/**
* Allows for a direct subscription to picker events, without having to use addEventListener on the element.
* @param eventTypes See Namespace.Events
* @param callbacks Function to call when event is triggered
* @public
*/
subscribe(eventTypes, callbacks) {
if (typeof eventTypes === 'string') {
eventTypes = [eventTypes];
}
let callBackArray = [];
if (!Array.isArray(callbacks)) {
callBackArray = [callbacks];
}
else {
callBackArray = callbacks;
}
if (eventTypes.length !== callBackArray.length) {
Namespace.errorMessages.subscribeMismatch;
}
const returnArray = [];
for (let i = 0; i < eventTypes.length; i++) {
const eventType = eventTypes[i];
if (!Array.isArray(this._subscribers[eventType])) {
this._subscribers[eventType] = [];
}
this._subscribers[eventType].push(callBackArray[i]);
returnArray.push({
unsubscribe: this._unsubscribe.bind(this, eventType, this._subscribers[eventType].length - 1),
});
if (eventTypes.length === 1) {
return returnArray[0];
}
}
return returnArray;
}
// noinspection JSUnusedGlobalSymbols
/**
* Hides the picker and removes event listeners
*/
dispose() {
var _a, _b;
this._display.hide();
// this will clear the document click event listener
this._display._dispose();
(_a = this._input) === null || _a === void 0 ? void 0 : _a.removeEventListener('change', this._inputChangeEvent);
if (this._options.allowInputToggle) {
(_b = this._input) === null || _b === void 0 ? void 0 : _b.removeEventListener('click', this._toggleClickEvent);
}
this._toggle.removeEventListener('click', this._toggleClickEvent);
this._subscribers = {};
}
/**
* Triggers an event like ChangeEvent when the picker has updated the value
* of a selected date.
* @param event Accepts a BaseEvent object.
* @private
*/
_triggerEvent(event) {
// checking hasOwnProperty because the BasicEvent also falls through here otherwise
if (event && event.hasOwnProperty('date')) {
const { date, oldDate, isClear } = event;
// this was to prevent a max call stack error
// https://github.com/tempusdominus/core/commit/15a280507f5277b31b0b3319ab1edc7c19a000fb
// todo see if this is still needed or if there's a cleaner way
this._notifyChangeEventContext++;
if ((date && oldDate && date.isSame(oldDate)) ||
(!isClear && !date && !oldDate) ||
this._notifyChangeEventContext > 1) {
this._notifyChangeEventContext = 0;
return;
}
this._handleAfterChangeEvent(event);
}
this._element.dispatchEvent(new CustomEvent(event.type, { detail: event }));
if (window.jQuery) {
const $ = window.jQuery;
$(this._element).trigger(event);
}
const publish = () => {
// return if event is not subscribed
if (!Array.isArray(this._subscribers[event.type])) {
return;
}
// Trigger callback for each subscriber
this._subscribers[event.type].forEach((callback) => {
callback(event);
});
};
publish();
this._notifyChangeEventContext = 0;
}
/**
* Fires a ViewUpdate event when, for example, the month view is changed.
* @param {Unit} unit
* @private
*/
_viewUpdate(unit) {
this._triggerEvent({
type: Namespace.events.update,
change: unit,
viewDate: this._viewDate.clone,
});
}
_unsubscribe(eventName, index) {
this._subscribers[eventName].splice(index, 1);
}
/**
* Merges two Option objects together and validates options type
* @param config new Options
* @param mergeTo Options to merge into
* @param includeDataset When true, the elements data-td attributes will be included in the
* @private
*/
_initializeOptions(config, mergeTo, includeDataset = false) {
var _a;
config = OptionConverter._mergeOptions(config, mergeTo);
if (includeDataset)
config = OptionConverter._dataToOptions(this._element, config);
OptionConverter._validateConflcits(config);
config.viewDate = config.viewDate.setLocale(config.localization.locale);
if (!this._viewDate.isSame(config.viewDate)) {
this._viewDate = config.viewDate;
}
/**
* Sets the minimum view allowed by the picker. For example the case of only
* allowing year and month to be selected but not date.
*/
if (config.display.components.year) {
this._minViewModeNumber = 2;
}
if (config.display.components.month) {
this._minViewModeNumber = 1;
}
if (config.display.components.date) {
this._minViewModeNumber = 0;
}
this._currentViewMode = Math.max(this._minViewModeNumber, this._currentViewMode);
// Update view mode if needed
if (DatePickerModes[this._currentViewMode].name !== config.display.viewMode) {
this._currentViewMode = Math.max(DatePickerModes.findIndex((x) => x.name === config.display.viewMode), this._minViewModeNumber);
}
// defaults the input format based on the components enabled
if (config.hooks.inputFormat === undefined) {
const components = config.display.components;
config.hooks.inputFormat = (_, date) => {
if (!date)
return '';
return date.format({
year: components.calendar && components.year ? 'numeric' : undefined,
month: components.calendar && components.month ? '2-digit' : undefined,
day: components.calendar && components.date ? '2-digit' : undefined,
hour: components.clock && components.hours
? components.useTwentyfourHour
? '2-digit'
: 'numeric'
: undefined,
minute: components.clock && components.minutes ? '2-digit' : undefined,
second: components.clock && components.seconds ? '2-digit' : undefined,
hour12: !components.useTwentyfourHour,
});
};
}
if ((_a = this._display) === null || _a === void 0 ? void 0 : _a.isVisible) {
this._display._update('all');
}
return config;
}
/**
* Checks if an input field is being used, attempts to locate one and sets an
* event listener if found.
* @private
*/
_initializeInput() {
if (this._element.tagName == 'INPUT') {
this._input = this._element;
}
else {
let query = this._element.dataset.tdTargetInput;
if (query == undefined || query == 'nearest') {
this._input = this._element.querySelector('input');
}
else {
this._input = this._element.querySelector(query);
}
}
if (!this._input)
return;
this._input.addEventListener('change', this._inputChangeEvent);
if (this._options.allowInputToggle) {
this._input.addEventListener('click', this._toggleClickEvent);
}
if (this._input.value) {
this._inputChangeEvent();
}
}
/**
* Attempts to locate a toggle for the picker and sets an event listener
* @private
*/
_initializeToggle() {
if (this._options.display.inline)
return;
let query = this._element.dataset.tdTargetToggle;
if (query == 'nearest') {
query = '[data-td-toggle="datetimepicker"]';
}
this._toggle =
query == undefined ? this._element : this._element.querySelector(query);
this._toggle.addEventListener('click', this._toggleClickEvent);
}
/**
* If the option is enabled this will render the clock view after a date pick.
* @param e change event
* @private
*/
_handleAfterChangeEvent(e) {
var _a, _b;
if (
// options is disabled
!this._options.promptTimeOnDateChange ||
this._options.display.inline ||
this._options.display.sideBySide ||
// time is disabled
!this._display._hasTime ||
(
// clock component is already showing
(_a = this._display.widget) === null || _a === void 0 ? void 0 : _a.getElementsByClassName(Namespace.css.show)[0].classList.contains(Namespace.css.timeContainer)))
return;
// First time ever. If useCurrent option is set to true (default), do nothing
// because the first date is selected automatically.
// or date didn't change (time did) or date changed because time did.
if ((!e.oldDate && this._options.useCurrent) ||
(e.oldDate && ((_b = e.date) === null || _b === void 0 ? void 0 : _b.isSame(e.oldDate)))) {
return;
}
clearTimeout(this._currentPromptTimeTimeout);
this._currentPromptTimeTimeout = setTimeout(() => {
if (this._display.widget) {
this._action.do({
currentTarget: this._display.widget.querySelector(`.${Namespace.css.switch} div`),
}, ActionTypes.togglePicker);
}
}, this._options.promptTimeOnDateChangeTransitionDelay);
}
} |
JavaScript | class Application extends Base {
constructor(client, data) {
super(client);
this._patch(data);
}
_patch(data) {
/**
* The ID of the app
* @type {Snowflake}
*/
this.id = data.id;
/**
* The name of the app
* @type {?string}
*/
this.name = data.name ?? this.name ?? null;
/**
* The app's description
* @type {?string}
*/
this.description = data.description ?? this.description ?? null;
/**
* The app's icon hash
* @type {?string}
*/
this.icon = data.icon ?? this.icon ?? null;
}
/**
* The timestamp the app was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return SnowflakeUtil.deconstruct(this.id).timestamp;
}
/**
* The time the app was created at
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* A link to the application's icon.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string} URL to the icon
*/
iconURL({ format, size } = {}) {
if (!this.icon) return null;
return this.client.rest.cdn.AppIcon(this.id, this.icon, { format, size });
}
/**
* A link to this application's cover image.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string} URL to the cover image
*/
coverImage({ format, size } = {}) {
if (!this.cover) return null;
return Endpoints.CDN(this.client.options.http.cdn).AppIcon(this.id, this.cover, { format, size });
}
/**
* Asset data.
* @typedef {Object} ApplicationAsset
* @property {Snowflake} id The asset ID
* @property {string} name The asset name
* @property {string} type The asset type
*/
/**
* Gets the clients rich presence assets.
* @returns {Promise<Array<ApplicationAsset>>}
*/
fetchAssets() {
return this.client.api.oauth2
.applications(this.id)
.assets.get()
.then(assets =>
assets.map(a => ({
id: a.id,
name: a.name,
type: AssetTypes[a.type - 1],
})),
);
}
/**
* When concatenated with a string, this automatically returns the application's name instead of the
* Oauth2Application object.
* @returns {?string}
* @example
* // Logs: Application name: My App
* console.log(`Application name: ${application}`);
*/
toString() {
return this.name;
}
toJSON() {
return super.toJSON({ createdTimestamp: true });
}
} |
JavaScript | class MVT extends FeatureFormat {
/**
* @param {Options=} opt_options Options.
*/
constructor(opt_options) {
super();
const options = opt_options ? opt_options : {};
/**
* @type {Projection}
*/
this.dataProjection = new Projection({
code: '',
units: Units.TILE_PIXELS
});
/**
* @private
* @type {import("../Feature.js").FeatureClass}
*/
this.featureClass_ = options.featureClass ? options.featureClass : RenderFeature;
/**
* @private
* @type {string|undefined}
*/
this.geometryName_ = options.geometryName;
/**
* @private
* @type {string}
*/
this.layerName_ = options.layerName ? options.layerName : 'layer';
/**
* @private
* @type {Array<string>}
*/
this.layers_ = options.layers ? options.layers : null;
/**
* @private
* @type {string}
*/
this.idProperty_ = options.idProperty;
}
/**
* Read the raw geometry from the pbf offset stored in a raw feature's geometry
* property.
* @param {PBF} pbf PBF.
* @param {Object} feature Raw feature.
* @param {Array<number>} flatCoordinates Array to store flat coordinates in.
* @param {Array<number>} ends Array to store ends in.
* @private
*/
readRawGeometry_(pbf, feature, flatCoordinates, ends) {
pbf.pos = feature.geometry;
const end = pbf.readVarint() + pbf.pos;
let cmd = 1;
let length = 0;
let x = 0;
let y = 0;
let coordsLen = 0;
let currentEnd = 0;
while (pbf.pos < end) {
if (!length) {
const cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
length = cmdLen >> 3;
}
length--;
if (cmd === 1 || cmd === 2) {
x += pbf.readSVarint();
y += pbf.readSVarint();
if (cmd === 1) { // moveTo
if (coordsLen > currentEnd) {
ends.push(coordsLen);
currentEnd = coordsLen;
}
}
flatCoordinates.push(x, y);
coordsLen += 2;
} else if (cmd === 7) {
if (coordsLen > currentEnd) {
// close polygon
flatCoordinates.push(
flatCoordinates[currentEnd], flatCoordinates[currentEnd + 1]);
coordsLen += 2;
}
} else {
assert(false, 59); // Invalid command found in the PBF
}
}
if (coordsLen > currentEnd) {
ends.push(coordsLen);
currentEnd = coordsLen;
}
}
/**
* @private
* @param {PBF} pbf PBF
* @param {Object} rawFeature Raw Mapbox feature.
* @param {import("./Feature.js").ReadOptions} options Read options.
* @return {import("../Feature.js").FeatureLike} Feature.
*/
createFeature_(pbf, rawFeature, options) {
const type = rawFeature.type;
if (type === 0) {
return null;
}
let feature;
const values = rawFeature.properties;
let id;
if (!this.idProperty_) {
id = rawFeature.id;
} else {
id = values[this.idProperty_];
delete values[this.idProperty_];
}
values[this.layerName_] = rawFeature.layer.name;
const flatCoordinates = [];
const ends = [];
this.readRawGeometry_(pbf, rawFeature, flatCoordinates, ends);
const geometryType = getGeometryType(type, ends.length);
if (this.featureClass_ === RenderFeature) {
feature = new this.featureClass_(geometryType, flatCoordinates, ends, values, id);
feature.transform(options.dataProjection, options.featureProjection);
} else {
let geom;
if (geometryType == GeometryType.POLYGON) {
const endss = [];
let offset = 0;
let prevEndIndex = 0;
for (let i = 0, ii = ends.length; i < ii; ++i) {
const end = ends[i];
if (!linearRingIsClockwise(flatCoordinates, offset, end, 2)) {
endss.push(ends.slice(prevEndIndex, i));
prevEndIndex = i;
}
offset = end;
}
if (endss.length > 1) {
geom = new MultiPolygon(flatCoordinates, GeometryLayout.XY, endss);
} else {
geom = new Polygon(flatCoordinates, GeometryLayout.XY, ends);
}
} else {
geom = geometryType === GeometryType.POINT ? new Point(flatCoordinates, GeometryLayout.XY) :
geometryType === GeometryType.LINE_STRING ? new LineString(flatCoordinates, GeometryLayout.XY) :
geometryType === GeometryType.POLYGON ? new Polygon(flatCoordinates, GeometryLayout.XY, ends) :
geometryType === GeometryType.MULTI_POINT ? new MultiPoint(flatCoordinates, GeometryLayout.XY) :
geometryType === GeometryType.MULTI_LINE_STRING ? new MultiLineString(flatCoordinates, GeometryLayout.XY, ends) :
null;
}
const ctor = /** @type {typeof import("../Feature.js").default} */ (this.featureClass_);
feature = new ctor();
if (this.geometryName_) {
feature.setGeometryName(this.geometryName_);
}
const geometry = transformGeometryWithOptions(geom, false, options);
feature.setGeometry(geometry);
feature.setId(id);
feature.setProperties(values, true);
}
return feature;
}
/**
* @inheritDoc
*/
getType() {
return FormatType.ARRAY_BUFFER;
}
/**
* Read all features.
*
* @param {ArrayBuffer} source Source.
* @param {import("./Feature.js").ReadOptions=} opt_options Read options.
* @return {Array<import("../Feature.js").FeatureLike>} Features.
* @api
*/
readFeatures(source, opt_options) {
const layers = this.layers_;
const options = /** @type {import("./Feature.js").ReadOptions} */ (this.adaptOptions(opt_options));
const dataProjection = get(options.dataProjection);
dataProjection.setWorldExtent(options.extent);
options.dataProjection = dataProjection;
const pbf = new PBF(/** @type {ArrayBuffer} */ (source));
const pbfLayers = pbf.readFields(layersPBFReader, {});
const features = [];
for (const name in pbfLayers) {
if (layers && layers.indexOf(name) == -1) {
continue;
}
const pbfLayer = pbfLayers[name];
const extent = pbfLayer ? [0, 0, pbfLayer.extent, pbfLayer.extent] : null;
dataProjection.setExtent(extent);
for (let i = 0, ii = pbfLayer.length; i < ii; ++i) {
const rawFeature = readRawFeature(pbf, pbfLayer, i);
features.push(this.createFeature_(pbf, rawFeature, options));
}
}
return features;
}
/**
* @inheritDoc
* @api
*/
readProjection(source) {
return this.dataProjection;
}
/**
* Sets the layers that features will be read from.
* @param {Array<string>} layers Layers.
* @api
*/
setLayers(layers) {
this.layers_ = layers;
}
} |
JavaScript | class GoveePlatform {
constructor (log, config, api) {
// Don't load the plugin if these aren't accessible for any reason
if (!log || !api) {
return
}
// Begin plugin initialisation
try {
this.api = api
this.consts = require('./utils/constants')
this.funcs = require('./utils/functions')
this.log = log
// Configuration objects for accessories
this.deviceConf = {}
this.ignoredDevices = []
// Retrieve the user's chosen language file
this.lang = require('./utils/lang-en')
// Make sure user is running Homebridge v1.3 or above
if (!api.versionGreaterOrEqual || !api.versionGreaterOrEqual('1.3.0')) {
throw new Error(this.lang.hbVersionFail)
}
// Check the user has configured the plugin
if (!config) {
throw new Error(this.lang.pluginNotConf)
}
// Log some environment info for debugging
this.log(
'%s v%s | Node %s | HB v%s | HAPNodeJS v%s%s...',
this.lang.initialising,
plugin.version,
process.version,
api.serverVersion,
api.hap.HAPLibraryVersion ? api.hap.HAPLibraryVersion() : '?',
config.plugin_map
? ' | HOOBS v3'
: require('os')
.hostname()
.includes('hoobs')
? ' | HOOBS v4'
: ''
)
// Apply the user's configuration
this.config = this.consts.defaultConfig
this.applyUserConfig(config)
// Set up the Homebridge events
this.api.on('didFinishLaunching', () => this.pluginSetup())
this.api.on('shutdown', () => this.pluginShutdown())
} catch (err) {
// Catch any errors during initialisation
const eText = this.funcs.parseError(err, [this.lang.hbVersionFail, this.lang.pluginNotConf])
log.warn('***** %s. *****', this.lang.disabling)
log.warn('***** %s. *****', eText)
}
}
applyUserConfig (config) {
// These shorthand functions save line space during config parsing
const logDefault = (k, def) => {
this.log.warn('%s [%s] %s %s.', this.lang.cfgItem, k, this.lang.cfgDef, def)
}
const logDuplicate = k => {
this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgDup)
}
const logIgnore = k => {
this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgIgn)
}
const logIgnoreItem = k => {
this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgIgnItem)
}
const logIncrease = (k, min) => {
this.log.warn('%s [%s] %s %s.', this.lang.cfgItem, k, this.lang.cfgLow, min)
}
const logQuotes = k => {
this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgQts)
}
const logRemove = k => {
this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgRmv)
}
// Begin applying the user's config
for (const [key, val] of Object.entries(config)) {
switch (key) {
case 'apiKey':
case 'password':
case 'username':
if (typeof val !== 'string' || val === '') {
logIgnore(key)
} else {
if (key === 'apiKey') {
this.config[key] = val.toLowerCase().replace(/[^a-z0-9-]+/g, '')
} else {
this.config[key] = val
}
}
break
case 'controlInterval':
case 'refreshTime': {
if (typeof val === 'string') {
logQuotes(key)
}
const intVal = parseInt(val)
if (isNaN(intVal)) {
logDefault(key, this.consts.defaultValues[key])
this.config[key] = this.consts.defaultValues[key]
} else if (intVal < this.consts.minValues[key]) {
logIncrease(key, this.consts.minValues[key])
this.config[key] = this.consts.minValues[key]
} else {
this.config[key] = intVal
}
break
}
case 'debug':
case 'debugFakegato':
case 'disableDeviceLogging':
case 'disablePlugin':
case 'offlineAsOff':
if (typeof val === 'string') {
logQuotes(key)
}
this.config[key] = val === 'false' ? false : !!val
break
case 'heaterDevices':
case 'humidifierDevices':
case 'leakDevices':
case 'lightDevices':
case 'purifierDevices':
case 'switchDevices':
case 'thermoDevices':
if (Array.isArray(val) && val.length > 0) {
val.forEach(x => {
if (!x.deviceId) {
logIgnoreItem(key)
return
}
const id = this.funcs.parseDeviceId(x.deviceId)
if (Object.keys(this.deviceConf).includes(id)) {
logDuplicate(key + '.' + id)
return
}
const entries = Object.entries(x)
if (entries.length === 1) {
logRemove(key + '.' + id)
return
}
this.deviceConf[id] = {}
for (const [k, v] of entries) {
if (!this.consts.allowed[key].includes(k)) {
logRemove(key + '.' + id + '.' + k)
continue
}
switch (k) {
case 'adaptiveLightingShift':
case 'brightnessStep':
case 'lowBattThreshold': {
if (typeof v === 'string') {
logQuotes(key + '.' + k)
}
const intVal = parseInt(v)
if (isNaN(intVal)) {
logDefault(key + '.' + id + '.' + k, this.consts.defaultValues[k])
this.deviceConf[id][k] = this.consts.defaultValues[k]
} else if (intVal < this.consts.minValues[k]) {
logIncrease(key + '.' + id + '.' + k, this.consts.minValues[k])
this.deviceConf[id][k] = this.consts.minValues[k]
} else {
this.deviceConf[id][k] = intVal
}
break
}
case 'customAddress':
case 'diyMode':
case 'diyModeTwo':
case 'diyModeThree':
case 'diyModeFour':
case 'musicMode':
case 'musicModeTwo':
case 'scene':
case 'sceneTwo':
case 'sceneThree':
case 'sceneFour':
case 'segmented':
case 'segmentedTwo':
case 'segmentedThree':
case 'segmentedFour':
case 'temperatureSource':
case 'videoMode':
case 'videoModeTwo':
if (typeof v !== 'string' || v === '') {
logIgnore(key + '.' + id + '.' + k)
} else {
this.deviceConf[id][k] = v.replace(/[\s]+/g, '')
}
break
case 'deviceId':
case 'label':
break
case 'disableAWS':
case 'enableBT':
if (typeof v === 'string') {
logQuotes(key + '.' + id + '.' + k)
}
this.deviceConf[id][k] = v === 'false' ? false : !!v
break
case 'ignoreDevice':
if (typeof v === 'string') {
logQuotes(key + '.' + id + '.' + k)
}
if (!!v && v !== 'false') {
this.ignoredDevices.push(id)
}
break
case 'overrideLogging':
case 'showAs': {
const inSet = this.consts.allowed[k].includes(v)
if (typeof v !== 'string' || !inSet) {
logIgnore(key + '.' + id + '.' + k)
} else {
this.deviceConf[id][k] = inSet ? v : this.consts.defaultValues[k]
}
break
}
}
}
})
} else {
logIgnore(key)
}
break
case 'name':
case 'platform':
case 'plugin_map':
break
default:
logRemove(key)
break
}
}
}
async pluginSetup () {
// Plugin has finished initialising so now onto setup
try {
// If the user has disabled the plugin then remove all accessories
if (this.config.disablePlugin) {
devicesInHB.forEach(accessory => this.removeAccessory(accessory))
throw new Error(this.lang.disabled)
}
// Log that the plugin initialisation has been successful
this.log('%s.', this.lang.initialised)
// Require any libraries that the plugin uses
this.colourUtils = require('./utils/colour-utils')
this.cusChar = new (require('./utils/custom-chars'))(this.api)
this.eveChar = new (require('./utils/eve-chars'))(this.api)
this.eveService = require('./fakegato/fakegato-history')(this.api)
// Persist files are used to store device info that can be used by my other plugins
try {
this.storageData = storage.create({
dir: require('path').join(this.api.user.persistPath(), '/../bwp91_cache'),
forgiveParseErrors: true
})
await this.storageData.init()
this.storageClientData = true
} catch (err) {
if (this.config.debug) {
const eText = this.funcs.parseError(err)
this.log.warn('%s %s.', this.lang.storageSetupErr, eText)
}
}
// Setup the HTTP client if Govee username and password have been provided
try {
if (!this.config.username || !this.config.password) {
throw new Error(this.lang.noCreds)
}
httpClient = new (require('./connection/http'))(this)
const data = await httpClient.login()
this.accountTopic = data.topic
const devices = await httpClient.getDevices()
if (!Array.isArray(devices)) {
throw new Error(this.lang.noDevList)
}
devices.forEach(device => httpDevices.push(device))
} catch (err) {
const eText = this.funcs.parseError(err, [this.lang.noCreds, this.lang.noDevList])
this.log.warn('%s %s.', this.lang.disableHTTP, eText)
}
// Setup the API client if Govee API token has been provided
try {
if (!this.config.apiKey) {
throw new Error(this.lang.noAPIKey)
}
apiClient = new (require('./connection/api'))(this)
const devices = await apiClient.getDevices()
if (!Array.isArray(devices)) {
throw new Error(this.lang.noDevList)
}
devices.forEach(device => apiDevices.push(device))
} catch (err) {
const eText = err.message.includes('401')
? this.lang.invalidApiKey
: this.funcs.parseError(err, [this.lang.noAPIKey, this.lang.noDevList])
this.log.warn('%s %s.', this.lang.disableAPI, eText)
apiClient = false
}
// Setup the bluetooth client
try {
// See if the bluetooth client is available
/*
Noble sends the plugin into a crash loop if there is no bluetooth adapter available
This if statement follows the logic of Noble up to the offending socket.bindRaw(device)
Put inside a try/catch now to check for error and disable ble control for rest of plugin
*/
if (['linux', 'freebsd', 'win32'].includes(require('os').platform())) {
const socket = new (require('@abandonware/bluetooth-hci-socket'))()
const device = process.env.NOBLE_HCI_DEVICE_ID
? parseInt(process.env.NOBLE_HCI_DEVICE_ID, 10)
: undefined
socket.bindRaw(device)
}
try {
require('@abandonware/noble')
} catch (err) {
throw new Error(this.lang.btNoPackage)
}
if (Object.values(this.deviceConf).filter(el => el.enableBT).length === 0) {
throw new Error(this.lang.btNoDevices)
}
bleClient = new (require('./connection/ble'))(this)
this.log('%s.', this.lang.btAvailable)
} catch (err) {
// This error thrown from bluetooth-hci-socket does not contain an err.message
if (err.code === 'ERR_DLOPEN_FAILED') {
err.message = 'ERR_DLOPEN_FAILED'
}
const eText = this.funcs.parseError(err, [
this.lang.btNoPackage,
this.lang.btNoDevices,
'ENODEV, No such device',
'ERR_DLOPEN_FAILED'
])
this.log.warn('%s %s.', this.lang.disableBT, eText)
bleClient = false
}
// Initialise the devices
let httpSyncNeeded = false
if (httpDevices && httpDevices.length > 0) {
// We have some devices from HTTP client
httpDevices.forEach(httpDevice => {
// It appears sometimes the deviceid isn't quite in the form I first expected
if (httpDevice.device.length === 16) {
// Eg converts abcd1234abcd1234 to AB:CD:12:34:AB:CD:12:34
httpDevice.device = httpDevice.device.replace(/..\B/g, '$&:').toUpperCase()
}
// Sets the flag to see if we need to setup the HTTP sync
if (
[...this.consts.models.leak, ...this.consts.models.thermoWifi].includes(httpDevice.sku)
) {
httpSyncNeeded = true
}
// Check it's not a user-ignored device
if (this.ignoredDevices.includes(httpDevice.device)) {
return
}
// Find the any matching device from the API client
const apiDevice = apiDevices.find(el => el.device === httpDevice.device)
if (apiDevice) {
// Device exists in API data so add the http info to the API object and initialise
apiDevice.httpInfo = httpDevice
apiDevice.isAPIDevice = true
// Initialise the device into Homebridge
this.initialiseDevice(apiDevice)
} else {
// Device doesn't exist in API data, but try to initialise as could be other device type
this.initialiseDevice({
device: httpDevice.device,
deviceName: httpDevice.deviceName,
model: httpDevice.sku,
httpInfo: httpDevice,
isAPIDevice: false
})
}
})
} else if (apiDevices && apiDevices.length > 0) {
// No devices from HTTP client, but API token has been given, and devices exist there
apiDevices.forEach(apiDevice => {
// Check it's not a user-ignored device
if (this.ignoredDevices.includes(apiDevice.device)) {
return
}
// Initialise the device into Homebridge
apiDevice.isAPIDevice = true
this.initialiseDevice(apiDevice)
})
} else {
// No devices either from HTTP client or API client
throw new Error(this.lang.noDevs)
}
// Check for redundant Homebridge accessories
devicesInHB.forEach(async accessory => {
// If the accessory doesn't exist in Govee then remove it
if (
(!httpDevices.some(el => el.device === accessory.context.gvDeviceId) &&
!apiDevices.some(el => el.device === accessory.context.gvDeviceId)) ||
this.ignoredDevices.includes(accessory.context.gvDeviceId)
) {
this.removeAccessory(accessory)
}
})
// Setup the http client sync needed for leak and thermo sensor devices
if (httpSyncNeeded) {
this.goveeHTTPSync()
this.refreshHTTPInterval = setInterval(
() => this.goveeHTTPSync(),
this.config.refreshTime * 1000
)
}
// Setup the API client sync used for API token models
if (apiClient) {
this.goveeAPISync()
this.refreshAPIInterval = setInterval(
() => this.goveeAPISync(),
this.config.refreshTime * 1000
)
}
// Log that the plugin setup has been successful with a welcome message
const randIndex = Math.floor(Math.random() * this.lang.zWelcome.length)
setTimeout(() => {
this.log('%s. %s', this.lang.complete, this.lang.zWelcome[randIndex])
}, 2000)
} catch (err) {
// Catch any errors during setup
const eText = this.funcs.parseError(err, [this.lang.noDevs, this.lang.disabled])
this.log.warn('***** %s. *****', this.lang.disabling)
this.log.warn('***** %s. *****', eText)
this.pluginShutdown()
}
}
pluginShutdown () {
// A function that is called when the plugin fails to load or Homebridge restarts
try {
// Stop the refresh intervals
if (this.refreshHTTPInterval) {
clearInterval(this.refreshHTTPInterval)
}
if (this.refreshAPIInterval) {
clearInterval(this.refreshAPIInterval)
}
} catch (err) {
// No need to show errors at this point
}
}
initialiseDevice (device) {
// Get the correct device type instance for the device
try {
const deviceConf = this.deviceConf[device.device] || {}
const uuid = this.api.hap.uuid.generate(device.device)
let instance
if (this.consts.models.rgb.includes(device.model)) {
// Device is an API enabled wifi (and maybe bluetooth) LED strip/bulb
instance = 'light-colour'
} else if (this.consts.models.rgbBT.includes(device.model)) {
// Device is a bluetooth-only LED strip/bulb, check it's configured and ble enabled
if (deviceConf.enableBT) {
instance = 'light-colour-bt'
} else {
// Not configured, so remove if exists, log a helpful message, and return
if (devicesInHB.has(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
this.log('[%s] [%s] %s.', device.deviceName, device.device, this.lang.devNotBT)
return
}
} else if (this.consts.models.switchSingle.includes(device.model)) {
// Device is an API enabled wifi switch
instance = deviceConf.showAs || this.consts.defaultValues.showAs
switch (instance) {
case 'heater':
case 'cooler': {
if (!deviceConf.temperatureSource) {
this.log.warn('[%s] %s.', device.deviceName, this.lang.heaterSimNoSensor)
if (devicesInHB.has(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
return
}
break
}
case 'default':
instance = 'outlet'
break
}
instance += '-single'
} else if (this.consts.models.switchDouble.includes(device.model)) {
// Device is an API enabled wifi double switch
instance = deviceConf.showAs || this.consts.defaultValues.showAs
if (['audio', 'box', 'default', 'purifier', 'stick', 'tap', 'valve'].includes(instance)) {
instance = 'outlet'
}
instance += '-double'
} else if (this.consts.models.leak.includes(device.model)) {
// Device is a leak sensor
instance = 'sensor-leak'
} else if (this.consts.models.thermoWifi.includes(device.model)) {
// Device is a wifi (supported) thermo-hygrometer sensor
instance = 'sensor-thermo'
} else if (this.consts.models.thermoBLE.includes(device.model)) {
// Device is a BLE (unsupported) thermo-hygrometer sensor
this.log('[%s] %s', device.deviceName, this.lang.devBLENoSupp)
// Remove any existing accessory if exists
if (devicesInHB.has(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
return
} else if (this.consts.models.fan.includes(device.model)) {
// Device is a fan
instance = 'fan'
} else if (this.consts.models.heater.includes(device.model)) {
// Device is a heater
instance = 'heater'
} else if (this.consts.models.humidifier.includes(device.model)) {
// Device is a humidifier
instance = 'humidifier'
} else if (this.consts.models.purifier.includes(device.model)) {
// Device is a purifier
instance = 'purifier'
} else if (this.consts.models.noSupport.includes(device.model)) {
// Device is not and cannot be supported by the plugin
if (this.config.debug) {
this.log.warn('[%s] %s.', device.deviceName, this.lang.devNoSupp)
}
// Remove any existing accessory if exists
if (devicesInHB.has(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
return
} else {
// Device is not in any supported model list but could be implemented into the plugin
this.log.warn(
'[%s] %s:\n%s',
device.deviceName,
this.lang.devMaySupp,
JSON.stringify(device)
)
return
}
// Get the cached accessory or add to Homebridge if doesn't exist
let accessory
switch (instance) {
case 'audio-single':
if (devicesInHB.get(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
accessory = this.addExternalAccessory(device, 34)
instance = 'tv-single'
break
case 'box-single':
if (devicesInHB.get(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
accessory = this.addExternalAccessory(device, 35)
instance = 'tv-single'
break
case 'stick-single':
if (devicesInHB.get(uuid)) {
this.removeAccessory(devicesInHB.get(uuid))
}
accessory = this.addExternalAccessory(device, 36)
instance = 'tv-single'
break
default:
accessory = devicesInHB.get(uuid) || this.addAccessory(device)
break
}
// Final check the accessory now exists in Homebridge
if (!accessory) {
throw new Error(this.lang.accNotFound)
}
// Set the logging level for this device
accessory.context.enableLogging = !this.config.disableDeviceLogging
accessory.context.enableDebugLogging = this.config.debug
switch (deviceConf.overrideLogging) {
case 'standard':
accessory.context.enableLogging = true
accessory.context.enableDebugLogging = false
break
case 'debug':
accessory.context.enableLogging = true
accessory.context.enableDebugLogging = true
break
case 'disable':
accessory.context.enableLogging = false
accessory.context.enableDebugLogging = false
break
}
// Add the config to the context for heater and cooler simulations
if (['heater', 'cooler'].includes(deviceConf.showAs)) {
accessory.context.temperatureSource = deviceConf.temperatureSource
}
// Get a kelvin range if provided
if (device.properties && device.properties.colorTem && device.properties.colorTem.range) {
accessory.context.minKelvin = device.properties.colorTem.range.min
accessory.context.maxKelvin = device.properties.colorTem.range.max
}
// Get a supported command list if provided
if (device.supportCmds) {
accessory.context.supportedCmds = device.supportCmds
}
// Add some initial context information which is changed later
accessory.context.hasAPIControl = device.isAPIDevice
accessory.context.useAPIControl = device.isAPIDevice
accessory.context.hasAWSControl = false
accessory.context.useAWSControl = false
accessory.context.hasBLEControl = false
accessory.context.useBLEControl = false
accessory.context.firmware = false
accessory.context.hardware = false
accessory.context.image = false
// See if we have extra HTTP client info for this device
if (device.httpInfo) {
// Save the hardware and firmware versions
accessory.context.firmware = device.httpInfo.versionSoft
accessory.context.hardware = device.httpInfo.versionHard
// It's possible to show a nice little icon of the device in the Homebridge UI
if (device.httpInfo.deviceExt && device.httpInfo.deviceExt.extResources) {
const parsed = JSON.parse(device.httpInfo.deviceExt.extResources)
if (parsed && parsed.skuUrl) {
accessory.context.image = parsed.skuUrl
}
}
// HTTP info lets us see if other connection methods are available
if (device.httpInfo.deviceExt && device.httpInfo.deviceExt.deviceSettings) {
const parsed = JSON.parse(device.httpInfo.deviceExt.deviceSettings)
// Check to see if AWS is possible
if (parsed && parsed.topic) {
accessory.context.hasAWSControl = !!parsed.topic
accessory.context.awsTopic = parsed.topic
if (!deviceConf.disableAWS) {
accessory.context.useAWSControl = true
accessory.awsControl = new (require('./connection/aws'))(this, accessory)
}
}
// Check to see if BLE is possible
if (parsed && parsed.bleName) {
accessory.context.hasBLEControl = !!parsed.bleName
accessory.context.bleAddress = deviceConf.customAddress
? deviceConf.customAddress.toLowerCase()
: parsed.address
? parsed.address.toLowerCase()
: device.device.substring(6).toLowerCase()
accessory.context.bleName = parsed.bleName
if (
['light-colour', 'light-colour-bt'].includes(instance) &&
deviceConf.enableBT &&
bleClient
) {
accessory.context.useBLEControl = true
}
}
// Get a min and max temperature/humidity range to show in the homebridge-ui
if (parsed && this.funcs.hasProperty(parsed, 'temMin') && parsed.temMax) {
accessory.context.minTemp = parsed.temMin / 100
accessory.context.maxTemp = parsed.temMax / 100
accessory.context.offTemp = parsed.temCali
}
if (parsed && this.funcs.hasProperty(parsed, 'humMin') && parsed.humMax) {
accessory.context.minHumi = parsed.humMin / 100
accessory.context.maxHumi = parsed.humMax / 100
accessory.context.offHumi = parsed.humCali
}
}
}
// Create the instance for this device type
accessory.control = new (require('./device/' + instance))(this, accessory)
// Log the device initialisation
this.log(
'[%s] %s [%s] [%s].',
accessory.displayName,
this.lang.devInit,
device.device,
device.model
)
// Update any changes to the accessory to the platform
this.api.updatePlatformAccessories(plugin.name, plugin.alias, [accessory])
devicesInHB.set(accessory.UUID, accessory)
} catch (err) {
// Catch any errors during device initialisation
const eText = this.funcs.parseError(err, [this.lang.accNotFound])
this.log.warn('[%s] %s %s.', device.deviceName, this.lang.devNotInit, eText)
}
}
async goveeHTTPSync () {
try {
// Obtain a refreshed device list
const devices = await httpClient.getDevices(true)
// Filter those which are leak sensors
devices
.filter(device =>
[...this.consts.models.leak, ...this.consts.models.thermoWifi].includes(device.sku)
)
.forEach(async device => {
try {
// Generate the UIID from which we can match our Homebridge accessory
const uiid = this.api.hap.uuid.generate(device.device)
// Don't continue if the accessory doesn't exist
if (!devicesInHB.has(uiid)) {
return
}
// Retrieve the Homebridge accessory
const accessory = devicesInHB.get(uiid)
// Make sure the data we need for the device exists
if (
!device.deviceExt ||
!device.deviceExt.deviceSettings ||
!device.deviceExt.lastDeviceData
) {
return
}
// Parse the data received
const parsedSettings = JSON.parse(device.deviceExt.deviceSettings)
const parsedData = JSON.parse(device.deviceExt.lastDeviceData)
// Temporary debug logging for leak sensor
if (device.sku === 'H5054' && accessory.context.enableDebugLogging) {
this.log.warn(
'[%s] %s.',
device.deviceName,
JSON.stringify(device.deviceExt.lastDeviceData)
)
}
const toReturn = { source: 'HTTP' }
if (this.consts.models.leak.includes(device.sku)) {
// Leak Sensors - check to see of any warnings if the lastTime is above 0
let hasUnreadLeak = false
if (parsedData.lastTime > 0) {
// Obtain the leak warning messages for this device
const msgs = await httpClient.getLeakDeviceWarning(device.device)
// Check to see if unread messages exist
const unreadCount = msgs.filter(msg => {
return !msg.read && msg.message.toLowerCase().indexOf('leakage alert') > -1
})
//
if (unreadCount.length > 0) {
hasUnreadLeak = true
}
}
// Generate the params to return
toReturn.battery = parsedSettings.battery
toReturn.leakDetected = hasUnreadLeak
toReturn.online = parsedData.gwonline && parsedData.online
} else if (this.consts.models.thermoWifi.includes(device.sku)) {
toReturn.battery = parsedSettings.battery
toReturn.temperature = parsedData.tem
toReturn.humidity = parsedData.hum
toReturn.online = parsedData.online
}
// Send the information to the update receiver function
this.receiveDeviceUpdate(accessory, toReturn)
} catch (err) {
const eText = this.funcs.parseError(err)
this.log.warn('[%s] %s %s.', device.deviceName, this.lang.devNotRef, eText)
}
})
} catch (err) {
const eText = this.funcs.parseError(err)
this.log.warn('%s %s.', this.lang.httpSyncFail, eText)
}
}
async goveeAPISync () {
devicesInHB.forEach(async accessory => {
try {
// Don't continue if the device doesn't support API retrieval
if (!accessory.context.hasAPIControl) {
return
}
// Skip the sync if the client is busy sending updates to Govee
if (this.disableAPISync) {
if (this.config.debug) {
this.log('%s.', this.lang.clientBusy)
}
return
}
// Retrieve the current accessory state from Govee
const res = await apiClient.getDevice(accessory.context)
// Send the data to the receiver function
this.receiveDeviceUpdate(accessory, Object.assign({ source: 'API' }, ...res))
} catch (err) {
// Catch any errors during accessory state refresh
// 400 response is normal when a device's state is not retrievable - log in debug mode
if (err.message.includes('400')) {
if (accessory.context.enableDebugLogging) {
this.log.warn('[%s] %s.', accessory.displayName, this.lang.devNotRet)
}
return
}
// Response is not 400 so check to see if it's a different standard govee error
let eText
if (this.funcs.isGoveeError(err)) {
if (this.hideLogTimeout) {
return
}
this.hideLogTimeout = true
setTimeout(() => (this.hideLogTimeout = false), 60000)
eText = this.lang.goveeErr
} else {
eText = this.funcs.parseError(err)
}
if (accessory.context.enableDebugLogging) {
this.log.warn('[%s] %s %s.', accessory.displayName, this.lang.devNotRef, eText)
}
}
})
}
addAccessory (device) {
// Add an accessory to Homebridge
try {
const uuid = this.api.hap.uuid.generate(device.device)
const accessory = new this.api.platformAccessory(device.deviceName, uuid)
accessory
.getService(this.api.hap.Service.AccessoryInformation)
.setCharacteristic(this.api.hap.Characteristic.Name, device.deviceName)
.setCharacteristic(this.api.hap.Characteristic.ConfiguredName, device.deviceName)
.setCharacteristic(this.api.hap.Characteristic.Manufacturer, this.lang.brand)
.setCharacteristic(this.api.hap.Characteristic.SerialNumber, device.device)
.setCharacteristic(this.api.hap.Characteristic.Model, device.model)
.setCharacteristic(this.api.hap.Characteristic.Identify, true)
accessory.context.gvDeviceId = device.device
accessory.context.gvModel = device.model
this.api.registerPlatformAccessories(plugin.name, plugin.alias, [accessory])
this.configureAccessory(accessory)
this.log('[%s] %s.', device.deviceName, this.lang.devAdd)
return accessory
} catch (err) {
// Catch any errors during add
const eText = this.funcs.parseError(err)
this.log.warn('[%s] %s %s.', device.deviceName, this.lang.devNotAdd, eText)
}
}
addExternalAccessory (device, category) {
try {
// Add the new accessory to Homebridge
const accessory = new this.api.platformAccessory(
device.deviceName,
this.api.hap.uuid.generate(device.device),
category
)
// Set the accessory characteristics
accessory
.getService(this.api.hap.Service.AccessoryInformation)
.setCharacteristic(this.api.hap.Characteristic.Name, device.deviceName)
.setCharacteristic(this.api.hap.Characteristic.ConfiguredName, device.deviceName)
.setCharacteristic(this.api.hap.Characteristic.Manufacturer, this.lang.brand)
.setCharacteristic(this.api.hap.Characteristic.SerialNumber, device.device)
.setCharacteristic(this.api.hap.Characteristic.Model, device.model)
.setCharacteristic(this.api.hap.Characteristic.Identify, true)
// Register the accessory
this.api.publishExternalAccessories(plugin.name, [accessory])
this.log('[%s] %s.', device.name, this.lang.devAdd)
// Return the new accessory
this.configureAccessory(accessory)
return accessory
} catch (err) {
// Catch any errors during add
const eText = this.funcs.parseError(err)
this.log.warn('[%s] %s %s.', device.deviceName, this.lang.devNotAdd, eText)
}
}
configureAccessory (accessory) {
// Set the correct firmware version if we can
if (this.api && accessory.context.firmware) {
accessory
.getService(this.api.hap.Service.AccessoryInformation)
.updateCharacteristic(
this.api.hap.Characteristic.FirmwareRevision,
accessory.context.firmware
)
}
// Add the configured accessory to our global map
devicesInHB.set(accessory.UUID, accessory)
}
removeAccessory (accessory) {
// Remove an accessory from Homebridge
try {
this.api.unregisterPlatformAccessories(plugin.name, plugin.alias, [accessory])
devicesInHB.delete(accessory.UUID)
this.log('[%s] %s.', accessory.displayName, this.lang.devRemove)
} catch (err) {
// Catch any errors during remove
const eText = this.funcs.parseError(err)
const name = accessory.displayName
this.log.warn('[%s] %s %s.', name, this.lang.devNotRemove, eText)
}
}
async sendDeviceUpdate (accessory, params) {
// Add the request to the queue - don't start an update until the previous has finished
const data = {}
try {
// Construct the params for BLE/API/AWS
switch (params.cmd) {
case 'state': {
/*
ON/OFF
<= INPUT params.value with values 'on' or 'off'
API needs { cmd: 'turn', data: 'on'/'off' }
AWS needs { cmd: 'turn', data: { val: 1/0 } }
BLE needs { cmd: 0x01, data: 0x1/0x0 }
*/
data.apiParams = {
cmd: 'turn',
data: params.value
}
data.awsParams = {
cmd: 'turn',
data: { val: params.value === 'on' ? 1 : 0 }
}
data.bleParams = {
cmd: 0x01,
data: params.value === 'on' ? 0x1 : 0x0
}
break
}
case 'stateDual':
case 'stateFan':
case 'stateHumi':
case 'statePuri': {
data.awsParams = {
cmd: 'turn',
data: { val: params.value }
}
break
}
case 'speedHeat':
case 'speedHumi':
case 'speedPuri':
case 'stateHeat': {
data.awsParams = {
cmd: 'ptReal',
data: { command: [params.value] }
}
break
}
case 'brightness': {
/*
BRIGHTNESS
<= INPUT params.value INT in range [0, 100]
API needs { cmd: 'brightness', data: INT[0, 100] or INT[0, 254] }
AWS needs { cmd: 'brightness', data: { val: INT[0, 254] } }
BLE needs { cmd: 0x04, data: (based on) INT[0, 100] }
*/
data.apiParams = {
cmd: 'brightness',
data: this.consts.apiBrightnessScale.includes(accessory.context.gvModel)
? Math.round(params.value * 2.54)
: params.value
}
data.awsParams = {
cmd: 'brightness',
data: {
val: this.consts.awsBrightnessNoScale.includes(accessory.context.gvModel)
? params.value
: Math.round(params.value * 2.54)
}
}
data.bleParams = {
cmd: 0x04,
data: Math.floor((params.value / 100) * 0xff)
}
break
}
case 'color': {
/*
COLOUR (RGB)
<= INPUT params.value OBJ with properties { r, g, b }
API needs { cmd: 'color', data: { r, g, b } }
AWS needs { cmd: 'color', data: { red, green, blue } }
BLE needs { cmd: 0x05, data: [0x02, r, g, b] }
H613B needs { cmd: 0x05, data: [0x0D, r, g, b] }
*/
data.apiParams = {
cmd: 'color',
data: params.value
}
if (this.consts.awsColourWC.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'colorwc',
data: {
color: {
r: params.value.r,
g: params.value.g,
b: params.value.b,
red: params.value.r,
green: params.value.g,
blue: params.value.b
},
colorTemInKelvin: 0
}
}
} else if (this.consts.awsColourLong.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'color',
data: {
r: params.value.r,
g: params.value.g,
b: params.value.b,
red: params.value.r,
green: params.value.g,
blue: params.value.b
}
}
} else if (this.consts.awsColourShort.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'color',
data: params.value
}
} else if (!this.consts.awsColourNone.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'color',
data: {
red: params.value.r,
green: params.value.g,
blue: params.value.b
}
}
}
data.bleParams = {
cmd: 0x05,
data: [accessory.context.gvModel === 'H613B' ? 0x0D : 0x02, params.value.r, params.value.g, params.value.b]
}
break
}
case 'colorTem': {
/*
COLOUR TEMP (KELVIN)
<= INPUT params.value INT in [2000, 7143]
API needs { cmd: 'colorTem', data: INT[2000, 7143] }
AWS needs { cmd: 'colorTem', data: { color: {},"colorTemInKelvin": } }
BLE needs { cmd: 0x05, data: [0x02, 0xff, 0xff, 0xff, 0x01, r, g, b] }
*/
const [r, g, b] = this.colourUtils.k2rgb(params.value)
data.apiParams = {
cmd: 'colorTem',
data: params.value
}
if (this.consts.awsColourWC.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'colorwc',
data: {
color: {
r: r,
g: g,
b: b
},
colorTemInKelvin: params.value
}
}
} else if (this.consts.awsColourLong.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'colorTem',
data: {
colorTemInKelvin: params.value,
color: {
r: r,
g: g,
b: b,
red: r,
green: g,
blue: b
}
}
}
} else if (this.consts.awsColourShort.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'colorTem',
data: {
color: {
r: r,
g: g,
b: b,
red: r,
green: g,
blue: b
},
colorTemInKelvin: params.value
}
}
} else if (!this.consts.awsColourNone.includes(accessory.context.gvModel)) {
data.awsParams = {
cmd: 'colorTem',
data: {
color: {
red: r,
green: g,
blue: b
},
colorTemInKelvin: params.value
}
}
}
data.bleParams = {
cmd: 0x05,
data: [0x02, 0xff, 0xff, 0xff, 0x01, r, g, b]
}
break
}
case 'scene': {
/*
SCENES
<= INPUT params.value STR code
API doesn't support this yet
AWS needs { cmd: 'pt', data: { op: 'mode' OR opcode: 'mode', value: code STR } }
BLE plugin doesn't support this yet
*/
if (params.value.charAt() === '0') {
data.bleParams = {
cmd: 0x05,
data: params.value.replace(/[\s]+/g, '').split(',')
}
} else if (['M', 'o'].includes(params.value.charAt())) {
const codeParts = params.value.trim().split('||')
if (![2, 3].includes(codeParts.length)) {
// Code doesn't seem to be in the right format
throw new Error(this.lang.sceneCodeWrong)
}
data.awsParams = {
cmd: codeParts[1],
data: {}
}
if (codeParts[1] === 'ptReal') {
data.awsParams.data.command = codeParts[0].split(',')
} else {
data.awsParams.data.value = codeParts[0].split(',')
}
if (codeParts[2]) {
data.awsParams.data[codeParts[2]] = 'mode'
}
} else {
// Code doesn't seem to be in the right format
throw new Error(this.lang.sceneCodeWrong)
}
break
}
}
// Check to see if we have the option to use AWS
try {
if (!accessory.context.useAWSControl) {
throw new Error(this.lang.notAvailable)
}
// Check the command is supported by AWS
if (!data.awsParams) {
throw new Error(this.lang.cmdNotAWS)
}
// Send the command (we don't get a response from this)
accessory.awsControl.updateDevice(data.awsParams)
// If the only connection method is AWS or we have sent an AWS scene we can return now
if (
(!accessory.context.useAPIControl && !accessory.context.useBLEControl) ||
(data.awsParams && params.cmd === 'scene')
) {
return
}
await this.funcs.sleep(500)
} catch (err) {
// Print the reason to the log if in debug mode, it's not always necessarily an error
if (accessory.context.enableDebugLogging) {
const eText = this.funcs.parseError(err, [
this.lang.sceneCodeWrong,
this.lang.notAvailable,
this.lang.cmdNotAWS
])
this.log.warn('[%s] %s %s.', accessory.displayName, this.lang.notAWSSent, eText)
}
}
// If the only connection method is AWS or BLE is disabled we need to throw the error again
if (
(!accessory.context.useAPIControl && !accessory.context.useBLEControl) ||
!accessory.context.useBLEControl
) {
throw new Error(this.lang.notAvailable)
}
// Check the command is supported by bluetooth
if (!data.bleParams) {
throw new Error(this.lang.cmdNotBLE)
}
/*
Send the command to the bluetooth client to send
API+AWS+BLE devices: we try once before reverting to API/AWS
API+AWS devices: we throw an error to skip straight to API/AWS control in the catch{}
BLE devices: we try four three before finally returning an error to HomeKit
*/
try {
await bleClient.updateDevice(accessory, data.bleParams)
} catch (err) {
// Try a couple more times for bt only models
if (!accessory.context.hasAPIControl) {
try {
await bleClient.updateDevice(accessory, data.bleParams)
} catch (err) {
// Last attempt not needed inside a try here as it would be caught below in catch
await bleClient.updateDevice(accessory, data.bleParams)
}
} else {
throw err
}
}
} catch (err) {
// If it's the 'incorrect scene code format' error then throw it here again
if (err.message === this.lang.sceneCodeWrong) {
throw err
}
// Check to see if we have the option to use API
if (accessory.context.useAPIControl && data.apiParams) {
// Set this flag true to pause the API device sync interval
this.disableAPISync = true
// Bluetooth didn't work or not enabled
if (accessory.context.enableDebugLogging && accessory.context.useBLEControl) {
const eText = this.funcs.parseError(err, [this.lang.btTimeout])
this.log.warn('[%s] %s %s.', accessory.displayName, this.lang.notBTSent, eText)
}
// Send the command
return await apiClient.updateDevice(accessory, data.apiParams)
} else {
/*
At this point we return the error to HomeKit to show a 'No Response' message
API+AWS+BLE devices: bluetooth failed once and API request failed (AWS may have worked)
API+AWS: API request has failed (AWS may have worked)
BLE devices: bluetooth failed three times
*/
// Throw the error to show the no response in HomeKit
throw err
}
}
}
receiveDeviceUpdate (accessory, params) {
// No need to continue if the accessory doesn't have the receiver function setup
if (!accessory.control || !accessory.control.externalUpdate) {
return
}
// Log the incoming update
if (accessory.context.enableDebugLogging) {
this.log(
'[%s] [%s] %s [%s].',
accessory.displayName,
params.source,
this.lang.receivingUpdate,
JSON.stringify(params)
)
}
// Standardise the object for the receiver function
const data = {}
/*
ONLINE
API gives online property with values true/false or "true"/"false" (annoying)
=> OUTPUT property online BOOL with values true or false
*/
if (this.funcs.hasProperty(params, 'online')) {
data.online = typeof params.online === 'boolean' ? params.online : params.online === 'true'
}
/*
ON/OFF
API gives powerState property with values 'on' or 'off'
AWS gives cmd:'turn' and data.val property INT with values 1 or 0
=> OUTPUT property state STR with values 'on' or 'off
*/
if (params.powerState) {
data.state = params.powerState
} else if (params.cmd === 'turn') {
if (params.data.val > 1) {
data.stateDual = params.data.val
} else {
data.state = params.data.val ? 'on' : 'off'
}
}
/*
BRIGHTNESS
API gives brightness property in range [0, 100] or [0, 254] for some models
AWS gives cmd:'brightness' and data.val property INT always in range [0, 254]
=> OUTPUT property brightness INT in range [0, 100]
*/
if (this.funcs.hasProperty(params, 'brightness')) {
data.brightness = this.consts.apiBrightnessScale.includes(accessory.context.gvModel)
? Math.round(params.brightness / 2.54)
: params.brightness
} else if (params.cmd === 'brightness') {
data.brightness = this.consts.awsBrightnessNoScale.includes(accessory.context.gvModel)
? params.data.val
: Math.round(params.data.val / 2.54)
}
// Sometimes Govee can provide a value out of range of [0, 100]
if (this.funcs.hasProperty(data, 'brightness')) {
data.brightness = Math.max(Math.min(data.brightness, 100), 0)
}
/*
COLOUR (RGB)
API gives color property which is an object {r, g, b}
AWS gives cmd:'color|colorwc' and data property OBJ {red, green, blue}
=> OUTPUT property color OBJ in format {r, g, b}
*/
if (params.color) {
data.rgb = params.color
} else if (params.cmd === 'color') {
if (this.funcs.hasProperty(params.data, 'red')) {
data.rgb = {
r: params.data.red,
g: params.data.green,
b: params.data.blue
}
} else if (this.funcs.hasProperty(params.data, 'r')) {
data.rgb = {
r: params.data.r,
g: params.data.g,
b: params.data.b
}
// Show a message in the log saying this device supports color{r, g, b} command if not known
if (
!this.consts.awsColourShort.includes(accessory.context.gvModel) &&
!this.funcs.hasProperty(params.data, 'red')
) {
this.log.warn(
'[%s] %s [%s].',
accessory.displayName,
this.lang.supportColorShort,
accessory.context.gvModel
)
}
}
} else if (params.cmd === 'colorwc' && this.funcs.hasProperty(params.data.color, 'red')) {
data.rgb = {
r: params.data.color.red,
g: params.data.color.green,
b: params.data.color.blue
}
// Show a message in the log saying this device supports colorwc command if not known
if (
!this.consts.awsColourWC.includes(accessory.context.gvModel) &&
!this.consts.awsColourShort.includes(accessory.context.gvModel) &&
!this.consts.awsColourLong.includes(accessory.context.gvModel) &&
!this.consts.awsColourNone.includes(accessory.context.gvModel)
) {
this.log.warn(
'[%s] %s [%s].',
accessory.displayName,
this.lang.supportColorWC,
accessory.context.gvModel
)
}
}
/*
COLOUR TEMP (KELVIN)
API gives colorTem property normally in range [2000, 9000]
AWS gives cmd:'colorTem' and data.colorTemInKelvin property INT
=> OUTPUT property kelvin INT in range [2000, 7143] (HomeKit range)
*/
if (params.colorTem) {
data.kelvin = Math.max(Math.min(params.colorTem, 7143), 2000)
} else if (params.cmd === 'colorTem') {
data.kelvin = Math.max(Math.min(params.data.colorTemInKelvin, 7143), 2000)
} else if (params.cmd === 'colorwc' && params.data.colorTemInKelvin > 0) {
data.kelvin = Math.max(Math.min(params.data.colorTemInKelvin, 7143), 2000)
// Show a message in the log saying this device supports colorwc command if not known
if (!this.consts.awsColourWC.includes(accessory.context.gvModel)) {
this.log.warn(
'[%s] %s [%s].',
accessory.displayName,
this.lang.supportColorWC,
accessory.context.gvModel
)
}
}
/*
SCENES
API doesn't support this yet
AWS gives cmd:'pt' and data OBJ { op: 'mode' OR opcode: 'mode', value: [code, code2?] } }
BLE plugin doesn't support this yet
=> OUTPUT property scene STR with the code
*/
if (['bulb', 'pt', 'ptReal'].includes(params.cmd)) {
data.scene =
params.cmd === 'ptReal' ? params.data.command.join(',') : params.data.value.join(',')
data.cmd = params.cmd
data.prop = ['bulb', 'ptReal'].includes(params.cmd)
? ''
: params.data.op === 'mode'
? 'op'
: 'opcode'
}
/*
BATTERY (leak and thermo sensors)
*/
if (this.funcs.hasProperty(params, 'battery')) {
data.battery = Math.min(Math.max(params.battery, 0), 100)
}
/*
LEAK DETECTED (leak sensors)
*/
if (this.funcs.hasProperty(params, 'leakDetected')) {
data.leakDetected = params.leakDetected
}
/*
TEMPERATURE (thermo sensors)
*/
if (this.funcs.hasProperty(params, 'temperature')) {
data.temperature = params.temperature
}
/*
HUMIDITY (thermo sensors)
*/
if (this.funcs.hasProperty(params, 'humidity')) {
data.humidity = params.humidity
}
// Send the update to the receiver function
data.source = params.source
try {
accessory.control.externalUpdate(data)
} catch (err) {
const eText = this.funcs.parseError(err)
this.log.warn('[%s] %s %s.', accessory.displayName, this.lang.devNotUpdated, eText)
}
}
updateAccessoryStatus (accessory, newStatus) {
// Log the change, at a warning level if the device is reported offline
if (accessory.context.enableLogging) {
if (newStatus) {
this.log('[%s] %s.', accessory.displayName, this.lang.onlineAPI)
} else {
this.log.warn('[%s] %s.', accessory.displayName, this.lang.offlineAPI)
}
}
// Update the context item for the plugin UI
accessory.context.isOnline = newStatus ? 'yes' : 'no'
// Update any changes to the accessory to the platform
this.api.updatePlatformAccessories(plugin.name, plugin.alias, [accessory])
devicesInHB.set(accessory.UUID, accessory)
}
} |
JavaScript | class ReplicationControllerDetailController {
/**
* @param {!backendApi.ReplicationControllerDetail} replicationControllerDetail
* @param {!ui.router.$state} $state
* @param {!../../common/resource/resourcedetail.StateParams} $stateParams
* @param {!angular.Resource} kdRCPodsResource
* @param {!angular.Resource} kdRCServicesResource
* @param {!angular.Resource} kdRCEventsResource
* @ngInject
*/
constructor(
replicationControllerDetail, $state, $stateParams, kdRCPodsResource, kdRCServicesResource,
kdRCEventsResource) {
/** @export {!backendApi.ReplicationControllerDetail} */
this.replicationControllerDetail = replicationControllerDetail;
/** @export {!angular.Resource} */
this.podListResource = kdRCPodsResource;
/** @export {!angular.Resource} */
this.serviceListResource = kdRCServicesResource;
/** @export {!angular.Resource} */
this.eventListResource = kdRCEventsResource;
/** @private {!ui.router.$state} */
this.state_ = $state;
/** @private {!../../common/resource/resourcedetail.StateParams} */
this.stateParams_ = $stateParams;
}
/**
* @param {!backendApi.Pod} pod
* @return {boolean}
* @export
*/
hasCpuUsage(pod) {
return !!pod.metrics && !!pod.metrics.cpuUsageHistory && pod.metrics.cpuUsageHistory.length > 0;
}
/**
* @param {!backendApi.Pod} pod
* @return {boolean}
* @export
*/
hasMemoryUsage(pod) {
return !!pod.metrics && !!pod.metrics.memoryUsageHistory &&
pod.metrics.memoryUsageHistory.length > 0;
}
} |
JavaScript | class RegionRequest {
/**
* Constructs a new <code>RegionRequest</code>.
* Region Request Body
* @alias module:model/RegionRequest
* @param ids {Array.<String>} Security or Entity identifiers. FactSet Identifiers, tickers, CUSIP and SEDOL are accepted input. <p>***ids limit** = 300 per request*</p> *<p>Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \"POST\" method.</p>*
*/
constructor(ids) {
RegionRequest.initialize(this, ids);
}
/**
* 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, ids) {
obj['ids'] = ids;
}
/**
* Constructs a <code>RegionRequest</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/RegionRequest} obj Optional instance to populate.
* @return {module:model/RegionRequest} The populated <code>RegionRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new RegionRequest();
if (data.hasOwnProperty('ids')) {
obj['ids'] = ApiClient.convertToType(data['ids'], ['String']);
}
if (data.hasOwnProperty('regionIds')) {
obj['regionIds'] = ApiClient.convertToType(data['regionIds'], ['String']);
}
if (data.hasOwnProperty('startDate')) {
obj['startDate'] = ApiClient.convertToType(data['startDate'], 'String');
}
if (data.hasOwnProperty('endDate')) {
obj['endDate'] = ApiClient.convertToType(data['endDate'], 'String');
}
if (data.hasOwnProperty('frequency')) {
obj['frequency'] = Frequency.constructFromObject(data['frequency']);
}
if (data.hasOwnProperty('currency')) {
obj['currency'] = ApiClient.convertToType(data['currency'], 'String');
}
}
return obj;
}
} |
JavaScript | class InteractionLimit {
/**
* Constructs a new <code>InteractionLimit</code>.
* Interaction limit settings.
* @alias module:model/InteractionLimit
* @param expiresAt {Date}
* @param limit {module:model/InteractionLimit.LimitEnum} The interaction limit to enable.
* @param origin {String}
*/
constructor(expiresAt, limit, origin) {
InteractionLimit.initialize(this, expiresAt, limit, origin);
}
/**
* 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, expiresAt, limit, origin) {
obj['expires_at'] = expiresAt;
obj['limit'] = limit;
obj['origin'] = origin;
}
/**
* Constructs a <code>InteractionLimit</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/InteractionLimit} obj Optional instance to populate.
* @return {module:model/InteractionLimit} The populated <code>InteractionLimit</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InteractionLimit();
if (data.hasOwnProperty('expires_at')) {
obj['expires_at'] = ApiClient.convertToType(data['expires_at'], 'Date');
}
if (data.hasOwnProperty('limit')) {
obj['limit'] = ApiClient.convertToType(data['limit'], 'String');
}
if (data.hasOwnProperty('origin')) {
obj['origin'] = ApiClient.convertToType(data['origin'], 'String');
}
}
return obj;
}
} |
JavaScript | class pLoader extends Hls.DefaultConfig.loader {
/**
* Original (default) playlist load method
* @param {Object} ctx - loading context
* @param {Object} config - loading config
* @param {Object} callbacks - loading callbacks
*/
_load = this.load.bind(this);
/**
* Modified playlist load method
* Mostly just adds some extra logging whenever a manifest is requested
* @param {Object} ctx - loading context
* @param {Object} config - loading config
* @param {Object} callbacks - loading callbacks
*/
load = (ctx, config, cbs) => {
const { type, url } = ctx;
if (type === "manifest") console.log(`Manifest ${url} will be loaded.`);
else console.log("loading", url);
const loader = new ctx.loader(config);
const _ctx = { ...ctx, loader };
const _cbs = {
...cbs,
onSuccess: (res, stats, ctx) => {
// we can also add in some extra success logging here if desired
cbs.onSuccess(res, stats, ctx);
},
};
this._load(_ctx, config, _cbs);
};
} |
JavaScript | class QualityPicker extends Component {
static propTypes = {
actions: PropTypes.object,
player: PropTypes.object,
video: PropTypes.object,
levels: PropTypes.array,
currentLevel: PropTypes.number,
};
constructor(props, context) {
super(props, context);
this.createResOptions = this.createResOptions.bind(this);
this.state = {
visible: false,
};
}
/**
* toggles menu visibility
*/
toggleMenu() {
this.setState({ visible: !this.state.visible });
}
/**
* change current Resolution
* @param {event} ev button HTML event object
*/
handleQualityChange(ev) {
let { video } = this.props;
if (video) {
video.loadLevel(parseInt(ev.target.dataset["id"]));
} else {
console.error(`ev: this.video is null ${this.video}`);
}
}
/**
* create the single resolution items in the res list
* @return {Array} returns an array of items.
*/
createResOptions(levels, video) {
levels = levels || this.props.levels;
let res = [];
let currentLevel = this.props.currentLevel || -1;
if (levels && levels.length >= 1 && levels[0].attrs) {
for (let i = levels.length - 1; i >= 0; i--) {
res.push(
this.generateListItem(currentLevel, i, levels[i].attrs.RESOLUTION)
);
}
}
res.push(this.generateListItem(currentLevel, -1, "auto"));
return res;
}
/**
* generate a single item on the resolution menu
* @param {Number} currentLevel index of the current level
* @param {number} i index of the level being generated
* @param {string} resolution resolution string (1920x1080 or 1080p .. whatever)
* @return {object} HTML List element
*/
generateListItem(currentLevel, i, resolution) {
return (
<li key={i}>
<button
className={currentLevel === i ? "active" : ""}
data-id={i}
onClick={this.handleQualityChange.bind(this)}>
{resolution}
</button>
</li>
);
}
render() {
const { levels, video } = this.props;
return (
<div className={"video-react-control"}>
<div
className={"menu-container"}
style={{
display: !this.state.visible ? "none" : "block",
}}>
<ul>{this.createResOptions(levels, video)}</ul>
</div>
<button
ref={(c) => {
this.button = c;
}}
className={
"video-react-icon video-react-control video-react-button video-react-icon-settings"
}
tabIndex="0"
onClick={this.toggleMenu.bind(this)}
/>
</div>
);
}
} |
JavaScript | class VideoPlayer extends Component {
static propTypes = {
// video-react props (https://video-react.js.org/components/player/)
actions: PropTypes.object,
player: PropTypes.object,
children: PropTypes.any,
startTime: PropTypes.number,
loop: PropTypes.bool,
muted: PropTypes.bool,
autoPlay: PropTypes.bool,
playsInline: PropTypes.bool,
src: PropTypes.string,
poster: PropTypes.string,
className: PropTypes.string,
preload: PropTypes.oneOf(["auto", "metadata", "none"]),
crossOrigin: PropTypes.string,
onLoadStart: PropTypes.func,
onWaiting: PropTypes.func,
onCanPlay: PropTypes.func,
onCanPlayThrough: PropTypes.func,
onPlaying: PropTypes.func,
onEnded: PropTypes.func,
onSeeking: PropTypes.func,
onSeeked: PropTypes.func,
onPlay: PropTypes.func,
onPause: PropTypes.func,
onProgress: PropTypes.func,
onDurationChange: PropTypes.func,
onError: PropTypes.func,
onSuspend: PropTypes.func,
onAbort: PropTypes.func,
onEmptied: PropTypes.func,
onStalled: PropTypes.func,
onLoadedMetadata: PropTypes.func,
onLoadedData: PropTypes.func,
onTimeUpdate: PropTypes.func,
onRateChange: PropTypes.func,
onVolumeChange: PropTypes.func,
onResize: PropTypes.func,
// custom props
onLive: PropTypes.func,
onDead: PropTypes.func,
};
static defaultProps = {
preload: "auto",
onLive: () => {},
onDead: () => {},
};
constructor(props) {
super(props);
this.state = {
levels: [],
currentLevel: -1,
};
// this.onLevels = this.onLevels.bind(this)
}
/**
* get all available bitrates
* @return {Array} array of res objects
*/
getLevels() {
if (this.source) {
return this.source.getLevels();
} else {
return [];
}
}
/**
* get Current level playing
* @return {Number} returns level index
*/
getCurrentLevel() {
if (this.source) {
let x = this.source.getCurrentLevel();
return x;
} else {
return -1;
}
}
/**
* immediate change to a new resolution
* @param {Number} level index of the level
*/
loadLevel(level) {
if (this.source) {
this.source.loadLevel(level);
this.setState({ currentLevel: level });
}
}
onLive(...args) {
this.setState({
levels: args.length ? args[0].levels : [],
currentLevel: this.getCurrentLevel(),
});
// pass it along to onLive (check @livepeer/player/src/Channel/index.js)
this.props.onLive(...args);
}
render() {
const {
src,
onLive,
onDead,
autoPlay,
hlsOptions,
videoOptions,
...props
} = this.props;
return (
<Player muted autoPlay={autoPlay} playsInline {...props}>
<BigPlayButton position="center" />
<ControlBar autoHide={false}>
<QualityPicker
order={7}
video={this}
levels={this.state.levels}
currentLevel={this.state.currentLevel}
/>
</ControlBar>
<Source
ref={(instance) => {
this.source = instance;
}}
isVideoChild
onLive={this.onLive.bind(this)}
onDead={onDead}
autoPlay={autoPlay}
src={src}
type={getSourceType(src)}
hlsOptions={{
...Source.defaultProps.hlsOptions,
...hlsOptions,
}}
videoOptions={{
...Source.defaultProps.videoOptions,
...videoOptions,
}}
/>
</Player>
);
}
} |
JavaScript | @connect(({ home, loading }) => ({
...home,
loading: loading.effects["home/query"],
}))
class Home extends Component {
rowSelection = {
// eslint-disable-next-line no-unused-vars
onChange: (selectedRowKeys, selectedRows) => {
/* console.log(
`selectedRowKeys: ${selectedRowKeys}`,
"selectedRows: ",
selectedRows
); */
},
getCheckboxProps: record => ({
disabled: record.sysName === "Disabled User", // Column configuration not to be checked
sysName: record.sysName,
}),
};
columns = [
{
title: "系统名称",
dataIndex: "sysName",
render: text => <a>{text}</a>,
},
{
title: "系统描述",
dataIndex: "sysDes",
},
{
title: "创建时间",
dataIndex: "created",
},
{
title: "创建人",
dataIndex: "creator",
},
{
title: "操作",
dataIndex: "operation",
render: (text, record) => (
<div>
<Button
type = "primary"
onClick = {this.getSecretKey(record)}
size = "small"
>
获取秘钥
</Button>
<Popconfirm
placement = "topRight"
title = "是否确定删除"
onConfirm = {this.onDelete(record)}
okText = "确定"
cancelText = "取消"
>
<Button
type = "primary"
className = {`${styles["ml-small"]}`}
size = "small"
>
删除
</Button>
</Popconfirm>
</div>
),
},
];
constructor(props) {
super(props);
this.state = {
showSecModal: false, // 是否展示复制秘钥弹出框
showLoding: false,
// inputVal: 'aasssdafdafdf'
};
this.setKeyRef = ele => {
this.keyInput = ele;
};
}
componentDidMount() {
const { dispatch } = this.props;
/* this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
) */
dispatch({
type: "home/query",
payload: {
paging: {
pageSize: 10,
currentPage: 1,
},
},
});
}
/**
* 当前方法为新增编辑查看公用方法
* @param {string} operateId 操作动作表示,新增:add、编辑:edit、查看:detail
*/
onComClick = operateId => () => {
const pathname = "/home/compage";
router.push({
pathname,
query: {
pageType: operateId,
},
});
};
/**
*
* 系统删除事件
* @param {Object} record 为行数据
*/
onDelete = record => () => {
const { dispatch } = this.props;
this.setState({ showLoding: true });
dispatch({
type: "home/delSys",
payload: {
funcType: "sys",
id: record.id,
},
callback: msg => {
message.info(msg, 2);
this.componentDidMount();
this.setState({ showLoding: false });
},
});
};
onDoubleClick = record => () => {
router.push({
pathname: "/home/sys-env",
query: {
sysId: record.id,
},
});
};
/**
*
*
* @param {string} pagingType 操作类型标识,pagingType值为pageIndex、pageSize
*/
onPageChange = pagingType => (pageIndex, pageSize) => {
const { dispatch } = this.props;
dispatch({
type: "home/query",
payload: {
paging: {
currentPage: pagingType === "pageIndex" ? pageIndex : 1,
pageSize,
},
},
});
};
/**
* 密钥输入框onChange事件,这里采用的是受控的input组件
*/
/* onInputChange = (e) => {
this.setState({
inputVal: e.target.value
})
} */
/**
*
* 获取当前行数据对应的密钥,获取完成后打开弹窗
* @param record
*/
getSecretKey = record => () => {
const { dispatch } = this.props;
dispatch({
type: "home/getSecretKey",
payload: {
id: record.id,
},
callback: () => {
this.setState({
showSecModal: true,
});
},
});
this.setState({
showSecModal: true,
});
};
onModalBtnClick = isShow => {
if (isShow) {
// 执行复制值密钥
const copytNode = document.querySelector(".inputBox input");
const range = document.createRange();
range.selectNode(copytNode);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
const tag = document.execCommand("copy");
if (tag) {
message.success("复制成功");
}
}
this.setState({
showSecModal: false,
});
};
render() {
const { showSecModal, showLoding } = this.state;
const {
sys: { data, totalCount },
secretKey,
sysReq: { currentPage },
} = this.props;
return (
<div className = {styles.home}>
<Spin tip = "Loading..." spinning = {showLoding}>
<div className = {styles.btnCon}>
<Button
type = "primary"
className = {`${styles["ml-middle"]}`}
onClick = {this.onComClick("add")}
>
创建系统
</Button>
</div>
<div>
<Table
rowSelection = {this.rowSelection}
columns = {this.columns}
dataSource = {data}
pagination = {{
showSizeChanger: true,
onShowSizeChange: this.onPageChange("pageSize"),
onChange: this.onPageChange("pageIndex"),
total: totalCount,
current: currentPage,
}}
onRow = {record => ({
onDoubleClick: this.onDoubleClick(record),
})}
rowKey = "id"
/>
</div>
{/* 复制秘钥弹框 */}
<div>
<Modal
title = "系统秘钥"
centered
visible = {showSecModal}
onOk = {() => this.onModalBtnClick(true)}
onCancel = {() => this.onModalBtnClick(false)}
okText = "复制"
>
<Form
className = {styles["ant-advanced-search-form"]}
>
<Form.Item className = "inputBox">
<Input
placeholder = "秘钥"
value = {secretKey}
/>
</Form.Item>
</Form>
</Modal>
</div>
</Spin>
</div>
);
}
} |
JavaScript | class Consumer extends Component {
render () {
return this.props.children(this.context);
}
} |
JavaScript | class ComplianceCalculator {
constructor(evaluationResults) {
this.evaluationResults = evaluationResults;
this.passed = 0;
this.failed = 0;
this.error = 0;
this.total = 0;
}
/**
* Calculates compliance statistics (how many rules are passed and failed, and couldn't be evaluated (error))
*/
calculateComplianceStatistics() {
this.total = this.evaluationResults.length;
this.countPassFailRules();
this.error = this.total - this.passed - this.failed;
}
/**
* Calculates the percentage out of total
* @param {*} value
*/
calculatePercentage(value) {
if (this.total === 0) {
return 0;
}
return parseFloat(Number((value * 100) / this.total).toFixed(2));
}
/**
* Counts passed and failed rules
*/
countPassFailRules() {
this.evaluationResults.forEach((result) => {
if (result.result.toLowerCase() === "pass") {
++this.passed;
} else if (result.result.toLowerCase() === "fail") {
++this.failed;
}
});
}
/**
* Formats the compliance summary into (#Passed --> <#Passed> (<#Passed in percentage>))
* @param {*} label
* @param {*} count
* @param {*} percentage
*/
formatComplianceSummary(label, count, percentage) {
let csvData = label + " --> ";
return csvData.concat(count)
.concat(" (")
.concat(percentage)
.concat("%)\n");
}
/**
* Gets the compliance summary in CSV format
*/
getComplianceSummary() {
return new Promise(resolve => {
utils.convertJsonToCsv(this.getHeaderFields(), this.evaluationResults).then((csvData) => {
resolve(csvData.concat(this.getRuleComplianceStatisticsInCSV()));
}).catch(exception => {
log.error(exception);
return resolve([]);
});
});
}
/**
* Returns list of fields as headers for summay section in resuts.csv
*/
getHeaderFields() {
let fields = Object.getOwnPropertyNames(this.evaluationResults[0]);
fields = fields.filter(function(item) {
return item != "detail"; // Details are shown below the statistics section
});
return fields;
}
/**
* Converts the compliance statistics into csv
*/
getRuleComplianceStatisticsInCSV() {
let csvData = "\n\n";
this.calculateComplianceStatistics();
return csvData.concat(this.formatComplianceSummary("#Passed", this.passed, this.calculatePercentage(this.passed)))
.concat(this.formatComplianceSummary("#Failed", this.failed, this.calculatePercentage(this.failed)))
.concat(this.formatComplianceSummary("#Error", this.error, this.calculatePercentage(this.error)));
}
} |
JavaScript | class ContainerInstance extends RenderableInstance {
/**
* Set a message on the current request context.
* @param {String} id
* An identifier for this message.
* @param {String} content
* The message to be displayed.
* @param {String} [type="default"]
* The grouping for this message.
*/
set(id, content, type='default') {
if (!this.context.messageRegistryMap) {
/**
* @member {Map<String,Defiant.util.Registry>} Defiant.Context#messageRegistryMap
* A key/value store of messages. The key is the message type and the
* value is a Registry to hold the message. The message may be a
* string.
*/
this.context.messageRegistryMap = {};
}
if (typeof this.context.messageRegistryMap[type] === 'undefined') {
this.context.messageRegistryMap[type] = new Registry();
}
this.context.messageRegistryMap[type].set({id, content});
return this;
}
/**
* Perform any initialization needed, and in particular, async operations.
*
* When this function is finished, then the renderable should be ready to
* be rendered as a string.
* @function
* @async
* @param {Object} [data={}]
* The initialization data.
*/
async init(data={}) {
return super.init(merge({
messageRegistryMap: this.context.messageRegistryMap,
}, data));
}
/**
* Take all data that was passed in via the constructor as well as any work
* done by the [init()]{@link Defiant.Plugin.Theme.RenderableInstance#init},
* and compile it using the
* [Renderable.templateFunction]{@link Defiant.Plugin.Theme.Renderable#templateFunction}.
* @function
* @async
* @returns {String}
* The final string that should be provided to the user.
*/
async commit() {
// TODO: Each message should be its own renderable.
let contentBlock = '';
for (let type in this.context.messageRegistryMap || {}) {
let content = '';
for (let message of this.context.messageRegistryMap[type].getOrderedElements()) {
content += `<div class="message ${message.id}">${message.content}</div>`;
}
contentBlock += `<div class="message-block ${type}">${content}</div>`;
// Clear the messages.
delete this.context.messageRegistryMap[type];
}
merge(this.data, {
attributes: {
class: new Set(['messages']),
},
content: contentBlock,
})
return super.commit();
}
} |
JavaScript | class CustomElementRegistry {
/**
* @param {!Window} win
* @param {!Registry} registry
*/
constructor(win, registry) {
/**
* @const @private
*/
this.win_ = win;
/**
* @const @private
*/
this.registry_ = registry;
/**
* @type {!Object<string, DeferredDef>}
* @private
* @const
*/
this.pendingDefines_ = this.win_.Object.create(null);
}
/**
* Register the custom element.
*
* @param {string} name
* @param {!CustomElementConstructorDef} ctor
* @param {!Object=} options
*/
define(name, ctor, options) {
this.registry_.define(name, ctor, options);
// If anyone is waiting for this custom element to be defined, resolve
// their promise.
const pending = this.pendingDefines_;
const deferred = pending[name];
if (deferred) {
deferred.resolve();
delete pending[name];
}
}
/**
* Get the constructor of the (already defined) custom element.
*
* @param {string} name
* @return {!CustomElementConstructorDef|undefined}
*/
get(name) {
const def = this.registry_.getByName(name);
if (def) {
return def.ctor;
}
}
/**
* Returns a promise that waits until the custom element is defined.
* If the custom element is already defined, returns a resolved promise.
*
* @param {string} name
* @return {!Promise<undefined>}
*/
whenDefined(name) {
const {Promise, SyntaxError} = this.win_;
assertValidName(SyntaxError, name);
if (this.registry_.getByName(name)) {
return Promise.resolve();
}
const pending = this.pendingDefines_;
const deferred = pending[name];
if (deferred) {
return deferred.promise;
}
let resolve;
const promise = new /*OK*/Promise(res => resolve = res);
pending[name] = {
promise,
resolve,
};
return promise;
}
/**
* Upgrade all custom elements inside root.
*
* @param {!Node} root
*/
upgrade(root) {
this.registry_.upgrade(root);
}
} |
JavaScript | class Registry {
/**
* @param {!Window} win
*/
constructor(win) {
/**
* @private @const
*/
this.win_ = win;
/**
* @private @const
*/
this.doc_ = win.document;
/**
* @type {!Object<string, !CustomElementDef>}
* @private
* @const
*/
this.definitions_ = win.Object.create(null);
/**
* A up-to-date DOM selector for all custom elements.
* @type {string}
*/
this.query_ = '';
/**
* The currently upgrading element.
* @private {Element}
*/
this.current_ = null;
}
/**
* The currently-being-upgraded custom element.
*
* When an already created (through the DOM parsing APIs, or innerHTML)
* custom element node is being upgraded, we can't just create a new node
* (it's illegal in the spec). But we still need to run the custom element's
* constructor code on the node. We avoid this conundrum by running the
* constructor while returning this current node in the HTMLElement
* class constructor (the base class of all custom elements).
*
* @return {Element}
*/
current() {
const current = this.current_;
this.current_ = null;
return current;
}
/**
* Finds the custom element definition by name.
*
* @param {string} name
* @return {CustomElementDef|undefined}
*/
getByName(name) {
const definition = this.definitions_[name];
if (definition) {
return definition;
}
}
/**
* Finds the custom element definition by constructor instance.
*
* @param {CustomElementConstructorDef} ctor
* @return {CustomElementDef|undefined}
*/
getByConstructor(ctor) {
const definitions = this.definitions_;
for (const name in definitions) {
const def = definitions[name];
if (def.ctor === ctor) {
return def;
}
}
}
/**
* Registers the custom element definition, and upgrades all elements by that
* name in the root document.
*
* @param {string} name
* @param {!CustomElementConstructorDef} ctor
* @param {!Object|undefined} options
*/
define(name, ctor, options) {
const {Error, SyntaxError} = this.win_;
if (options) {
throw new Error('Extending native custom elements is not supported');
}
assertValidName(SyntaxError, name);
if (this.getByName(name) ||
this.getByConstructor(ctor)) {
throw new Error(`duplicate definition "${name}"`);
}
// TODO(jridgewell): Record connectedCallback, disconnectedCallback,
// adoptedCallback, attributeChangedCallback, and observedAttributes.
// TODO(jridgewell): If attributeChangedCallback, gather observedAttributes
this.definitions_[name] = {
name,
ctor,
};
this.observe_(name);
this.upgrade(this.doc_, name);
}
/**
* Upgrades custom elements descendants of root (but not including root).
*
* When called with an opt_query, it both upgrades and connects the custom
* elements (this is used during the custom element define algorithm).
*
* @param {!Node} root
* @param {string=} opt_query
*/
upgrade(root, opt_query) {
// Only CustomElementRegistry.p.define provides a query (the newly defined
// custom element). In this case, we are both upgrading _and_ connecting
// the custom elements.
const newlyDefined = !!opt_query;
const query = opt_query || this.query_;
const upgradeCandidates = this.queryAll_(root, query);
for (let i = 0; i < upgradeCandidates.length; i++) {
const candidate = upgradeCandidates[i];
if (newlyDefined) {
this.connectedCallback_(candidate);
} else {
this.upgradeSelf(candidate);
}
}
}
/**
* Upgrades the custom element node, if a custom element has been registered
* by this name.
*
* @param {!Node} node
*/
upgradeSelf(node) {
const def = this.getByName(node.localName);
if (!def) {
return;
}
this.upgradeSelf_(/** @type {!Element} */(node), def);
}
/**
* @param {!Node} root
* @param {string} query
* @return {!Array|!NodeList}
*/
queryAll_(root, query) {
if (!query || !root.querySelectorAll) {
// Nothing to do...
return [];
}
return root.querySelectorAll(query);
}
/**
* Upgrades the (already created via DOM parsing) custom element.
*
* @param {!Element} node
* @param {!CustomElementDef} def
*/
upgradeSelf_(node, def) {
const {ctor} = def;
if (node instanceof ctor) {
return;
}
// Despite how it looks, this is not a useless construction.
// HTMLElementPolyfill (the base class of all custom elements) will return
// the current node, allowing the custom element's subclass constructor to
// run on the node. The node itself is already constructed, so the return
// value is just the node.
this.current_ = node;
const el = new ctor();
if (el !== node) {
throw new this.win_.Error(
'Constructor illegally returned a different instance.');
}
}
/**
* Fires connectedCallback on the custom element, if it has one.
* This also upgrades the custom element, since it may not have been
* accessible via the root document before (a detached DOM tree).
*
* @param {!Node} node
*/
connectedCallback_(node) {
const def = this.getByName(node.localName);
if (!def) {
return;
}
this.upgradeSelf_(/** @type {!Element} */(node), def);
// TODO(jridgewell): It may be appropriate to adoptCallback, if the node
// used to be in another doc.
// TODO(jridgewell): I should be calling the definitions connectedCallback
// with node as the context.
if (node.connectedCallback) {
node.connectedCallback();
}
}
/**
* Fires disconnectedCallback on the custom element, if it has one.
*
* @param {!Node} node
*/
disconnectedCallback_(node) {
// TODO(jridgewell): I should be calling the definitions connectedCallback
// with node as the context.
if (node.disconnectedCallback) {
node.disconnectedCallback();
}
}
/**
* Records name as a registered custom element to observe.
*
* Starts the Mutation Observer if this is the first registered custom
* element. This is deferred until the first custom element is defined to
* speed up initial rendering of the page.
*
* Mutation Observers are conveniently available in every browser we care
* about. When a node is connected to the root document, all custom
* elements (including that node iteself) will be upgraded and call
* connectedCallback. When a node is disconnectedCallback from the root
* document, all custom elements will call disconnectedCallback.
*
* @param {string} name
*/
observe_(name) {
if (this.query_) {
this.query_ += `,${name}`;
return;
}
this.query_ = name;
// The first registered name starts the mutation observer.
const observer = new this.win_.MutationObserver(records => {
if (records) {
this.handleRecords_(records);
}
});
observer.observe(this.doc_, {
childList: true,
subtree: true,
});
}
/**
* Handle all the Mutation Observer's Mutation Records.
* All added custom elements will be upgraded (if not already) and call
* connectedCallback. All removed custom elements will call
* disconnectedCallback.
*
* @param {!Array<!MutationRecord>} records
*/
handleRecords_(records) {
for (let i = 0; i < records.length; i++) {
const record = records[i];
if (!record) {
continue;
}
const {addedNodes, removedNodes} = record;
for (let i = 0; i < addedNodes.length; i++) {
const node = addedNodes[i];
const connectedCandidates = this.queryAll_(node, this.query_);
this.connectedCallback_(node);
for (let i = 0; i < connectedCandidates.length; i++) {
this.connectedCallback_(connectedCandidates[i]);
}
}
for (let i = 0; i < removedNodes.length; i++) {
const node = removedNodes[i];
const disconnectedCandidates = this.queryAll_(node, this.query_);
this.disconnectedCallback_(node);
for (let i = 0; i < disconnectedCandidates.length; i++) {
this.disconnectedCallback_(disconnectedCandidates[i]);
}
}
}
}
} |
JavaScript | class ByIdReferenceProperty extends AbstractProperty_1.AbstractProperty {
/** @internal */
initialize(value) {
const observableValue = new ByIdReference_1.ByIdReference(this.parent);
observableValue.intercept(change => this.beforeChange(change));
return { observableValue };
}
get() {
this.assertReadable();
return this.observableValue.get();
}
set(value) {
this.assertWritable();
if (!value && this.isRequired) {
throw new Error(`Cannot unset property that is a required by-id reference`);
}
this.observableValue.set(value);
}
updateWithRawValue(value) {
this.observableValue.updateWithRawValue(value);
}
resolveReference() {
this.observableValue.resolve();
}
/** @internal */
beforeChange(change) {
if (this.shouldHandleChange()) {
this.observableValue.assertValueHasSameUnit(change.newValue);
this.parent._sendChangeDelta(this.name, change.newValue ? change.newValue.id : null);
}
return change;
}
updateElementContainer() {
// We didn't know our container before, now we know it, let's check the referred value:
this.observableValue.assertValueHasSameUnit(this.observableValue.get());
}
/** @internal */
_toJSON() {
const value = this.get();
return value ? value.id : null;
}
deepCopyInto(clone, idMap, unresolvedIdentifierFixers) {
unresolvedIdentifierFixers.push(map => {
const val = this.get();
if (!val) {
// no target
clone[this.name] = val;
}
else {
if (map.hasOwnProperty(val.id)) {
// The target was cloned
const cloneProperty = clone["__" + this.name];
cloneProperty.observableValue.target.set(map[val.id]);
}
else {
// The target was outside the cloned range, not supported
throw new Error(`By-id referred element ${val.structureTypeName} with ID ${val.id} was not included in the deepCopy`);
}
}
});
}
} |
JavaScript | class GithubLoader {
loaderId() {
return 'github-loader';
}
async canLoad(pointer) {
return typeof pointer === 'string' && pointer.toLowerCase().startsWith('github:');
}
canLoadSync() {
return false;
}
async load(pointer, options) {
const { owner, name, ref, path } = extractData(pointer);
const request = await crossFetch.fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `bearer ${options.token}`,
},
body: JSON.stringify({
query: `
query GetGraphQLSchemaForGraphQLtools($owner: String!, $name: String!, $expression: String!) {
repository(owner: $owner, name: $name) {
object(expression: $expression) {
... on Blob {
text
}
}
}
}
`,
variables: {
owner,
name,
expression: ref + ':' + path,
},
operationName: 'GetGraphQLSchemaForGraphQLtools',
}),
});
const response = await request.json();
let errorMessage = null;
if (response.errors && response.errors.length > 0) {
errorMessage = response.errors.map((item) => item.message).join(', ');
}
else if (!response.data) {
errorMessage = response;
}
if (errorMessage) {
throw new Error('Unable to download schema from github: ' + errorMessage);
}
const content = response.data.repository.object.text;
if (/\.(gql|graphql)s?$/i.test(path)) {
return utils.parseGraphQLSDL(pointer, content, options);
}
if (/\.json$/i.test(path)) {
return utils.parseGraphQLJSON(pointer, content, options);
}
const rawSDL = await graphqlTagPluck.gqlPluckFromCodeString(pointer, content, options.pluckConfig);
if (rawSDL) {
return {
location: pointer,
rawSDL,
};
}
throw new Error(`Invalid file extension: ${path}`);
}
loadSync() {
throw new Error('Loader GitHub has no sync mode');
}
} |
JavaScript | class SchemaEndpointResolver {
constructor() {
this.getMethodSchema = memoize(getMethodSchemaInternal, { maxAge: -1 });
}
} |
JavaScript | class GitEmail {
constructor (account, accountType = Account.NAME) {
this.API_BASE = "https://api.github.com";
this.account = account;
this.accountType = accountType;
}
/**
* Attempts to return a jsonified response.
* @param {string} url_end Basically the url suffix that contains the parameters.
* @returns The returned json from the GitHub API.
*/
async getResponse (url_end) {
const response = await fetch(
this.API_BASE + "/" + url_end,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
return response.json();
}
/**
* Sets the object's account and account type.
* @param {String} account The account name or id to set.
* @param {Repo} accountType Defines the type of account.
* @returns The account name.
*/
setAccount (account, accountType) {
this.account = account;
this.accountType = accountType;
return account;
}
/**
* Converts the objects' account from Account.ID to Account.Name.
* @returns The username or null.
*/
async convertToName () {
const response = await this.getUser();
return (user != null) ?
this.setAccount(response["login"], Account.NAME) :
null;
}
/**
* Fetches the user account JSON from the GitHub API.
* @returns The user JSON.
*/
async getUser () {
const user = await this.getResponse(`${this.accountType}/${this.account}`);
return (user.hasOwnProperty("message")) ? null : user;
}
/**
* Fetches the users' repositories (code piece created with the help of @nikitakhutorni).
* @param {Repo} repoType The type filter for accepted repositories.
* @param {Boolean} onlyNames Converts the results strictly to their repository name.
* @returns A list of repositories. Either each entry is JSON-type or a string.
*/
async getUserRepos (repoType = Repo.ALL, onlyNames = false) {
const response = await this.getResponse(`${this.accountType}/${this.account}/repos`);
return (response.hasOwnProperty("message")) ?
null :
response.filter(repo => repoType == Repo.ALL || repoType == repo["fork"])
.map(repo => onlyNames ? repo.name : repo);
}
/**
* Fetches a specific repositories' commits for the objects' user.
* @param {String} repo The repository to get the commits for.
* @returns A list of commits. Maximum amount is 30 due to public API limitations.
*/
async getRepoCommits (repo) {
return await this.getResponse(`repos/${this.account}/${repo}/commits`);
}
async getRepoLanguages () {
}
/**
* Determines the users public committing email.
* @returns The users' public email, true if no repos to scan, false if no repos
* that contain the user's commits or null if user doesn't exist.
*/
async gitEmail () {
const user = await this.getUser();
if (user == null) return null;
const repos = await this.getUserRepos(Repo.OWNED, true);
if (repos.length == 0) {
return true;
}
else {
for (let repo in repos) {
let commits = await this.getRepoCommits(repos[repo]);
for (var commit in commits) {
if (commits[commit].author != null) {
if (commits[commit].author.login == this.account) {
return commits[commit].commit.author.email;
}
}
}
}
return false;
}
}
} |
JavaScript | class Account {
static ID = "user";
static NAME = "users";
constructor (accountType) {
this.accountType = accountType;
}
toString () {
return this.accountType;
}
} |
JavaScript | class Repo {
static ALL = null;
static FORKED = true;
static OWNED = false;
constructor (repo_type) {
this.repo_type = repo_type;
}
toBoolean () {
return this.repo_type;
}
} |
JavaScript | class UserProfileTerms {
constructor () {
this.acceptButton = 'button:contains("Accept Terms")'
this.declineButton = 'button:contains("Decline") '
}
visit (url) {
cy.visit(url)
}
verifyElements () {
cy.get(this.acceptButton).should('be.visible')
cy.get(this.declineButton).should('be.visible')
}
acceptTerms () {
cy.get(this.acceptButton).click()
}
declineTerms () {
cy.get(this.declineButton).click()
}
} |
JavaScript | class StylusInject {
constructor() {
this.files = [];
}
push(file) {
this.files.push(file);
}
} |
JavaScript | class ViewInject {
constructor() {
this.raws = [];
}
raw(name, raw, ...args) {
this.raws.push({name, raw, args});
}
file(name, file, ...args) {
this.raw(name, fs.readFileSync(file, 'utf8'), ...args);
}
} |
JavaScript | class DynamicColumn {
/**
* Get kind specific dynamic column mapping.
*
* @param {string} kind
*
* @returns {*}
*/
static getDynamicColumnMapForKind(kind) {
if (kindSpecificDynamicColumnMapping[kind]) {
return kindSpecificDynamicColumnMapping[kind];
}
kindSpecificDynamicColumnMapping[kind] = {};
for (const columnName in dynamicColumnMap) {
const columnMapping = dynamicColumnMap[columnName];
for (const notificationKind in columnMapping) {
kindSpecificDynamicColumnMapping[notificationKind] = kindSpecificDynamicColumnMapping[notificationKind] || {};
kindSpecificDynamicColumnMapping[notificationKind][columnName] = columnMapping[notificationKind];
}
}
return kindSpecificDynamicColumnMapping[kind];
}
/**
* Get kind specific inverted dynamic column mapping.
*
* @param {string} kind
*
* @returns {*}
*/
static getInvertedDynamicColumnMapForKind(kind) {
kindSpecificInvertedDynamicColumnMapping[kind] = kindSpecificInvertedDynamicColumnMapping[kind]
? kindSpecificInvertedDynamicColumnMapping[kind]
: util.invert(DynamicColumn.getDynamicColumnMapForKind(kind));
return kindSpecificInvertedDynamicColumnMapping[kind];
}
} |
JavaScript | class ObservedContext {
/**
* @param {!INode} node
* @param {!IRenderContext} renderContext
*/
constructor(node, renderContext) {
this.observed = {}
this.node = node
this.graphComponent = renderContext.canvasComponent
this.defsSupport = renderContext.svgDefsManager
this.contextZoom = renderContext.zoom
this.reset()
}
/**
* @param {!IRenderContext} renderContext
*/
update(renderContext) {
this.defsSupport = renderContext.svgDefsManager
this.contextZoom = renderContext.zoom
}
/**
* Resets the context object to an empty object if none of the properties is used.
* @returns {?Object}
*/
reset() {
const oldState = this.observed
this.observed = {}
if (
oldState &&
['tag', 'layout', 'zoom', 'selected', 'highlighted', 'focused'].some(name =>
oldState.hasOwnProperty(name)
)
) {
return oldState
}
return null
}
/**
* Checks the current state for changes and returns the differences to the old state.
* @param {!State} oldState
* @returns {!object}
*/
checkModification(oldState) {
const delta = {}
let change = false
if (oldState.hasOwnProperty('layout')) {
const layout = this.node.layout
const newValue = {
x: layout.x,
y: layout.y,
width: layout.width,
height: layout.height
}
const oldLayout = oldState.layout
if (
newValue.x !== oldLayout.x ||
newValue.y !== oldLayout.y ||
newValue.width !== oldLayout.width ||
newValue.height !== oldLayout.height
) {
delta.layout = newValue
change = true
}
}
if (oldState.hasOwnProperty('zoom')) {
const newValue = this.contextZoom
if (newValue !== oldState.zoom) {
delta.zoom = newValue
change = true
}
}
if (oldState.hasOwnProperty('tag')) {
const newValue = this.node.tag
if (newValue !== oldState.tag) {
delta.tag = newValue
change = true
}
}
if (oldState.hasOwnProperty('selected')) {
const newValue = this.graphComponent.selection.selectedNodes.isSelected(this.node)
if (newValue !== oldState.selected) {
delta.selected = newValue
change = true
}
}
if (oldState.hasOwnProperty('highlighted')) {
const newValue = this.graphComponent.highlightIndicatorManager.selectionModel.isSelected(
this.node
)
if (newValue !== oldState.highlighted) {
delta.highlighted = newValue
change = true
}
}
if (oldState.hasOwnProperty('focused')) {
const newValue = this.graphComponent.focusIndicatorManager.focusedItem === this.node
if (newValue !== oldState.focused) {
delta.focused = newValue
change = true
}
}
return {
change,
delta
}
}
/**
* Returns the layout.
* @type {!NodeLayout}
*/
get layout() {
if (this.observed.hasOwnProperty('layout')) {
return this.observed.layout
}
const layout = this.node.layout
const val = {
x: layout.x,
y: layout.y,
height: layout.height,
width: layout.width
}
return (this.observed.layout = val)
}
/**
* Returns the zoom level.
* @type {number}
*/
get zoom() {
if (this.observed.hasOwnProperty('zoom')) {
return this.observed.zoom
}
return (this.observed.zoom = this.contextZoom)
}
/**
* Returns the tag.
* @type {!object}
*/
get tag() {
if (this.observed.hasOwnProperty('tag')) {
return this.observed.tag
}
return (this.observed.tag = this.node.tag)
}
/**
* Returns the selected state.
* @type {boolean}
*/
get selected() {
if (this.observed.hasOwnProperty('selected')) {
return this.observed.selected
}
return (this.observed.selected = this.graphComponent.selection.selectedNodes.isSelected(
this.node
))
}
/**
* Returns the highlighted state.
* @type {boolean}
*/
get highlighted() {
if (this.observed.hasOwnProperty('highlighted')) {
return this.observed.highlighted
}
return (this.observed.highlighted =
this.graphComponent.highlightIndicatorManager.selectionModel.isSelected(this.node))
}
/**
* Returns the focused state.
* @type {boolean}
*/
get focused() {
if (this.observed.hasOwnProperty('focused')) {
return this.observed.focused
}
return (this.observed.focused =
this.graphComponent.focusIndicatorManager.focusedItem === this.node)
}
/**
* Generates an id for use in SVG defs elements that is unique for the current rendering context.
* @returns {!string}
*/
generateDefsId() {
return this.defsSupport.generateUniqueDefsId()
}
} |
JavaScript | class VuejsNodeStyle extends NodeStyleBase {
/**
* @param {!string} template
*/
constructor(template) {
super()
this._template = ''
this.template = template
}
/**
* Returns the Vuejs template.
* @type {!string}
*/
get template() {
return this._template
}
/**
* Sets the Vuejs template.
* @type {!string}
*/
set template(value) {
if (value !== this._template) {
this._template = value
this.constructorFunction = Vue.extend({
template: value,
data() {
return {
yFilesContext: null,
idMap: {},
urlMap: {}
}
},
methods: {
localId(id) {
let localId = this.idMap[id]
if (typeof localId === 'undefined') {
localId = this.yFilesContext.observedContext.generateDefsId()
this.idMap[id] = localId
}
return localId
},
localUrl(id) {
let localUrl = this.urlMap[id]
if (typeof localUrl === 'undefined') {
const localId = this.localId(id)
localUrl = `url(#${localId})`
this.urlMap[id] = localUrl
}
return localUrl
}
},
computed: {
layout() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('layout')) {
return yFilesContext.layout
}
const layout = yFilesContext.observedContext.layout
return {
width: layout.width,
height: layout.height,
x: layout.x,
y: layout.y
}
},
tag() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('tag')) {
return yFilesContext.tag || {}
}
return yFilesContext.observedContext.tag || {}
},
selected() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('selected')) {
return yFilesContext.selected
}
return yFilesContext.observedContext.selected
},
zoom() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('zoom')) {
return yFilesContext.zoom
}
return yFilesContext.observedContext.zoom
},
focused() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('focused')) {
return yFilesContext.focused
}
return yFilesContext.observedContext.focused
},
highlighted() {
const yFilesContext = this.yFilesContext
if (yFilesContext.hasOwnProperty('highlighted')) {
return yFilesContext.highlighted
}
return yFilesContext.observedContext.highlighted
},
fill() {
return this.tag.fill
},
scale() {
return this.tag.scale
}
}
})
}
}
/**
* Creates a visual that uses a Vuejs component to display a node.
* @see Overrides {@link LabelStyleBase#createVisual}
* @param {!IRenderContext} context
* @param {!INode} node
* @returns {!SvgVisual}
*/
createVisual(context, node) {
// eslint-disable-next-line new-cap
const component = new this.constructorFunction()
this.prepareVueComponent(component, context, node)
// mount the component without passing in a DOM element
component.$mount()
const svgElement = component.$el
if (!(svgElement instanceof SVGElement)) {
throw 'VuejsNodeStyle: Invalid template!'
}
const yFilesContext = component.yFilesContext
const observedContext = yFilesContext.observedContext
if (observedContext) {
const changes = observedContext.reset()
if (changes) {
observedContext.changes = changes
}
}
// set the location
this.updateLocation(node, svgElement)
// save the component instance with the DOM element so we can retrieve it later
svgElement['data-vueComponent'] = component
// return an SvgVisual that uses the DOM element of the component
const svgVisual = new SvgVisual(svgElement)
context.setDisposeCallback(svgVisual, (context, visual) => {
// clean up vue component instance after the visual is disposed
const svgElement = visual.svgElement
svgElement['data-vueComponent'].$destroy()
return null
})
return svgVisual
}
/**
* Updates the visual by returning the old visual, as Vuejs handles updating the component.
* @see Overrides {@link LabelStyleBase#updateVisual}
* @param {!IRenderContext} context
* @param {!SvgVisual} oldVisual
* @param {!INode} node
* @returns {!SvgVisual}
*/
updateVisual(context, oldVisual, node) {
if (oldVisual.svgElement) {
const component = oldVisual.svgElement['data-vueComponent']
if (component) {
const yfilesContext = component.yFilesContext
const observedContext = yfilesContext.observedContext
observedContext.update(context)
if (observedContext && observedContext.changes && !observedContext.updatePending) {
const { change } = observedContext.checkModification(observedContext.changes)
if (change) {
observedContext.updatePending = true
this.updateVueComponent(component, yfilesContext, node)
component.$nextTick(() => {
if (observedContext.updatePending) {
observedContext.updatePending = false
const changes = observedContext.reset()
if (changes) {
observedContext.changes = changes
} else {
delete observedContext.changes
}
}
})
}
}
this.updateLocation(node, oldVisual.svgElement)
return oldVisual
}
}
return this.createVisual(context, node)
}
/**
* Prepares the Vuejs component for rendering.
* @param {*} component
* @param {!IRenderContext} context
* @param {!INode} node
*/
prepareVueComponent(component, context, node) {
const yFilesContext = {}
const ctx = new ObservedContext(node, context)
// Values added using Object.defineProperty() are immutable and not enumerable and thus are not observed by Vuejs.
Object.defineProperty(yFilesContext, 'observedContext', {
configurable: false,
enumerable: false,
value: ctx
})
component.yFilesContext = yFilesContext
}
/**
* Updates the Vuejs component for rendering.
* @param {*} component
* @param {!IRenderContext} context
* @param {!INode} node
*/
updateVueComponent(component, context, node) {
const yFilesContext = {}
const ctx = component.yFilesContext.observedContext
// Values added using Object.defineProperty() are immutable and not enumerable and thus are not observed by Vuejs.
Object.defineProperty(yFilesContext, 'observedContext', {
configurable: false,
enumerable: false,
value: ctx
})
component.yFilesContext = yFilesContext
component.$forceUpdate()
}
/**
* Updates the location of the given visual.
* @param {!INode} node
* @param {!SVGElement} svgElement
*/
updateLocation(node, svgElement) {
if (svgElement.transform) {
SvgVisual.setTranslate(svgElement, node.layout.x, node.layout.y)
}
}
} |
JavaScript | class KubernetesEntityClient {
static entityApiPrefix = {
cluster: clusterEndpoint,
machine: clusterEndpoint,
publickey: kaasEndpoint,
openstackcredential: kaasEndpoint,
awscredential: kaasEndpoint,
byocredential: kaasEndpoint,
clusterrelease: kaasEndpoint,
kaasrelease: kaasEndpoint,
openstackresource: kaasEndpoint,
awsresource: kaasEndpoint,
kaascephcluster: kaasEndpoint,
baremetalhost: metalEndpoint,
};
constructor(baseUrl, token, entity) {
if (!baseUrl || !token || !entity) {
throw new Error('baseUrl, token, and entity are required');
}
this.baseUrl = baseUrl.replace(/\/$/, ''); // remove end slash if any
this.apiPrefix = KubernetesEntityClient.entityApiPrefix[entity];
this.token = token;
this.headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.token}`,
};
}
request(url, { options = {}, expectedStatuses = [200], errorMessage }) {
return request(
`${this.baseUrl}/${this.apiPrefix}/${url}`,
{
credentials: 'same-origin',
...options,
headers: {
...this.headers,
...((options && options.headers) || {}),
},
},
{ expectedStatuses, errorMessage }
);
}
get(entity, { namespaceName, name, entityDescriptionName } = {}) {
return this.request(`${namespacePrefix(namespaceName)}${entity}s/${name}`, {
errorMessage: strings.apiClient.error.failedToGet(
entityDescriptionName || entity
),
});
}
list(entity, { namespaceName, entityDescriptionName } = {}) {
return this.request(`${namespacePrefix(namespaceName)}${entity}s`, {
errorMessage: strings.apiClient.error.failedToGetList(
entityDescriptionName || entity
),
});
}
listAll(entity, { entityDescriptionName } = {}) {
return this.request(`${entity}s`, {
errorMessage: strings.apiClient.error.failedToGetList(
entityDescriptionName || entity
),
});
}
create(entity, { namespaceName, config, entityDescriptionName } = {}) {
return this.request(`${namespacePrefix(namespaceName)}${entity}s/create`, {
options: { method: 'POST', body: JSON.stringify(config) },
expectedStatuses: [201],
errorMessage: strings.apiClient.error.failedToCreate(
entityDescriptionName || entity
),
});
}
delete(entity, { namespaceName, name, entityDescriptionName } = {}) {
return this.request(`${namespacePrefix(namespaceName)}${entity}s/${name}`, {
options: { method: 'DELETE' },
errorMessage: strings.apiClient.error.failedToDelete(
`${entityDescriptionName || entity} "${name}"`
),
});
}
update(entity, { namespaceName, name, entityDescriptionName, patch } = {}) {
return this.request(`${namespacePrefix(namespaceName)}${entity}s/${name}`, {
options: {
method: 'PATCH',
body: JSON.stringify(patch),
headers: { 'Content-Type': 'application/merge-patch+json' },
},
errorMessage: strings.apiClient.error.failedToUpdate(
`${entityDescriptionName || entity} "${name}"`
),
});
}
} |
JavaScript | class MultipleCollisionTest {
/**
* @private
*/
constructor() { throw new Error(); };
static test() {
schedule(goog.partial(MultipleCollisionTest.test1_0, CollisionHandling.SIMULTANEOUS));
schedule(goog.partial(MultipleCollisionTest.test1_0, CollisionHandling.HYBRID));
schedule(goog.partial(MultipleCollisionTest.test1_1, CollisionHandling.SERIAL_GROUPED_LASTPASS));
schedule(goog.partial(MultipleCollisionTest.test2_0, CollisionHandling.SIMULTANEOUS, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test2_0, CollisionHandling.SIMULTANEOUS, MultipleCollisionTest.BLOCK));
schedule(goog.partial(MultipleCollisionTest.test2_1, CollisionHandling.SERIAL_GROUPED_LASTPASS, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test2_1, CollisionHandling.HYBRID, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test2_1, CollisionHandling.HYBRID, MultipleCollisionTest.BLOCK));
schedule(goog.partial(MultipleCollisionTest.test3_0, CollisionHandling.SIMULTANEOUS));
schedule(goog.partial(MultipleCollisionTest.test3_0, CollisionHandling.HYBRID));
schedule(goog.partial(MultipleCollisionTest.test3_1, CollisionHandling.SERIAL_GROUPED_LASTPASS));
schedule(goog.partial(MultipleCollisionTest.test4_0, CollisionHandling.SIMULTANEOUS));
schedule(goog.partial(MultipleCollisionTest.test4_0, CollisionHandling.HYBRID));
schedule(goog.partial(MultipleCollisionTest.test4_1, CollisionHandling.SERIAL_GROUPED_LASTPASS));
schedule(goog.partial(MultipleCollisionTest.test5_0, CollisionHandling.SIMULTANEOUS, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test5_0, CollisionHandling.HYBRID, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test5_0, CollisionHandling.SERIAL_GROUPED_LASTPASS, MultipleCollisionTest.BALL));
schedule(goog.partial(MultipleCollisionTest.test5_0, CollisionHandling.SIMULTANEOUS, MultipleCollisionTest.BLOCK));
schedule(goog.partial(MultipleCollisionTest.test5_0, CollisionHandling.HYBRID, MultipleCollisionTest.BLOCK));
schedule(goog.partial(MultipleCollisionTest.test6_0, CollisionHandling.SERIAL_GROUPED_LASTPASS));
schedule(goog.partial(MultipleCollisionTest.test6_1, CollisionHandling.SIMULTANEOUS));
schedule(goog.partial(MultipleCollisionTest.test6_1, CollisionHandling.HYBRID));
schedule(goog.partial(MultipleCollisionTest.test7_0, CollisionHandling.SIMULTANEOUS));
schedule(goog.partial(MultipleCollisionTest.test7_1, CollisionHandling.HYBRID));
schedule(goog.partial(MultipleCollisionTest.test7_2, CollisionHandling.SERIAL_GROUPED_LASTPASS));
schedule(MultipleCollisionTest.test8_0);
schedule(MultipleCollisionTest.test8_1);
schedule(MultipleCollisionTest.test8_2);
schedule(MultipleCollisionTest.test8_3);
schedule(MultipleCollisionTest.test8_5);
schedule(MultipleCollisionTest.two_in_box);
schedule(MultipleCollisionTest.one_hits_two_in_box);
};
/**
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@private
*/
static commonSetup1(sim, advance) {
sim.addForceLaw(new DampingLaw(0, 0.15, sim.getSimList()));
sim.setCollisionAccuracy(0.6);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(99999);
if (sim instanceof ContactSim) {
sim.setDistanceTol(MultipleCollisionTest.distanceTol_);
sim.setVelocityTol(MultipleCollisionTest.velocityTol_);
sim.setExtraAccel(ExtraAccel.VELOCITY);
}
advance.setJointSmallImpacts(false);
advance.setTimeStep(0.025);
advance.setDiffEqSolver(new RungeKutta(sim));
};
/** 'one hits wall': Square block collides into a wall, both corners simultaneously.
The result depends on the collision handling mechanism.
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_wall_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var b0 = Shapes.makeBlock(1, 1, 'block');
b0.setPosition(new Vector(0, 2), 0);
b0.setVelocity(new Vector(0, -3), 0);
sim.addBody(b0);
var b1 = Shapes.makeBlock(3, 1, 'wall');
b1.setPosition(new Vector(0, -2), 0);
b1.setMass(Util.POSITIVE_INFINITY);
sim.addBody(b1);
sim.setElasticity(1.0);
};
/** With sequential or hybrid collision handling, the block bounces straight off the wall.
@param {!CollisionHandling} collisionType
*/
static test1_0(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test1_0 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.one_hits_wall_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*2);
setBodyVars(sim, vars, 0, 0, 0, 2.01, 3, 0, 0);
setBodyVars(sim, vars, 1, 0, 0, -2, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** With serial collision handling, the block starts rotating.
@param {!CollisionHandling} collisionType
*/
static test1_1(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test1_1 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.one_hits_wall_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*2);
setBodyVars(sim, vars, 0, 0, 0, 1.7696, 2.76, -2.8848, -2.88);
setBodyVars(sim, vars, 1, 0, 0, -2, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'one hits two': A ball (or square block) on the left moves to hit two balls that are
in resting contact.
The result depends on the type of collision handling being used.
Because resting contact is involved, we need to use ContactSim instead of ImpulseSim.
@param {!ImpulseSim} sim the ImpulseSim to add the objects to
@param {!CollisionAdvance} advance
@param {number} offset additional distance between the stationary objects
@param {boolean} balls true gives round balls, false gives square blocks
*/
static test2_prep(sim, advance, offset, balls) {
MultipleCollisionTest.commonSetup1(sim, advance);
var radius = 0.5;
var b0 = balls ? Shapes.makeBall(radius, 'ball0')
: Shapes.makeBlock(2*radius, 2*radius, 'block0');
b0.setPosition(new Vector(-3, 0), 0);
b0.setVelocity(new Vector(3, 0), 0);
sim.addBody(b0);
var b1 = balls ? Shapes.makeBall(radius, 'ball1')
: Shapes.makeBlock(2*radius, 2*radius, 'block1');
b1.setPosition(new Vector(0, 0), 0);
sim.addBody(b1);
var b2 = balls ? Shapes.makeBall(radius, 'ball2')
: Shapes.makeBlock(2*radius, 2*radius, 'block2');
b2.setPosition(new Vector(2*radius + MultipleCollisionTest.distanceTol_/2 + offset, 0), 0);
sim.addBody(b2);
sim.setElasticity(1.0);
};
/**
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_ball_setup(sim, advance) {
MultipleCollisionTest.test2_prep(sim, advance, 0, MultipleCollisionTest.BALL);
};
/**
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_block_setup(sim, advance) {
MultipleCollisionTest.test2_prep(sim, advance, 0, MultipleCollisionTest.BLOCK);
};
/** With simultaneous collision handling, all the balls are moving after the collision
(which is physically wrong, but it is how it should behave).
@param {!CollisionHandling} collisionType
@param {boolean} balls true gives round balls, false gives square blocks
*/
static test2_0(collisionType, balls) {
setTestName(MultipleCollisionTest.groupName+'test2_0 '+collisionType+' balls='+balls);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.test2_prep(sim, advance, 0, balls);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -2.34, -1, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 2.67, 2, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 3.675, 2, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** With serial or hybrid collision handling, the result is only the right-most ball is moving.
@param {!CollisionHandling} collisionType
@param {boolean} balls true gives round balls, false gives square blocks
*/
static test2_1(collisionType, balls) {
setTestName(MultipleCollisionTest.groupName+'test2_1 '+collisionType+' balls='+balls);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.test2_prep(sim, advance, 0, balls);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -1.005, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 5.01, 3, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'Two hits one asymmetric': Two balls approach a central stationary ball so that the collisions
happen at the same moment; the balls have different velocities. The result should
be that the central ball should remain motionless and the moving balls bounce off but
exchange velocities.
Because there are no static contacts, but only two dynamic collisions, we can use
ImpulseSim here (don't need to use ContactSim).
* Here is why we need to add distTol/2 to starting position of body1:
* The collision happens when the blocks are distTol/2 apart, so the distance
* travelled is slightly less than you would expect.
* Suppose distTol = 0.01; and distTol/2 = 0.005.
* body2.left = 0.5; body3.right = 2.5; body3 travels 2.5 - 0.5 - 0.005 = 1.995
* If body1 starts at -5, it travels a distance of 3.995 which is more than
* twice the distance that body3 travels, so it arrives after body3 collision.
* To have them collide at the same moment:
* Since body1 travels at twice the speed, it should travel 1.995 * 2 = 3.99
* Therefore body1.right = body2.left - 0.005 - 3.99 = -4.495
* Therefore body1.center = -4.995 = -5 + distTol/2
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static two_hits_one_asymmetric_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var distTol = sim.getDistanceTol();
var radius = 0.5;
var b0 = Shapes.makeBall(radius, 'left');
b0.setPosition(new Vector(-5 + distTol/2, 0), 0);
b0.setVelocity(new Vector(3, 0), 0);
sim.addBody(b0);
var b1 = Shapes.makeBall(radius, 'center');
b1.setPosition(new Vector(0, 0), 0);
sim.addBody(b1);
var b2 = Shapes.makeBall(radius, 'right');
b2.setPosition(new Vector(3, 0), 0);
b2.setVelocity(new Vector(-1.5, 0), 0);
sim.addBody(b2);
sim.setElasticity(1.0);
};
/**With simultaneous collision handling, all the balls are moving after the collision
(which is physically wrong, but it is how it should behave).
OCT 2011: for some unknown reason, the “two hits one asymmetric” multiple collision
test now works identically for all collision solvers.
MAY 2016: I've solved the above problem, see the setup function above.
@param {!CollisionHandling} collisionType
*/
static test3_0(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test3_0 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.two_hits_one_asymmetric_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -2.345, -2, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0.67, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 2.68, 2.5, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/**With serial collision handling, the center ball remains motionless, and
the two balls exchange velocity.
@param {!CollisionHandling} collisionType
*/
static test3_1(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test3_1 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.two_hits_one_asymmetric_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -2.01, -1.5, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 3.015, 3, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'one hits two separate': a moving block hits two separated balls simultaneously.
The result depends on the type of collision handling used.
Because there are no static contacts, but only two dynamic collisions, we can use
ImpulseSim here (don't need to use ContactSim).
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_separate_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var b0 = Shapes.makeBlock(1, 3, 'block0');
b0.setPosition(new Vector(-4, 0), 0); // could modify angle slightly here
b0.setVelocity(new Vector(3, 0), 0);
b0.setMass(2);
sim.addBody(b0);
var b1 = Shapes.makeBall(0.5, 'ball1');
b1.setPosition(new Vector(0, 1), 0);
sim.addBody(b1);
var b2 = Shapes.makeBall(0.5, 'ball2');
b2.setPosition(new Vector(0, -1), 0);
sim.addBody(b2);
sim.setElasticity(1.0);
};
/**
@param {!CollisionHandling} collisionType
*/
static test4_0(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test4_0 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.one_hits_two_separate_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -1.005, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 3.005, 3, 1, 0, 0, 0);
setBodyVars(sim, vars, 2, 3.005, 3, -1, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/**
@param {!CollisionHandling} collisionType
*/
static test4_1(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test4_1 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.one_hits_two_separate_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -0.9981859, 0.0068027, 0, 0, 0.1635374, 0.1632653);
setBodyVars(sim, vars, 1, 3.1344671, 3.1292517, 1, 0, 0, 0);
setBodyVars(sim, vars, 2, 2.8619048, 2.8571429, -1, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'one hits two on wall': two balls (or blocks) are in stationary contact with
a wall (infinite mass); a third ball collides into them from the left; the result
is usually that the ball just bounces off and the two balls stay in stationary contact.
The exception is when using serial collision handling and square blocks instead of
round balls (because then the two corner collisions on the blocks are handled
serially instead of simultaneously).
Because this test involves resting contacts, we must use ContactSim.
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@param {boolean} balls true gives round balls, false gives square blocks
*/
static test5_prep(sim, advance, balls) {
MultipleCollisionTest.commonSetup1(sim, advance);
var radius = 0.5;
var b0 = balls ? Shapes.makeBall(radius, 'ball0')
: Shapes.makeBlock(2*radius, 2*radius, 'block0');
b0.setPosition(new Vector(-3, 0), 0);
b0.setVelocity(new Vector(3, 0), 0);
sim.addBody(b0);
var b1 = balls ? Shapes.makeBall(radius, 'ball1')
: Shapes.makeBlock(2*radius, 2*radius, 'block1');
b1.setPosition(new Vector(0, 0), 0);
sim.addBody(b1);
var b2 = balls ? Shapes.makeBall(radius, 'ball2')
: Shapes.makeBlock(2*radius, 2*radius, 'block2');
b2.setPosition(new Vector(2*radius + MultipleCollisionTest.distanceTol_/2, 0), 0);
sim.addBody(b2);
var b3 = Shapes.makeBlock(1, 3, 'wall');
b3.setMass(Util.POSITIVE_INFINITY);
b3.setPosition(new Vector(3*radius + 0.5 + MultipleCollisionTest.distanceTol_, 0), 0);
sim.addBody(b3);
sim.setElasticity(1.0);
};
/**
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_on_wall_ball_setup(sim, advance) {
MultipleCollisionTest.test5_prep(sim, advance, MultipleCollisionTest.BALL);
};
/**
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_on_wall_block_setup(sim, advance) {
MultipleCollisionTest.test5_prep(sim, advance, MultipleCollisionTest.BLOCK);
};
/**
@param {!CollisionHandling} collisionType
@param {boolean} balls true gives round balls, false gives square blocks
*/
static test5_0(collisionType, balls) {
setTestName(MultipleCollisionTest.groupName+'test5_0 '+collisionType+' balls='+balls);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.test5_prep(sim, advance, balls);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -5.01, -3, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 1.005, 0, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'center spin': There are two stationary blocks with a third block in between them;
the center block is spinning and will simultaneously hit the other two blocks.
This is similar to the 'one hits two separate' scenario, except its a spinning
block instead of a translating block that causes the collision.
There are no static contacts so either ImpulseSim or ContactSim shows the
same results.
This corresponds to the 'center spin' version of the interactive SimultaneousCollision test.
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static center_spin_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var b0 = Shapes.makeBlock(1, 3, 'block0');
b0.setPosition(new Vector(0, 0), 0);
b0.setVelocity(new Vector(0, 0), 2);
sim.addBody(b0);
var b1 = Shapes.makeBlock(1, 3, 'block1');
b1.setPosition(new Vector(2.8, 0), Math.PI/2);
sim.addBody(b1);
var b2 = Shapes.makeBlock(1, 3, 'block2');
b2.setPosition(new Vector(-2.8, 0), -Math.PI/2);
sim.addBody(b2);
sim.setElasticity(1.0);
};
/** Serial collision handling case: non-symmetric result.
@param {!CollisionHandling} collisionType
*/
static test6_0(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test6_0 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.center_spin_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, 0.1855924, 0.3179762, 0.2040219, 0.3495516, 0.4374322, -0.6771538);
setBodyVars(sim, vars, 1, 3.0447046, 0.4192534, 0.269004, 0.4608857, 1.2334118, -0.5780423);
setBodyVars(sim, vars, 2, -3.230297, -0.7372296, -0.473026, -0.8104373, -2.1640649, -1.0164494);
// runUntil=1.0
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** Simultaneous collision handling case: symmetric result.
@param {!CollisionHandling} collisionType
*/
static test6_1(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test6_1 '+collisionType);
var sim = new ImpulseSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.center_spin_setup(sim, advance);
sim.setCollisionHandling(collisionType);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, 0, 0, 0, 0, 0.3612164, -0.8077347);
setBodyVars(sim, vars, 1, 3.1539628, 0.6064458, 0.3891116, 0.6666666, 1.082773, -0.8361323);
setBodyVars(sim, vars, 2, -3.1539628, -0.6064458, -0.3891116, -0.6666666, -2.0588196, -0.8361323);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** 'side spin': There are two stationary blocks in resting contact, with a third block
nearby; the third block is spinning and will hit one of the two blocks.
This is similar to the 'one hits two' scenario, except its a spinning
block instead of a translating block that causes the collision.
Because this test involves resting contacts, we must use ContactSim.
This corresponds to the 'side spin' version of the interactive SimultaneousCollision test.
@param {!ImpulseSim} sim
@param {!CollisionAdvance} advance
@export
*/
static side_spin_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var b0 = Shapes.makeBlock(1, 3, 'block0');
b0.setPosition(new Vector(0, 0), Math.PI/2);
sim.addBody(b0);
var b1 = Shapes.makeBlock(1, 3, 'block1');
b1.setPosition(new Vector(2.8, 1.001), 0);
b1.setVelocity(new Vector(0, 0), 2);
sim.addBody(b1);
var b2 = Shapes.makeBlock(1, 3, 'block2');
b2.setPosition(new Vector(-2.8, 1.001), Math.PI/2);
sim.addBody(b2);
sim.setElasticity(1.0);
};
/** Simultaneous collision handling case.
Note (March 30 2011): This failed with ContactSim.VELOCITY_TOL = 0.5, so I lowered
VELOCITY_TOL to 0.05.
The problem was that energy was increasing after the collision; the cause was that a contact
was being detected that had a relatively high velocity of 0.28, and a contact force
was acting there (and because work = force * distance, there was energy being added as
the contact was separating).
@param {!CollisionHandling} collisionType
*/
static test7_0(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test7_0 '+collisionType);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.side_spin_setup(sim, advance);
sim.setCollisionHandling(collisionType);
sim.setVelocityTol(0.05);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -0, -0, -0.2407811, -1.1140238, 1.3296854, -1.1155496);
setBodyVars(sim, vars, 1, 2.8, 0, 1.2018587, 0.9293143, 1.6380862, 0.3255308);
setBodyVars(sim, vars, 2, -2.8, 0, 1.0409225, 0.1847096, 1.6330754, 0.2881469);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** Hybrid collision handling case.
@param {!CollisionHandling} collisionType
*/
static test7_1(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test7_1 '+collisionType);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.side_spin_setup(sim, advance);
sim.setCollisionHandling(collisionType);
sim.setRandomSeed(86161959);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -0, -0, -0.2696156, -1.2474324, 1.4082314, -0.7521404);
setBodyVars(sim, vars, 1, 2.8, 0, 1.1939246, 0.8926056, 1.6523821, 0.3916737);
setBodyVars(sim, vars, 2, -2.8, 0, 1.077691, 0.3548268, 1.6904343, 0.5535298);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** Serial collision handling case.
@param {!CollisionHandling} collisionType
*/
static test7_2(collisionType) {
setTestName(MultipleCollisionTest.groupName+'test7_2 '+collisionType);
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.side_spin_setup(sim, advance);
sim.setCollisionHandling(collisionType);
sim.setRandomSeed(86161959);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, -0.0005129, -0.002373, -0.2514185, -1.16324, 1.4220696, -0.6881151);
setBodyVars(sim, vars, 1, 2.8005129, 0.002373, 1.1681077, 0.7731586, 1.7396203, 0.7952992);
setBodyVars(sim, vars, 2, -2.8, 0, 1.0853108, 0.3900814, 1.7023212, 0.608527);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** Two blocks are connected by a joint and lie on the ground; a third block collides
into the connected blocks. This is a fairly simple test of joints and contacts during
a collision.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static joint_collision_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var zel = Walls.make(sim, /*width=*/20, /*height=*/10);
var j1 = Shapes.makeBlock(1, 3, 'joint1');
j1.setPosition(new Vector(2, -5 + 0.5 + 0.005), Math.PI/2);
var j2 = Shapes.makeBlock(1, 3, 'joint2');
j2.setPosition(new Vector(4, -5 + 0.5 + 0.005), Math.PI/2);
sim.addBody(j1);
sim.addBody(j2);
JointUtil.attachRigidBody(sim,
j1, /*attach_body=*/new Vector(0, 1.0),
j2, /*attach_body=*/new Vector(0, -1.0),
/*normalType=*/CoordType.BODY
);
/* move the bodies so their joints line up over each other. */
sim.alignConnectors();
var f1 = Shapes.makeBlock(1, 3, 'free1');
f1.setPosition(new Vector(-6, -5 + 0.5 + 0.005), Math.PI/2);
f1.setVelocity(new Vector(3, 0), 0);
sim.addBody(f1);
var gravity = new GravityLaw(4.0, sim.getSimList());
sim.addForceLaw(gravity);
gravity.setZeroEnergyLevel(zel + 0.5);
sim.setElasticity(0.8);
};
/**
@return {undefined}
*/
static test8_0() {
setTestName(MultipleCollisionTest.groupName+'test8_0');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.joint_collision_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*7);
setBodyVars(sim, vars, 4, 5.3468095, 1.3378378, -4.4909991, -0, 1.5708394, -0);
setBodyVars(sim, vars, 5, 3.3468392, 1.3378378, -4.4943779, 0, 1.5741319, 0);
setBodyVars(sim, vars, 6, -2.1936486, 0.3243243, -4.49445, 0.0000026, 1.5687089, -0.0000012);
runTest(sim, advance, /*runUntil=*/3.5,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
runTest(sim, advance, /*runUntil=*/5.5,
/*expectedVars=*/null, /*tolerance=*/0.000001,
/*expectedEnergyDiff=*/0.0, /*energyTol=*/0.000001,
/*expectedCollisions=*/-1);
};
/** Show that get same results with elastic or inelastic joints.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static joint_collision_2_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var j1 = Shapes.makeBlock(1, 3, 'joint1');
j1.setPosition(new Vector(2, 0), Math.PI/2);
var j2 = Shapes.makeBlock(1, 3, 'joint2');
j2.setPosition(new Vector(0, 0), Math.PI/2);
j2.setVelocity(new Vector(3, 0), 0);
sim.addBody(j1);
sim.addBody(j2);
JointUtil.attachRigidBody(sim,
j1, /*attach_body=*/new Vector(0, 1.0),
j2, /*attach_body=*/new Vector(0, -1.0),
/*normalType=*/CoordType.BODY
);
/* move the bodies so their joints line up over each other. */
sim.alignConnectors();
var collisions = [];
sim.findCollisions(collisions, sim.getVarsList().getValues(), 0);
sim.handleCollisions(collisions);
sim.setElasticity(0.8);
};
/**
@return {undefined}
*/
static test8_1() {
setTestName(MultipleCollisionTest.groupName+'test8_1');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.joint_collision_2_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*2);
setBodyVars(sim, vars, 0, 6.5, 1.5, -0, -0, 1.5707963, 0);
setBodyVars(sim, vars, 1, 4.5, 1.5, 0, 0, 1.5707963, 0);
runTest(sim, advance, /*runUntil=*/3.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
/** Show that get same results with elastic or inelastic joints.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static joint_collision_3_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var j1 = Shapes.makeBlock(1, 3, 'joint1');
j1.setPosition(new Vector(2, 0), Math.PI/2);
sim.addBody(j1);
var j2 = Shapes.makeBlock(1, 3, 'joint2');
j2.setPosition(new Vector(0, 0), Math.PI/2);
sim.addBody(j2);
JointUtil.attachRigidBody(sim,
j1, /*attach_body=*/new Vector(0, 1.0),
j2, /*attach_body=*/new Vector(0, -1.0),
/*normalType=*/CoordType.BODY
);
/* move the bodies so their joints line up over each other. */
sim.alignConnectors();
var f1 = Shapes.makeBall(/*radius=*/0.5, 'free1');
f1.setPosition(new Vector(-6, 0), Math.PI/2);
f1.setVelocity(new Vector(3, 0), 0);
sim.addBody(f1);
sim.setElasticity(1.0);
};
/**
@return {undefined}
*/
static test8_2() {
setTestName(MultipleCollisionTest.groupName+'test8_2');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.joint_collision_3_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, 5.3366667, 2, -0, -0, 1.5707963, 0);
setBodyVars(sim, vars, 1, 3.3366667, 2, -0, -0, 1.5707963, 0);
setBodyVars(sim, vars, 2, -3.6733333, -1, 0, 0, 1.5707963, 0);
runTest(sim, advance, /*runUntil=*/3.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
/** The simplest case of a 'spinning joint': two bodies connected by a joint, they are
rotating about the joint at different rates. This shows that we are unable to keep
spinning joints tight with just contact force calculations.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static joint_collision_4_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var j1 = Shapes.makeBlock(1, 3, 'joint1');
j1.setPosition(new Vector(2, 0), Math.PI/2);
j1.setVelocity(new Vector(0, 0), 3);
sim.addBody(j1);
var j2 = Shapes.makeBlock(1, 3, 'joint2');
j2.setPosition(new Vector(0, 0), Math.PI/2);
j2.setVelocity(new Vector(0, 0), -5);
sim.addBody(j2);
JointUtil.attachRigidBody(sim,
j1, /*attach_body=*/new Vector(0, 1.0),
j2, /*attach_body=*/new Vector(0, -1.0),
/*normalType=*/CoordType.BODY
);
/* move the bodies so their joints line up over each other. */
sim.alignConnectors();
sim.setElasticity(0.8);
var collisions = [];
sim.findCollisions(collisions, sim.getVarsList().getValues(), 0);
sim.handleCollisions(collisions);
};
/**
@return {undefined}
*/
static test8_3() {
setTestName(MultipleCollisionTest.groupName+'test8_3');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.joint_collision_4_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*2);
setBodyVars(sim, vars, 0, 1.4983143, 0.2052494, 0.8618191, -0.5534606, 8.9952832, 3.5216341);
setBodyVars(sim, vars, 1, 0.5016857, -0.2052494, -0.8618191, 0.5534606, -10.0437751, -4.435186);
runTest(sim, advance, /*runUntil=*/3.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
/** Two rectangle blocks are connected by a joint; the blocks are at rest with
a ball object in contact with them on their right; from left a ball object strikes
the jointed rectangle blocks.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static joint_collision_5_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var distTol = sim.getDistanceTol();
var body = Shapes.makeBall(0.5, 'body4');
body.setMass(2);
body.setPosition(new Vector(1 + distTol/2, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body1');
body.setMass(2);
body.setPosition(new Vector(-5, 0), 0);
body.setVelocity(new Vector(3, 0), 0);
sim.addBody(body);
var body2 = Shapes.makeBlock(2, 1, 'body2');
body2.setPosition(new Vector(-2, 0));
sim.addBody(body2);
var body3 = Shapes.makeBlock(2, 1, 'body3');
body3.setPosition(new Vector(-0.5, 0));
sim.addBody(body3);
JointUtil.attachRigidBody(sim,
body2, /*attach_body1=*/new Vector(0.75, 0),
body3, /*attach_body2=*/new Vector(-0.75, 0),
/*normalType=*/CoordType.BODY
);
sim.alignConnectors();
sim.setElasticity(1.0);
};
/**
@return {undefined}
*/
static test8_5() {
setTestName(MultipleCollisionTest.groupName+'test8_5');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.joint_collision_5_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*4);
setBodyVars(sim, vars, 0, 2.51, 3, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, -3.505, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, -2, 0, 0, 0, 0, 0);
setBodyVars(sim, vars, 3, -0.5, 0, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
/** Two balls are inside a rectangular frame. One ball is given a rightward initial
velocity. This causes an infinite series of collisions, but certain settings for the
collision handling can cope with this problem. See Physics Based Animation by Erleben,
et. al. Chapter 6-2 'Multiple Points of Collision'.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static two_in_box_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var distTol = sim.getDistanceTol();
var body = Shapes.makeFrame(/*width=*/2 + 3*distTol/2 + 0.2,
/*height=*/1 + 2*distTol/2 + 0.2, /*thickness=*/0.2, 'body1');
body.setPosition(new Vector(0, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body2');
body.setPosition(new Vector(-0.5-distTol/4, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body3');
body.setPosition(new Vector(0.5+distTol/4, 0));
body.setVelocity(new Vector(3, 0), 0);
sim.addBody(body);
sim.setElasticity(1.0);
};
/**
@return {undefined}
*/
static two_in_box() {
setTestName(MultipleCollisionTest.groupName+'two_in_box');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.two_in_box_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*3);
setBodyVars(sim, vars, 0, 1, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0.4975, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 1.5025, 1, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/1.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
/** Two balls are inside a rectangular frame. A third ball strikes the frame from left.
This causes an infinite series of collisions, but certain settings for the
collision handling can cope with this problem. See Physics Based Animation by Erleben,
et. al. Chapter 6-2 'Multiple Points of Collision'.
@param {!ContactSim} sim
@param {!CollisionAdvance} advance
@export
*/
static one_hits_two_in_box_setup(sim, advance) {
MultipleCollisionTest.commonSetup1(sim, advance);
var distTol = sim.getDistanceTol();
var body = Shapes.makeFrame(/*width=*/2 + 3*distTol/2 + 0.2,
/*height=*/1 + 2*distTol/2 + 0.2, /*thickness=*/0.2, 'body1');
body.setPosition(new Vector(0, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body2');
body.setPosition(new Vector(-0.5-distTol/4, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body3');
body.setPosition(new Vector(0.5+distTol/4, 0));
sim.addBody(body);
body = Shapes.makeBall(0.5, 'body4');
body.setPosition(new Vector(-5, 0));
body.setVelocity(new Vector(3, 0), 0);
sim.addBody(body);
sim.setElasticity(1.0);
};
/**
@return {undefined}
*/
static one_hits_two_in_box() {
setTestName(MultipleCollisionTest.groupName+'two_in_box');
var sim = new ContactSim();
var advance = new CollisionAdvance(sim);
MultipleCollisionTest.one_hits_two_in_box_setup(sim, advance);
sim.setCollisionHandling(CollisionHandling.SERIAL_GROUPED_LASTPASS);
sim.setRandomSeed(86161959);
var vars = makeVars(6*4);
setBodyVars(sim, vars, 0, 0.9041667, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 1, 0.4016667, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 2, 1.4066667, 1, 0, 0, 0, 0);
setBodyVars(sim, vars, 3, -1.7125, 0, 0, 0, 0, 0);
runTest(sim, advance, /*runUntil=*/2.0,
/*expectedVars=*/vars, /*tolerance=*/0.000001);
};
} // end class |
JavaScript | class HexPicker extends LitElement {
static get haxProperties() {
return {
canScale: false,
canPosition: false,
canEditSource: true,
gizmo: {
title: "Hex Picker",
description: "Hexcode color picker",
icon: "image:colorize",
color: "grey",
groups: ["color", "picker"],
handles: [],
meta: {
author: "collinkleest",
owner: "ELMS:LN",
},
},
settings: {
configure: [
{
property: "value",
title: "Value",
description: "Default hex value",
inputMethod: "textfield",
},
{
property: "disabled",
title: "Disabled",
description: "Disable the text field",
inputMethod: "boolean",
},
{
property: "largeDisplay",
title: "Large Display",
description: "Include color in large display",
inputMethod: "boolean",
},
],
advanced: [],
},
demoSchema: [
{
tag: "hex-picker",
properties: {
org: "elmsln",
repo: "lrnwebcomponents",
},
content: "",
},
],
};
}
static get properties() {
return {
...super.properties,
value: {
type: String,
reflect: true,
attribute: "value",
},
disabled: {
type: Boolean,
reflect: true,
attribute: "disabled",
},
largeDisplay: {
type: Boolean,
reflect: true,
attribute: "large-display",
},
};
}
static get styles() {
return [
css`
:host {
--color-picker-width: 200px;
--color-picker-input-margin: 5px;
--color-picker-input-padding: 5px;
display: flex;
flex-direction: column;
}
.input-container {
display: inline-flex;
align-items: center;
box-sizing: border-box;
width: var(--color-picker-width);
}
.color-square {
background-color: #000000ff;
border: 1px dotted black;
width: var(--color-picker-square-width, 15px);
height: var(--color-picker-square-height, 15px);
margin-left: -35px;
}
.slider-container {
width: var(--color-picker-width);
}
fieldset {
border: none;
display: flex;
align-items: center;
}
.text-input {
margin-top: var(--color-picker-input-margin);
margin-bottom: var(--color-picker-input-margin);
padding: var(--color-picker-input-padding);
width: calc(
var(--color-picker-width) - 8px - var(--color-picker-input-margin)
);
}
.large-display {
width: var(--color-picker-width);
height: var(--color-picker-lg-block-height, 100px);
background-color: #000000ff;
border: 1px dotted black;
border-radius: 2px;
}
`,
];
}
/**
* Convention we use
*/
static get tag() {
return "hex-picker";
}
/**
* HTMLElement
*/
constructor() {
super();
this.value = "#000000FF";
this._rValue = 0;
this._gValue = 0;
this._bValue = 0;
this._oValue = 255;
this.disabled = false;
}
render() {
return html`
${this.largeDisplay ? html`<div class="large-display"></div>` : ``}
<div class="input-container">
<input
class="text-input"
maxlength="9"
@input="${this._inputChanged}"
@keydown="${this._validateInput}"
.disabled=${this.disabled}>
</input>
<div class="color-square"></div>
</div>
<div class="slider-container">
${this.renderFieldSet("R")}
${this.renderFieldSet("G")}
${this.renderFieldSet("B")}
${this.renderFieldSet("O")}
</div>
`;
}
_validateInput(event) {
let char = String.fromCharCode(event.which);
if (
!char.match(/[0-9A-Fa-f\b]/g) &&
event.which !== 39 &&
event.which !== 37
) {
event.preventDefault();
}
}
_padHex(n) {
return n.length < 2 ? "0" + n : n;
}
_computeHex() {
let rHex = this._rValue.toString(16),
gHex = this._gValue.toString(16),
bHex = this._bValue.toString(16),
oHex = this._oValue.toString(16),
hexValue =
"#" +
this._padHex(rHex) +
this._padHex(gHex) +
this._padHex(bHex) +
this._padHex(oHex);
return hexValue;
}
_inputChanged(event) {
let hexInput = event.target.value;
if (!hexInput.startsWith("#")) {
hexInput = "#" + hexInput;
}
this.shadowRoot.querySelector(
".color-square"
).style.backgroundColor = hexInput;
this.value = hexInput;
if (this.largeDisplay) {
this.shadowRoot.querySelector(
".large-display"
).style.backgroundColor = hexInput;
}
this._dispatchChange(hexInput);
let rgb = this._hexToRgb(hexInput);
if (rgb !== null) {
this._updateSliders(rgb);
}
}
_updateSliders(rgb) {
this.shadowRoot.querySelector("#R").value = rgb.r;
this.shadowRoot.querySelector("#R_out").value = rgb.r;
this.shadowRoot.querySelector("#G").value = rgb.g;
this.shadowRoot.querySelector("#G_out").value = rgb.g;
this.shadowRoot.querySelector("#B").value = rgb.b;
this.shadowRoot.querySelector("#B_out").value = rgb.b;
this.shadowRoot.querySelector("#O").value = rgb.o;
this.shadowRoot.querySelector("#O_out").value = rgb.o;
}
_hexToRgb(hex) {
if (hex.length === 4) {
return {
r: parseInt(hex[1] + "F", 16),
g: parseInt(hex[2] + "F", 16),
b: parseInt(hex[3] + "F", 16),
o: 0,
};
} else if (hex.length === 5) {
return {
r: parseInt(hex[1] + "F", 16),
g: parseInt(hex[2] + "F", 16),
b: parseInt(hex[3] + "F", 16),
o: parseInt(hex[4] + "F", 16),
};
} else if (hex.length === 7) {
return {
r: parseInt(hex[1] + hex[2], 16),
g: parseInt(hex[3] + hex[4], 16),
b: parseInt(hex[5] + hex[6], 16),
o: 0,
};
} else if (hex.length === 9) {
return {
r: parseInt(hex[1] + hex[2], 16),
g: parseInt(hex[3] + hex[4], 16),
b: parseInt(hex[5] + hex[6], 16),
o: parseInt(hex[7] + hex[8], 16),
};
} else {
return {
r: 0,
g: 0,
b: 0,
o: 0,
};
}
}
_fieldSetChange(event) {
let colorValueLabel = this.shadowRoot.querySelector(
`#${event.target.id}_out`
);
let colorSquare = this.shadowRoot.querySelector(".color-square");
let inputLabel = this.shadowRoot.querySelector("input");
colorValueLabel.value = event.target.value;
if (event.target.id === "R") {
this._rValue = parseInt(event.target.value, 10);
} else if (event.target.id === "G") {
this._gValue = parseInt(event.target.value, 10);
} else if (event.target.id === "B") {
this._bValue = parseInt(event.target.value, 10);
} else if (event.target.id === "O") {
this._oValue = parseInt(event.target.value, 10);
}
let computedHex = this._computeHex();
colorSquare.style.backgroundColor = computedHex;
inputLabel.value = computedHex;
if (this.largeDisplay) {
this.shadowRoot.querySelector(
".large-display"
).style.backgroundColor = computedHex;
}
this._dispatchChange(computedHex);
}
_dispatchChange() {
this.dispatchEvent(
new CustomEvent("value-changed", {
bubbles: true,
cancelable: false,
composed: false,
detail: { value: this },
})
);
}
renderFieldSet(value) {
return html`
<fieldset>
<label for="${value}">${value}</label>
<input
@input=${this._fieldSetChange}
type="range"
min="0"
max="255"
id="${value}"
step="1"
value="0"
/>
<output for="${value}" id="${value}_out">0</output>
</fieldset>
`;
}
/**
* LitElement life cycle - property changed
*/
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName === "value" && this[propName]) {
this.shadowRoot.querySelector(
".color-square"
).style.backgroundColor = this.value;
this.shadowRoot.querySelector("input").value = this.value;
if (this.largeDisplay) {
this.shadowRoot.querySelector(
".large-display"
).style.backgroundColor = this.value;
}
let rgb = this._hexToRgb(this.value);
if (rgb !== null) {
this._updateSliders(rgb);
}
}
});
}
} |
JavaScript | class Modal{
constructor(...args){
[
this.canvas,
this.x,
this.y,
this.width,
this.height,
this.leftArr = true,
this.rightArr = false,
// this.gifler = gifler
] = args;
}
// render method which get needed parameters to render Modal with corresponding game state data.
render(...args){
let [state, level, player, keyCode, img] = args;
/* draw base Modal rect */
// ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.font = '26px coda,arial';
// ctx.shadowBlur = 10;
// ctx.shadowOffsetX = 10;
// ctx.shadowColor = "rgba(0,0,0,0.3)";
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// ctx.beginPath();
ctx.rect((this.canvas.width/2)/4,(this.canvas.height/2)/4,(this.canvas.width/2)*1.5,(this.canvas.height/2)*1.5);
ctx.fillStyle = 'rgba(0,0,0,0.7)';
ctx.textAlign ='center';
ctx.fill();
// ctx.clip();
// ctx.closePath();
/* show suitable state's Modal template */
switch (state) {
case 'paused':
this.pauseTemplate(level, player, keyCode, state, img);
break;
case 'won':
this.winningTemplate(level, player, keyCode, state, img);
break;
case 'lost':
this.loseTemplate(level, player, keyCode, state, img);
break;
case 'stopped':
this.defaultTemplate(level, player, keyCode, state, img);
break;
default:
this.defaultTemplate(level, player, keyCode, state, img);
break;
}
}
/*
Methods to actualy set the dialogue displayed by the render() method
*/
winningTemplate(level, player, keyCode, state, img) {
ctx.font = '28px coda,arial';
ctx.fillStyle = 'mediumseagreen';
ctx.fillText('YES! YOU WIN',(this.canvas.width/2),(this.canvas.height/2)/2);
ctx.fillStyle = 'rgba(0,0,0,0.0)';
ctx.fillRect((this.canvas.width/5),(this.canvas.height/2)/3, 150, 200);
ctx.beginPath();
ctx.rect((this.canvas.width/5),(this.canvas.height/2)/3, 150, 200);
ctx.strokeStyle = 'mediumseagreen';
ctx.stroke();
ctx.closePath();
ctx.fillStyle = 'gold';
ctx.fillText('Lifes: '+ player.lifes, (this.canvas.width/4),(this.canvas.height/2)/2);
ctx.fillText('Gems: '+ player.gems, (this.canvas.width/4),(this.canvas.height/2)/2+50);
ctx.fillText('Keys: '+ player.keys, (this.canvas.width/4),(this.canvas.height/2)/2+100);
ctx.drawImage(Resources.get('img/Star.png'), (this.canvas.width/4.7),(this.canvas.height/2)/2+125);
ctx.fillStyle = '#fff';
ctx.fillText('Hit Enter key to play again',(this.canvas.width/2),(this.canvas.height/2)/2+50);
// ctx.drawImage(Resources.get('img/Selector.png'), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
if(img){
// ctx.drawImage(Resources.get(img), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
ctx.save();
this.onDrawFrame(ctx, player, img);
ctx.restore();
}
ctx.fillStyle = 'mediumseagreen';
ctx.fillText('Congratulation Bug thieve!', global.mx+120, global.my);
}
/* lose state template */
loseTemplate(level, player, keyCode, state, img) {
ctx.font = '28px coda,arial';
ctx.fillStyle = 'tomato';
ctx.fillText('GAME OVER !',(this.canvas.width/2),(this.canvas.height/2)/2);
ctx.fillStyle = '#fff';
ctx.font = '24px arial';
ctx.fillText('Hit Enter to start a new game',(this.canvas.width/2),(this.canvas.height/2)/2+50);
if(img){
// ctx.drawImage(Resources.get(img), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
ctx.save();
this.onDrawFrame(ctx, player, img);
ctx.restore();
}
ctx.fillText('Loser! @J@', global.mx+60, global.my);
}
/* pause state template */
pauseTemplate(level, player, keyCode, state, img) {
ctx.font = '28px coda,arial';
ctx.fillStyle = '#fff';
ctx.fillText('GAME PAUSED',(this.canvas.width/2),(this.canvas.height/2)/2);
ctx.font = '24px arial';
ctx.fillText('Hit the escape key again to resume',(this.canvas.width/2),(this.canvas.height/2)/2+50);
if(img){
// ctx.drawImage(Resources.get(img), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
ctx.save();
this.onDrawFrame(ctx, player, img);
ctx.restore();
}
ctx.fillText('Zzzzzzzz', global.mx+60, global.my);
}
/* default state template [at start] */
defaultTemplate(level, player, keyCode, state, img) {
ctx.font = '28px coda,arial';
ctx.fillStyle = '#fff';
if(this.leftArr && state == 'stopped'){
ctx.fillText('Get The Key!',(this.canvas.width/2),(this.canvas.height/2)/2);
ctx.font = '24px arial';
ctx.fillStyle = 'goldenrod';
ctx.fillText('Hit Enter to start a new game',(this.canvas.width/2),(this.canvas.height/2)/2+60);
ctx.fillText('Left Arrow [<] to Go to Settings / Instructions',(this.canvas.width/2),(this.canvas.height/2)/2+100);
if(img){
// this.gifler(img).frames(this.canvas, this.onDrawFrame);
// this.gifler(img).animate(this.canvas);
// ctx.drawImage(this.gifler(img).frames(this.canvas, this.onDrawFrame), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
// ctx.drawImage(Resources.get(img), (this.canvas.width/2 - (player.width/1)),(this.canvas.height/2)/2+150);
ctx.save();
this.onDrawFrame(ctx, player, img);
ctx.restore();
}
}
/* show arrows [left or right] upon which key pressed with it's suitable data */
if(this.rightArr && state == 'stopped'){
ctx.font = '24px arial';
ctx.fillStyle = 'gold';
ctx.fillText('Note: Press Esc to pause/resume game',(this.canvas.width/2),(this.canvas.height/2)/2);
ctx.fillText('Use [ L ] key to set game difficulty',(this.canvas.width/2),(this.canvas.height/2)/2+50);
ctx.fillStyle = level == 'Easy' ? 'mediumslateblue' : level == 'Medium' ? 'mediumseagreen' : 'crimson';
ctx.fillRect((this.canvas.width/2)-200/2,(this.canvas.height/2)/2+73, 200, 40);
ctx.strokeStyle = level == 'Easy' ? 'mediumslateblue' : level == 'Medium' ? 'mediumseagreen' : 'crimson';
ctx.lineWidth = 3;
ctx.fillStyle = '#fff';
ctx.fillText(level,(this.canvas.width/2),(this.canvas.height/2)/2+100);
ctx.fillText('Choose player with Space key',(this.canvas.width/2),(this.canvas.height/2)/2+150);
ctx.drawImage(Resources.get('img/Selector.png'), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
ctx.drawImage(Resources.get(player.sprite), (this.canvas.width/2 - (player.width/2)),(this.canvas.height/2)/2+190);
}
/* drawing arrows */
if(this.leftArr && state == 'stopped'){
ctx.beginPath();
ctx.moveTo(((this.canvas.width/2)/4)-20, (this.canvas.height/2)/1.35);
ctx.lineTo(((this.canvas.width/2)/4)-70, (this.canvas.height/2));
ctx.lineTo(((this.canvas.width/2)/4)-20, (this.canvas.height/2)*1.30);
ctx.lineTo(((this.canvas.width/2)/4)-20, (this.canvas.height/2)/1.35);
ctx.fillStyle = 'rgba(0,0,0,0)';
ctx.fill();
ctx.closePath();
}
if(this.rightArr && state == 'stopped'){
ctx.beginPath();
ctx.moveTo(((this.canvas.width/2)/4)+20+(this.canvas.width/2)*1.5, (this.canvas.height/2)/1.35);
ctx.lineTo(((this.canvas.width/2)/4)+20+(this.canvas.width/2)*1.5+50, (this.canvas.height/2));
ctx.lineTo(((this.canvas.width/2)/4)+20+(this.canvas.width/2)*1.5, (this.canvas.height/2)*1.30);
ctx.lineTo(((this.canvas.width/2)/4)+20+(this.canvas.width/2)*1.5, (this.canvas.height/2)/1.35);
ctx.fillStyle = 'rgba(0,0,0,0)';
ctx.fill();
ctx.closePath();
}
/* switch arrows depending on key code pressed */
if(keyCode && keyCode == 'left' && state == 'stopped') { this.rightArr = true; this.leftArr = false; }
if(keyCode && keyCode == 'right' && state == 'stopped') { this.leftArr = true; this.rightArr = false; }
}
/* Draw circle and desired img inside */
onDrawFrame(ctx, frame, img) {
ctx.globalCompositeOperation = 'source-over';
ctx.imageSmoothingQuality = 'high';
// frame.interlaced = true;
ctx.beginPath();
ctx.arc(ctx.canvas.width/2,(ctx.canvas.height/2)/2+250, 100, 0 , 2*Math.PI);
ctx.fillStyle = 'red';
ctx.strokeStyle = 'red';
ctx.stroke();
// ctx.fill();
ctx.clip();
// ctx.drawImage(frame.buffer,(ctx.canvas.width/2 - (frame.width/3)),(ctx.canvas.height/2)/2+150, 250, 200);
if(img == 'img/Key.png'){
ctx.drawImage(Resources.get(img), (ctx.canvas.width/2 - (frame.width/1)+50),(ctx.canvas.height/2)/2+150);
}else{
ctx.drawImage(Resources.get(img), (ctx.canvas.width/2 - (frame.width/1)), (ctx.canvas.height/2)/2+150, 250, 200);
}
ctx.closePath();
}
// playersTemplate(num, playersImg){
// // Resources.load(playersImg);
// // Resources.onReady(generate);
// return (function generate(){
// let allEntities = [];
// for (let i = 0; i < num; i++) {
// let c = (i == 0 ? 1 : i+1),
// x = ((this.canvas.width/2)/4)*c+120,
// y = ((this.canvas.height/2)/4)+65;
// if(x > (this.canvas.width-this.width)){
// c = (c == 1 ? c+1 : num - c);
// x = ((this.canvas.width/2)/4)*(c == 0 ? c+2 : c)+120;
// y = (((this.canvas.height/2)/4)+65) * (c == 0 ? c+2 : c+1);
// }
// allEntities[i] = new Player(x, y, Array.isArray(playersImg) ? playersImg[i] : playersImg);
// // allEntities[i].render();
// }
// return allEntities;
// }).call(this);
// }
/* static method to create itself */
static create(...args){
let [
canvas,
x,
y,
w,
h,
...otherArgs
] = args;
return new this(canvas, x = (canvas.width/2)/4, y = (canvas.height/2)/4, w = (canvas.width/2)*0.5, h = (canvas.height/1)*0.5, otherArgs);
}
} |
JavaScript | class V1StatefulSetStatus {
static getAttributeTypeMap() {
return V1StatefulSetStatus.attributeTypeMap;
}
} |
JavaScript | class Prompt extends EventEmitter {
constructor(opts = {}) {
super();
this.firstRender = true;
this.in = opts.stdin || process.stdin;
this.out = opts.stdout || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline.createInterface({
input: this.in,
escapeCodeTimeout: 50
});
readline.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1;
const keypress = (str, key) => {
let a = action(key, isSelect);
if (a === false) {
this._ && this._(str, key);
} else if (typeof this[a] === 'function') {
this[a](key);
} else {
this.bell();
}
};
this.close = () => {
this.out.write(cursor.show);
this.in.removeListener('keypress', keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value);
this.closed = true;
};
this.in.on('keypress', keypress);
}
fire() {
this.emit('state', {
value: this.value,
aborted: !!this.aborted,
exited: !!this.exited
});
}
bell() {
this.out.write(beep);
}
render() {
this.onRender(color);
if (this.firstRender) this.firstRender = false;
}
} |
JavaScript | class Theme {
/**
* Theme colors[read]
*
* @return {array} theme colors
*/
get colors() {
return colors;
}
/**
* Theme names[read]
*
* @return {array} theme name array
*/
get names() {
return names;
}
/**
* Current theme name[read]
*
* @return {string} theme name
*/
get theme() {
return curtheme;
}
/**
* Change theme
*
* @param {string} theme name
*/
Change( theme ) {
curtheme = theme;
findThemeStyle( function( name, css, $target ) {
if ( name == theme ) $target.html( themes[theme] );
else $target.html( `${flag}${name}` + "{}" );
});
tocTheme( theme );
}
constructor() {
require( `../assets/css/theme_common.css` );
names.forEach( name => require( `../assets/css/theme_${name}.css` ) );
findThemeStyle( ( name, content ) => themes[name] = content );
}
} |
JavaScript | class RasterMap {
/**
* Constructor: allocates the raster image
* @param {Object} min - bottom left point such as {lat: Number, lon: Number}
* @param {Object} max - top right point such as {lat: Number, lon: Number}
* @param {Number} longestPixelSize - number of pixel on the longest side of the image,
* @param {boolean} alphaToMax - OPTIONAL - puts the alpha channel to 255 if true. Leaves it at zero is false (default: true)
* whether it's along the S-N axis or the W-E axis
*/
constructor(min, max, longestPixelSize, alphaToMax=true){
this._rasterSize = {
width: null,
height: null
};
this._corners = {
bottomLeft: min,
topRight: max,
bottomRight: {lat: min.lat, lon: max.lon},
topLeft: {lat: max.lat, lon: min.lon}
};
// in meters
let southToNorthDistance = greatCircleDistance(this._corners.bottomLeft, this._corners.topLeft);
let westToEastDistance = greatCircleDistance(this._corners.bottomLeft, this._corners.bottomRight);
this._meterSize = {
width: westToEastDistance,
height: southToNorthDistance
};
this._angleSize = {
height: max.lat - min.lat,
width: max.lon - min.lon
};
if(southToNorthDistance > westToEastDistance){
// portrait image
this._rasterSize.height = longestPixelSize;
this._rasterSize.width = Math.ceil(longestPixelSize * (westToEastDistance / southToNorthDistance));
} else {
// landscape image
this._rasterSize.width = longestPixelSize;
this._rasterSize.height = Math.ceil(longestPixelSize * (southToNorthDistance / westToEastDistance));
}
this._anglePerPixel = {
width: this._angleSize.width / this._rasterSize.width,
height: this._angleSize.height / this._rasterSize.height,
};
this._pixelPerAngle = {
width: this._rasterSize.width / this._angleSize.width,
height: this._rasterSize.height / this._angleSize.height,
};
// number of components per pixel = 4 (RGBA)
this._ncpp = 4;
this._buffer = new Uint8Array(this._rasterSize.height * this._rasterSize.width * this._ncpp);
if(alphaToMax){
for(let i=3; i<this._buffer.length; i+=this._ncpp){
this._buffer[i] = 255;
}
}
}
getRasterWidth(){
return this._rasterSize.width
}
getRasterHeight(){
return this._rasterSize.height
}
getRasterData(){
return this._buffer
}
/**
* Transform a geo position (lat, lon) to a raster position (x, y), as long as this
* geo position is within the boundaries of this rasterMap.
* @param {Object} geoPos - geographic point in {lat: Number, lon: number}
* @param {boolean} nn - round it to the nearest neighbor raster position (default: true)
* @return {Object} raster position such as {x: Number, y: Number}
*/
geoPosToRasterPos(geoPos, nn=true){
if(geoPos.lat <= this._corners.bottomLeft.lat ||
geoPos.lat >= this._corners.topLeft.lat ||
geoPos.lon <= this._corners.bottomLeft.lon ||
geoPos.lon >= this._corners.bottomRight.lon ){
throw new Error('The geo position is out of bound')
}
let x = (geoPos.lon - this._corners.bottomLeft.lon) * this._pixelPerAngle.width;
let y = this._rasterSize.height - (geoPos.lat - this._corners.bottomLeft.lat) * this._pixelPerAngle.height - 1;
if(nn){
x = Math.round(x);
y = Math.round(y);
}
return {x: x, y: y}
}
/**
* Transform a raster position (x, y) into a geo position (lat, lon), as long as this
* raster position is within the boundaries of this rasterMap.
* @param {Object} rasterPos - raster position such as {x: Number, y: Number}
* @return {Object} a geo position such as {lat: Number, lon: number}
*/
rasterPosToGeoPos(rasterPos){
if(rasterPos.x < 0 || rasterPos.x >= this._rasterSize.width ||
rasterPos.y < 0 || rasterPos.y >= this._rasterSize.height){
throw new Error('The raster position is out of bound')
}
let lon = this._corners.bottomLeft.lon + rasterPos.x * this._anglePerPixel.width;
let lat = this._corners.bottomLeft.lat + (this._rasterSize.height - rasterPos.y - 1) * this._anglePerPixel.height;
return {
lat: lat,
lon: lon
}
}
/**
* Transform a raster position (x, y) into a the 1D position within the buffer.
* Note that the position is the position in the buffer of the first component (red)
* over the 4 (RGBA)
* @param {Object} rasterPos - raster position such as {x: Number, y: Number}
* @return {Number} the position in the buffer
*/
rasterPositionToBufferPosition(rasterPos){
if(rasterPos.x < 0 || rasterPos.x >= this._rasterSize.width ||
rasterPos.y < 0 || rasterPos.y >= this._rasterSize.height){
throw new Error('The raster position is out of bound')
}
return (rasterPos.y * this._rasterSize.width + rasterPos.x) * this._ncpp
}
/**
* Set the color at a given raster position
* @param {Array} color - the color as [r, g, b, a] or as [r, g, b]
* @param {Object} rasterPosition - raster position such as {x: Number, y: Number}
*/
setColorRaster(color, rasterPos){
let pos1D = this.rasterPositionToBufferPosition(rasterPos);
if(color.length > this._ncpp){
throw new Error(`The color must contain at most ${this._ncpp} elements.`)
}
for(let i=0; i<color.length; i++){
this._buffer[pos1D + i] = color[i];
}
}
/**
* Set the color at the given raster position
* @param {Array} color - the color as [r, g, b, a] or as [r, g, b]
* @param {Object} geoPos - geographic point in {lat: Number, lon: number}
*/
setColorGeo(color, geoPos){
let rasterPos = this.geoPosToRasterPos(geoPos);
this.setColorRaster(color, rasterPos);
}
} |
JavaScript | class TreeDropdownFieldMenu extends Component {
constructor(props) {
super(props);
this.render = this.render.bind(this);
this.renderOption = this.renderOption.bind(this);
this.renderBreadcrumbs = this.renderBreadcrumbs.bind(this);
this.handleBack = this.handleBack.bind(this);
}
/**
* Handle clicking "back" on breadcrumbs
*
* @param {Event} event
*/
handleBack(event) {
event.stopPropagation();
event.preventDefault();
if (typeof this.props.onBack === 'function') {
this.props.onBack(event);
}
}
/**
* Render breadcrumbs
*
* @return {XML}
*/
renderBreadcrumbs() {
if (this.props.breadcrumbs.length === 0) {
return null;
}
// Join titles with ' / '
const breadcrumbs = this.props.breadcrumbs.map((item) => item.title).join(' / ');
const button = (
<button className="treedropdownfield__breadcrumbs-button">
<span className="icon font-icon-level-up" />
</button>
);
return (
<div className="Select-option treedropdownfield__breadcrumbs flexbox-area-grow fill-width"
onClick={this.handleBack}
>
{button}
<span className="treedropdownfield__breadcrumbs-crumbs flexbox-area-grow">
{breadcrumbs}
</span>
</div>
);
}
/**
* Renders a single child node
*
* @param {Object} tree - Subtree to render
* @param {Number} index
*/
renderOption(tree, index) {
if (!this.props.renderMenuOptions) {
return null;
}
// Destructure Select.js options
const {
focusedOption,
instancePrefix,
onFocus,
onSelect,
optionClassName,
optionComponent,
optionRenderer,
valueArray,
onOptionRef,
} = this.props.renderMenuOptions;
// mostly copied from defaultMenuRenderer.js
let Option = optionComponent;
let isSelected = valueArray.findIndex(
(nextNode) => (nextNode.id === tree.id)
) > -1;
let isFocused = focusedOption && tree.id === focusedOption.id;
let optionClass = classNames(optionClassName, {
treedropdownfield__option: true,
'Select-option': true,
'is-selected': isSelected,
'is-focused': isFocused,
'is-disabled': tree.disabled,
});
return (
<Option
className={optionClass}
instancePrefix={instancePrefix}
isDisabled={tree.disabled}
isFocused={isFocused}
isSelected={isSelected}
key={`option-${index}-${tree.id}`}
onFocus={onFocus}
onSelect={onSelect}
option={tree}
optionIndex={index}
ref={ref => { onOptionRef(ref, isFocused); }}
>
{optionRenderer(tree, index)}
</Option>
);
}
render() {
if (this.props.loading) {
return (
<div className="Select-option flexbox-area-grow fill-width">
<span className="Select-loading-zone" aria-hidden="true">
<span className="Select-loading" />
</span>
<span className="treedropdownfield__menu-loading flexbox-area-grow">
{i18n._t('Admin.TREEDROPDOWN_LOADING', 'Loading...')}
</span>
</div>
);
}
if (this.props.failed) {
return (
<div className="Select-option">
{i18n._t('Admin.TREEDROPDOWN_FAILED', 'Failed to load')}
</div>
);
}
if (this.props.tree.count === 0) {
return (
<div className="Select-option">
{i18n._t('Admin.TREEDROPDOWN_NO_CHILDREN', 'No children')}
</div>
);
}
// Breadcrumbs
const breadcrumbs = this.renderBreadcrumbs();
// Render child items in this level
const children = this.props.tree.children.map(
(nextChild, i) => this.renderOption(nextChild, i)
);
return (
<div className="treedropdownfield__menu">
{breadcrumbs}
{children}
</div>
);
}
} |
JavaScript | class Default {
constructor(element, url) {
this.url = url;
if (this.url !== undefined)
element.autocomplete(this.options(element))
}
options(element) {
return {
minLength: 2,
source: (request, response) => {
$.getJSON(this.url, {
q: request.term
}, response );
},
focus: function() {
// prevent value inserted on focus
return false;
},
complete: function(event) {
$('.ui-autocomplete-loading').removeClass("ui-autocomplete-loading");
},
select: function() {
if (element.data('autocomplete-read-only') === true) {
element.attr('readonly', true);
}
}
}
}
} |
JavaScript | class UEX {
constructor (mediator) {
this.mediator = mediator;
med = this.mediator;
self = this;
return this;
}
initialRegister() {
/* What follows is a long list of events previously
* found in events.js.
* They are decoupled and also trigger events
* into the app scope for modules to listen to
* via med.ee
*/
/*
// GRID: Load/Unload custom CSS classes (Chrome Only?)
document.getElementById("toggle-grid-stage").addEventListener("click", e => {
e.preventDefault();
document.getElementById("grid-stage-css").disabled = !document.getElementById("grid-stage-css").disabled;
if (med.DEBUG) console.log("Local Grid Stage changed", !document.getElementById("grid-stage-css").disabled);
});
*/
// CHAT: Open and Close Chat
document.querySelector('#toggle-chat-pane').addEventListener('click', (e) => {
document.querySelector('#chat-pane').classList.toggle('chat-opened');
med.ee.emit('uex:ChatPaneToggle', e);
//remove the 'New' badge on chat icon (if any) once chat is opened.
setTimeout(() => {
if (document.querySelector('#chat-pane').classList.contains('chat-opened')) {
med.h.toggleChatNotificationBadge();
}
}, 300);
});
// CHAT: On enter, emit to chat
document.querySelector('#chat-input').addEventListener('keydown', (e)=>{
let val = document.querySelector('#chat-input').value;
var chatcont = document.getElementById('chat-messages');
if(val !==''){
if(e.key == 'Enter') {
// assemble the chat message
let chatMessage = {
sender: med.username,
msg: val
};
med.chat.broadcast(chatMessage);
chatcont.scrollBy(0,80 * chatcont.childElementCount)
document.querySelector('#chat-input').value = '';
document.querySelector('#chat-input').blur();
}
}
});
// CHAT: On button, emit to chat
document.querySelector('#chat-send').addEventListener('click', (e)=>{
let val = document.querySelector('#chat-input').value;
var chatcont = document.getElementById('chat-messages');
// assemble the chat message
if(val!==''){
let chatMessage = {
sender: med.username,
msg: val
};
med.chat.broadcast(chatMessage);
chatcont.scrollBy(0,80 * chatcont.childElementCount)
document.querySelector('#chat-input').value = '';
document.querySelector('#chat-input').blur();
}
});
// Show / Hide User List
document.getElementById("toggle-users").addEventListener("click", e => {
e.preventDefault();
var div = document.getElementById('mydiv');
if (!div.style.display || div.style.display === 'block') div.style.display = 'none';
else div.style.display = 'block';
med.ee.emit('uex:UserListToggle', e);
});
// Toggle Main Menu
document.getElementById("toggle-main-menu").addEventListener("click", e => {
e.preventDefault();
let div = document.getElementById("top-menu");
if (!div.style.display || div.style.display === 'block') div.style.display = 'none';
else div.style.display = 'block';
e.srcElement.classList.toggle("fa-ellipsis-h");
e.srcElement.classList.toggle("fa-ellipsis-v");
med.ee.emit('uex:MainMenuToggle', e);
});
// picture in picture button on local
med.ee.on('connection:VideoLoaded', function() {
//When the video frame is clicked. This will enable picture-in-picture
if ("pictureInPictureEnabled" in document
&& typeof document.getElementById('local').requestPictureInPicture === 'function' )
{
document.getElementById('local').addEventListener('click', () => {
if (!document.pictureInPictureElement) {
document.getElementById('local').requestPictureInPicture()
.catch(error => {
// Video failed to enter Picture-in-Picture mode.
console.error(error);
});
}
else {
document.exitPictureInPicture()
.catch(error => {
// Video failed to leave Picture-in-Picture mode.
console.error(error);
});
}
});
}
});
// options: we got the mediaStream
med.ee.on('media:Got MediaStream', function(stream) {
var local = document.querySelector('#local');
if(local) {
var _stream = med.myStream;
if(med.DEBUG) console.log(_stream,med.h.typeOf(_stream))
if(_stream && med.h.typeOf(_stream) == "mediastream") {
local.srcObject =_stream;
local.play().then().catch((err)=>{console.warn(err);}); //not working in ios
}
}
});
// options: got deviceList and set it on preview
med.currentVideoDevice = '';
med.currentAudioDevice = '';
med.ee.on('media:Got DeviceList', async function() {
med.videoDevices['Muted Video'] = {deviceId:false, label:'Mute Video'};
med.videoDevices['Avatar Lego'] = {deviceId:"avatar-lego", label:'Lego'};
med.videoDevices['Avatar Boy'] = {deviceId:"avatar-boy", label:'Boy'};
med.videoDevices['Avatar Girl'] = {deviceId:"avatar-girl", label:'Girl'};
med.videoDevices['Avatar Blathers'] = {deviceId:"avatar-blathers", label:'Blathers'};
med.videoDevices['Avatar Tom Nook'] = {deviceId:"avatar-tom-nook", label:'Tom Nook'};
med.videoDevices['VR Video'] = {deviceId:"vr-video", label:'VR Video'};
var propsV = Object.keys(med.videoDevices);
for(let i=0; i < propsV.length; i++) {
console.log(med.videoDevices[propsV[i]].deviceId + "::" + med.videoDevices[propsV[i]].label);
if(i == 0) {
// add last item in array to prev of first
med.videoDevices[propsV[i]].prev = med.videoDevices[propsV[propsV.length-1]];
if(propsV[i+1] !== undefined) {
med.videoDevices[propsV[i]].next = med.videoDevices[propsV[i+1]];
}
// we don't currently have a currentVideoDevice
if(med.currentVideoDevice == '') {
med.currentVideoDevice = med.videoDevices[propsV[i]];
document.querySelector('#currentVideoDevice').innerText = med.videoDevices[propsV[i]].label;
}
// if it's the last not the first
} else if (i == propsV.length-1 ) {
med.videoDevices[propsV[i]].next = med.videoDevices[propsV[0]];
if(propsV[i-1] !== undefined) {
med.videoDevices[propsV[i]].prev = med.videoDevices[propsV[i-1]];
}
}
// if it's also the last item
if(i == propsV.length-1) {
med.videoDevices[propsV[i]].next = med.videoDevices[propsV[0]];
if(propsV[i-1] !== undefined) {
med.videoDevices[propsV[i]].prev = med.videoDevices[propsV[i-1]];
}
} else {
med.videoDevices[propsV[i]].next = med.videoDevices[propsV[i+1]];
if(propsV[i-1] !== undefined) {
med.videoDevices[propsV[i]].prev = med.videoDevices[propsV[i-1]];
}
}
}
// set device to list
med.audioDevices['Muted Audio'] = {deviceId:false, label:'Mute Audio'};
var propsA = Object.keys(med.audioDevices);
for(let y=0; y < propsA.length; y++) {
console.log(med.audioDevices[propsA[y]].deviceId + "::" + med.audioDevices[propsA[y]].label);
if(y == 0) {
// add last item in array to prev of first
med.audioDevices[propsA[y]].prev = med.audioDevices[propsA[propsA.length-1]];
if(propsA[y+1] !== undefined) {
med.audioDevices[propsA[y]].next = med.audioDevices[propsA[y+1]];
}
// we don't currently have a currentVideoDevice
if(med.currentAudioDevice == '') {
med.currentAudioDevice = med.audioDevices[propsA[y]];
document.querySelector('#currentAudioDevice').innerText = med.audioDevices[propsA[y]].label;
}
// if it's the last not the first
} else if (y == propsA.length-1 ) {
med.audioDevices[propsA[y]].next = med.audioDevices[propsA[0]];
if(propsA[y-1] !== undefined) {
med.audioDevices[propsA[y]].prev = med.audioDevices[propsA[y-1]];
}
}
// if it's also the last item
if(y == propsA.length-1) {
med.audioDevices[propsA[y]].next = med.audioDevices[propsA[0]];
if(propsA[y-1] !== undefined) {
med.audioDevices[propsA[y]].prev = med.audioDevices[propsA[y-1]];
}
} else {
med.audioDevices[propsA[y]].next = med.audioDevices[propsA[y+1]];
if(propsA[y-1] !== undefined) {
med.audioDevices[propsA[y]].prev = med.audioDevices[propsA[y-1]];
}
}
}
await med.getMediaStream(med.currentVideoDevice.deviceId, med.currentAudioDevice.deviceId)
});
/* options : navigating through cameras */
document.querySelector('#nextCam').addEventListener('click', async function (ev) {
med.currentVideoDevice = med.currentVideoDevice.next;
await med.getMediaStream(med.currentVideoDevice.deviceId, med.currentAudioDevice.deviceId);
document.querySelector('#currentVideoDevice').innerText = med.currentVideoDevice.label;
});
document.querySelector('#prevCam').addEventListener('click', async function (ev) {
med.currentVideoDevice = med.currentVideoDevice.prev;
await med.getMediaStream(med.currentVideoDevice.deviceId, med.currentAudioDevice.deviceId);
document.querySelector('#currentVideoDevice').innerText = med.currentVideoDevice.label;
});
/* options: navigating through microphones */
document.querySelector('#nextAudio').addEventListener('click', async function (ev) {
med.currentAudioDevice = med.currentAudioDevice.next;
await med.getMediaStream(med.currentVideoDevice.deviceId, med.currentAudioDevice.deviceId);
document.querySelector('#currentAudioDevice').innerText = med.currentAudioDevice.label;
});
document.querySelector('#prevAudio').addEventListener('click', async function (ev) {
med.currentAudioDevice = med.currentAudioDevice.prev;
await med.getMediaStream(med.currentVideoDevice.deviceId, med.currentAudioDevice.deviceId);
document.querySelector('#currentAudioDevice').innerText = med.currentAudioDevice.label;
});
// options: password on / off
document.querySelector('#password').addEventListener( 'change', function(ev) {
if(this.checked) {
document.querySelector('#pass').removeAttribute("hidden");
} else {
document.querySelector('#pass').setAttribute("hidden", "");
}
});
// options: clear button
document.querySelector('#clear').addEventListener('click', function (ev) {
//remove sessionStorage
sessionStorage.clear()
med.room = '';
med.username = '';
window.location = '/';
if(document.querySelector('#username')){document.querySelector('#username').setAttribute('value', '')}
if(document.querySelector('#username')){document.querySelector('#roomname').setAttribute('value', '')}
if(document.querySelector('#pass')){document.querySelector('#pass').setAttribute('value', '')}
});
// options: avatar button
document.querySelector('#avatar').addEventListener('click', function (ev) {
//remove sessionStorage
alert("Coming Soon: Use an Avatar to allow for expressions, but also Anonimity. Only your face coordinates and Audio will stream to others. Caution, it's CPU intensive");
});
// options: slide out options
document.querySelector('#options-button').addEventListener('click', function(ev) {
var opt = document.querySelector('#options');
opt.classList.toggle('out')
});
// options: go button pushed
document.querySelector('#randomGo').addEventListener('click', async function (ev) {
// When go is pushed, we get the values from the form and adjust accordingly
// get username, if empty make an random one
med.username = document.querySelector('#username').value || window.chance.name();
sessionStorage.setItem('username', med.username);
// get roomname, if empty make an random one
med.room = document.querySelector('#roomname').value || window.chance.city().trim() + "-" + window.chance.first().trim() + "-" + window.chance.city().trim();
sessionStorage.setItem('roomname', med.room);
window.history.pushState(null,'',`?room=${med.room}&mesh=${med.mesh}`);
// if password option is on
let _pass = document.querySelector('#pass');
if(document.querySelector('#password').checked && _pass.value !== "") {
var pval = _pass && _pass.value ? _pass.value : false;
if(pval) await med.storePass(pval);
} else if (document.querySelector('#password').checked){
// get password, if empty alert that it is empty
alert('Password must be filled in')
return;
}
// otherwise ignore
// hide the options
if(document.querySelector('#inputs')){document.querySelector('#inputs').setAttribute("hidden","");}
if(document.querySelector('#title')){document.querySelector('#title').setAttribute("hidden","");}
if(document.querySelector('#selfview')){document.querySelector('#selfview').setAttribute("hidden","");}
if(document.querySelector('#options')){document.querySelector('#options').setAttribute("hidden","");}
if(document.querySelector('#options')){document.querySelector('#options').setAttribute("class","floating-1 out");}
if(!med.myStream){
await self.resetDevices();
}
var ve = document.getElementById('local');
med.localVideo = ve;
var vs = document.getElementById('localStream');
if(ve && vs){
ve.className="local-video clipped";
vs.appendChild(ve);
med.ee.emit("local-video-loaded");
}
med.socket = await med.initSocket();
med.initComm();
});
// options: show options or hide options from room
self.optShown = false;
document.querySelector('#toggle-modal').addEventListener('click', function(ev){
// TODO: disable Mesh selection in options?
if(!self.optShown) {
if(document.querySelector('#selfview')){document.querySelector('#selfview').removeAttribute("hidden");}
if(document.querySelector('#options')){document.querySelector('#options').removeAttribute("hidden");}
self.optShown = true;
var ve = document.getElementById('local');
med.localVideo = ve;
var el = document.getElementById('selfview');
document.querySelector("#top-menu").style.display = 'none'
document.querySelector("#toggle-ok-option").style.display = "inline-block"
if(ve && el){
ve.className="";
el.appendChild(ve);
}
} else {
if(document.querySelector('#selfview')){document.querySelector('#selfview').setAttribute("hidden","");}
if(document.querySelector('#options')){document.querySelector('#options').setAttribute("hidden","");}
var ve = document.getElementById('local');
document.querySelector("#toggle-ok-option").style.display = 'none';
med.localVideo = ve;
var vs = document.getElementById('localStream');
if(ve && vs){
ve.className="local-video clipped";
vs.appendChild(ve);
med.ee.emit("local-video-loaded");
}
self.optShown = false;
}
});
document.querySelector("#toggle-ok-option").addEventListener("click",function(){
document.querySelector("#toggle-ok-option").style.display = 'none';
if(document.querySelector('#selfview')){document.querySelector('#selfview').setAttribute("hidden","");}
if(document.querySelector('#options')){document.querySelector('#options').setAttribute("hidden","");}
var ve = document.getElementById('local');
med.localVideo = ve;
var vs = document.getElementById('localStream');
if(ve && vs){
ve.className="local-video clipped";
vs.appendChild(ve);
med.ee.emit("local-video-loaded");
}
})
}
/* Since some of the buttons we care about don't exist until modal
* is created. We call this to register the buttons after creation
*/
afterModalRegister () {
// Audio Mute / Unmute Button Pressed
document.getElementById("sam").addEventListener("click", e => {
e.preventDefault();
e.srcElement.classList.toggle("fa-volume-up");
e.srcElement.classList.toggle("fa-volume-mute");
med.ee.emit('uex:AudioMuteToggle', e);
});
// Video Mute / Unmute Button Pressed
document.getElementById("svm").addEventListener("click", e => {
e.preventDefault();
e.srcElement.classList.toggle("fa-video");
e.srcElement.classList.toggle("fa-video-slash");
med.ee.emit('uex:VideoMuteToggle', e);
});
// Toggle Device Selection
document.getElementById("toggle-device-selection").addEventListener("click", e => {
e.preventDefault();
if(event.target.classList.contains("fa-sliders-h")) {
e.state = "open";
} else {
e.state = "closed";
}
document.getElementById("devices-selection").classList.toggle('speech-bubble-open');
e.srcElement.classList.toggle("fa-sliders-h");
e.srcElement.classList.toggle("fa-times");
med.ee.emit('toggle-device-selection', e);
});
}
////
} |
JavaScript | class Controller {
/**
* Constructor.
* @param {!angular.JQLite} $element
* @ngInject
*/
constructor($element) {
/**
* @type {!angular.JQLite}
* @private
*/
this.element_ = $element;
/**
* @type {boolean}
*/
this['hasFocus'] = false;
/**
* @type {!angular.JQLite}
*/
this.container = angular.element('body');
// tabindex allows divs to have focus; the 0 allows the focus without mucking up the tab order
this.element_[0].setAttribute('tabindex', 0);
this.initScrollHandler_();
this.element_[0].addEventListener('blur', this.setFocus.bind(this), true);
this.element_[0].addEventListener('focus', this.setFocus.bind(this), true);
}
/**
*
* @param {Event} e
* @private
*/
firefoxScrollHandler_(e) {
var el = this.element_[0];
if (!this['hasFocus']) {
if (this.container) {
this.container.scrollTop(this.container.scrollTop() + (19 * e.detail));
} else {
window.scrollBy(0, 19 * e.detail);
}
e.stopPropagation();
e.preventDefault();
} else if (this['hasFocus'] && this.hasScrollBar_()) {
if ((e.detail > 0 && el.scrollHeight - this.element_.height() ===
el.scrollTop) || (e.detail < 0 && el.scrollTop === 0)) {
e.stopPropagation();
e.preventDefault();
}
}
}
/**
*
* @param {Event} e
* @private
*/
scrollHandler_(e) {
var el = this.element_[0];
var x;
var y;
var wheelY;
if (e.wheelDeltaX != null &&
e.wheelDeltaY != null) { // chrome
x = 0.4 * e.wheelDeltaX;
y = -0.45 * e.wheelDeltaY;
wheelY = e.wheelDeltaY;
} else if (e.wheelDelta != null) { // i freaking e.
x = 0;
y = -2.1 * e.wheelDelta; // +120 away -120 toward the user
wheelY = e.wheelDelta;
} else { // ffox
x = 0;
y = 57;
wheelY = 0;
}
if (!this['hasFocus']) {
if (this.container) {
this.container.scrollTop(this.container.scrollTop() + y);
} else {
window.scrollBy(x, y);
}
e.stopPropagation();
e.preventDefault();
} else if (this['hasFocus'] && this.hasScrollBar_()) {
if ((wheelY < 0 && el.scrollHeight - this.element_.height() ===
el.scrollTop) || (wheelY > 0 && el.scrollTop === 0)) {
e.stopPropagation();
e.preventDefault();
}
}
}
/**
* Initializes the scroll event handler.
*
* @private
*/
initScrollHandler_() {
if (navigator.userAgent.indexOf('Firefox') !== -1) {
this.element_[0].addEventListener('DOMMouseScroll', this.firefoxScrollHandler_.bind(this), true);
} else {
this.element_[0].addEventListener('mousewheel', this.scrollHandler_.bind(this), true);
}
}
/**
*
* @private
* @return {boolean}
*/
hasScrollBar_() {
return this.element_[0].scrollHeight > this.element_[0].clientHeight;
}
/**
* Listener for focus and blur events to activate and deactivate scrolling.
*
* @param {goog.events.Event} e The event
* @export
*/
setFocus(e) {
if (e.type === 'focus') {
this['hasFocus'] = true;
} else {
this['hasFocus'] = false;
}
}
} |
JavaScript | class Lists extends Core {
constructor(options) {
super(options);
this._render(Template, options);
// #TODO: NEED TO REFACTOR, THIS SHOULD LIVE ON THE REACT LAYER
this.options = options;
this.projectList = false;
this.accountList = false;
this.projectTitle = false;
this.accountTitle = false;
}
_componentDidMount() {
if (this.options.accountTitle) {
this.setAccountTitle(this.options.accountTitle);
}
if (this.options.projectTitle) {
this.setProjectTitle(this.options.projectTitle);
}
}
addProject(newInstance, referenceInstance) {
this._ensureProjectsList();
this.projectList.addItem(newInstance, referenceInstance);
}
addAccount(newInstance, referenceInstance) {
this._ensureAccountsList();
this.accountList.addItem(newInstance, referenceInstance);
}
setProjectTitle(title) {
if (this.projectTitle) {
this.projectTitle.setTitle(title);
} else {
this._ensureProjectsList();
this.projectTitle = this.projectList.addTitle(title);
}
}
setAccountTitle(title) {
if (this.accountTitle) {
this.accountTitle.setTitle(title);
} else {
this._ensureAccountsList();
this.accountTitle = this.accountList.addTitle(title);
}
}
_ensureAccountsList() {
if (this.accountList) { return; }
this.accountList = new List();
this.mountPartialToComment('ACCOUNTS', this.accountList);
}
_ensureProjectsList() {
if (this.projectList) { return; }
this.projectList = new List();
this.mountPartialToComment('PROJECTS', this.projectList);
}
} |
JavaScript | class WhereBuilder {
constructor(Model, comparisonBuilder = new comparison_builder_1.ComparisonBuilder(Model)) {
this.Model = Model;
this.comparisonBuilder = comparisonBuilder;
}
/**
* Builds a WHERE clause from a Filter.
* @param filter - the filter to build the WHERE clause from.
*/
build(filter) {
const { and, or } = filter;
let ands = [];
let ors = [];
let filterQuery = {};
if (and && and.length) {
ands = and.map((f) => this.build(f));
}
if (or && or.length) {
ors = or.map((f) => this.build(f));
}
const filterAnds = this.filterFields(filter);
if (filterAnds) {
ands = [...ands, filterAnds];
}
if (ands.length) {
filterQuery = { ...filterQuery, $and: ands };
}
if (ors.length) {
filterQuery = { ...filterQuery, $or: ors };
}
return filterQuery;
}
/**
* Creates field comparisons from a filter. This method will ignore and/or properties.
* @param filter - the filter with fields to create comparisons for.
*/
filterFields(filter) {
const ands = Object.keys(filter)
.filter((f) => f !== 'and' && f !== 'or')
.map((field) => this.withFilterComparison(field, this.getField(filter, field)));
if (ands.length === 1) {
return ands[0];
}
if (ands.length) {
return { $and: ands };
}
return undefined;
}
getField(obj, field) {
return obj[field];
}
withFilterComparison(field, cmp) {
const opts = Object.keys(cmp);
if (opts.length === 1) {
const cmpType = opts[0];
return this.comparisonBuilder.build(field, cmpType, cmp[cmpType]);
}
return {
$or: opts.map((cmpType) => this.comparisonBuilder.build(field, cmpType, cmp[cmpType])),
};
}
} |
JavaScript | class WFRP_Tables
{
/**
* The base function to retrieve a result from a table given various parameters.
*
* Options:
* `modifier` - modify the roll result by a certain amount
* `minOne` - If true, the minimum roll on the table is 1 (used when a negative modifier is applied)
* `lookup` - forego rolling and use this value to lookup the result on the table.
*
* @param {String} table Table name - the filename of the table file
* @param {Object} options Various options for rolling the table, like modifier
* @param {String} column Which column to roll on, if possible.
*/
static rollTable(table, options = {}, column = null)
{
let modifier = options.modifier || 0;
let minOne = options.minOne || false;
let maxSize = options.maxSize || false;
table = table.toLowerCase();
if (this[table])
{
let die = this[table].die;
let tableSize;
// Take the last result of the table, and find it's max range, that is the highest value on the table.
if (!this[table].columns)
tableSize = this[table].rows[this[table].rows.length - 1].range[1];
else
{
tableSize = this[table].rows[this[table].rows.length - 1].range[this[table].columns[0]][1]; // This isn't confusing at all - take the first column, find its last (max) value, that is the table size
}
// If no die specified, just use the table size and roll
if (!die)
die = `1d${tableSize}`;
let roll = new Roll(`${die} + @modifier`,{modifier}).roll();
let rollValue = options.lookup || roll.total; // options.lookup will ignore the rolled value for the input value
let displayTotal = options.lookup || roll.result; // Roll value displayed to the user
if (modifier == 0)
displayTotal = eval(displayTotal) // Clean up display value if modifier 0 (59 instead of 59 + 0)
if (rollValue <= 0 && minOne) // Min one provides a lower bound of 1 on the result
rollValue = 1;
else if (rollValue <= 0)
return {
roll: rollValue
};
if (rollValue > tableSize)
rollValue = tableSize;
// Scatter is a special table - calculate distance and return
if (table == "scatter")
{
if (roll.total <= 8) // Rolls of 9 and 10 do not need distance calculated
{
let distRoll = new Roll('2d10').roll().total;
return {roll: roll.total, dist: distRoll}
}
else
return {roll: roll.total}
}
// Lookup the value on the table, merge it with the roll, and return
return mergeObject(this._lookup(table, rollValue, column), ({roll: displayTotal}));
}
else
{}
}
/**
* Retrieves a value from a table, using the column if specified
*
* @param {String} table table name
* @param {Number} value value to lookup
* @param {String} column column to look under, if needed
*/
static _lookup(table, value, column = null)
{
if (!column)
for (let row of this[table].rows)
{
if (value >= row.range[0] && value <= row.range[1])
return row
}
else
{
for (let row of this[table].rows)
{
if (value >= row.range[column][0] && value <= row.range[column][1])
return row
}
}
}
/* -------------------------------------------- */
// critlleg doesn't exist, yet will be asked for because hit location and 'crit' are concatenated
// Therefore, change specific locations to generalized ones (rarm -> arm)
static generalizeTable(table)
{
table = table.toLowerCase();
table = table.replace("lleg", "leg");
table = table.replace("rleg", "leg");
table = table.replace("rarm", "arm");
table = table.replace("larm", "arm");
return table;
}
/* -------------------------------------------- */
/**
*
* Wrapper for rollTable to format rolls from chat commands nicely.
*
* Calls rollTable() and displays the result in a specific format depending
* on the table rolled on.
*
* @param {String} table Table name - the filename of the table file
* @param {Object} options Various options for rolling the table, like modifier
* @param {String} column Which column to roll on, if possible.
*/
static formatChatRoll(table, options = {}, column = null)
{
table = this.generalizeTable(table);
// If table has columns but none given, prompt for one.
if (this[table] && this[table].columns && column == null)
{
return this.promptColumn(table, options);
}
let result = this.rollTable(table, options, column);
if (options.lookup && !game.user.isGM) // If the player (not GM) rolled with a lookup value, display it so they can't be cheeky cheaters
result.roll = "Lookup: " + result.roll;
try
{
// Cancel the roll if below 1 and not minimum one
if (result.roll <= 0 && !options.minOne)
return `Roll: ${result.roll} - canceled`
}
catch
{}
// Provide specialized display for different tables
// I should probably standardize this better.
switch (table)
{
case "hitloc":
return `<b>${this[table].name}</b><br>` + game.i18n.localize(result.description);
case "crithead":
case "critbody":
case "critarm":
case "critleg":
case "crit":
WFRP_Audio.PlayContextAudio({item : {type:"hit"}, action : "hit", outcome : "crit"})
return `<b>${this[table].name}</b><br><a class = "item-lookup" data-type = "critical"><b>${result.name}</b></a><br>(${result.roll})`
case "minormis":
case "majormis":
case "event":
case "wrath":
case "travel":
return `<b>${this[table].name}</b><br><b>${result.name}</b><br>${result.description} (${result.roll})`;
case "mutatephys":
case "mutatemental":
return `<b>${this[table].name}</b><br><a class = "item-lookup" data-type = "critical"><b>${result.name}</b></a><br>(${result.roll})`;
case "doom":
return `<b>The Prophet Speaketh</b><br>${result.description} (${result.roll})`;
case "species":
return `<b>Random Species</b><br>${result.name} (${result.roll})`;
case "oops":
return `<b>Oops!</b><br>${result.description} (${result.roll})`;
case "winds":
return `<b>The Swirling Winds</b><br> <b>Roll:</b> ${eval(result.roll)} <br> <b>Modifier: </b> ${result.modifier}`;
case "career":
return `<b>Random Career - ${WFRP4E.species[column]}</b><br> <a class = "item-lookup">${result.name}</a> <br> <b>Roll:</b> ${result.roll}`;
case "eyes":
case "hair":
return `<b>${this[table].name} - ${WFRP4E.species[column]}</b><br>${result.name}<br><b>Roll:</b> ${eval(result.roll)}`
// Special scatter table display
case "scatter":
let tableHtml = '<table class = "scatter-table">' +
" <tr>" +
"<td position='1'> " +
"</td>" +
"<td position='2'> " +
"</td>" +
"<td position='3'> " +
"</td>" +
"</tr>" +
" <tr>" +
"<td position='4'> " +
"</td>" +
"<td position='10'> T" +
"</td>" +
"<td position='5'> " +
"</td>" +
"</tr>" +
" <tr>" +
"<td position='6'> " +
"</td>" +
"<td position='7'> " +
"</td>" +
"<td position='8'> " +
"</td>" +
"</tr>" +
"</table>"
if (result.roll == 9)
tableHtml += game.i18n.localize("CHAT.ScatterYou");
else if (result.roll == 10)
tableHtml += game.i18n.localize("CHAT.ScatterThem");
else
tableHtml += game.i18n.localize("CHAT.ScatterNote")
tableHtml = tableHtml.replace(`position='${result.roll}'`, "class='selected-position'")
if (result.dist)
tableHtml = tableHtml.replace("'selected-position'>", `'selected-position'> ${result.dist} ${game.i18n.localize("yards")}`)
return tableHtml;
case "talents":
return `<b>Random Talent</b><br> <a class="talent-drag"><i class="fas fa-suitcase"></i> ${result.name}</a>`
// Non-system table display. Display everything associated with that row.
default:
try
{
if (result)
{
let html = `<b>${this[table].name}</b><br>`;
for (let part in result)
{
if (part == "name")
html += `<b>${result[part]}</b><br>`
else if (part == "roll")
html += "<b>Roll</b>: " + eval(result[part])
else if (part != "range")
html += result[part] + "<br>"
}
return html;
}
else
throw ""
}
catch
{
return this.tableMenu();
}
}
}
/**
* Show the table help menu, display all tables as clickables and hidden tables if requested.
*
* @param {Boolean} showHidden Show hidden tables
*/
static tableMenu(showHidden = false)
{
let tableMenu = "<b><code>/table</code> Commands</b><br>"
let hiddenTableCounter = 0;
// For each table, display a clickable link.
for (let tableKey of Object.keys(this))
{
if (!showHidden)
{
if (!this[tableKey].hide)
tableMenu += `<a data-table='${tableKey}' class='table-click'><i class="fas fa-list"></i> <code>${tableKey}</code></a> - ${this[tableKey].name}<br>`
else
hiddenTableCounter++;
}
else
{
tableMenu += `<a data-table='${tableKey}' class='table-click'><i class="fas fa-list"></i> <code>${tableKey}</code></a> - ${this[tableKey].name}<br>`
}
}
if (hiddenTableCounter)
{
if (!showHidden)
tableMenu += `<a class = 'hidden-table'>+ ${hiddenTableCounter} Hidden Tables</a>`
}
return tableMenu;
}
// When critical casting, there are few options available, one could be a critical wound on a location, so offer a clickable link.
static criticalCastMenu(crittable)
{
return `${game.i18n.localize("CHAT.ChooseFrom")}:<ul>
<li><b>${game.i18n.localize("ROLL.CritCast")}</b>: ${game.i18n.localize("CHAT.CritCast")} <a class=table-click data-table=${crittable}><i class="fas fa-list"></i> ${game.i18n.localize("Critical Wound")}</a></li>
<li><b>${game.i18n.localize("ROLL.TotalPower")}</b>: ${game.i18n.localize("CHAT.TotalPower")}</li>
<li><b>${game.i18n.localize("ROLL.UnstoppableForce")}</b>: ${game.i18n.localize("CHAT.UnstoppableForce")}</li>
</ul`;
}
// Critical casting without reaching appropriate SL - forced to be Total power in order to get the spell off
static restrictedCriticalCastMenu()
{
return `${game.i18n.localize("CHAT.MustChoose")}:<ul>
<li><b>${game.i18n.localize("ROLL.TotalPower")}</b>: ${game.i18n.localize("CHAT.TotalPower")}</li>
</ul`;
}
// Display all columns for a table so the user can click on them and roll them.
static promptColumn(table, column)
{
let prompt = `<h3>${game.i18n.localize("CHAT.ColumnPrompt")}</h3>`
for (let c of this[table].columns)
prompt += `<div><a class = "table-click" data-table="${table}" data-column = "${c}"><i class="fas fa-list"></i> ${c}</a></div>`
return prompt;
}
} |
JavaScript | class CAGovContentNavigation extends window.HTMLElement {
connectedCallback() {
this.type = "wordpress";
/* https://unpkg.com/[email protected]/dist/smoothscroll.min.js */
/* Smooth scroll polyfill for safari, since it does not support scroll behaviors yet - can be moved to a dependency bundle split out by browser support later or in headless implementation */
!(function () {
"use strict";
function o() {
var o = window,
t = document;
if (
!(
"scrollBehavior" in t.documentElement.style &&
!0 !== o.__forceSmoothScrollPolyfill__
)
) {
var l,
e = o.HTMLElement || o.Element,
r = 468,
i = {
scroll: o.scroll || o.scrollTo,
scrollBy: o.scrollBy,
elementScroll: e.prototype.scroll || n,
scrollIntoView: e.prototype.scrollIntoView,
},
s =
o.performance && o.performance.now
? o.performance.now.bind(o.performance)
: Date.now,
c =
((l = o.navigator.userAgent),
new RegExp(["MSIE ", "Trident/", "Edge/"].join("|")).test(l)
? 1
: 0);
(o.scroll = o.scrollTo = function () {
void 0 !== arguments[0] &&
(!0 !== f(arguments[0])
? h.call(
o,
t.body,
void 0 !== arguments[0].left
? ~~arguments[0].left
: o.scrollX || o.pageXOffset,
void 0 !== arguments[0].top
? ~~arguments[0].top
: o.scrollY || o.pageYOffset
)
: i.scroll.call(
o,
void 0 !== arguments[0].left
? arguments[0].left
: "object" != typeof arguments[0]
? arguments[0]
: o.scrollX || o.pageXOffset,
void 0 !== arguments[0].top
? arguments[0].top
: void 0 !== arguments[1]
? arguments[1]
: o.scrollY || o.pageYOffset
));
}),
(o.scrollBy = function () {
void 0 !== arguments[0] &&
(f(arguments[0])
? i.scrollBy.call(
o,
void 0 !== arguments[0].left
? arguments[0].left
: "object" != typeof arguments[0]
? arguments[0]
: 0,
void 0 !== arguments[0].top
? arguments[0].top
: void 0 !== arguments[1]
? arguments[1]
: 0
)
: h.call(
o,
t.body,
~~arguments[0].left + (o.scrollX || o.pageXOffset),
~~arguments[0].top + (o.scrollY || o.pageYOffset)
));
}),
(e.prototype.scroll = e.prototype.scrollTo = function () {
if (void 0 !== arguments[0])
if (!0 !== f(arguments[0])) {
var o = arguments[0].left,
t = arguments[0].top;
h.call(
this,
this,
void 0 === o ? this.scrollLeft : ~~o,
void 0 === t ? this.scrollTop : ~~t
);
} else {
if (
"number" == typeof arguments[0] &&
void 0 === arguments[1]
)
throw new SyntaxError("Value could not be converted");
i.elementScroll.call(
this,
void 0 !== arguments[0].left
? ~~arguments[0].left
: "object" != typeof arguments[0]
? ~~arguments[0]
: this.scrollLeft,
void 0 !== arguments[0].top
? ~~arguments[0].top
: void 0 !== arguments[1]
? ~~arguments[1]
: this.scrollTop
);
}
}),
(e.prototype.scrollBy = function () {
void 0 !== arguments[0] &&
(!0 !== f(arguments[0])
? this.scroll({
left: ~~arguments[0].left + this.scrollLeft,
top: ~~arguments[0].top + this.scrollTop,
behavior: arguments[0].behavior,
})
: i.elementScroll.call(
this,
void 0 !== arguments[0].left
? ~~arguments[0].left + this.scrollLeft
: ~~arguments[0] + this.scrollLeft,
void 0 !== arguments[0].top
? ~~arguments[0].top + this.scrollTop
: ~~arguments[1] + this.scrollTop
));
}),
(e.prototype.scrollIntoView = function () {
if (!0 !== f(arguments[0])) {
var l = (function (o) {
for (
;
o !== t.body &&
!1 ===
((e = p((l = o), "Y") && a(l, "Y")),
(r = p(l, "X") && a(l, "X")),
e || r);
)
o = o.parentNode || o.host;
var l, e, r;
return o;
})(this),
e = l.getBoundingClientRect(),
r = this.getBoundingClientRect();
l !== t.body
? (h.call(
this,
l,
l.scrollLeft + r.left - e.left,
l.scrollTop + r.top - e.top
),
"fixed" !== o.getComputedStyle(l).position &&
o.scrollBy({
left: e.left,
top: e.top,
behavior: "smooth",
}))
: o.scrollBy({
left: r.left,
top: r.top,
behavior: "smooth",
});
} else
i.scrollIntoView.call(
this,
void 0 === arguments[0] || arguments[0]
);
});
}
function n(o, t) {
(this.scrollLeft = o), (this.scrollTop = t);
}
function f(o) {
if (
null === o ||
"object" != typeof o ||
void 0 === o.behavior ||
"auto" === o.behavior ||
"instant" === o.behavior
)
return !0;
if ("object" == typeof o && "smooth" === o.behavior) return !1;
throw new TypeError(
"behavior member of ScrollOptions " +
o.behavior +
" is not a valid value for enumeration ScrollBehavior."
);
}
function p(o, t) {
return "Y" === t
? o.clientHeight + c < o.scrollHeight
: "X" === t
? o.clientWidth + c < o.scrollWidth
: void 0;
}
function a(t, l) {
var e = o.getComputedStyle(t, null)["overflow" + l];
return "auto" === e || "scroll" === e;
}
function d(t) {
var l,
e,
i,
c,
n = (s() - t.startTime) / r;
(c = n = n > 1 ? 1 : n),
(l = 0.5 * (1 - Math.cos(Math.PI * c))),
(e = t.startX + (t.x - t.startX) * l),
(i = t.startY + (t.y - t.startY) * l),
t.method.call(t.scrollable, e, i),
(e === t.x && i === t.y) || o.requestAnimationFrame(d.bind(o, t));
}
function h(l, e, r) {
var c,
f,
p,
a,
h = s();
l === t.body
? ((c = o),
(f = o.scrollX || o.pageXOffset),
(p = o.scrollY || o.pageYOffset),
(a = i.scroll))
: ((c = l), (f = l.scrollLeft), (p = l.scrollTop), (a = n)),
d({
scrollable: c,
method: a,
startTime: h,
startX: f,
startY: p,
x: e,
y: r,
});
}
}
"object" == typeof exports && "undefined" != typeof module
? (module.exports = { polyfill: o })
: o();
})();
if (this.type === "wordpress") {
document.addEventListener("DOMContentLoaded", () =>
this.buildContentNavigation()
);
}
}
buildContentNavigation() {
// Parse header tags
let markup = this.getHeaderTags();
let label = null;
if (markup !== null) {
label = this.dataset.label || "On this page";
}
let content = null;
if (markup !== null) {
content = `<div class="label">${label}</div> ${markup}`;
}
this.template({ content }, "wordpress");
}
template(data, type) {
if (data !== undefined && data !== null && data.content !== null) {
if (type === "wordpress") {
this.innerHTML = `${data.content}`;
}
}
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
anchor.addEventListener("click", function (e) {
let hashval = decodeURI(anchor.getAttribute("href"));
try {
let target = document.querySelector(hashval);
if (target !== null) {
let position = target.getBoundingClientRect();
const prefersReducedMotion = window.matchMedia(
"(prefers-reduced-motion)"
).matches;
// console.log("prefersReducedMotion", prefersReducedMotion);
if (!prefersReducedMotion) {
window.scrollTo({
behavior: "smooth",
left: position.left,
top: position.top - 200,
});
}
history.pushState(null, null, hashval);
}
} catch (error) {
console.error(error);
}
e.preventDefault();
});
});
return null;
}
renderNoContent() {
this.innerHTML = "";
}
getHeaderTags() {
let selector = this.dataset.selector;
let editor = this.dataset.editor;
let label = this.dataset.label;
// let display = this.dataset.display;
let display = "render";
let callback = this.dataset.callback; // Editor only right now
var h = ["h2"];
var headings = [];
for (var i = 0; i < h.length; i++) {
// Pull out the header tags, in order & render as links with anchor tags
// auto convert h tags with tag names
if (selector !== undefined && selector !== null) {
if (display === "render") {
let selectorContent = document.querySelector(selector);
if (selectorContent !== null) {
let outline = this.outliner(selectorContent);
return outline;
}
}
}
}
return null;
}
outliner(content) {
let headers = content.querySelectorAll("h2");
let output = ``;
if (headers !== undefined && headers !== null && headers.length > 0) {
headers.forEach((tag) => {
let tagId = tag.getAttribute("id");
let title = tag.innerHTML;
// Alt: [a-zA-Z\u00C0-\u017F]+,\s[a-zA-Z\u00C0-\u017F]+
let anchor = tag.innerHTML
.toLowerCase()
.trim()
.replace(/ /g, "-")
// Strip out unallowed CSS characters (Selector API is used with the anchor links)
// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, `, {, |, }, and ~.
.replace(
/\(|\)|\!|\"|\#|\$|\%|\&|\'|\*|\+|\,|\.|\/|\:|\;|\<|\=|\>|\?|\@|\[|\]|\\|\^|\`|\{|\||\|\}|\~/g,
""
)
// All other characters are encoded and decoded using encodeURI/decodeURI which escapes UTF-8 characters.
// If we want to do this with allowed characters only
// .replace(/a-zA-ZÀ-ÖÙ-öù-ÿĀ-žḀ-ỿ0-9/g,"")
.replace(/a-zA-ZÀ-ÖÙ-öù-ÿĀ-žḀ-ỿ0-9\u00A0-\u017F/g, "");
// If id not set already, create an id to jump to.
if (tagId !== undefined && tagId !== null) {
anchor = tagId;
}
if (title !== "" && title !== null) {
output += `<li><a href="#${encodeURI(anchor)}">${title}</a></li>`;
if (tagId === undefined || tagId === null) {
tagId = anchor;
tag.setAttribute("id", tagId);
}
}
});
return `<ul>${output}</ul>`;
}
return null;
}
} |
JavaScript | class Typeahead extends HTMLParsedElement {
static get observedAttributes() {
return ["placeholder"];
}
get placeholder() {
return this.getAttribute("placeholder");
}
set placeholder(value) {
this.setAttribute("placeholder", value);
}
parsedCallback() {
this.render();
}
attributeChangedCallback(name, oldValue, newValue) {
if (this.parsed) {
this.render();
}
}
focus() {
if (this.rendered) {
var focusElement = this.querySelector(".tt-input");
if (focusElement) {
focusElement.focus();
}
}
}
updateUrls(prefetchUrl, remoteUrl) {
this.setAttribute("prefetch-url", prefetchUrl);
this.setAttribute("remote-url", remoteUrl);
this.render();
this.focus();
}
render() {
if (!this.style.display) {
this.style.display = "block";
}
this.innerHTML = "";
var form;
if (this.getAttribute("type") === "form") {
form = this.closest("form");
if (form) {
form.addEventListener("submit", onFromSubmit);
}
}
var input = document.createElement("input");
input.type = "text";
input.className = this.getAttribute("class");
input.placeholder = this.placeholder;
this.appendChild(input);
var namePrefix = this.getAttribute("name");
if (!namePrefix) {
namePrefix = this.id;
}
var idInput = document.createElement("input");
idInput.type = "hidden";
idInput.name = namePrefix ? namePrefix + "Id" : "";
this.appendChild(idInput);
var valueInput = document.createElement("input");
valueInput.type = "hidden";
valueInput.name = namePrefix ? namePrefix + "Value" : "";
this.appendChild(valueInput);
// Datums is an array of objects with properties id and value
// [{"id":21,"value":"21 Penelope Grant"},{"id":22,"value":"22 Rudolph Goodwin"}]
var bloodhound;
var bloodhoundOptions = {
limit: 10,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(datum) {
return datum.id;
},
sufficient: 1,
};
var prefetchUrl = this.getAttribute("prefetch-url");
var prefetchDataAdditionalStorage = new PrefetchDataAdditionalStorage();
if (prefetchUrl) {
prefetchDataAdditionalStorage.dataKey = `__${prefetchUrl}__data__additional`;
bloodhoundOptions.prefetch = {
url: prefetchUrl,
prepare: function(settings) {
prefetchDataAdditionalStorage.clear();
return settings;
},
};
}
var remoteUrl = this.getAttribute("remote-url");
if (remoteUrl) {
bloodhoundOptions.remote = {
url: remoteUrl,
wildcard: "searchTerm",
rateLimitBy: "throttle",
transform: function(datums) {
bloodhound.add(datums);
prefetchDataAdditionalStorage.add(datums);
return datums;
},
};
}
bloodhound = new Bloodhound(bloodhoundOptions);
bloodhound.initialize().done(function() {
var datums = prefetchDataAdditionalStorage.get();
bloodhound.add(datums);
});
var typeaheadOptions = {
hint: true,
highlight: true,
minLength: 1,
};
var suggestionName = this.getAttribute("suggestion-name");
var typeaheadDataset = {
name: "value",
displayKey: "value",
source: bloodhound.ttAdapter(),
templates: {
empty: `
<div class="tt-item">
${suggestionName} not found
</div>`,
pending: `
<div class="tt-item">
<i class="fas fa-circle-notch fa-spin mr-2 text-primary"></i>Updating...
</div>`,
suggestion: function(context) {
var value = escape(context.value);
return `<div data-id="${context.id}" data-value="${value}">${value}</div>`;
},
},
};
var $input = $(input);
$input.typeahead(typeaheadOptions, typeaheadDataset);
$input.bind("typeahead:cursorchange", function(event, suggestion) {
if (suggestion) {
setFormCursor(event.target.parentElement, suggestion.id, idInput, valueInput);
}
});
$input.bind("typeahead:open", function() {
setCursor(event.target.parentElement, idInput, valueInput);
});
$input.bind("typeahead:render", function(event) {
setCursor(event.target.parentElement, idInput, valueInput);
});
$input.bind("typeahead:select", function(event, suggestion) {
if (suggestion) {
idInput.value = suggestion.id;
valueInput.value = suggestion.value;
submitForm(form, suggestion.id);
}
});
// NOTE: Internal typeahead menu event found in src/typeahead/typeahead.js line 57.
$input.data("tt-typeahead").menu.bind()
.onSync("datasetCleared", function() {
idInput.value = "";
valueInput.value = "";
}, this);
var value = this.getAttribute("value");
if (value) {
value = unescape(value);
$input.typeahead("val", value);
}
this.rendered = true;
}
} |
JavaScript | class RefDemo extends Component {
constructor(props) {
super(props);
this.refList = new Array(3);
for (let i = 0; i < this.refList.length; i++) {
this.refList[i] = React.createRef();
}
this.childComponentRef = React.createRef();
this.setCallbackChildRef = (element) => {
this.cbChildRef = element;
};
this.handleClick = this.handleClick.bind(this);
this.myFancyButtonRef = React.createRef(); //fancy button reference
this.calledFunction = this.calledFunction.bind(this);
}
calledFunction(e){
console.log('hello function will be called as the component renders');
}
handleClick(e) {
this.refList.forEach((value) => {
if (value.current.getAttribute("class") === "active") {
value.current.removeAttribute("class");
}
});
this.refList[e.target.getAttribute("index")].current.setAttribute(
"class",
"active"
);
}
componentDidMount(prevProps, prevState) {
console.log("RefDemo Mounted...");
console.log(this.myFancyButtonRef);
}
render() {
let divStyle = {
padding: 5,
fontFamily: "monospace",
fontWeight: "bold",
fontSize: 15,
};
let RefFancyButton = LogPropsHoc(FancyButton);
return (
<>
<div
style={{
padding: 5,
backgroundColor: "#fafafa",
textAlign: "center",
}}>
Ref. usage demo
</div>
{this.refList.map((ref, index) => (
<div
key={index}
index={index}
style={divStyle}
ref={ref}
onClick={this.handleClick}>
Ref#{index}
</div>
))}
<CreateRefChildComponent ref={this.childComponentRef} />
<button
onClick={(e) => {
// console.log(this.childComponentRef);
this.childComponentRef.current.focusTextInput();
}}>
Focus
</button>
(Simple Ref.)
<br />
<CallbackRefChildComponent childRef={this.setCallbackChildRef} />
<button
onClick={(e) => {
console.log(this.cbChildRef);
// this.cbChildRef.current.focusTextInput();
this.cbChildRef.focus();
}}>
Focus
</button>
(Callback Ref.)
<br />
{/* {Difference from approach 2 because we are forwarding the ref not attaching to component.?} */}
{<RefFancyButton label="Click Me" ref={this.myFancyButtonRef} />}
<br/>
<br/>
<br/>
<div><button onClick={this.calledFunction()}>Function called (check console)</button></div>
</>
);
}
} |
JavaScript | class CreateRefChildComponent extends Component {
constructor(props) {
super(props);
this.textInputRef = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// console.log("inside focusTextInput");
// console.log(this.textInputRef);
this.textInputRef.current.focus();
}
render() {
return <input ref={this.textInputRef} type="text" />;
}
} |
JavaScript | class CallbackRefChildComponent extends Component {
constructor(props) {
super(props);
}
render() {
return <input ref={this.props.childRef} type="text" />;
}
} |
JavaScript | class InlineModal extends React.PureComponent {
handleCancel = ev => {
ev.preventDefault()
ev.stopPropagation()
const { onCancel } = this.props
onCancel && onCancel()
}
handleConfirm = ev => {
ev.preventDefault()
ev.stopPropagation()
const { onConfirm } = this.props
onConfirm && onConfirm()
}
get popoverProps() {
const { anchorElement, open, anchorOrigin } = this.props
const popProps = {
anchorOrigin,
open,
onClose: this.handleCancel,
}
if (anchorElement) {
popProps.anchorEl = anchorElement
popProps.anchorReference = 'anchorEl'
}
return popProps
}
render() {
const { children, leftButton, noButtons } = this.props
return (
<Popover {...this.popoverProps}>
{noButtons ? (
<NoGridWrapper>{children}</NoGridWrapper>
) : (
<Fragment>
<Grid container spacing={2}>
<Grid item xs={4}>
{children}
</Grid>
</Grid>
<ButtonsWrapper>
<Grid container spacing={0}>
<Grid item xs={4}>
{leftButton}
</Grid>
<Grid item xs={8} style={{ textAlign: 'right' }}>
<TextButton
onClick={this.handleCancel}
fontSizeEm={0.75}
color={v.colors.black}
style={{ marginRight: '2em' }}
className="cancel-button"
>
Cancel
</TextButton>
<TextButton
onClick={this.handleConfirm}
fontSizeEm={0.75}
color={v.colors.black}
className="ok-button"
data-cy="InlineModal-Ok"
>
OK
</TextButton>
</Grid>
</Grid>
</ButtonsWrapper>
</Fragment>
)}
</Popover>
)
}
} |
JavaScript | class PerformanceReportPerformanceDataStepsItem {
/**
* Create a PerformanceReportPerformanceDataStepsItem.
* @member {number} [avgCpu]
* @member {number} [avgMem]
* @member {array} [samples]
* @member {number} [elapsedSecsEnd]
* @member {number} [elapsedSecsStart]
* @member {number} [elapsedSecs]
* @member {string} [name]
* @member {string} [id]
*/
constructor() {
}
/**
* Defines the metadata of PerformanceReportPerformanceDataStepsItem
*
* @returns {object} metadata of PerformanceReportPerformanceDataStepsItem
*
*/
mapper() {
return {
required: false,
serializedName: 'PerformanceReport_performance_data_stepsItem',
type: {
name: 'Composite',
className: 'PerformanceReportPerformanceDataStepsItem',
modelProperties: {
avgCpu: {
required: false,
serializedName: 'avg-cpu',
type: {
name: 'Number'
}
},
avgMem: {
required: false,
serializedName: 'avg-mem',
type: {
name: 'Number'
}
},
samples: {
required: false,
serializedName: 'samples',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'PerformanceReportPerformanceDataStepsItemSamplesItemElementType',
type: {
name: 'Composite',
className: 'PerformanceReportPerformanceDataStepsItemSamplesItem'
}
}
}
},
elapsedSecsEnd: {
required: false,
serializedName: 'elapsed-secs-end',
type: {
name: 'Number'
}
},
elapsedSecsStart: {
required: false,
serializedName: 'elapsed-secs-start',
type: {
name: 'Number'
}
},
elapsedSecs: {
required: false,
serializedName: 'elapsed-secs',
type: {
name: 'Number'
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
id: {
required: false,
serializedName: 'id',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class Wall extends Aabb {
/**
* - If the x parameter is given, then a wall will be constructed along the y-z plane with its
* surface at the x coordinate. The y and z parameters are handled similarly.
* - Only one of the x/y/z parameters should be specified.
* - If isOpenOnPositiveSide is true, then the wall will be open toward the positive direction.
*
* @param {WallParams} wallParams
*/
constructor(wallParams) {
let minX;
let minY;
let minZ;
let maxX;
let maxY;
let maxZ;
let { x, y, z, isOpenOnPositiveSide, thickness, halfSideLength } = wallParams;
thickness = thickness || 80000;
halfSideLength = halfSideLength || 80000;
if (typeof x === 'number') {
if (isOpenOnPositiveSide) {
minX = x - thickness;
maxX = x;
}
else {
minX = x;
maxX = x + thickness;
}
minY = -halfSideLength;
minZ = -halfSideLength;
maxY = halfSideLength;
maxZ = halfSideLength;
}
else if (typeof y === 'number') {
if (isOpenOnPositiveSide) {
minY = y - thickness;
maxY = y;
}
else {
minY = y;
maxY = y + thickness;
}
minX = -halfSideLength;
minZ = -halfSideLength;
maxX = halfSideLength;
maxZ = halfSideLength;
}
else {
if (isOpenOnPositiveSide) {
minZ = z - thickness;
maxZ = z;
}
else {
minZ = z;
maxZ = z + thickness;
}
minX = -halfSideLength;
minY = -halfSideLength;
maxX = halfSideLength;
maxY = halfSideLength;
}
super(minX, minY, minZ, maxX, maxY, maxZ, true);
}
/**
* @returns {vec3}
* @override
*/
get scale() {
// Reuse the same object when this is called multiple times.
this._scale = this._scale || vec3.create();
vec3.set(this._scale, this.rangeX, this.rangeY, this.rangeZ);
return this._scale;
}
} |
JavaScript | class FileInlineEditing extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ FileEditing, FileUtils, ClipboardPipeline ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'FileInlineEditing';
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const schema = editor.model.schema;
// Converters 'alt' and 'srcset' are added in 'FileEditing' plugin.
schema.register( 'fileInline', {
isObject: true,
isInline: true,
allowWhere: '$text',
allowAttributesOf: '$text',
allowAttributes: [ 'alt', 'src', 'srcset' ]
} );
// Disallow inline files in captions (for now). This is the best spot to do that because
// independent packages can introduce captions (FileCaption, TableCaption, etc.) so better this
// be future-proof.
// schema.addChildCheck( ( context, childDefinition ) => {
// if ( context.endsWith( 'caption' ) && childDefinition.name === 'fileInline' ) {
// return false;
// }
// } );
this._setupConversion();
if ( editor.plugins.has( 'FileBlockEditing' ) ) {
editor.commands.add( 'fileTypeInline', new FileTypeCommand( this.editor, 'fileInline' ) );
this._setupClipboardIntegration();
}
}
/**
* Configures conversion pipelines to support upcasting and downcasting
* inline files (inline file widgets) and their attributes.
*
* @private
*/
_setupConversion() {
console.log("fileInline");
const editor = this.editor;
const t = editor.t;
const conversion = editor.conversion;
const fileUtils = editor.plugins.get( 'FileUtils' );
conversion.for( 'dataDowncast' )
.elementToElement( {
model: 'fileInline',
view: ( modelElement, { writer } ) => writer.createEmptyElement( 'iframe' )
} ).elementToElement( {
model: 'fileInline',
view: ( modelElement, { writer } ) => writer.createEmptyElement( 'custom' )
} );
conversion.for( 'editingDowncast' )
.elementToElement( {
model: 'fileInline',
view: ( modelElement, { writer } ) => fileUtils.toFileWidget(
createFileViewElement( writer, 'fileInline' ), writer, t( 'file widget' )
)
} );
conversion.for( 'downcast' )
.add( downcastFileAttribute( fileUtils, 'fileInline', 'src' ) )
.add( downcastFileAttribute( fileUtils, 'fileInline', 'alt' ) )
.add( downcastFileAttribute( fileUtils, 'fileInline', 'data-type' ) )
.add( downcastSrcsetAttribute( fileUtils, 'fileInline' ) );
// More file related upcasts are in 'FileEditing' plugin.
conversion.for( 'upcast' )
.elementToElement( {
view: getImgViewElementMatcher( editor, 'fileInline' ),
model: ( viewFile, { writer } ) => writer.createElement(
'fileInline',
viewFile.hasAttribute( 'src' ) ? { src: viewFile.getAttribute( 'src' ) } : null
)
} ).elementToElement( {
view: getCustomViewElementMatcher( editor, 'fileInline' ),
model: ( viewFile, { writer } ) => writer.createElement(
'fileInline',
viewFile.hasAttribute( 'src' ) ? { src: viewFile.getAttribute( 'src' ) } : null
)
} );
}
/**
* Integrates the plugin with the clipboard pipeline.
*
* Idea is that the feature should recognize the user's intent when an **block** file is
* pasted or dropped. If such an file is pasted/dropped into a non-empty block
* (e.g. a paragraph with some text) it gets converted into an inline file on the fly.
*
* We assume this is the user's intent if they decided to put their file there.
*
* **Note**: If a block file has a caption, it will not be converted to an inline file
* to avoid the confusion. Captions are added on purpose and they should never be lost
* in the clipboard pipeline.
*
* See the `FileBlockEditing` for the similar integration that works in the opposite direction.
*
* @private
*/
_setupClipboardIntegration() {
const editor = this.editor;
const model = editor.model;
const editingView = editor.editing.view;
const fileUtils = editor.plugins.get( 'FileUtils' );
this.listenTo( editor.plugins.get( 'ClipboardPipeline' ), 'inputTransformation', ( evt, data ) => {
const docFragmentChildren = Array.from( data.content.getChildren() );
let modelRange;
// Make sure only <figure class="file"></figure> elements are dropped or pasted. Otherwise, if there some other HTML
// mixed up, this should be handled as a regular paste.
if ( !docFragmentChildren.every( fileUtils.isBlockFileView ) ) {
return;
}
// When drag and dropping, data.targetRanges specifies where to drop because
// this is usually a different place than the current model selection (the user
// uses a drop marker to specify the drop location).
if ( data.targetRanges ) {
modelRange = editor.editing.mapper.toModelRange( data.targetRanges[ 0 ] );
}
// Pasting, however, always occurs at the current model selection.
else {
modelRange = model.document.selection.getFirstRange();
}
const selection = model.createSelection( modelRange );
// Convert block files into inline files only when pasting or dropping into non-empty blocks
// and when the block is not an object (e.g. pasting to replace another widget).
// if ( determineFileTypeForInsertionAtSelection( model.schema, selection ) === 'fileInline' ) {
// const writer = new UpcastWriter( editingView.document );
// // Unwrap <figure class="file"><iframe .../></figure> -> <iframe ... />
// // but <figure class="file"><iframe .../><figcaption>...</figcaption></figure> -> stays the same
// const inlineViewFiles = docFragmentChildren.map( blockViewFile => {
// // If there's just one child, it can be either <iframe /> or <a><iframe></a>.
// // If there are other children than <iframe>, this means that the block file
// // has a caption or some other features and this kind of file should be
// // pasted/dropped without modifications.
// if ( blockViewFile.childCount === 1 ) {
// // Pass the attributes which are present only in the <figure> to the <iframe>
// // (e.g. the style="width:10%" attribute applied by the FileResize plugin).
// Array.from( blockViewFile.getAttributes() )
// .forEach( attribute => writer.setAttribute(
// ...attribute,
// fileUtils.findViewImgElement( blockViewFile )
// ) );
// return blockViewFile.getChild( 0 );
// } else {
// return blockViewFile;
// }
// } );
// data.content = writer.createDocumentFragment( inlineViewFiles );
// }
} );
}
} |
JavaScript | class PublishWebhook {
/**
* Constructor to publish webhook.
*
* @param {object} params
* @param {array} params.pendingWebhookId: pending webhook id.
* @param {boolean} [params.retryWebhook]: is webhook being retried or not.
*
* @constructor
*/
constructor(params) {
const oThis = this;
oThis.pendingWebhookId = params.pendingWebhookId;
oThis.retryWebhook = params.retryWebhook || false;
oThis.pendingWebhook = null;
oThis.webhookEndpoints = null;
oThis.webhookEndpointUuids = [];
oThis.entity = null;
oThis.apiSecret = null;
oThis.apiGraceSecret = null;
oThis.mappyErrors = {};
oThis.failedWebhookEndpointUuid = [];
oThis.updateData = {};
}
/**
* Main performer for class.
*
* @returns {Promise}
*/
perform() {
const oThis = this;
return oThis.asyncPerform().catch(async function(error) {
logger.error('lib/webhooks/PublishWebhook.js::perform::catch');
logger.error(error);
await oThis._markPendingWebhookFailed().catch(function(err) {
logger.error('Could not mark pendingWebhooks fail', err);
});
if (responseHelper.isCustomResult(error)) {
logger.error(error.getDebugData());
return error;
}
return responseHelper.error({
internal_error_identifier: 'l_w_pw_1',
api_error_identifier: 'unhandled_catch_response',
debug_options: { error: error }
});
});
}
/**
* Async perform.
*
* @returns {Promise<>}
*/
async asyncPerform() {
const oThis = this;
await oThis._getPendingWebhookDetails();
await oThis._getEndpointDetails();
await oThis._fireWebhook();
await oThis._resetCache();
}
/**
* Get pending webhook details.
*
* @sets oThis.pendingWebhook
*
* @returns {Promise}
* @private
*/
async _getPendingWebhookDetails() {
const oThis = this;
const pendingWebhookCacheResp = await new PendingWebhooksCache({
pendingWebhookId: oThis.pendingWebhookId
}).fetch();
if (pendingWebhookCacheResp.isSuccess()) {
oThis.pendingWebhook = pendingWebhookCacheResp.data;
await new PendingWebhookModel()
.update({
status: pendingWebhookConstants.invertedStatuses[pendingWebhookConstants.inProgressStatus]
})
.where({ id: oThis.pendingWebhookId })
.fire();
} else {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_w_pw_2',
api_error_identifier: 'unhandled_catch_response',
debug_options: { pendingWebhookCacheResp: pendingWebhookCacheResp }
})
);
}
return responseHelper.successWithData({});
}
/**
* Get endpoint details.
*
* @sets oThis.webhookEndpoints
*
* @returns {Promise}
* @private
*/
async _getEndpointDetails() {
const oThis = this;
let webhookEndpointUuids = [];
if (
oThis.pendingWebhook.extraData.failedWebhookEndpointUuid &&
oThis.pendingWebhook.extraData.failedWebhookEndpointUuid.length > 0
) {
webhookEndpointUuids = oThis.pendingWebhook.extraData.failedWebhookEndpointUuid;
} else {
webhookEndpointUuids = oThis.pendingWebhook.extraData.webhookEndpointUuid;
}
logger.log('----webhookEndpointUuids-----------', webhookEndpointUuids);
const webhookEndpointsCacheResp = await new WebhookEndpointsByUuidCache({
webhookEndpointUuids: webhookEndpointUuids
}).fetch();
if (webhookEndpointsCacheResp.isSuccess()) {
oThis.webhookEndpoints = webhookEndpointsCacheResp.data;
} else {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_w_pw_3',
api_error_identifier: 'unhandled_catch_response',
debug_options: { webhookEndpointsCacheResp: webhookEndpointsCacheResp }
})
);
}
return responseHelper.successWithData({});
}
/**
* Fire webhook.
*
* @sets oThis.mappyErrors, oThis.failedWebhookEndpointUuid
*
* @returns {Promise}
* @private
*/
async _fireWebhook() {
const oThis = this;
for (const webhookEndpointUuid in oThis.webhookEndpoints) {
const rawWebhook = oThis.webhookEndpoints[webhookEndpointUuid],
webhookStatus = webhookEndpointsConstants.invertedStatuses[webhookEndpointsConstants.activeStatus];
if (!rawWebhook || rawWebhook.status != webhookStatus || !rawWebhook.secret) {
continue;
}
const apiSecrets = [],
apiVersion = rawWebhook.apiVersion;
apiSecrets.push(await oThis._getSecret(rawWebhook.secret));
if (rawWebhook.graceSecret) {
apiSecrets.push(await oThis._getGraceSecret(rawWebhook.graceSecret));
}
const webhookEvent = await new WebhookEventFormatter({
pendingWebhook: oThis.pendingWebhook,
rawWebhook: rawWebhook
}).perform();
const webhookPost = new WebhookPostKlass({
apiSecrets: apiSecrets,
apiEndpoint: rawWebhook.endpoint,
apiVersion: `v${apiVersion}`
});
const postResponse = await webhookPost.post(webhookEvent);
if (postResponse.isFailure()) {
oThis.mappyErrors[webhookEndpointUuid] = postResponse.getDebugData();
oThis.failedWebhookEndpointUuid.push(webhookEndpointUuid);
}
}
if (oThis.failedWebhookEndpointUuid.length > 0) {
await oThis._markPendingWebhookFailed();
} else {
await oThis._markPendingWebhookCompleted();
}
logger.log('------oThis.mappyErrors-------', JSON.stringify(oThis.mappyErrors));
logger.log('------oThis.failedWebhookEndpointUuid-------', JSON.stringify(oThis.failedWebhookEndpointUuid));
}
/**
* Mark pendingWebhook failed or completely failed.
*
* @sets oThis.updateData
*
* @returns {Promise}
* @private
*/
async _markPendingWebhookFailed() {
const oThis = this;
if (!oThis.pendingWebhook) {
return responseHelper.successWithData({});
}
if (oThis.pendingWebhook.retryCount >= pendingWebhookConstants.maxRetryCount) {
oThis.updateData.status =
pendingWebhookConstants.invertedStatuses[pendingWebhookConstants.completelyFailedStatus];
} else if (oThis.failedWebhookEndpointUuid.length > 0) {
oThis.updateData.status = pendingWebhookConstants.invertedStatuses[pendingWebhookConstants.failedStatus];
oThis.updateData.extra_data = oThis.pendingWebhook.extraData;
oThis.updateData.extra_data.failedWebhookEndpointUuid = oThis.failedWebhookEndpointUuid;
oThis.updateData.extra_data = JSON.stringify(oThis.updateData.extra_data);
const retryDetails = oThis._getRetryDetails();
oThis.updateData.retry_count = retryDetails.retryCount;
oThis.updateData.next_retry_at = retryDetails.nextRetryAt;
oThis.updateData.mappy_error = JSON.stringify(oThis.mappyErrors);
}
await oThis._updatePendingWebhook();
return responseHelper.successWithData({});
}
/**
* Mark pendingWebhook completed.
*
* @sets oThis.updateData
*
* @returns {Promise}
* @private
*/
async _markPendingWebhookCompleted() {
const oThis = this;
oThis.updateData.status = pendingWebhookConstants.invertedStatuses[pendingWebhookConstants.completedStatus];
oThis.updateData.extra_data = oThis.pendingWebhook.extraData;
oThis.updateData.extra_data.failedWebhookEndpointUuid = oThis.failedWebhookEndpointUuid;
oThis.updateData.extra_data = JSON.stringify(oThis.updateData.extra_data);
await oThis._updatePendingWebhook();
return responseHelper.successWithData({});
}
/**
* Update PendingWebhook
*
* @returns {Promise}
* @private
*/
async _updatePendingWebhook() {
const oThis = this;
oThis.updateData.lock_id = null;
await new PendingWebhookModel()
.update(oThis.updateData)
.where({ id: oThis.pendingWebhookId })
.fire();
}
/**
* Get retry datails
*
* @returns {{retryCount: number, nextRetryAt: *}}
* @private
*/
_getRetryDetails() {
const oThis = this;
let retryCount = 0;
if (oThis.retryWebhook) {
retryCount = oThis.pendingWebhook.retryCount + 1;
}
return {
retryCount: retryCount,
nextRetryAt: Math.floor(Date.now() / 1000) + pendingWebhookConstants.getNextRetryAtDelta(retryCount)
};
}
/**
* Reset cache with new data.
*
* @returns {Promise}
* @private
*/
async _resetCache() {
const oThis = this;
oThis.pendingWebhook.status = oThis.updateData.status || oThis.pendingWebhook.status;
if (oThis.updateData.extra_data) {
oThis.pendingWebhook.extraData = JSON.parse(oThis.updateData.extra_data);
}
oThis.pendingWebhook.retryCount = oThis.updateData.retry_count || oThis.pendingWebhook.retryCount;
oThis.pendingWebhook.nextRetryAt = oThis.updateData.next_retry_at || oThis.pendingWebhook.nextRetryAt;
await new PendingWebhooksCache({
pendingWebhookId: oThis.pendingWebhookId
})._setCache(oThis.pendingWebhook);
}
/**
* Since secret is same for all endpoints of a client, dont decrypt secret always.
*
* @param {string} secret
*
* @sets oThis.apiSecret
*
* @returns {Promise}
* @private
*/
async _getSecret(secret) {
const oThis = this;
if (oThis.apiSecret || !secret) {
return oThis.apiSecret;
}
oThis.apiSecret = await localCipher.decrypt(coreConstants.CACHE_SHA_KEY, secret);
logger.log('----------oThis.apiSecret--', oThis.apiSecret);
return oThis.apiSecret;
}
/**
* Since secret is same for all endpoints of a client, dont decrypt secret always.
*
* @param {string} secret
*
* @sets oThis.apiGraceSecret
*
* @returns {Promise}
* @private
*/
async _getGraceSecret(secret) {
const oThis = this;
if (oThis.apiGraceSecret || !secret) {
return oThis.apiGraceSecret;
}
oThis.apiGraceSecret = await localCipher.decrypt(coreConstants.CACHE_SHA_KEY, secret);
return oThis.apiGraceSecret;
}
} |
JavaScript | class CompoundStream extends stream.Readable {
constructor(generator) {
super();
this.generator = generator;
this.closed = false;
this.ready = false;
this.queue = [];
this.stream = null;
this._next();
}
_next() {
Promise.resolve(Array.isArray(this.generator) ? this.generator.shift() : this.generator()).then((s) => {
if (!s) return this._done();
this.stream = s;
s.on("readable", () => this._readable());
s.on("end", () => this._next());
s.on("error", (err) => this.emit("error", err));
this._readable();
}).catch((error) => {
this.emit("error", err);
});
}
_readable() {
if (!this.ready || this.closed || !this.stream) return;
const chunk = this.stream.read();
if (!chunk) return;
this.queue.push(chunk);
this._drain();
}
// push out any data we have buffered up.
// node uses this as the "unpause" signal. the "pause" signal is returning false from a push().
_read(n) {
this.ready = true;
this._drain();
}
_drain() {
while (this.ready && this.queue.length > 0) {
this.ready = this.push(this.queue.shift());
}
// if the consumer is still hungry for more, see if a read() will pull out any more
if (this.ready) this._readable();
}
_done() {
this.queue.push(null);
this.closed = true;
this._drain();
}
} |
JavaScript | class Box {
/**
*
* @param {number} xmin - minimal x coordinate
* @param {number} ymin - minimal y coordinate
* @param {number} xmax - maximal x coordinate
* @param {number} ymax - maximal y coordinate
*/
constructor(xmin = undefined, ymin = undefined, xmax = undefined, ymax = undefined) {
/**
* Minimal x coordinate
* @type {number}
*/
this.xmin = xmin;
/**
* Minimal y coordinate
* @type {number}
*/
this.ymin = ymin;
/**
* Maximal x coordinate
* @type {number}
*/
this.xmax = xmax;
/**
* Maximal y coordinate
* @type {number}
*/
this.ymax = ymax;
}
/**
* Return new cloned instance of box
* @returns {Box}
*/
clone() {
return new Box(this.xmin, this.ymin, this.xmax, this.ymax);
}
/**
* Property low need for interval tree interface
* @returns {Point}
*/
get low() {
return new Flatten.Point(this.xmin, this.ymin);
}
/**
* Property high need for interval tree interface
* @returns {Point}
*/
get high() {
return new Flatten.Point(this.xmax, this.ymax);
}
/**
* Property max returns the box itself !
* @returns {Box}
*/
get max() {
return this.clone();
}
/**
* Return center of the box
* @returns {Point}
*/
get center() {
return new Flatten.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);
}
/**
* Return property box like all other shapes
* @returns {Box}
*/
get box() {
return this.clone();
}
/**
* Returns true if not intersected with other box
* @param {Box} other_box - other box to test
* @returns {boolean}
*/
not_intersect(other_box) {
return (
this.xmax < other_box.xmin ||
this.xmin > other_box.xmax ||
this.ymax < other_box.ymin ||
this.ymin > other_box.ymax
);
}
/**
* Returns true if intersected with other box
* @param {Box} other_box - Query box
* @returns {boolean}
*/
intersect(other_box) {
return !this.not_intersect(other_box);
}
/**
* Returns new box merged with other box
* @param {Box} other_box - Other box to merge with
* @returns {Box}
*/
merge(other_box) {
return new Box(
this.xmin === undefined ? other_box.xmin : Math.min(this.xmin, other_box.xmin),
this.ymin === undefined ? other_box.ymin : Math.min(this.ymin, other_box.ymin),
this.xmax === undefined ? other_box.xmax : Math.max(this.xmax, other_box.xmax),
this.ymax === undefined ? other_box.ymax : Math.max(this.ymax, other_box.ymax)
);
}
/**
* Defines predicate "less than" between two boxes. Need for interval index
* @param {Box} other_box - other box
* @returns {boolean} - true if this box less than other box, false otherwise
*/
less_than(other_box) {
if (this.low.lessThan(other_box.low))
return true;
if (this.low.equalTo(other_box.low) && this.high.lessThan(other_box.high))
return true;
return false;
}
/**
* Returns true if this box is equal to other box, false otherwise
* @param {Box} other_box - query box
* @returns {boolean}
*/
equal_to(other_box) {
return (this.low.equalTo(other_box.low) && this.high.equalTo(other_box.high));
}
output() {
return this.clone();
}
static comparable_max(box1, box2) {
// return pt1.lessThan(pt2) ? pt2.clone() : pt1.clone();
return box1.merge(box2);
}
static comparable_less_than(pt1, pt2) {
return pt1.lessThan(pt2);
}
/**
* Set new values to the box object
* @param {number} xmin - miminal x coordinate
* @param {number} ymin - minimal y coordinate
* @param {number} xmax - maximal x coordinate
* @param {number} ymax - maximal y coordinate
*/
set(xmin, ymin, xmax, ymax) {
this.xmin = xmin;
this.ymin = ymin;
this.xmax = xmax;
this.ymax = ymax;
}
/**
* Transform box into array of points from low left corner in counter clockwise
* @returns {Point[]}
*/
toPoints() {
return [
new Flatten.Point(this.xmin, this.ymin),
new Flatten.Point(this.xmax, this.ymin),
new Flatten.Point(this.xmax, this.ymax),
new Flatten.Point(this.xmin, this.ymax)
];
}
/**
* Transform box into array of segments from low left corner in counter clockwise
* @returns {Segment[]}
*/
toSegments() {
let pts = this.toPoints();
return [
new Flatten.Segment(pts[0], pts[1]),
new Flatten.Segment(pts[1], pts[2]),
new Flatten.Segment(pts[2], pts[3]),
new Flatten.Segment(pts[3], pts[0])
];
}
/**
* Calculate distance and shortest segment from box to shape and return array [distance, shortest segment]
* @param {Shape} shape Shape of the one of supported types Point, Line, Circle, Segment, Arc, Polygon or Planar Set
* @returns {number} distance from box to shape
* @returns {Segment} shortest segment between box and shape (started at circle, ended at shape)
*/
distanceTo(shape) {
if (shape instanceof Flatten.Point) {
let [distance, shortest_segment] = Flatten.Distance.point2box(shape, this);
return [distance, shortest_segment];
}
if (shape instanceof Flatten.Circle) {
let [distance, shortest_segment] = Flatten.Distance.circle2box(this, shape);
return [distance, shortest_segment];
}
// if (shape instanceof Flatten.Line) {
// let [distance, shortest_segment] = Flatten.Distance.circle2line(this, shape);
// return [distance, shortest_segment];
// }
// if (shape instanceof Flatten.Segment) {
// let [distance, shortest_segment] = Flatten.Distance.segment2circle(shape, this);
// shortest_segment = shortest_segment.reverse();
// return [distance, shortest_segment];
// }
// if (shape instanceof Flatten.Arc) {
// let [distance, shortest_segment] = Flatten.Distance.arc2circle(shape, this);
// shortest_segment = shortest_segment.reverse();
// return [distance, shortest_segment];
// }
// if (shape instanceof Flatten.Polygon) {
// let [distance, shortest_segment] = Flatten.Distance.shape2polygon(this, shape);
// return [distance, shortest_segment];
// }
// if (shape instanceof Flatten.PlanarSet) {
// let [dist, shortest_segment] = Flatten.Distance.shape2planarSet(this, shape);
// return [dist, shortest_segment];
// }
}
/**
* Return true if rect contains shape: no point of shape lies outside of the rect
* @param {Shape} shape - test shape
* @returns {boolean}
*/
contains(shape) {
if (shape instanceof Flatten.Point) {
return shape.x >= this.xmin && shape.x <= this.xmax &&
shape.y >= this.ymin && shape.y <= this.ymax;
}
if (shape instanceof Flatten.Box) {
return shape.xmin >= this.xmin && shape.xmax <= this.xmax &&
shape.ymin >= this.ymin && shape.ymax <= this.ymax;
}
if (shape instanceof Flatten.Segment) {
return shape.ps.x >= this.xmin && shape.ps.x <= this.xmax &&
shape.ps.y >= this.ymin && shape.ps.y <= this.ymax &&
shape.pe.x >= this.xmin && shape.pe.x <= this.xmax &&
shape.pe.y >= this.ymin && shape.pe.y <= this.ymax;
}
if (shape instanceof Flatten.Arc) {
const boundingBox = shape.box;
return boundingBox.xmin >= this.xmin && boundingBox.xmax <= this.xmax &&
boundingBox.ymin >= this.ymin && boundingBox.ymax <= this.ymax;
}
if (shape instanceof Flatten.Circle) {
const cminx = shape.pc.x - shape.r;
const cmaxx = shape.pc.x + shape.r;
const cminy = shape.pc.y - shape.r;
const cmaxy = shape.pc.y + shape.r;
return (cminx >= this.xmin) && (cmaxx <= this.xmax) &&
(cminy >= this.ymin) && (cmaxy <= this.ymax);
}
/* TODO: polygon */
}
/**
* Return string to draw circle in svg
* @param {Object} attrs - an object with attributes of svg rectangle element,
* like "stroke", "strokeWidth", "fill" <br/>
* Defaults are stroke:"black", strokeWidth:"1", fill:"none"
* @returns {string}
*/
svg(attrs = {}) {
let {stroke, strokeWidth, fill, id, className} = attrs;
// let rest_str = Object.keys(rest).reduce( (acc, key) => acc += ` ${key}="${rest[key]}"`, "");
let id_str = (id && id.length > 0) ? `id="${id}"` : "";
let class_str = (className && className.length > 0) ? `class="${className}"` : "";
let width = this.xmax - this.xmin;
let height = this.ymax - this.ymin;
return `\n<rect x="${this.xmin}" y="${this.ymin}" width=${width} height=${height} stroke="${stroke || "black"}" stroke-width="${strokeWidth || 1}" fill="${fill || "none"}" ${id_str} ${class_str} />`;
};
} |
JavaScript | class StandardActions {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @const @private {!./action-impl.ActionService} */
this.actions_ = actionServiceForDoc(ampdoc);
/** @const @private {!./resources-impl.Resources} */
this.resources_ = installResourcesServiceForDoc(ampdoc);
this.installActions_(this.actions_);
}
/** @override */
adoptEmbedWindow(embedWin) {
this.installActions_(actionServiceForDoc(embedWin.document));
}
/**
* @param {!./action-impl.ActionService} actionService
* @private
*/
installActions_(actionService) {
actionService.addGlobalTarget('AMP', this.handleAmpTarget.bind(this));
actionService.addGlobalMethodHandler('hide', this.handleHide.bind(this));
}
/**
* Handles global `AMP` actions.
*
* See `amp-actions-and-events.md` for documentation.
*
* @param {!./action-impl.ActionInvocation} invocation
*/
handleAmpTarget(invocation) {
switch (invocation.method) {
case 'setState':
bindForDoc(this.ampdoc).then(bind => {
bind.setState(invocation.args);
});
return;
case 'goBack':
historyForDoc(this.ampdoc).goBack();
return;
}
throw user().createError('Unknown AMP action ', invocation.method);
}
/**
* Handles "hide" action. This is a very simple action where "display: none"
* is applied to the target element.
* @param {!./action-impl.ActionInvocation} invocation
*/
handleHide(invocation) {
const target = dev().assertElement(invocation.target);
this.resources_.mutateElement(target, () => {
if (target.classList.contains('i-amphtml-element')) {
target./*OK*/collapse();
} else {
toggle(target, false);
}
});
}
} |
JavaScript | class RangeSlider extends StyledComponent {
init(record, {
leftLabel,
rightLabel,
name,
}) {
this.leftLabel = leftLabel;
this.rightLabel = rightLabel;
this.name = name;
this.handleClick = this.handleClick.bind(this);
this.onHandleDown = this.onHandleDown.bind(this);
this.onHandleUp = this.onHandleUp.bind(this);
this.onHandleMove = this.onHandleMove.bind(this);
// for dragging
this.initialV = null;
this.initialX = null;
this.incrementX = null;
this.bind(record, data => this.render(data));
}
value() {
return this.record.data[this.name];
}
handleClick(evt) {
evt.preventDefault();
const x = evt.clientX || evt.touches[0].clientX || 0;
const {left, right, width} = this.node.querySelector('.slider')
.getBoundingClientRect();
this.incrementX = width / 5;
const middle = (left + right) / 2;
this.record.update({[this.name]: ~~((x - middle) / this.incrementX)});
}
onHandleDown(evt) {
evt.preventDefault();
const handle = evt.target;
this.initialV = this.value();
this.initialX = evt.clientX || evt.touches[0].clientX || 0;
this.incrementX = this.node.querySelector('.slider')
.getBoundingClientRect().width / 5;
document.body.addEventListener('mousemove', this.onHandleMove);
document.body.addEventListener('mouseup', this.onHandleUp);
}
onHandleUp(evt) {
evt.preventDefault();
const handle = evt.target;
this.initialV = null;
this.initialX = null;
this.incrementX = null;
document.body.removeEventListener('mousemove', this.onHandleMove);
document.body.removeEventListener('mouseup', this.onHandleUp);
}
onHandleMove(evt) {
evt.preventDefault();
const handle = evt.target;
const nowX = evt.clientX || evt.touches[0].clientX || 0;
const delta = nowX - this.initialX;
this.record.update({[this.name]: ~~(delta / this.incrementX) + this.initialV});
}
styles() {
return css`
margin-bottom: 32px;
.labels {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
font-size: 1.4em;
font-weight: bold;
}
.sliderContainer {
position: relative;
}
.slider {
width: 100%;
height: 14px;
border-radius: 7px;
background: var(--fore);
margin: 16px 0;
}
.handle {
cursor: grab;
position: absolute;
top: calc(50% - 8px);
left: calc(50% - 8px);
box-sizing: border-box;
height: 16px;
width: 16px;
border-radius: 8px;
box-shadow: 0 3px 6px -1px rgba(0, 0, 0, .3);
transition: transform .2s, left .2s;
transform: scale(1.4);
&:hover,
&:active {
transform: scale(1.8);
}
&:active {
cursor: grabbing;
}
}
.clickPoints {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.clickPoint {
height: 10px;
width: 10px;
border-radius: 5px;
background: var(--fore);
}
`;
}
compose(data) {
const pct = (this.value() + 2) * 25;
return jdom`<div class="rangeSlider" onclick="${this.handleClick}">
<div class="labels">
<div class="label left">${this.leftLabel}</div>
<div class="label right">${this.rightLabel}</div>
</div>
<div class="sliderContainer">
<div class="slider"></div>
<div class="handle"
tabindex="1"
onmousedown=${this.onHandleDown}
style="background:#${data.base};left:calc(${pct}% - 8px)"
></div>
</div>
<div class="clickPoints">
<div class="clickPoint"></div>
<div class="clickPoint"></div>
<div class="clickPoint"></div>
<div class="clickPoint"></div>
<div class="clickPoint"></div>
</div>
</div>`;
}
} |
JavaScript | class Weather extends React.Component {
constructor() {
super(),
this.state = {
cityWeather: {},
selectDate: moment().format('YYYY-MM-DD')
}
this.handleSubmit = this.handleSubmit.bind(this);
}
fetchData() {
// Get the data from the cache if possible
if (cityWeather[currentCity]) {
this.updateData();
}
else {
// Request new data to the API
Api.get(cities[currentCity])
.then(function(data) {
cityWeather[currentCity] = data;
this.updateData();
}.bind(this));
}
}
updateData() {
// Update the data for the UI
// cityWeather[currentCity] - array, where each element is a collection of data for one period of time (3h)
this.setState({ cityWeather: cityWeather[currentCity].list });
}
componentWillMount() {
cities[0] = 'Moscow';
// Create a timer to clear the cache after 5 minutes, so we can get updated data from the API
setInterval(function() {
cityWeather = []; // Empty the cache
}, (1000*60*5));
this.fetchData();
}
handleSubmit(dateMoment) {
this.setState({
selectDate: dateMoment
})
}
render() {
const weatherHourly = this.state.cityWeather;
const today = moment().subtract('days', 1);
const inFiveDays = moment().add('days', 5);
let result = [];
let periods = [];
Object.keys(weatherHourly).map((period) => {
if ((weatherHourly[period].dt_txt).match(this.state.selectDate)) {
periods.push(period);
}
});
switch (today.isAfter(moment(this.state.selectDate)) || inFiveDays.isBefore(moment(this.state.selectDate))) {
case true:
result.push(
<div className="weather-details">
<span className="title">К сожалению, информация о погоде в прошедшие дни, а также дальше, чем через 5 дней, отсутвует.</span>
</div>
);
break;
case false:
periods.forEach(period => {
const temp = Math.round(weatherHourly[period].main.temp);
const humidity = Math.round(weatherHourly[period].main.humidity);
const windSpeed = weatherHourly[period].wind.speed;
result.push(
<div className="weather-details" key={weatherHourly[period].dt}>
<div className="weather-param time">
<span className="title">День и время: </span><span className="number">{ weatherHourly[period].dt_txt }</span>
</div>
<div className="weather-param temp">
<span className="title">Температура воздуха: </span><span className="number">{ temp }°C</span>
</div>
<div className="weather-param humidity">
<span className="title">Уровень влажности: </span><span className="number">{ humidity }%</span>
</div>
<div className="weather-param wind">
<span className="title">Скорость ветра: </span><span className="number">{ windSpeed } м/с</span>
</div>
</div>
);
});
break;
}
return (
<div className="weather-widget">
<div className="weather-city"><h1 className="city-title">{ cities[currentCity] }</h1></div>
<Calendar handleSubmitButton={ this.handleSubmit }/>
<section className="weather-details-container">
{ result }
</section>
</div>
);
}
} |
JavaScript | class FactoryClient {
constructor (options) {
options = options || {}
if (!options.host) { options.host = 'localhost' }
if (!options.port) { options.port = 43134 }
if (typeof options.host === 'number') {
options.port = options.host
options.host = 'localhost'
}
this.port = options.port
this.host = options.host
this.type = options.type || 'go'
if (this.type === 'proc') {
throw new Error(`'proc' is not supported in client mode`)
}
this.baseUrl = `${options.secure ? 'https://' : 'http://'}${this.host}:${this.port}`
}
/**
* Utility method to get a temporary directory
* useful in browsers to be able to generate temp
* repos manually
*
* @param {String} type - the type of the node
* @param {function(Error, string)} callback
* @returns {undefined}
*/
tmpDir (type, callback) {
request
.get(`${this.baseUrl}/util/tmp-dir`)
.end((err, res) => {
if (err) {
return callback(new Error(err.response ? err.response.body.message : err))
}
callback(null, res.body.tmpDir)
})
}
/**
* Get the version of the IPFS Daemon.
*
* @memberof FactoryDaemon
* @param {Object} [options={}]
* @param {function(Error, string)} callback
* @returns {undefined}
*/
version (options, callback) {
if (typeof options === 'function') {
callback = options
options = undefined
}
options = options || { type: this.type }
request
.get(`${this.baseUrl}/version`)
.query(options)
.end((err, res) => {
if (err) {
return callback(new Error(err.response ? err.response.body.message : err))
}
callback(null, res.body.version)
})
}
spawn (options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
request
.post(`${this.baseUrl}/spawn`)
.send({ options: options, type: this.type })
.end((err, res) => {
if (err) {
return callback(new Error(err.response ? err.response.body.message : err))
}
const apiAddr = res.body.api ? res.body.api.apiAddr : ''
const gatewayAddr = res.body.api ? res.body.api.gatewayAddr : ''
const ipfsd = new DaemonClient(
this.baseUrl,
res.body.id,
res.body.initialized,
apiAddr,
gatewayAddr
)
callback(null, ipfsd)
})
}
} |
JavaScript | class IconTel extends Component {
render() {
return (
<div>
<svg
width="19px"
height="19px"
viewBox="0 0 19 19"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xlink="http://www.w3.org/1999/xlink"
>
<title>phone</title>
<desc>Created with Sketch.</desc>
<g
id="phone"
stroke="none"
strokeWidth="1"
fill="none"
fillRule="evenodd"
strokeLinecap="square"
strokeLinejoin="round"
>
<g
id="telephone-handle-silhouette"
transform="translate(1.000000, 1.000000)"
stroke="#6B6B6B"
strokeWidth="0.944444444"
>
<path
d="M16.9631667,13.1718284 C16.9150846,13.0269478 16.6091692,12.8135174 16.0456318,12.5320448 C15.8929701,12.4433234 15.6754378,12.3227587 15.3939652,12.169801 C15.1122388,12.0168433 14.8565199,11.8758955 14.6272736,11.7470846 C14.3975622,11.6183159 14.1823557,11.4935647 13.9812736,11.373 C13.9491343,11.3488532 13.8485299,11.2785274 13.6795025,11.1615572 C13.510306,11.0449254 13.3676244,10.9583607 13.2506965,10.9019055 C13.1340224,10.8457886 13.0192512,10.8175398 12.9065522,10.8175398 C12.745602,10.8175398 12.5445622,10.9323109 12.3031791,11.1615572 C12.061796,11.3910995 11.8403731,11.6404328 11.6392488,11.9103184 C11.4380821,12.1800771 11.2247363,12.4294104 10.999592,12.6588259 C10.7741095,12.8883259 10.5888433,13.0029701 10.4441318,13.0029701 C10.3714801,13.0029701 10.280898,12.9827139 10.1723433,12.9427512 C10.0638308,12.9025348 9.98128358,12.8680697 9.92461692,12.8402861 C9.86845771,12.8119104 9.77208209,12.7557512 9.63515174,12.6709627 C9.49796766,12.5864279 9.4216791,12.5401219 9.40560945,12.5320448 C8.30293532,11.9201716 7.35723632,11.2198731 6.56834328,10.4313184 C5.77970398,9.64229851 5.0793209,8.69668408 4.46761692,7.59388308 C4.45958209,7.57777114 4.41319154,7.50127114 4.32874129,7.36450995 C4.24416418,7.22762189 4.18779353,7.13116169 4.15962935,7.07466418 C4.13146517,7.01837811 4.09725373,6.93583085 4.0570796,6.82719154 C4.01690547,6.71855224 3.99673383,6.62805473 3.99673383,6.55552985 C3.99673383,6.41073383 4.11146269,6.22550995 4.34087811,6.00011194 C4.57025124,5.7748408 4.81983831,5.56145274 5.08938557,5.36037065 C5.35914428,5.15928856 5.60847761,4.93786567 5.83793532,4.69648259 C6.06730846,4.45497264 6.18199502,4.25384826 6.18199502,4.09289801 C6.18199502,3.98028358 6.15383085,3.86547015 6.09754478,3.74879602 C6.04121642,3.63186816 5.95469403,3.48918657 5.83793532,3.32007463 C5.72113433,3.15104726 5.65072388,3.05052736 5.62653483,3.01817662 C5.50592786,2.81709453 5.38130348,2.60180348 5.25236567,2.37238806 C5.12342786,2.14301493 4.98269154,1.88733831 4.82969154,1.60565423 C4.67681841,1.32409701 4.55616915,1.10669154 4.46753234,0.953776119 C4.18597512,0.390450249 3.97271393,0.0844502488 3.82779104,0.0363258706 C3.7714204,0.0121791045 3.68684328,0 3.57427114,0 C3.35682338,0 3.07315174,0.0401741294 2.72304478,0.120776119 C2.37281095,0.201251244 2.09721642,0.285659204 1.89596517,0.374338308 C1.49350498,0.543281095 1.0669403,1.03425124 0.616144279,1.8470796 C0.205649254,2.60353731 0.000422885572,3.35225622 0.000422885572,4.09268657 C0.000422885572,4.30983831 0.0145049751,4.52111194 0.0426691542,4.72654975 C0.0708333333,4.93177612 0.121156716,5.16322139 0.193681592,5.42084328 C0.266079602,5.6783806 0.3244801,5.86969403 0.368629353,5.99427612 C0.412820896,6.11894279 0.495325871,6.34226866 0.61610199,6.66433831 C0.736708955,6.98632338 0.809233831,7.18343035 0.833380597,7.25587065 C1.11506468,8.04472139 1.44910199,8.74895274 1.83540796,9.36877612 C2.47100498,10.39901 3.33838557,11.463709 4.43704229,12.5624502 C5.53574129,13.661107 6.60022886,14.5284453 7.63054726,15.164296 C8.25028607,15.5505597 8.95477114,15.8845547 9.74349502,16.1664502 C9.81597761,16.1904701 10.0130846,16.2628259 10.3349428,16.3838557 C10.6569279,16.5045473 10.8803383,16.5870522 11.005005,16.6313284 C11.1297139,16.6756468 11.3210697,16.7340896 11.5783955,16.8066144 C11.8362711,16.8791393 12.067505,16.9294627 12.2727313,16.9578383 C12.4780846,16.9856219 12.6894005,16.9999577 12.9065945,16.9999577 C13.6469826,16.9999577 14.3957438,16.7946045 15.1523284,16.3841517 C15.9650721,15.9335249 16.4559154,15.5068756 16.6249428,15.1041194 C16.7138333,14.9030796 16.7980299,14.6274005 16.878505,14.2771667 C16.9592338,13.927102 16.9993234,13.6434726 16.9993234,13.4260672 C16.9995771,13.3130299 16.9874403,13.2286642 16.9631667,13.1718284 Z"
id="Path"
></path>
</g>
</g>
</svg>
</div>
);
}
} |
JavaScript | class Persona {
constructor(nombre, email) {
this.nombre = nombre;
this.emial = email;
}
} |
JavaScript | class OxiFieldUploadComponent extends Component {
@service('intl') intl;
fileUploadElement = null;
@tracked data;
@tracked textOutput = "";
@tracked filename = "";
@tracked lockTextInput = false;
get cols() { return (this.args.content.textAreaSize || {}).width || 150 }
get rows() { return (this.args.content.textAreaSize || {}).height || 10 }
@action
onKeydown(event) {
// prevent form submit when hitting ENTER
if (event.keyCode === 13) {
event.stopPropagation();
}
}
@action
setFileUploadElement(element) {
this.fileUploadElement = element;
}
@action
setTextInput(evt) {
this.setData(evt.target.value);
}
@action
openFileUpload() {
this.fileUploadElement.click();
}
@action
fileSelected(evt) {
if (evt.target.type !== "file") { return }
this.setFile(evt.target.files[0]);
}
@action
fileDropped(evt) {
evt.stopPropagation();
evt.preventDefault();
this.setFile(evt.dataTransfer.files[0]);
}
@action
showCopyEffect(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // show as "copy" action
}
@action
resetInput() {
this.setData(null);
this.textOutput = "";
this.filename = "";
this.lockTextInput = false;
}
// expects a File object
setFile(file) {
this.lockTextInput = true;
this.filename = file.name;
let reader = new FileReader();
reader.onload = (e) => this.setFileData(e.target.result);
debug(`oxifield-uploadarea: setFile() - loading contents of ${file.name}`);
reader.readAsArrayBuffer(file);
}
setFileData(arrayBuffer) {
this.setData(arrayBuffer);
// show contents if it's a text block
const textStart = "-----BEGIN";
let start = String.fromCharCode(...new Uint8Array(arrayBuffer.slice(0, textStart.length)));
let isText = (start === textStart);
let isSmall = (arrayBuffer.byteLength < 10*1024);
if (isText && isSmall) {
this.textOutput = String.fromCharCode(...new Uint8Array(arrayBuffer));
}
else {
this.textOutput = `<${!isSmall
? this.intl.t('component.oxifield_uploadarea.large_file')
: this.intl.t('component.oxifield_uploadarea.binary_file')
}>`;
}
}
setData(data) {
this.data = data;
this.args.onChange(data);
}
} |
JavaScript | class LocalDB extends DB {
ticketPath = undefined;
constructor(ticketFolderPath = undefined) {
super();
// If no ticket path is provided, defualt to Tickets in directory from which process calling this was invoked
if (!ticketFolderPath) {
ticketFolderPath = path.join('.', 'Tickets');
}
// Create new directory if path does not exist
if (!fs.existsSync(ticketFolderPath)) {
fs.mkdirSync(ticketFolderPath, { recursive: true });
}
this.ticketPath = ticketFolderPath;
}
save(serverName, ServerObj) {
const pathname = path.join(this.ticketPath, serverName);
/** For default ticketPath, Servername = 'A' will create a text file
* at path './Tickets/A'
*/
fs.writeFileSync(pathname, JSON.stringify(ServerObj));
}
get(serverName) {
const pathname = path.join(this.ticketPath, serverName);
// Any file with given name was not found
if (!fs.existsSync(pathname)) {
throw new ServerError(
`Requested Server with name ${serverName} not Found`
);
}
let ticketStr = '';
ticketStr = fs.readFileSync(pathname, 'utf8');
// Empty File, or some error in reading file
if (ticketStr === '') {
throw new ServerError(
`Requested Server with name ${serverName} not Found`
);
}
try {
const t = JSON.parse(ticketStr);
return t;
} catch (e) {
throw new ServerError('Error in decoding server information');
}
}
} |
JavaScript | class SttApi extends base_1.BaseAPI {
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttEntriesIdDelete(id, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttEntriesIdDelete(id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttEntriesIdGet(id, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttEntriesIdGet(id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {SttEntryPatchDTO} [sttEntryPatchDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttEntriesIdPatch(id, sttEntryPatchDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttEntriesIdPatch(id, sttEntryPatchDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {SttEntryRequestDTO} [sttEntryRequestDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttEntriesPost(sttEntryRequestDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttEntriesPost(sttEntryRequestDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {SttEntryWeightRequestDTO} [sttEntryWeightRequestDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttEntriesWeightPost(sttEntryWeightRequestDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttEntriesWeightPost(sttEntryWeightRequestDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {Array<string>} [names]
* @param {number} [skip]
* @param {number} [take]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsGet(names, skip, take, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsGet(names, skip, take, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsIdDelete(id, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsIdDelete(id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsIdEntriesGet(id, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsIdEntriesGet(id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsIdGet(id, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsIdGet(id, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {SttGroupPatchDTO} [sttGroupPatchDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsIdPatch(id, sttGroupPatchDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsIdPatch(id, sttGroupPatchDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {SttGroupRequestDTO} [sttGroupRequestDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsPost(sttGroupRequestDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsPost(sttGroupRequestDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} customerId
* @param {string} sttGroupId
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessDelete(customerId, sttGroupId, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessDelete(customerId, sttGroupId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} customerId
* @param {string} sttGroupId
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessGet(customerId, sttGroupId, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessGet(customerId, sttGroupId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} customerId
* @param {string} sttGroupId
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessPost(customerId, sttGroupId, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdCustomersCustomerIdAccessPost(customerId, sttGroupId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} sttGroupId
* @param {string} sttEntryId
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightDelete(sttGroupId, sttEntryId, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightDelete(sttGroupId, sttEntryId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} sttGroupId
* @param {string} sttEntryId
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightGet(sttGroupId, sttEntryId, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightGet(sttGroupId, sttEntryId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} sttGroupId
* @param {string} sttEntryId
* @param {SttEntryWeightPatchDTO} [sttEntryWeightPatchDTO]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightPatch(sttGroupId, sttEntryId, sttEntryWeightPatchDTO, options) {
return exports.SttApiFp(this.configuration).apiV1ManagementSttGroupsSttGroupIdEntriesSttEntryIdWeightPatch(sttGroupId, sttEntryId, sttEntryWeightPatchDTO, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {Array<string>} [names]
* @param {number} [skip]
* @param {number} [take]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1SttGroupsGet(names, skip, take, options) {
return exports.SttApiFp(this.configuration).apiV1SttGroupsGet(names, skip, take, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} id
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SttApi
*/
apiV1SttGroupsIdGet(id, options) {
return exports.SttApiFp(this.configuration).apiV1SttGroupsIdGet(id, options).then((request) => request(this.axios, this.basePath));
}
} |
JavaScript | class GetShardIteratorCommand extends smithy_client_1.Command {
// Start section: command_properties
// End section: command_properties
constructor(input) {
// Start section: command_constructor
super();
this.input = input;
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(clientStack, configuration, options) {
this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "KinesisClient";
const commandName = "GetShardIteratorCommand";
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: models_0_1.GetShardIteratorInput.filterSensitiveLog,
outputFilterSensitiveLog: models_0_1.GetShardIteratorOutput.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
serialize(input, context) {
return Aws_json1_1_1.serializeAws_json1_1GetShardIteratorCommand(input, context);
}
deserialize(output, context) {
return Aws_json1_1_1.deserializeAws_json1_1GetShardIteratorCommand(output, context);
}
} |
JavaScript | class JsonGraph {
constructor(id) {
this.id = id;
this.root = true;
this['@type'] = [];
this.label = [];
this.shape = '';
this.metadata = {};
this.nodes = [];
this.edges = [];
this.subnodes = [];
}
// Add node to the graph architecture. The caller must keep track that all node IDs
// are unique -- this code doesn't verify this.
// id: uniquely identify the node
// label: text to display in the node; it can be an array to display a list of labels
// options: Object containing options to save in the node that can be used later when displayed
// subnodes: Array of nodes to use as subnodes of a regular node.
addNode(id, label, options, subnodes) {
const newNode = {};
newNode.id = id;
newNode['@type'] = [];
newNode['@type'][0] = options.type;
newNode.label = [];
if (typeof label === 'string' || typeof label === 'number') {
// label is a string; assign to first array element
newNode.label[0] = label;
} else {
// Otherwise, assume label is an array; clone it
newNode.label = label.slice(0);
}
newNode.metadata = _.clone(options);
newNode.nodes = [];
newNode.subnodes = subnodes;
const target = (options.parentNode && options.parentNode.nodes) || this.nodes;
target.push(newNode);
}
// Add edge to the graph architecture
// source: ID of node for the edge to originate; corresponds to 'id' parm of addNode
// target: ID of node for the edge to terminate
// options: Object containing options to save in the edge that can be used later when displayed
addEdge(source, target, options) {
const newEdge = {};
newEdge.id = '';
newEdge.source = source;
newEdge.target = target;
newEdge.class = options ? options.class : '';
newEdge.metadata = _.clone(options);
this.edges.push(newEdge);
}
// Return the JSON graph node matching the given ID. This function finds the node
// regardless of where it is in the hierarchy of nodes.
// id: ID of the node to search for
// parent: Optional parent node to begin the search; graph root by default
getNode(id, parent) {
const nodes = (parent && parent.nodes) || this.nodes;
for (let i = 0; i < nodes.length; i += 1) {
if (nodes[i].id === id) {
return nodes[i];
}
if (nodes[i].nodes.length > 0) {
const matching = this.getNode(id, nodes[i]);
if (matching) {
return matching;
}
}
if (nodes[i].subnodes && nodes[i].subnodes.length > 0) {
const matching = nodes[i].subnodes.find((subnode) => id === subnode.id);
if (matching) {
return matching;
}
}
}
return undefined;
}
getSubnode(id, parent) {
const nodes = (parent && parent.nodes) || this.nodes;
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
if (node.subnodes && node.subnodes.length > 0) {
for (let j = 0; j < node.subnodes.length; j += 1) {
if (node.subnodes[j].id === id) {
return node.subnodes[j];
}
}
} else if (nodes[i].nodes.length > 0) {
const matching = this.getSubnode(id, nodes[i]);
if (matching) {
return matching;
}
}
}
return undefined;
}
getEdge(source, target) {
if (this.edges && this.edges.length > 0) {
const matching = _(this.edges).find((edge) => (
(source === edge.source) && (target === edge.target)
));
return matching;
}
return undefined;
}
// Return array of function results for each node in the graph. The supplied function, fn, gets called with each node
// in the graph. An array of these function results is returned.
map(fn, context, nodes) {
const thisNodes = nodes || this.nodes;
let returnArray = [];
for (let i = 0; i < thisNodes.length; i += 1) {
const node = thisNodes[i];
// Call the given function and add its return value to the array we're collecting
returnArray.push(fn.call(context, node));
// If the node has its own nodes, recurse
if (node.nodes && node.nodes.length > 0) {
returnArray = returnArray.concat(this.map(fn, context, node.nodes));
}
}
return returnArray;
}
} |
JavaScript | class StyleGridView extends View {
/**
* Creates an instance of the {@link module:style/ui/stylegridview~StyleGridView} class.
*
* @param {module:utils/locale~Locale} locale The localization services instance.
* @param {Array.<module:style/style~StyleDefinition>} styleDefinitions Definitions of the styles.
*/
constructor( locale, styleDefinitions ) {
super( locale );
/**
* Array of active style names. They must correspond to the names of styles from
* definitions passed to the {@link #constructor}.
*
* @observable
* @readonly
* @default []
* @member {Array.<String>} #activeStyles
*/
this.set( 'activeStyles', [] );
/**
* Array of enabled style names. They must correspond to the names of styles from
* definitions passed to the {@link #constructor}.
*
* @observable
* @readonly
* @default []
* @member {Array.<String>} #enabledStyles
*/
this.set( 'enabledStyles', [] );
/**
* A collection of style {@link module:style/ui/stylegridbuttonview~StyleGridButtonView buttons}.
*
* @readonly
* @member {module:ui/viewcollection~ViewCollection}
*/
this.children = this.createCollection();
this.children.delegate( 'execute' ).to( this );
for ( const definition of styleDefinitions ) {
const gridTileView = new StyleGridButtonView( locale, definition );
this.children.add( gridTileView );
}
this.on( 'change:activeStyles', () => {
for ( const child of this.children ) {
child.isOn = this.activeStyles.includes( child.styleDefinition.name );
}
} );
this.on( 'change:enabledStyles', () => {
for ( const child of this.children ) {
child.isEnabled = this.enabledStyles.includes( child.styleDefinition.name );
}
} );
this.setTemplate( {
tag: 'div',
attributes: {
class: [
'ck',
'ck-style-grid'
],
role: 'listbox'
},
children: this.children
} );
/**
* Fired when a {@link module:style/ui/stylegridbuttonview~StyleGridButtonView style} was selected (clicked) by the user.
*
* @event execute
*/
}
} |
JavaScript | class APIService {
static async login (auth) {
const res = await axios.post(url + '/api/login', auth).catch(() => {
return {};
});
return res.data || {};
}
static async authenticate () {
const res = await axios.post(url + '/api/authenticate').catch(() => {
return {};
});
return res.data || {};
}
static async upload (api, file) {
const formData = new FormData();
formData.append('file', file);
const res = await axios.post(url + api, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).catch(() => {
return {};
});
return res.data || {};
}
static async get (api) {
const res = await axios.get(url + api).catch(() => {
return [];
});
return res.data || [];
}
static async getOne (api) {
const res = await axios.get(url + api).catch(() => {
return {};
});
if (res.data === undefined) {
return {};
}
return res.data || {};
}
static async post (api, json) {
const res = await axios.post(url + api, json).catch((err) => {
return { status: err.response.status };
});
return res;
}
static async delete (api) {
const res = await axios.delete(url + api).catch((err) => {
return { status: err.response.status };
});
return res;
}
static async put (api, json) {
const res = await axios.put(url + api, json).catch((err) => {
return { status: err.response.status };
});
return res;
}
} |
JavaScript | class NewError extends Error {
/**
* @param {*} value The evaluated scalar value
*/
constructor (value) {
super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)');
this.avoidNew = true;
this.value = value;
}
} |
JavaScript | class Bitfinex extends Driver {
/**
* @augments Driver.fetchTickers
* @returns {Promise.Array<Ticker>} Returns a promise of an array with tickers.
*/
async fetchTickers() {
const tickers = await request('https://api-pub.bitfinex.com/v2/tickers?symbols=ALL');
const [names, symbols] = await request('https://api-pub.bitfinex.com/v2/conf/pub:map:currency:label,pub:map:currency:sym');
const [currencies] = await request('https://api-pub.bitfinex.com/v2/conf/pub:list:currency');
const namesMap = new Map(names);
const symbolsMap = new Map(symbols);
return tickers.map((ticker) => {
const regex = new RegExp(`^t(${currencies.join('|')}):?(${currencies.join('|')})$`);
const pair = regex.exec(ticker[0]);
if (!pair) return undefined;
const [, base, quote] = pair;
const bid = parseToFloat(ticker[1]);
const ask = parseToFloat(ticker[3]);
const close = parseToFloat(ticker[7]);
const baseVolume = parseToFloat(ticker[8]);
const high = parseToFloat(ticker[9]);
const low = parseToFloat(ticker[10]);
return new Ticker({
base: symbolsMap.get(base) || base,
quote: symbolsMap.get(quote) || quote,
baseName: namesMap.get(base),
quoteName: namesMap.get(quote),
bid,
ask,
baseVolume,
close,
high,
low,
});
});
}
} |
JavaScript | class OrdersList {
constructor() {
// Initialization of the page plugins
if (typeof Checkall !== 'undefined') {
this._initCheckAll();
} else {
console.error('[CS] Checkall is undefined.');
}
}
// Check all button initialization
_initCheckAll() {
new Checkall(document.querySelector('.check-all-container .btn-custom-control'));
}
} |
JavaScript | class CommonIterator extends EventEmitter {
/**
* constructor
* @param {ChaincodeSupportClient} handler client handler
* @param {string} channel_id channel id
* @param {string} txID transaction id
* @param {object} response decoded payload
*/
constructor(handler, channel_id, txID, response, type) {
super();
this.type = type;
this.handler = handler;
this.channel_id = channel_id;
this.txID = txID;
this.response = response;
this.currentLoc = 0;
}
/**
* close the iterator.
* @async
* @return {promise} A promise that is resolved with the close payload or rejected
* if there is a problem
*/
async close() {
return await this.handler.handleQueryStateClose(this.response.id, this.channel_id, this.txID);
}
/*
* decode the payload depending on the type of iterator.
* @param {object} bytes
*/
_getResultFromBytes(bytes) {
if (this.type === 'QUERY') {
return _queryresultProto.KV.decode(bytes.resultBytes);
} else if (this.type === 'HISTORY') {
return _queryresultProto.KeyModification.decode(bytes.resultBytes);
}
throw new Error('Iterator constructed with unknown type: ' + this.type);
}
/*
* creates a return value and emits an event
*/
_createAndEmitResult() {
let queryResult = {};
queryResult.value = this._getResultFromBytes(this.response.results[this.currentLoc]);
this.currentLoc++;
queryResult.done = !(this.currentLoc < this.response.results.length || this.response.has_more);
if (this.listenerCount('data') > 0) {
this.emit('data', this, queryResult);
}
return queryResult;
}
/**
* Get the next value and return it through a promise and also emit
* it if event listeners have been registered.
* @async
* @return {promise} a promise that is fulfilled with the next value or
* is rejected otherwise
*/
async next() {
// check to see if there are some results left in the current result set
if (this.currentLoc < this.response.results.length) {
return this._createAndEmitResult();
}
else {
// check to see if there is more and go fetch it
if (this.response.has_more) {
try {
let response = await this.handler.handleQueryStateNext(this.response.id, this.channel_id, this.txID);
this.currentLoc = 0;
this.response = response;
return this._createAndEmitResult();
}
catch(err) {
// if someone is utilising the event driven way to work with
// iterators (by explicitly checking for data here, not error)
// then emit an error event. This means it will emit an event
// even if no-one is listening for the error event. Error events
// are handled specially by Node.
if (this.listenerCount('data') > 0) {
this.emit('error', this, err);
return;
}
throw err;
}
}
// no more, just return EMCA spec defined response
if (this.listenerCount('end') > 0) {
this.emit('end', this);
}
return {done: true};
}
}
} |
JavaScript | class StateQueryIterator extends CommonIterator {
constructor(handler, channel_id, txID, response) {
super(handler, channel_id, txID, response, 'QUERY');
}
} |
JavaScript | class HistoryQueryIterator extends CommonIterator {
constructor(handler, channel_id, txID, response) {
super(handler, channel_id, txID, response, 'HISTORY');
}
} |
JavaScript | class AttractorSnapshot extends Component {
constructor(map, rng) {
super();
this._map = map;
this._rng = rng;
}
get map() {
return this._map;
}
set map(val) {
this._map = val;
}
get rng() {
return this._rng;
}
set rng(val) {
this._rng = val;
}
} |
JavaScript | class Apollo {
constructor(self) {
if (!self.$apollo) {
console.log('No apollo') // eslint-disable-line
return
}
// apollo
this.apollo = self.$apollo
}
/**
* Throw a query.
*/
async query(query, variables) {
if (!this.apollo) throw new Error('No apollo')
const fetchPolicy = 'network-only'
const res = await this.apollo.query({
query,
variables,
fetchPolicy,
})
return res
}
} |
JavaScript | class PrivateUserPlan {
/**
* Constructs a new <code>PrivateUserPlan</code>.
* @alias module:model/PrivateUserPlan
* @param collaborators {Number}
* @param name {String}
* @param privateRepos {Number}
* @param space {Number}
*/
constructor(collaborators, name, privateRepos, space) {
PrivateUserPlan.initialize(this, collaborators, name, privateRepos, space);
}
/**
* 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, collaborators, name, privateRepos, space) {
obj['collaborators'] = collaborators;
obj['name'] = name;
obj['private_repos'] = privateRepos;
obj['space'] = space;
}
/**
* Constructs a <code>PrivateUserPlan</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/PrivateUserPlan} obj Optional instance to populate.
* @return {module:model/PrivateUserPlan} The populated <code>PrivateUserPlan</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PrivateUserPlan();
if (data.hasOwnProperty('collaborators')) {
obj['collaborators'] = ApiClient.convertToType(data['collaborators'], 'Number');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('private_repos')) {
obj['private_repos'] = ApiClient.convertToType(data['private_repos'], 'Number');
}
if (data.hasOwnProperty('space')) {
obj['space'] = ApiClient.convertToType(data['space'], 'Number');
}
}
return obj;
}
} |
JavaScript | class Buzz {
/**
* Unique id.
* @type {number}
* @private
*/
_id = -1;
/**
* Represents the source of the sound. The source can be an url or base64 string.
* @type {*}
* @private
*/
_src = null;
/**
* The formats of the passed audio sources.
* @type {Array<string>}
* @private
*/
_format = [];
/**
* The sprite definition.
* @type {object}
* @private
*/
_sprite = null;
/**
* True to use HTML5 audio node.
* @type {boolean}
* @private
*/
_stream = false;
/**
* The current volume of the sound. Should be from 0.0 to 1.0.
* @type {number}
* @private
*/
_volume = 1.0;
/**
* The current rate of the playback. Should be from 0.5 to 5.
* @type {number}
* @private
*/
_rate = 1;
/**
* True if the sound is currently muted.
* @type {boolean}
* @private
*/
_muted = false;
/**
* True if the sound should play repeatedly.
* @type {boolean}
* @private
*/
_loop = false;
/**
* True to pre-loaded the sound on construction.
* @type {boolean}
* @private
*/
_preload = false;
/**
* True to auto-play the sound on construction.
* @type {boolean}
* @private
*/
_autoplay = false;
/**
* Duration of the playback in seconds.
* @type {number}
* @private
*/
_duration = 0;
/**
* The best compatible source in the audio sources passed.
* @type {string|null}
* @private
*/
_compatibleSrc = null;
/**
* Represents the different states that occurs while loading the sound.
* @type {LoadState}
* @private
*/
_loadState = LoadState.NotLoaded;
/**
* Represents the state of this group.
* @type {BuzzState}
* @private
*/
_state = BuzzState.Ready;
/**
* True if the group is currently fading.
* @type {boolean}
* @private
*/
_fading = false;
/**
* The timer that runs function after the fading is complete.
* @type {number|null}
* @private
*/
_fadeTimer = null;
/**
* Number of audio resource loading calls in progress.
* @type {number}
* @private
*/
_noOfLoadCalls = 0;
/**
* Array of sounds belongs to this group.
* @type {Array<Sound>}
* @private
*/
_soundsArray = [];
/**
* Array of pre-loaded HTML5 audio elements.
* @type {Array<Audio>}
* @private
*/
_audioNodes = [];
/**
* The action queue.
* @type {Queue}
* @private
*/
_queue = null;
/**
* The audio engine.
* @type {Engine}
* @private
*/
_engine = null;
/**
* Web API's audio context.
* @type {AudioContext}
* @private
*/
_context = null;
/**
* The group's gain node.
* @type {GainNode}
* @private
*/
_gainNode = null;
/**
* Initializes the internal properties.
* @param {string|Array<string>|object} args The input parameters of this sound group.
* @param {string} [args.id] The unique id of the sound.
* @param {string|string[]} args.src Single or array of audio urls/base64 strings.
* @param {string|string[]} [args.format] The file format(s) of the passed audio source(s).
* @param {object} [args.sprite] The audio sprite definition.
* @param {boolean} [args.stream = false] True to use HTML5 audio node.
* @param {number} [args.volume = 1.0] The initial volume of the sound. Should be from 0.0 to 1.0.
* @param {number} [args.rate = 1] The initial playback rate of the sound. Should be from 0.5 to 5.0.
* @param {boolean} [args.muted = false] True to be muted initially.
* @param {boolean} [args.loop = false] True to play the sound repeatedly.
* @param {boolean} [args.preload = false] True to pre-load the sound after construction.
* @param {boolean} [args.autoplay = false] True to play automatically after construction.
* @param {function} [args.onload] Event-handler for the "load" event.
* @param {function} [args.onloadprogress] Event-handler for the "loadprogress" event (only for non-stream types).
* @param {function} [args.onunload] Event-handler for the "unload" event.
* @param {function} [args.onplaystart] Event-handler for the "playstart" event.
* @param {function} [args.onplayend] Event-handler for the "playend" event.
* @param {function} [args.onpause] Event-handler for the "pause" event.
* @param {function} [args.onstop] Event-handler for the "stop" event.
* @param {function} [args.onmute] Event-handler for the "mute" event.
* @param {function} [args.onvolume] Event-handler for the "volume" event.
* @param {function} [args.onrate] Event-handler for the "rate" event.
* @param {function} [args.onseek] Event-handler for the "seek" event.
* @param {function} [args.onerror] Event-handler for the "error" event.
* @param {function} [args.ondestroy] Event-handler for the "destroy" event.
* @constructor
*/
constructor(args) {
this._engine = engine;
this._onLoadProgress = this._onLoadProgress.bind(this);
if (typeof args === 'string') {
if (args.startsWith('#')) {
this._setSource(args);
} else {
this._src = [args];
}
} else if (Array.isArray(args) && args.length) {
this._src = args;
} else if (typeof args === 'object') {
const {
id,
src,
format,
sprite,
stream,
volume,
rate,
muted,
loop,
preload,
autoplay,
onload,
onloadprogress,
onunload,
onplaystart,
onplayend,
onpause,
onstop,
onmute,
onvolume,
onrate,
onseek,
onerror,
ondestroy
} = args;
// Set the passed id or the auto-generated one.
this._id = typeof id === 'number' ? id : utility.id();
// Set the source.
if (typeof src === 'string') {
if (src.startsWith('#')) {
this._setSource(src);
} else {
this._src = [src];
}
} else if (Array.isArray(src)) {
this._src = src;
}
// Set the format.
if (Array.isArray(format)) {
this._format = format;
} else if (typeof format === 'string' && format) {
this._format = [format];
}
// Set other properties.
typeof sprite === 'object' && (this._sprite = sprite);
typeof stream === 'boolean' && (this._stream = stream);
typeof volume === 'number' && volume >= 0 && volume <= 1.0 && (this._volume = volume);
typeof rate === 'number' && rate >= 0.5 && rate <= 5 && (this._rate = rate);
typeof muted === 'boolean' && (this._muted = muted);
typeof loop === 'boolean' && (this._loop = loop);
typeof preload === 'boolean' && (this._preload = preload);
typeof autoplay === 'boolean' && (this._autoplay = autoplay);
// Bind the passed event handlers to events.
typeof onload === 'function' && this.on(BuzzEvents.Load, onload);
typeof onloadprogress === 'function' && this.on(BuzzEvents.LoadProgress, onloadprogress);
typeof onunload === 'function' && this.on(BuzzEvents.UnLoad, onunload);
typeof onplaystart === 'function' && this.on(BuzzEvents.PlayStart, onplaystart);
typeof onplayend === 'function' && this.on(BuzzEvents.PlayEnd, onplayend);
typeof onpause === 'function' && this.on(BuzzEvents.Pause, onpause);
typeof onstop === 'function' && this.on(BuzzEvents.Stop, onstop);
typeof onmute === 'function' && this.on(BuzzEvents.Mute, onmute);
typeof onvolume === 'function' && this.on(BuzzEvents.Volume, onvolume);
typeof onrate === 'function' && this.on(BuzzEvents.Rate, onrate);
typeof onseek === 'function' && this.on(BuzzEvents.Seek, onseek);
typeof onerror === 'function' && this.on(BuzzEvents.Error, onerror);
typeof ondestroy === 'function' && this.on(BuzzEvents.Destroy, ondestroy);
}
// Throw error if source is not passed.
if (!this._src.length) {
throw new Error('You should pass the source for the audio.');
}
// Instantiate the queue.
this._queue = new Queue();
// Setup the audio engine.
this._engine.setup();
// If audio is not supported throw error.
if (!this._engine.isAudioAvailable()) {
this._fire(BuzzEvents.Error, null, { type: ErrorType.NoAudio, error: 'Web Audio is un-available' });
return this;
}
// Store the audio context.
this._context = this._engine.context();
// Add the created buzz to the engine and connect the gain nodes.
this._engine.add(this);
this._gainNode = this._engine.context().createGain();
this._gainNode.gain.setValueAtTime(this._muted ? 0 : this._volume, this._context.currentTime);
this._gainNode.connect(this._engine.masterGain());
// Subscribe to engine's resume event.
this._engine.on(EngineEvents.Resume, this._onEngineResume = this._onEngineResume.bind(this));
if (this._autoplay) {
this.play();
} else if (this._preload) {
this.load();
}
}
/**
* Loads the sound to the underlying audio object.
* @param {number} [soundId] The id of the sound to be loaded (for stream types).
* @return {Buzz}
*/
load(soundId) {
if (soundId) {
const sound = this.sound(soundId);
sound && sound.load();
return this;
}
// If the sound is not of stream and the source is loaded or currently loading then return.
if (!this._stream && this._loadState !== LoadState.NotLoaded) {
return this;
}
// Set the state to loading.
this._loadState = LoadState.Loading;
// Increment the calls which is needed for stream types.
this._noOfLoadCalls = this._noOfLoadCalls + 1;
// Get the first compatible source.
const src = this._compatibleSrc || (this._compatibleSrc = this.getCompatibleSource());
// Load the audio source.
const load$ = this._stream ? this._engine.allocateForGroup(src, this._id) : this._engine.load(src, this._onLoadProgress);
load$.then(downloadResult => {
this._noOfLoadCalls > 0 && (this._noOfLoadCalls = this._noOfLoadCalls - 1);
// During the loading, if buzz is destroyed or un-loaded then return.
if (this._state === BuzzState.Destroyed || this._loadState === LoadState.NotLoaded) {
this._stream && this._engine.releaseForGroup(this._compatibleSrc, this._id);
return;
}
// If loading succeeded,
// i. Save the result.
// ii. Set the load state as loaded.
// iii. Fire the load event.
// iv. Run the methods that are queued to run after successful load.
if (downloadResult.status === DownloadStatus.Success) {
if (this._stream) {
this._duration = downloadResult.value.duration;
} else {
this._buffer = downloadResult.value;
this._duration = this._buffer.duration;
}
this._loadState = LoadState.Loaded;
this._fire(BuzzEvents.Load, null, downloadResult);
if (this._engine.state() !== EngineState.Ready) {
this._queue.remove('after-load');
return;
}
this._queue.run('after-load');
return;
}
this._onLoadFailure(downloadResult.error);
});
return this;
}
/**
* Returns the first compatible source based on the passed sources and the format.
* @return {string}
*/
getCompatibleSource() {
// If the user has passed "format", check if it is supported or else retrieve the first supported source from the array.
return this._format.length ?
this._src[this._format.indexOf(utility.getSupportedFormat(this._format))] :
utility.getSupportedSource(this._src);
}
/**
* Plays the passed sound defined in the sprite or the sound that belongs to the passed id.
* @param {string|number} [soundOrId] The sound name defined in sprite or the sound id.
* @return {Buzz|number}
*/
play(soundOrId) {
const isIdPassed = typeof soundOrId === 'number';
// If id is passed then get the sound from the engine and play it.
if (isIdPassed) {
const sound = this.sound(soundOrId);
sound && this._play(sound);
return this;
}
// Create a unique id for sound.
const newSoundId = utility.id();
// Create the arguments of the sound.
const soundArgs = {
id: newSoundId,
stream: this._stream,
volume: this._volume,
rate: this._rate,
muted: this._muted,
loop: this._loop,
playEndCallback: () => this._fire(BuzzEvents.PlayEnd, newSoundId),
fadeEndCallback: () => this._fire(BuzzEvents.FadeEnd, newSoundId),
audioErrorCallback: (sound, err) => this._fire(BuzzEvents.Error, newSoundId, { type: ErrorType.LoadError, error: err }),
loadCallback: () => this._fire(BuzzEvents.Load, newSoundId),
destroyCallback: () => {
this._removeSound(newSoundId);
this._stream && this._engine.releaseForSound(this._compatibleSrc, this._id, newSoundId);
this._fire(BuzzEvents.Destroy, newSoundId);
emitter.clear(newSoundId);
}
};
// In case of sprite, set the positions.
if (typeof soundOrId === 'string' && this._sprite && this._sprite.hasOwnProperty(soundOrId)) {
const positions = this._sprite[soundOrId];
soundArgs.startPos = positions[0];
soundArgs.endPos = positions[1];
}
// Create the sound and connect the gains.
const newSound = new Sound(soundArgs);
newSound._gain().connect(this._gainNode);
this._soundsArray.push(newSound);
const playSound = () => {
newSound.source(this._stream ? this._engine.allocateForSound(this._compatibleSrc, this._id, newSoundId) : this._buffer);
this._play(newSound);
};
// If the sound is not yet loaded push an action to the queue to play the sound once it's loaded.
if (!this.isLoaded()) {
this._queue.add('after-load', `play-${newSoundId}`, () => playSound());
this.load();
} else {
playSound();
}
return newSoundId;
}
/**
* Pauses the sound belongs to the passed id or all the sounds belongs to this group.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
pause(id) {
const isGroup = typeof id === 'undefined';
this._removePlayActions(id);
isGroup && this.fadeStop();
this._sounds(id).forEach(sound => sound.pause());
this._fire(BuzzEvents.Pause, id);
return this;
}
/**
* Stops the sound belongs to the passed id or all the sounds belongs to this group.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
stop(id) {
const isGroup = typeof id === 'undefined';
this._removePlayActions(id);
isGroup && this.fadeStop();
this._sounds(id).forEach(sound => sound.stop());
this._fire(BuzzEvents.Stop, id);
return this;
}
/**
* Mutes the sound belongs to the passed id or all the sounds belongs to this group.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
mute(id) {
const isGroup = typeof id === 'undefined';
if (isGroup) {
this.fadeStop();
this._gainNode.gain.setValueAtTime(0, this._context.currentTime);
this._muted = true;
} else {
const sound = this.sound(id);
sound && sound.mute();
}
this._fire(BuzzEvents.Mute, id, this._muted);
return this;
}
/**
* Un-mutes the sound belongs to the passed id or all the sounds belongs to this group.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
unmute(id) {
const isGroup = typeof id === 'undefined';
if (isGroup) {
this.fadeStop();
this._gainNode.gain.setValueAtTime(this._volume, this._context.currentTime);
this._muted = false;
} else {
const sound = this.sound(id);
sound && sound.unmute();
}
this._fire(BuzzEvents.Mute, id, this._muted);
return this;
}
/**
* Gets/sets the volume of the passed sound or the group.
* @param {number} [volume] Should be from 0.0 to 1.0.
* @param {number} [id] The sound id.
* @return {Buzz|number}
*/
volume(volume, id) {
const isGroup = typeof id === 'undefined';
if (typeof volume === 'number' && volume >= 0 && volume <= 1.0) {
if (isGroup) {
this.fadeStop();
this._gainNode.gain.setValueAtTime(this._muted ? 0 : volume, this._context.currentTime);
this._volume = volume;
} else {
const sound = this.sound(id);
sound && sound.volume(volume);
}
this._fire(BuzzEvents.Volume, id, this._volume);
return this;
}
if (!isGroup) {
const sound = this.sound(id);
return sound ? sound.volume() : null;
}
return this._volume;
}
/**
* Fades the group's or passed sound's volume to the passed value in the passed duration.
* @param {number} to The destination volume.
* @param {number} duration The period of fade in seconds.
* @param {string} [type = linear] The fade type (linear or exponential).
* @param {number} [id] The sound id.
* @return {Buzz}
*/
fade(to, duration, type = 'linear', id) {
const isGroup = typeof id === 'undefined';
if (isGroup && this._fading) {
return this;
}
this._fire(BuzzEvents.FadeStart, id);
if (isGroup) {
this._fading = true;
if (type === 'linear') {
this._gainNode.gain.linearRampToValueAtTime(to, this._context.currentTime + duration);
} else {
this._gainNode.gain.exponentialRampToValueAtTime(to, this._context.currentTime + duration);
}
this._fadeTimer = setTimeout(() => {
this.volume(to);
clearTimeout(this._fadeTimer);
this._fadeTimer = null;
this._fading = false;
this._fire(BuzzEvents.FadeEnd);
}, duration * 1000);
} else {
const sound = this.sound(id);
sound && sound.fade(to, duration, type);
}
return this;
}
/**
* Stops the group's or passed sound's current running fade.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
fadeStop(id) {
const isGroup = typeof id === 'undefined';
if (isGroup) {
if (!this._fading) {
return this;
}
this._gainNode.gain.cancelScheduledValues(this._context.currentTime);
if (this._fadeTimer) {
clearTimeout(this._fadeTimer);
this._fadeTimer = null;
}
this._fading = false;
} else {
const sound = this.sound(id);
sound && sound.fadeStop();
}
this._fire(BuzzEvents.FadeStop, id);
return this;
}
/**
* Gets/sets the rate of the passed sound or the group.
* @param {number} [rate] Should be from 0.5 to 5.0.
* @param {number} [id] The sound id.
* @return {Buzz|number}
*/
rate(rate, id) {
const isGroup = typeof id === 'undefined';
if (typeof rate === 'number' && rate >= 0.5 && rate <= 5) {
this._sounds(id).forEach(sound => sound.rate(rate));
isGroup && (this._rate = rate);
this._fire(BuzzEvents.Rate, id, this._rate);
return this;
}
if (!isGroup) {
const sound = this.sound(id);
return sound ? sound.rate() : null;
}
return this._rate;
}
/**
* Gets/sets the current playback position of the sound.
* @param {number} id The sound id
* @param {number} [seek] The seek position.
* @return {Buzz|number}
*/
seek(id, seek) {
const sound = this.sound(id);
if (!sound) {
return this;
}
if (typeof seek === 'number') {
// If the audio source is not yet loaded push an item to the queue to seek after the sound is loaded
// and load the sound.
if (!this.isLoaded()) {
this._queue.add('after-load', `seek-${id}`, () => this.seek(id, seek));
this.load();
return this;
}
sound.seek(seek);
this._fire(BuzzEvents.Seek, id, seek);
return this;
}
return sound.seek();
}
/**
* Gets/sets the looping behavior of a sound or the group.
* @param {boolean} [loop] True to loop the sound.
* @param {number} [id] The sound id.
* @return {Buzz|boolean}
*/
loop(loop, id) {
const isGroup = typeof id === 'undefined';
if (typeof loop === 'boolean') {
this._sounds(id).forEach(sound => sound.loop(loop));
isGroup && (this._loop = loop);
return this;
}
if (!isGroup) {
const sound = this.sound(id);
return sound ? sound.loop() : null;
}
return this._loop;
}
/**
* Returns true if the passed sound is playing.
* @param {number} id The sound id.
* @return {boolean}
*/
playing(id) {
const sound = this.sound(id);
return sound ? sound.isPlaying() : null;
}
/**
* Returns true if the passed sound is muted or the group is muted.
* @param {number} [id] The sound id.
* @return {boolean}
*/
muted(id) {
if (typeof id === 'undefined') {
return this._muted;
}
const sound = this.sound(id);
return sound ? sound.muted() : null;
}
/**
* Returns the state of the passed sound or the group.
* @param {number} [id] The sound id.
* @return {BuzzState|SoundState}
*/
state(id) {
if (typeof id === 'undefined') {
return this._state;
}
const sound = this.sound(id);
return sound ? sound.state() : null;
}
/**
* Returns the duration of the passed sound or the total duration of the sound.
* @param {number} [id] The sound id.
* @return {number}
*/
duration(id) {
if (typeof id === 'undefined') {
return this._duration;
}
const sound = this.sound(id);
return sound ? sound.duration() : null;
}
/**
* Unloads the loaded audio buffer or free audio nodes.
* @return {Buzz}
*/
unload() {
this._queue.remove('after-load');
this._stream && this._engine.releaseForGroup(this._compatibleSrc, this._id);
this._buffer = null;
this._duration = 0;
this._loadState = LoadState.NotLoaded;
this._noOfLoadCalls = 0;
this._fire(BuzzEvents.UnLoad);
return this;
}
/**
* Stops and destroys all the sounds belongs to this group and release other dependencies.
* @param {number} [soundId] The sound id.
*/
destroy(soundId) {
if (soundId) {
const sound = this.sound(soundId);
sound && sound.destroy();
return;
}
if (this._state === BuzzState.Destroyed) {
return;
}
this.stop();
this._soundsArray.forEach(sound => sound.destroy());
this._queue.clear();
this._engine.off(EngineEvents.Resume, this._onEngineResume);
this._stream && this._engine.releaseForGroup(this._compatibleSrc, this._id);
this._gainNode.disconnect();
this._engine.remove(this);
this._soundsArray = [];
this._buffer = null;
this._queue = null;
this._context = null;
this._engine = null;
this._gainNode = null;
this._state = BuzzState.Destroyed;
this._fire(BuzzEvents.Destroy);
emitter.clear(this._id);
}
/**
* Makes the passed sound persistent that means it can't be auto-destroyed.
* @param {number} soundId The sound id.
*/
persist(soundId) {
const sound = this.sound(soundId);
sound && sound.persist();
}
/**
* Makes the passed sound un-persistent that means it can be auto-destroyed.
* @param {number} soundId The sound id.
*/
abandon(soundId) {
const sound = this.sound(soundId);
sound && sound.abandon();
}
/**
* Removes the inactive sounds.
*/
free() {
const now = new Date();
this._soundsArray = this._soundsArray.filter(sound => {
const inactiveDurationInSeconds = (now - sound.lastPlayed()) / 1000;
if (sound.isPersistent() ||
sound.isPlaying() ||
sound.isPaused() ||
inactiveDurationInSeconds < this._engine.inactiveTime() * 60) {
return true;
}
sound.destroy();
return false;
});
}
/**
* Subscribes to an event for the sound or the group.
* @param {string} eventName The event name.
* @param {function} handler The event handler.
* @param {boolean} [once = false] True for one-time event handling.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
on(eventName, handler, once = false, id) {
emitter.on(id || this._id, eventName, handler, once);
return this;
}
/**
* Un-subscribes from an event for the sound or the group.
* @param {string} eventName The event name.
* @param {function} handler The event handler.
* @param {number} [id] The sound id.
* @return {Buzz}
*/
off(eventName, handler, id) {
emitter.off(id || this._id, eventName, handler);
return this;
}
/**
* Returns the unique id of the sound.
* @return {number}
*/
id() {
return this._id;
}
/**
* Returns the gain node.
* @return {GainNode}
*/
gain() {
return this._gainNode;
}
/**
* Returns the audio resource loading status.
* @return {LoadState}
*/
loadState() {
return this._loadState;
}
/**
* Returns true if the audio source is loaded.
* @return {boolean}
*/
isLoaded() {
return this._stream ? this._engine.hasFreeNodes(this._compatibleSrc, this._id) : this._loadState === LoadState.Loaded;
}
/**
* Returns the sound for the passed id.
* @param {number} id The sound id.
* @return {Sound}
*/
sound(id) {
return this._soundsArray.find(x => x.id() === id);
}
/**
* Returns all the sounds.
* @return {Array<Sound>}
*/
sounds() {
return this._soundsArray;
}
/**
* Returns true if the passed sound exists.
* @param {number} id The sound id.
* @return {boolean}
*/
alive(id) {
return Boolean(this.sound(id));
}
/**
* Sets source, format and sprite from the assigned key.
* @param {string} key The source key.
* @private
*/
_setSource(key) {
const src = this._engine.getSource(key.substring(1));
if (typeof src === 'string') {
this._src = [src];
} else if (Array.isArray(src)) {
this._src = src;
} else if (typeof src === 'object') {
const {
url,
format,
sprite
} = src;
if (typeof url === 'string') {
this._src = [url];
} else if (Array.isArray(url)) {
this._src = url;
}
if (Array.isArray(format)) {
this._format = format;
} else if (typeof format === 'string' && format) {
this._format = [format];
}
typeof sprite === 'object' && (this._sprite = sprite);
}
}
/**
* Called on failure of loading audio source.
* @param {*} error The audio source load error.
* @private
*/
_onLoadFailure(error) {
// Remove the queued actions from this class that are supposed to run after load.
this._noOfLoadCalls === 0 && this._queue.remove('after-load');
// Set the load state back to not loaded.
this._loadState = LoadState.NotLoaded;
// Fire the error event.
this._fire(BuzzEvents.Error, null, { type: ErrorType.LoadError, error: error });
}
/**
* The resource load progress handler.
* @param {object} evt The progress data.
* @private
*/
_onLoadProgress(evt) {
this._fire(BuzzEvents.LoadProgress, null, evt.percentageDownloaded);
}
/**
* Whenever the engine resume run the actions queued for it.
* @private
*/
_onEngineResume() {
this._queue.run('after-engine-resume');
}
/**
* Checks the engine state and plays the passed sound.
* @param {Sound} sound The sound.
* @private
*/
_play(sound) {
if (this._engine.state() === EngineState.Destroying || this._engine.state() === EngineState.Done) {
this._fire(BuzzEvents.Error, null, { type: ErrorType.PlayError, error: 'The engine is stopping/stopped' });
return;
}
if (this._engine.state() === EngineState.NoAudio) {
this._fire(BuzzEvents.Error, null, { type: ErrorType.NoAudio, error: 'Web Audio is un-available' });
return;
}
const playAndFire = () => {
sound.play();
this._fire(BuzzEvents.PlayStart, sound.id());
};
if ([EngineState.Suspending, EngineState.Suspended, EngineState.Resuming].indexOf(this._engine.state()) > -1) {
this._queue.add('after-engine-resume', `sound-${sound.id()}`, () => playAndFire());
this._engine.state() !== EngineState.Resuming && this._engine.resume();
return;
}
playAndFire();
}
/**
* Remove the play actions queued from the queue.
* @param {number} [id] The sound id.
* @private
*/
_removePlayActions(id) {
this._queue.remove('after-load', id ? `play-${id}` : null);
this._queue.remove('after-engine-resume', id ? `sound-${id}` : null);
}
/**
* Returns the sound for the passed id or all the sounds belong to this group.
* @param {number} [id] The sound id.
* @return {Array<Sound>}
* @private
*/
_sounds(id) {
if (typeof id === 'number') {
const sound = this._soundsArray.find(x => x.id() === id);
return sound ? [sound] : [];
}
return this._soundsArray;
}
/**
* Removes the passed sound from the array.
* @param {number|Sound} sound The sound.
* @private
*/
_removeSound(sound) {
if (typeof sound === 'number') {
this._soundsArray = this._soundsArray.filter(x => x.id() !== sound);
return;
}
this._soundsArray.splice(this._soundsArray.indexOf(sound), 1);
}
/**
* Fires an event of group or sound.
* @param {string} eventName The event name.
* @param {number} [id] The sound id.
* @param {...*} args The arguments that to be passed to handler.
* @return {Buzz}
* @private
*/
_fire(eventName, id, ...args) {
if (id) {
emitter.fire(id, eventName, ...args, this.sound(id), this);
emitter.fire(this._id, eventName, ...args, this.sound(id), this);
} else {
emitter.fire(this._id, eventName, ...args, this);
}
return this;
}
} |
JavaScript | class AnimationModule {
constructor(app, isDeferred, params = {}) {
this.params = Object.assign({
speed: 1
}, params);
this.clock = new Clock();
this.app = app;
this.isDeferred = isDeferred;
}
/**
* @method play
* @instance
* @description Plays the given clip name
* @param {String} clipName - the clip to play
* @memberof module:modules/mesh.AnimationModule
*/
play(clipName) {
const clip = AnimationClip.findByName(this.clips, clipName);
const action = this.mixer.clipAction(clip);
action.play();
}
/**
* @method update
* @instance
* @description Update the mixer (being called on frame animation loop)
* @memberof module:modules/mesh.AnimationModule
*/
update() {
if (this.mixer) this.mixer.update(this.clock.getDelta() * this.params.speed);
}
integrate(self) {
self.loop = new Loop(() => {
self.update();
});
if (!self.isDeferred) self.loop.start(self.app);
}
manager(manager) {
manager.define('animation');
}
bridge = {
mesh(mesh, self) {
mesh.geometry.skeleton = mesh.skeleton;
self.mixer = new AnimationMixer(mesh.geometry);
self.clips = mesh.geometry.animations;
return mesh;
}
}
} |
JavaScript | class SearchStore extends React.Component {
constructor(props) {
super(props);
this.state = {
words: [],
searchType: '',
sources: [],
};
this.getSearch = this.getSearch.bind(this);
this.getWords = this.getWords.bind(this);
this.getSources = this.getSources.bind(this);
this.getEmotionalTone = this.getEmotionalTone.bind(this);
this.getEmotionalToneSentiment = this.getEmotionalToneSentiment.bind(this);
this.computeSearch = this.computeSearch.bind(this);
}
/**
* Search the index
*
* @function getSearch
* @param {Object} opts
*/
getSearch(opts) {
if (opts.startDate && opts.startDate.getTime)
opts.startDate = opts.startDate.getTime();
if (opts.endDate && opts.endDate.getTime)
opts.endDate = opts.endDate.getTime();
localStorage.setItem('prev-search', JSON.stringify(opts));
if (!opts.startDate)
opts.startDate = 0;
if (!opts.endDate)
opts.endDate = new Date().getTime();
this.setState({
...this.state, search: undefined, searchOpts: opts, searchType: opts.show ? 'emotion' : 'sentiment',
});
const sources = opts.checkedItemsNews.join(',');
fetch(`/api/search?q=${opts.search}${sources.length > 0 ? `&sources=${sources}` : ''}${opts.startDate ? `&intervalStart=${opts.startDate}` : ''}${opts.endDate ? `&intervalEnd=${opts.endDate}` : ''}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then(response => response.json()).then((data) => {
this.computeSearch(data, opts);
}).catch(console.error);
}
/**
* Compute the search data fetched
*
* @function computeSearch
* @param {Object} data
* @param {Object} opts
*/
computeSearch(data, opts) {
const search = JSON.parse(JSON.stringify(data));
search.docs = search.docs
.filter(doc => (opts.startDate ? doc.date >= opts.startDate : true)
&& (opts.endDate ? doc.date <= opts.endDate : true));
if (search.docs.length === 0) {
this.setState({
...this.state,
search: data,
searchOpts: opts,
searchType: opts.show ? 'emotion' : 'sentiment',
});
}
else if (!opts.show) {
const colors = ['#5EA3DB', '#FF5C54', '#AFBE8F'];
const average = search.docs.reduce((acc, val) => {
let sentiment = val.analysis.sentiment;
if (!sentiment) {
sentiment = {
score: 0,
label: 'neutral',
};
}
let label = 'neutral';
if (sentiment.score > opts.neutralThreshold)
label = 'positive';
else if (sentiment.score < -opts.neutralThreshold)
label = 'negative';
acc.sentiment[label]++;
return acc;
}, {
sentiment: { positive: 0, negative: 0, neutral: 0 },
});
Object.keys(average).forEach((key) => {
if (typeof average[key] === 'number')
average[key] /= search.docs.length;
else
Object.keys(average[key]).forEach((key2) => {
average[key][key2] /= search.docs.length;
});
});
this.setState({
...this.state,
graphData: Object.keys(average.sentiment ? average.sentiment : {}).map(
(key, i) => (
{
title: key,
value: Math.floor(average.sentiment[key] * 100),
color: colors[i],
}),
),
search: data,
emotionalTone: this.getEmotionalToneSentiment(search, opts),
searchOpts: opts,
searchType: opts.show ? 'emotion' : 'sentiment',
});
}
else if (opts.show) {
const colors = ['#D3C0CD', '#9FAF90', '#3A405A', '#3D70B2', '#E26D5A'];
const average = search.docs.reduce((acc, val) => {
let emotion = val.analysis.emotion;
if (!emotion) {
emotion = {
anger: 0,
joy: 0,
disgust: 0,
fear: 0,
sadness: 0,
};
}
Object.keys(emotion).forEach((k) => {
acc[k] += emotion[k];
});
acc.sentiment[val.analysis.sentiment.label]++;
return acc;
}, {
sentiment: { positive: 0, negative: 0, neutral: 0 },
joy: 0,
disgust: 0,
fear: 0,
sadness: 0,
anger: 0,
});
Object.keys(average).forEach((key) => {
if (typeof average[key] === 'number')
average[key] /= search.docs.length;
else
Object.keys(average[key]).forEach((key2) => {
average[key][key2] /= search.docs.length;
});
});
this.setState({
...this.state,
graphData: Object.keys(average).filter(e => e !== 'sentiment').map(
(key, i) => ({ title: key, value: Math.floor(average[key] * 100), color: colors[i] }),
),
search: data,
emotionalTone: this.getEmotionalTone(search),
searchOpts: opts,
searchType: opts.show ? 'emotion' : 'sentiment',
});
}
}
/**
* Fetch the sources indexed
*
* @function getSources
*/
getSources() {
fetch('/api/search/sources').then(res => res.json()).then((data) => {
this.setState({
...this.state,
sources: data,
});
});
}
/**
* Update the words for wordcloud
*
* @function getWords
* @param {number} count
*/
getWords(count) {
if (!count)
count = 30;
fetch(`/api/wordcloud?length=${count}`).then(res => res.json()).then((data) => {
this.setState({
...this.state,
words: data.map(elem => ({
value: elem.key,
count: elem.value,
})),
});
});
}
/**
* Get emotional tone for graph
*
* @function getEmotionalTone
* @param {Object} search
* @returns {Array<Object>}
*/
getEmotionalTone(search) {
const sortArr = search.docs.sort(
(a, b) => a.date - b.date,
).filter(a => a.date > 0).map((element) => {
const date = new Date(element.date);
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
element.date = date.getTime();
return element;
});
const days = {};
sortArr.forEach((element) => {
if (days[element.date])
days[element.date].push(element);
else
days[element.date] = [element];
});
const ret = [];
Object.keys(days).forEach((key, i) => {
const emotions = days[key].reduce((acc, val) => {
const emotion = val.analysis.emotion;
if (!emotion)
return acc;
Object.keys(acc).forEach((k) => {
acc[k].perc += emotion[k];
});
return acc;
}, {
anger: { perc: 0 },
joy: { perc: 0 },
disgust: { perc: 0 },
fear: { perc: 0 },
sadness: { perc: 0 },
});
Object.keys(emotions).forEach((k) => {
emotions[k].perc /= days[key].length;
emotions[k].perc *= 1000;
emotions[k].perc = Math.round(emotions[k].perc);
emotions[k].perc /= 10;
});
ret.push({
id: i,
date: new Date(Number(key)).toLocaleDateString(),
emotions,
time: new Date(Number(key)).getTime(),
});
});
return ret;
}
/**
* Get sentiment tone for graph
*
* @function getEmotionalToneSentiment
* @param {Object} search
* @param {Object} opts
* @returns {Array<Object>}
*/
getEmotionalToneSentiment(search, opts) {
const sortArr = search.docs.sort(
(a, b) => a.date - b.date,
).filter(a => a.date > 0).map((element) => {
const date = new Date(element.date);
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
element.date = date.getTime();
return element;
});
const days = {};
sortArr.forEach((element) => {
if (days[element.date])
days[element.date].push(element);
else
days[element.date] = [element];
});
const ret = Object.keys(days).map((key) => {
const sentiments = days[key].reduce((acc, val) => {
const sentiment = val.analysis.sentiment;
if (!sentiment)
return acc;
if (sentiment.score > opts.neutralThreshold)
acc.positive.score++;
if (sentiment.score > -opts.neutralThreshold)
acc.neutral.score++;
else
acc.negative.score++;
return acc;
}, {
negative: { score: 0 },
neutral: { score: 0 },
positive: { score: 0 },
});
return { sentiments, key };
});
return ret.map((val, i) => ({
id: i,
date: new Date(Number(val.key)).toLocaleDateString(),
sentiments: val.sentiments,
time: new Date(Number(val.key)).getTime(),
}));
}
render() {
return (
<SearchContext.Provider value={{
...this.state,
getSearch: this.getSearch,
getWords: this.getWords,
getSources: this.getSources,
getEmotionalTone: this.getEmotionalTone,
getEmotionalToneSentiment: this.getEmotionalToneSentiment,
computeSearch: this.computeSearch,
}}>
{this.props.children}
</SearchContext.Provider>
);
}
} |
JavaScript | class RootAttributeOperation extends Operation {
/**
* Creates an operation that changes, removes or adds attributes on root element.
*
* @see module:engine/model/operation/attributeoperation~AttributeOperation
* @param {module:engine/model/rootelement~RootElement} root Root element to change.
* @param {String} key Key of an attribute to change or remove.
* @param {*} oldValue Old value of the attribute with given key or `null` if adding a new attribute.
* @param {*} newValue New value to set for the attribute. If `null`, then the operation just removes the attribute.
* @param {Number|null} baseVersion Document {@link module:engine/model/document~Document#version} on which operation
* can be applied or `null` if the operation operates on detached (non-document) tree.
*/
constructor( root, key, oldValue, newValue, baseVersion ) {
super( baseVersion );
/**
* Root element to change.
*
* @readonly
* @member {module:engine/model/rootelement~RootElement}
*/
this.root = root;
/**
* Key of an attribute to change or remove.
*
* @readonly
* @member {String}
*/
this.key = key;
/**
* Old value of the attribute with given key or `null` if adding a new attribute.
*
* @readonly
* @member {*}
*/
this.oldValue = oldValue;
/**
* New value to set for the attribute. If `null`, then the operation just removes the attribute.
*
* @readonly
* @member {*}
*/
this.newValue = newValue;
}
/**
* @inheritDoc
*/
get type() {
if ( this.oldValue === null ) {
return 'addRootAttribute';
} else if ( this.newValue === null ) {
return 'removeRootAttribute';
} else {
return 'changeRootAttribute';
}
}
/**
* Creates and returns an operation that has the same parameters as this operation.
*
* @returns {module:engine/model/operation/rootattributeoperation~RootAttributeOperation} Clone of this operation.
*/
clone() {
return new RootAttributeOperation( this.root, this.key, this.oldValue, this.newValue, this.baseVersion );
}
/**
* See {@link module:engine/model/operation/operation~Operation#getReversed `Operation#getReversed()`}.
*
* @returns {module:engine/model/operation/rootattributeoperation~RootAttributeOperation}
*/
getReversed() {
return new RootAttributeOperation( this.root, this.key, this.newValue, this.oldValue, this.baseVersion + 1 );
}
/**
* @inheritDoc
*/
_validate() {
if ( this.root != this.root.root || this.root.is( 'documentFragment' ) ) {
/**
* The element to change is not a root element.
*
* @error rootattribute-operation-not-a-root
* @param {module:engine/model/rootelement~RootElement} root
* @param {String} key
* @param {*} value
*/
throw new CKEditorError(
'rootattribute-operation-not-a-root',
this,
{ root: this.root, key: this.key }
);
}
if ( this.oldValue !== null && this.root.getAttribute( this.key ) !== this.oldValue ) {
/**
* The attribute which should be removed does not exists for the given node.
*
* @error rootattribute-operation-wrong-old-value
* @param {module:engine/model/rootelement~RootElement} root
* @param {String} key
* @param {*} value
*/
throw new CKEditorError(
'rootattribute-operation-wrong-old-value',
this,
{ root: this.root, key: this.key }
);
}
if ( this.oldValue === null && this.newValue !== null && this.root.hasAttribute( this.key ) ) {
/**
* The attribute with given key already exists for the given node.
*
* @error rootattribute-operation-attribute-exists
* @param {module:engine/model/rootelement~RootElement} root
* @param {String} key
*/
throw new CKEditorError(
'rootattribute-operation-attribute-exists',
this,
{ root: this.root, key: this.key }
);
}
}
/**
* @inheritDoc
*/
_execute() {
if ( this.newValue !== null ) {
this.root._setAttribute( this.key, this.newValue );
} else {
this.root._removeAttribute( this.key );
}
}
/**
* @inheritDoc
*/
toJSON() {
const json = super.toJSON();
json.root = this.root.toJSON();
return json;
}
/**
* @inheritDoc
*/
static get className() {
return 'RootAttributeOperation';
}
/**
* Creates RootAttributeOperation object from deserilized object, i.e. from parsed JSON string.
*
* @param {Object} json Deserialized JSON object.
* @param {module:engine/model/document~Document} document Document on which this operation will be applied.
* @returns {module:engine/model/operation/rootattributeoperation~RootAttributeOperation}
*/
static fromJSON( json, document ) {
if ( !document.getRoot( json.root ) ) {
/**
* Cannot create RootAttributeOperation for document. Root with specified name does not exist.
*
* @error rootattribute-operation-fromjson-no-root
* @param {String} rootName
*/
throw new CKEditorError( 'rootattribute-operation-fromjson-no-root', this, { rootName: json.root } );
}
return new RootAttributeOperation( document.getRoot( json.root ), json.key, json.oldValue, json.newValue, json.baseVersion );
}
// @if CK_DEBUG_ENGINE // toString() {
// @if CK_DEBUG_ENGINE // return `RootAttributeOperation( ${ this.baseVersion } ): ` +
// @if CK_DEBUG_ENGINE // `"${ this.key }": ${ JSON.stringify( this.oldValue ) }` +
// @if CK_DEBUG_ENGINE // ` -> ${ JSON.stringify( this.newValue ) }, ${ this.root.rootName }`;
// @if CK_DEBUG_ENGINE // }
} |
JavaScript | class Shooter {
/**
* The Towers Shooter constructor
* @param {Towers} parent
*/
constructor(parent) {
this.parent = parent;
this.ammos = new List();
this.bullets = document.querySelector(".bullets");
this.bullets.innerHTML = "";
}
/**
* Iterates through the moving list of mobs and when posible, it asigns a tower to shoot each mob
* @returns {Void}
*/
shoot() {
this.parent.mobs.moving.forEach((it) => {
const mob = it.getPrev();
const towers = this.parent.ranges.getReducedList(mob.row, mob.col);
if (mob.hitPoints > 0 && towers && !towers.isEmpty) {
this.shootMob(towers, mob);
}
});
}
/**
* For a single mob, shot it with all the towers that can reach it and attack it
* @param {List.<Tower>} towers
* @param {Mob} mob
* @returns {Void}
*/
shootMob(towers, mob) {
towers.some((element) => {
const tower = this.parent.manager.get(element.id);
if (tower && !tower.isShooting && tower.canShoot(mob)) {
this.processShot(tower, mob);
}
if (mob.hitPoints <= 0) {
return true;
}
});
}
/**
* Makes the Tower shoot the mob and others depending on the tower
* @param {Tower} tower
* @param {Mob} mob
* @returns {Void}
*/
processShot(tower, mob) {
const targets = tower.getTargets(this.parent.mobs.moving, mob);
this.parent.ranges.startShoot(tower);
tower.startShoot();
targets.forEach((list, index) => {
const ammo = this.createAmmo(tower, list, index + 1);
this.parent.sounds[tower.sound]();
list.forEach(function (nmob) {
nmob.decHitPoints(tower.damage);
});
if (tower.canLock) {
tower.setAngle(mob, ammo);
}
tower.addAmmo(list.length);
});
this.parent.manager.addShoot(tower.id);
tower.toggleAttack(targets.length);
}
/**
* Creates a new Ammo
* @param {Tower} tower
* @param {Array.<Mob>} targets
* @param {Number} index
* @returns {Ammo}
*/
createAmmo(tower, targets, index) {
const ammo = tower.createAmmo(targets, index);
const it = this.ammos.addLast(ammo);
ammo.setIterator(it);
this.bullets.appendChild(ammo.createElement());
return ammo;
}
/**
* Moves all the Ammos till they reach the target, and it then performs the required tasks
* @param {Number} time
* @returns {Void}
*/
moveAmmos(time) {
this.ammos.forEach((ammo) => {
const tower = ammo.tower;
if (ammo.move(time)) {
this.attackTargets(ammo.targets, tower.damage);
this.parent.mobs.addToList(ammo.targets, tower);
if (tower.canFire && tower.canDestroy) {
this.parent.manager.destroyTower(tower);
}
if (ammo.hitSound) {
this.parent.sounds[ammo.hitSound]();
}
}
});
}
/**
* Does the final attack on the mobs reducing their actual life
* @param {Array.<Mob>} targets
* @param {Number} damage
* @returns {Void}
*/
attackTargets(targets, damage) {
targets.forEach((mob)=> {
mob.hit(damage);
this.parent.panel.updateMob(mob);
if (mob.life <= 0 && !mob.isDead) {
this.parent.mobs.killMob(mob);
}
});
}
} |
JavaScript | class Config {
constructor(options) {
this.defaultauthor = options.defaultauthor ?? null;
this.directory = options.directory ?? null;
this.output = options.output ?? null;
this.fields = {
/**
* Default fields
* @type {Array<Field>}
*/
default: [],
/**
* Custom fields from the user
* @type {Array<Field>}
*/
custom: [],
/**
* Fields to discard before use
* @type {Array<string>}
*/
remove: [],
};
let fieldIds = {};
for (const type of ['default', 'custom']) {
for (const field of options.fields[type]) {
const validatd = Config.validateField(field);
if (fieldIds[validatd.name]) {
this.fields[type][fieldIds[validatd.name]] = validatd;
} else {
fieldIds[validatd.name] = this.fields[type].push(validatd) - 1;
}
}
}
for (const remove of options.fields.remove) {
if (typeof remove !== 'string') throw new TypeError(`remove expected type string, got "${typeof remove}".`);
if (fieldIds[remove]) {
for (const type of ['default', 'custom']) {
if (this.fields[type][fieldIds[remove]]) {
this.fields[type].splice(fieldIds[remove], 1);
break;
}
}
}
}
}
/**
* Validate field data
* @param {Field} field The field data to validate
* @returns {Field}
*/
static validateField(field) {
if (typeof field.name !== 'string') {
throw new TypeError(`field.name expected type string, got "${typeof field.name}".`);
}
if (!/^[a-z0-9_-]+$/i.test(field.name)) {
throw new TypeError(`field.name must comply with the following pattern: /^[a-z0-9_-]+$/i`);
}
if (typeof field.value === 'undefined' || field.value === null) field.value = `manifest['${field.name}']`;
if (!['string', 'function'].includes(typeof field.value)) {
throw new TypeError(`field.value expected type string or function, got "${typeof field.value}".`);
}
if (!Array.isArray(field.handles) && typeof field.handles !== 'undefined' && field.handles !== null) {
throw new TypeError(`field.handles expected type array, undefined or null, got "${typeof field.handles}".`);
}
if (field.handles) {
for (let i = 0; i < field.handles.length; i++) {
const handle = field.handles[i];
if (typeof handle === 'string') {
field.handles[i] = { [handle]: [] };
} else if (typeof handle === 'object' && handle !== null) {
for (const key in handle) {
// @ts-ignore
if (typeof handle[key] === 'string') handle[key] = [handle[key]];
if (!Array.isArray(handle[key])) {
throw new TypeError(`field.handles[${i}].${key} expected type array, got "${typeof handle[key]}".`);
}
}
} else {
throw new TypeError(`field.handles[${i}] expected type string or object, got "${typeof handle}".`);
}
}
}
return field;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.