language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ElementAttribute extends _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Designator { /** * Creates a ne instance of the designator. * @param name {String} The name of the attribute */ constructor(name) { super(); this.name = name; } toString() { return this.name; } }
JavaScript
class ElementAttributeValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { /** * Creates a new instance of the value. * @param name {String} The name of the attribute in the DOM node * @param input {Object|Value} The DOM node, or a value containing the * DOM node * @param v {Object|Value} The value of the attribute in the DOM node */ constructor(name, input, v) { super(); this.name = name; this.input = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(input); this.value = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(v); } getValue() { return this.value.getValue(); } toString() { return this.value.getValue().toString(); } query(q, d, root, factory) { var leaves = []; var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(new ElementAttribute(this.name), d); var n = factory.getObjectNode(new_d, this.input); leaves.push(...this.input.query(q, new_d, n, factory)); root.addChild(n); return leaves; } }
JavaScript
class CssPropertyFunction extends WebElementFunction { constructor(name, returnType = null) { if (["float", "int", "string", null].indexOf(returnType) == -1) { throw new Error(`CssPropertyFunction returnType expects one of the following values: "float", "int", "string", null. Received ${returnType} instead.`); } super(name); this.returnType = returnType; } get(element) { const style = this.getElementComputedStyle(element); const value = style.getPropertyValue(this.name); switch (this.returnType) { case "float": return parseFloat(value); case "int": return parseInt(value); case "string": return typeof value == "string" ? value : value.toString(); } return value; } }
JavaScript
class DimensionWidth extends WebElementFunction { /** * Creates a new instance of the function. */ constructor() { super("width"); } get(element) { return element.offsetWidth; } }
JavaScript
class DimensionHeight extends WebElementFunction { /** * Creates a new instance of the function. */ constructor() { super("height"); } get(element) { return element.offsetHeight; } }
JavaScript
class FontSize extends CssPropertyFunction { constructor() { super("font-size"); } }
JavaScript
class FontWeight extends CssPropertyFunction { constructor() { super("font-weight"); } }
JavaScript
class FontFamily extends CssPropertyFunction { constructor() { super("font-family"); } }
JavaScript
class Color extends CssPropertyFunction { constructor() { super("color"); } }
JavaScript
class Opacity extends CssPropertyFunction { constructor() { super("opacity", "float"); } }
JavaScript
class BackgroundColor extends CssPropertyFunction { /** * Creates a new instance of the function. */ constructor() { super("background-color"); } }
JavaScript
class MarginTop extends CssPropertyFunction { constructor() { super("margin-top", "float"); } }
JavaScript
class MarginBottom extends CssPropertyFunction { constructor() { super("margin-bottom"); } }
JavaScript
class MarginLeft extends CssPropertyFunction { constructor() { super("margin-left"); } }
JavaScript
class MarginRight extends CssPropertyFunction { constructor() { super("margin-right"); } }
JavaScript
class PaddingTop extends CssPropertyFunction { constructor() { super("padding-top"); } }
JavaScript
class PaddingBottom extends CssPropertyFunction { constructor() { super("padding-bottom"); } }
JavaScript
class PaddingLeft extends CssPropertyFunction { constructor() { super("padding-left"); } }
JavaScript
class PaddingRight extends CssPropertyFunction { constructor() { super("padding-right"); } }
JavaScript
class BorderWidth extends CssPropertyFunction { constructor() { super("border-width"); } }
JavaScript
class BorderStyle extends CssPropertyFunction { constructor() { super("border-style"); } }
JavaScript
class BorderColor extends CssPropertyFunction { constructor() { super("border-color"); } }
JavaScript
class BorderRadius extends CssPropertyFunction { constructor() { super("border-radius"); } }
JavaScript
class Display extends CssPropertyFunction { constructor() { super("display"); } }
JavaScript
class Visibility extends CssPropertyFunction { constructor() { super("visibility"); } }
JavaScript
class Position extends CssPropertyFunction { constructor() { super("position"); } }
JavaScript
class Float extends CssPropertyFunction { constructor() { super("float"); } }
JavaScript
class BackgroundImage extends CssPropertyFunction { constructor() { super("background-image"); } }
JavaScript
class Zindex extends CssPropertyFunction { constructor() { super("z-index", "float"); } }
JavaScript
class Path extends _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Designator { /** * Creates a new instance of the designator. * @param path {String} A string containing an XPath expression */ constructor(path) { super(); this.path = path; } toString() { return this.path; } }
JavaScript
class PathValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { constructor(p, root, value) { super(); this.value = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(value); this.root = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(root); this.path = p; } query(q, d, root, factory) { var leaves = []; var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(d.tail(), this.path); var n = factory.getObjectNode(new_d, this.root); leaves.push(...this.root.query(q, new_d, n, factory)); root.addChild(n); return leaves; } getValue() { return this.value.getValue(); } toString() { return this.value.toString(); } }
JavaScript
class FindBySelector extends _enumerate_mjs__WEBPACK_IMPORTED_MODULE_3__.Enumerate { /** * Creates a new instance of the function. * @param selector The CSS selector used to fetch elements */ constructor(selector) { super(); this.selector = selector; } evaluate() { if (arguments.length !== 1) { throw "Invalid number of arguments"; } var v = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(arguments[0]); var root = v.getValue(); var elm_list = root.querySelectorAll(this.selector); var val_list = []; var out_list = []; for (let i = 0; i < elm_list.length; i++) { var path = FindBySelector.getPathTo(elm_list[i]); var pv = new PathValue(new Path(path), root, elm_list[i]); val_list.push(pv); } for (let i = 0; i < val_list.length; i++) { out_list.push(new _enumerate_mjs__WEBPACK_IMPORTED_MODULE_3__.EnumeratedValue(i, val_list)); } return new _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_1__.AtomicFunctionReturnValue(this, out_list, v); } static getPathTo(element) { if (element.id !== "") { return "id(\"" + element.id + "\")"; } if (element.tagName === "BODY") { return element.tagName; } var ix = 0; var siblings = element.parentNode.childNodes; for (let i = 0; i < siblings.length; i++) { var sibling = siblings[i]; if (sibling === element) { return this.getPathTo(element.parentNode) + "/" + element.tagName + "[" + (ix + 1) + "]"; } if (sibling.nodeType === 1 && sibling.tagName === element.tagName) { ix++; } } } }
JavaScript
class Nightingale { /** * The websocket connection * * @type {WebSocket} */ socket = null /** * The site ID * * @type {string} */ siteId = null /** * The visit ID for this session * * @type {string} */ visitId = null /** * The event queue * * @type {array} */ queue = [] /** * The session start time * * @type {int} */ startTime = (new Date).getTime() /** * Create the client instance, start the session, and setup listeners * for autotracked events * * @param {string} siteId * @param {int} startTime * @param {array} queue */ constructor(siteId, startTime, queue) { this.siteId = siteId this.startTime = startTime || (new Date()).getTime() this.queue = queue || [] // Check for the siteId to ensure the tracking snippet // has been embedded correctly. Without this, we can't connect if (typeof siteId === 'undefined') { console.error('Cannot find Nightingale site ID. Please ensure you have copied and pasted the nightingale tracker snippet exactly') return } // Retrieve the visitId from sessionStorage if set const visitId = sessionStorage.getItem(VISIT_KEY) if (visitId !== null) { this.visitId = visitId } // Connect to the server this.connect() } /** * Connect to the server */ connect() { this.socket = new WebSocket(URL) this.socket.addEventListener('open', this.start.bind(this)) this.socket.addEventListener('message', this.receive.bind(this)) } /** * Start the session * * @param {Event} evt */ start(evt) { this.send({ event: 'start', site: this.siteId, visit: this.visitId || null, url: location.href, referrer: document.referrer, timestamp: this.startTime }) // Send any events which were buffered before the client was instantiated this.sendBufferedEvents() // Set up event listeners for user interactions this.setupEventListeners() } /** * Trigger a navigation event to the given URL * * @param {string} url */ navigate(url) { url = url || location.href this.send({ event: 'navigate', url: url }) } /** * Send the current scroll position */ scroll() { this.send({ event: 'scroll', scroll_distance: window.pageYOffset }) } /** * Record an event * * @param {string} name * @param {object} data */ event(name, data) { if (['start', 'navigate', 'scroll'].includes(name)) { return this[name](data) } this.send({ event: name, metadata: data }) } /** * Send JSON-encoded data to the server * * @param {object} data */ send(data) { this.socket.send(JSON.stringify(data)) } /** * Receive responses from the server and handle them * * @param {MessageEvent} message */ receive(message) { // Parse the JSON response const data = JSON.parse(message.data) // If a visit ID is sent, store it for this session if (data.visit !== null) { this.visitId = data.visit sessionStorage.setItem(VISIT_KEY, data.visit) } } /** * Send any events which were buffered before the client was instantiated */ sendBufferedEvents() { this.queue = this.queue.filter((event) => { this.event(...event) return false }) } /** * Set up event listeners for user interactions */ setupEventListeners() { // Bind a listener to the scroll event, which sends the resting // scroll position to the server so scroll_distance can be // updated for this pageview window.addEventListener('scroll', (e) => { clearTimeout(window.nightingaleScrollBuffer) window.nightingaleScrollBuffer = setTimeout(this.scroll.bind(this), 100) }) } }
JavaScript
class GIAttribsCompare { modeldata; /** * Creates an object to store the attribute data. * @param modeldata The JSON data */ constructor(modeldata) { this.modeldata = modeldata; } /** * Compares this model and another model. * \n * If check_equality=false, the max total score will be equal to the number of attributes in this model. * It checks that each attribute in this model exists in the other model. If it exists, 1 mark is assigned. * \n * If check_equality=true, the max score will be increased by 10, equal to the number of entity levels. * For each entity level, if the other model contains no additional attributes, then one mark is assigned. * \n * @param other_model The model to compare with. */ compare(other_model, result) { result.comment.push('Comparing attribute names and types.'); // compare all attributes except model attributes // check that this model is a subset of other model // all the attributes in this model must also be in other model const attrib_comments = []; let matches = true; const attrib_names = new Map(); for (const ent_type of eny_type_array) { // get the attrib names const ent_type_str = ent_type_strs.get(ent_type); const this_attrib_names = this.modeldata.attribs.getAttribNames(ent_type); const other_attrib_names = other_model.modeldata.attribs.getAttribNames(ent_type); attrib_names.set(ent_type, this_attrib_names); // check that each attribute in this model exists in the other model for (const this_attrib_name of this_attrib_names) { // check is this is built in let is_built_in = false; if (this_attrib_name === 'xyz' || this_attrib_name === 'rgb' || this_attrib_name.startsWith('_')) { is_built_in = true; } // update the total if (!is_built_in) { result.total += 1; } // compare names if (other_attrib_names.indexOf(this_attrib_name) === -1) { matches = false; attrib_comments.push('The "' + this_attrib_name + '" ' + ent_type_str + ' attribute is missing.'); } else { // get the data types const data_type_1 = this.modeldata.attribs.query.getAttribDataType(ent_type, this_attrib_name); const data_type_2 = other_model.modeldata.attribs.query.getAttribDataType(ent_type, this_attrib_name); // compare data types if (data_type_1 !== data_type_2) { matches = false; attrib_comments.push('The "' + this_attrib_name + '" ' + ent_type_str + ' attribute datatype is wrong. ' + 'It is "' + data_type_1 + '" but it should be "' + data_type_1 + '".'); } else { // update the score if (!is_built_in) { result.score += 1; } } } } // check if we have exact equality in attributes // total marks is not updated, we deduct marks // check that the other model does not have additional attribs if (other_attrib_names.length > this_attrib_names.length) { const additional_attribs = []; for (const other_attrib_name of other_attrib_names) { if (this_attrib_names.indexOf(other_attrib_name) === -1) { additional_attribs.push(other_attrib_name); } } attrib_comments.push('There are additional ' + ent_type_str + ' attributes. ' + 'The following attributes are not required: [' + additional_attribs.join(',') + ']. '); // update the score, deduct 1 mark result.score -= 1; } else if (other_attrib_names.length < this_attrib_names.length) { attrib_comments.push('Mismatch: Model has too few entities of type: ' + ent_type_strs.get(ent_type) + '.'); } else { // correct } } if (attrib_comments.length === 0) { attrib_comments.push('Attributes all match, both name and data type.'); } // add to result result.comment.push(attrib_comments); } }
JavaScript
class NumberAnimation extends anim.Animation { constructor() { super(); d.set(this, { interpolate: (v1, v2, x) => v1 + (v2 - v1) * x, enabled: true, duration: 300, from: 0, to: 1, easing: "InOutQuad", handle: null }); this.notifyable("enabled"); this.notifyable("duration"); this.notifyable("from"); this.notifyable("to"); this.notifyable("easing"); /** * Is triggered for each animation frame. * @event next * @param {number} value - The value for the animation frame. * @memberof mid.NumberAnimation */ this.registerEvent("next"); this.onDestruction = () => { if (d.get(this).handle) { d.get(this).handle.cancel(); } }; } get enabled() { return d.get(this).enabled; } set enabled(v) { d.get(this).enabled = v; this.enabledChanged(); } get duration() { return d.get(this).duration; } set duration(duration) { d.get(this).duration = duration; this.durationChanged(); } get from() { return d.get(this).from; } set from(v) { d.get(this).from = v; this.fromChanged(); } get to() { return d.get(this).to; } set to(v) { d.get(this).to = v; this.toChanged(); } get interpolate() { return d.get(this).interpolate; } set interpolate(f) { d.get(this).interpolate = f; } get easing() {return d.get(this).easing; } set easing(easing) { d.get(this).easing = easing; this.easingChanged(); } start(valueCallback) { let t = 0; let prevTimestamp = 0; const priv = d.get(this); const from = priv.from; const to = priv.to; const duration = priv.duration; const interpolate = priv.interpolate; const easing = createEasing(priv.easing); const runFrame = (timestamp) => { let diff = 0; if (prevTimestamp > 0) { diff = timestamp - prevTimestamp; } prevTimestamp = timestamp; t += diff; const value = (t >= duration) ? to : interpolate(from, to, easing(Math.min(t / duration, 1))); this.next(value); if (valueCallback) { valueCallback(value); } if (t >= duration) { if (this.repeat) { t = 0; } else { priv.handle.cancel(); priv.handle = null; this.finish(); } } }; if (priv.handle) { priv.handle.cancel(); } priv.handle = low.addFrameHandler(runFrame, this.objectType + "@" + this.objectLocation); return super.start(); } }
JavaScript
class MockFileOperationManager extends EventTarget { constructor() { super(); /** * Event to be dispatched when requestTaskCancel is called. Note: the * unittest writes this value before calling requestTaskCancel(). * @type {Event} */ this.cancelEvent = null; /** @type {!Array<string>} */ this.generatedTaskIds = []; /** @type {Function} */ this.pasteResolver = null; } /** * Dispatches a cancel event that has been specified by the unittest. */ requestTaskCancel() { assert(this.cancelEvent); this.dispatchEvent(this.cancelEvent); } /** * Kick off pasting. * * @param {Array<Entry>} sourceEntries Entries of the source files. * @param {DirectoryEntry} targetEntry The destination entry of the target * directory. * @param {boolean} isMove True if the operation is "move", otherwise (i.e. * if the operation is "copy") false. * @param {string=} opt_taskId If the corresponding item has already created * at another places, we need to specify the ID of the item. If the * item is not created, FileOperationManager generates new ID. */ paste(sourceEntries, targetEntry, isMove, opt_taskId) { if (this.pasteResolver) { this.pasteResolver.call(this, { sourceEntries: sourceEntries, targetEntry: targetEntry, isMove: isMove, opt_taskId: opt_taskId }); // Reset the resolver for the next paste call. this.pasteResolver = null; } } /** * @return {Promise<Object>} A promise that is resolved the next time #paste * is called. The Object contains the arguments that #paste was called with. */ whenPasteCalled() { if (this.pasteResolver) { throw new Error('Only one paste call can be waited on at a time.'); } return new Promise((resolve, reject) => { this.pasteResolver = resolve; }); } /** * Generates a unique task Id. * @return {string} */ generateTaskId() { const newTaskId = 'task' + this.generatedTaskIds.length; this.generatedTaskIds.push(newTaskId); return newTaskId; } /** * @return {boolean} Whether or not the given task ID belongs to a task * generated by this manager. */ isKnownTaskId(id) { return this.generatedTaskIds.indexOf(id) !== -1; } hasQueuedTasks() {} filterSameDirectoryEntry() {} willUseTrash() {} deleteEntries() {} restoreDeleted() {} emptyTrash() {} zipSelection() {} cancelZip() {} async writeFile() {} }
JavaScript
class CheckoutForm extends Component { constructor(props) { super(props); this.state = { complete: false, plans: "", billingName: "", billingEmail: "", plan: "", paymentToggle: false, pro: false, premium: false, open: false, buttonState: "", error: "", activeSelect: "" }; } handleOpen = () => { this.setState({ open: true }); }; handleClose = () => { this.setState({ open: false }); }; componentDidMount = () => { this.props.getPlans(); }; handleChange = (e, nickname) => { e.preventDefault(); if (e.currentTarget.name === "plan") { this.setState({ paymentToggle: true, buttonState: nickname, activeSelect: nickname }); } this.setState({ [e.currentTarget.name]: e.currentTarget.value }); }; /** * @function * @param {string} email * This step is adding functionality to the CheckoutForm component’s submit method * so that clicking the button tokenizes the card information. We choose to use * email, though anything could have been choosen as long as it's unique to each * user. * * */ createToken = async email => { try { let { token } = await this.props.stripe.createToken({ email: email }); return token.id; } catch (err) { this.setState({ error: "Please enter payment information" }); } }; // the submit method will tokenize the card information by invoking createToken on the stripe prop submit = async () => { const { name, email, id, stripe } = this.props.userProfile; const { plan } = this.state; let token = await this.createToken(email); if (token !== undefined) { await this.props.submit(token, name, email, id, stripe, plan); this.setState({ paymentToggle: false, activeSelect: "" }); } else { this.setState({ error: "Please enter payment information" }); } }; /** * @function * @param {object} user_id * @param {object} stripe id. * allows the user to unsubscribe from their current plan. */ unsub = (user_id, stripe) => { this.props.unsubscribe(user_id, stripe); this.setState({ open: false }); }; render() { //const { classes } is for material UI const { classes } = this.props; /*account type is to determine which plan our user is on. Our stripe plan has only 1 product, with 3 payment plans (Basic, Premium, Pro), but those 3 plans need 3 cooresponding subscriptions so Stripe knows to charge the account monthly */ let accountType; if (this.props.userProfile.subscription === "Premium") { accountType = "Premium"; } else if (this.props.userProfile.subscription === "Pro") { accountType = "Pro"; } //freeButton is for Material UI let freeButton; if (this.props.userProfile.subscription !== "free") { freeButton = ( <Button color="primary" className={classes.button} onClick={this.handleOpen} > Basic </Button> ); } else { freeButton = ( <Button color="default" className={classes.button} disabled> Current Plan </Button> ); } if (this.state.complete) return <h1>Purchase Complete</h1>; return ( <div className={classes.root}> <div> {this.props.userError} {this.props.stripeError} {/* <Pricing /> */} <FormControl component="fieldset" className={classes.formControl}> <div className={classes.buttonLayout}> <div className={classes.subCard}> <Typography className={classes.title}>Basic</Typography> <Typography className={classes.price}>FREE</Typography> <div className={classes.content}> <Typography className={classes.feature}> Automated Text/Email </Typography> <Typography className={classes.feature}> Unlimited Training Series </Typography> <Typography className={classes.feature}> Unlimited Team Members </Typography> <Typography className={classes.feature}> Notification Limit 50/month </Typography> </div> {freeButton} </div> {this.props.plans.map((plan, i) => { return plan.nickname === accountType ? ( <div key={plan.id} className={classes.subCard}> <Typography className={classes.title}> {plan.nickname} </Typography> <Typography className={classes.price}> ${plan.amount / 100} <span className={classes.subPrice}> / month</span> </Typography> <div className={classes.content}> <Typography className={classes.feature}> Automated Text/Email </Typography> <Typography className={classes.feature}> Unlimited Training Series </Typography> <Typography className={classes.feature}> Unlimited Team Members </Typography> <Typography className={classes.feature}> Notification Limit {plan.nickname === "Premium" ? " 200/month" : " 1000/month"} </Typography> </div> <Button key={plan.created} className={classes.button} disabled > Current Plan </Button> </div> ) : ( <div key={plan.id} className={classes.subCard}> <Typography className={classes.title}> {plan.nickname} </Typography> <Typography className={classes.price}> ${plan.amount / 100} <span className={classes.subPrice}> / month</span> </Typography> <div className={classes.content}> <Typography className={classes.feature}> Automated Text/Email </Typography> <Typography className={classes.feature}> Unlimited Training Series </Typography> <Typography className={classes.feature}> Unlimited Team Members </Typography> <Typography className={classes.feature}> Notification Limit {plan.nickname === "Premium" ? " 200/month" : " 1000/month"} </Typography> </div> <Button key={plan.created} color="primary" name="plan" className={classes.button} value={plan.id} onClick={e => this.handleChange(e, plan.nickname)} style={ this.state.activeSelect === plan.nickname ? { background: "#3DBC93" } : null } > {plan.nickname} </Button> </div> ); })} </div> </FormControl> {/* Payment Handling Below */} {this.props.paymentLoading ? ( <div className={classes.gifWrapper}> <img src={TrainingBotGIF} alt="Loading Icon" className={classes.LoadingImg} /> </div> ) : this.state.paymentToggle ? ( <FormControl component="fieldset" className={classes.paymentForm}> <CardElement style={{ base: { fontSize: "18px" } }} /> <Button variant="contained" className={classes.submitBtn} onClick={this.submit} > Submit Payment </Button> </FormControl> ) : ( <span /> )} </div> {/* Unsubscribe Modal */} <Modal aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description" open={this.state.open} onClose={this.handleClose} > <UnsubscribeModal handleClose={this.handleClose} unsub={this.unsub} /> </Modal> </div> ); // } } }
JavaScript
class StubCall { constructor( // Funcname is the name of the function that was called. funcName, // Args is the set of arguments passed to the function. They are // in the same order as the function's parameters. // tslint:disable-next-line:no-any args) { this.funcName = funcName; this.args = args; } }
JavaScript
class SingleSelectionSet { constructor() { this.selected = null; this.ordered = null; this.set = new Set(); } }
JavaScript
class SingleSelectionController { constructor(element) { this.sets = {}; this.focusedSet = null; this.mouseIsDown = false; this.updating = false; element.addEventListener('keydown', (e) => { this.keyDownHandler(e); }); element.addEventListener('mousedown', () => { this.mousedownHandler(); }); element.addEventListener('mouseup', () => { this.mouseupHandler(); }); } /** * Get a controller for the given element. If no controller exists, one will * be created. Defaults to getting the controller scoped to the element's root * node shadow root unless `element.global` is true. Then, it will get a * `window.document`-scoped controller. * * @param element Element from which to get / create a SelectionController. If * `element.global` is true, it gets a selection controller scoped to * `window.document`. */ static getController(element) { const useGlobal = !('global' in element) || ('global' in element && element.global); const root = useGlobal ? document : element.getRootNode(); let controller = root[selectionController]; if (controller === undefined) { controller = new SingleSelectionController(root); root[selectionController] = controller; } return controller; } keyDownHandler(e) { const element = e.target; if (!('checked' in element)) { return; } if (!this.has(element)) { return; } if (e.key == 'ArrowRight' || e.key == 'ArrowDown') { this.selectNext(element); } else if (e.key == 'ArrowLeft' || e.key == 'ArrowUp') { this.selectPrevious(element); } } mousedownHandler() { this.mouseIsDown = true; } mouseupHandler() { this.mouseIsDown = false; } /** * Whether or not the controller controls the given element. * * @param element element to check */ has(element) { const set = this.getSet(element.name); return set.set.has(element); } /** * Selects and returns the controlled element previous to the given element in * document position order. See * [Node.compareDocumentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). * * @param element element relative from which preceding element is fetched */ selectPrevious(element) { const order = this.getOrdered(element); const i = order.indexOf(element); const previous = order[i - 1] || order[order.length - 1]; this.select(previous); return previous; } /** * Selects and returns the controlled element next to the given element in * document position order. See * [Node.compareDocumentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). * * @param element element relative from which following element is fetched */ selectNext(element) { const order = this.getOrdered(element); const i = order.indexOf(element); const next = order[i + 1] || order[0]; this.select(next); return next; } select(element) { element.click(); } /** * Focuses the selected element in the given element's selection set. User's * mouse selection will override this focus. * * @param element Element from which selection set is derived and subsequently * focused. * @deprecated update() method now handles focus management by setting * appropriate tabindex to form element. */ focus(element) { // Only manage focus state when using keyboard if (this.mouseIsDown) { return; } const set = this.getSet(element.name); const currentFocusedSet = this.focusedSet; this.focusedSet = set; if (currentFocusedSet != set && set.selected && set.selected != element) { set.selected.focus(); } } /** * @return Returns true if atleast one radio is selected in the radio group. */ isAnySelected(element) { const set = this.getSet(element.name); for (const e of set.set) { if (e.checked) { return true; } } return false; } /** * Returns the elements in the given element's selection set in document * position order. * [Node.compareDocumentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). * * @param element Element from which selection set is derived and subsequently * ordered. */ getOrdered(element) { const set = this.getSet(element.name); if (!set.ordered) { set.ordered = Array.from(set.set); set.ordered.sort((a, b) => a.compareDocumentPosition(b) == Node.DOCUMENT_POSITION_PRECEDING ? 1 : 0); } return set.ordered; } /** * Gets the selection set of the given name and creates one if it does not yet * exist. * * @param name Name of set */ getSet(name) { if (!this.sets[name]) { this.sets[name] = new SingleSelectionSet(); } return this.sets[name]; } /** * Register the element in the selection controller. * * @param element Element to register. Registers in set of `element.name`. */ register(element) { // TODO(b/168546148): Remove accessing 'name' via getAttribute() when new // base class is created without single selection controller. Component // maybe booted up after it is connected to DOM in which case properties // (including `name`) are not updated yet. const name = element.name || element.getAttribute('name') || ''; const set = this.getSet(name); set.set.add(element); set.ordered = null; } /** * Unregister the element from selection controller. * * @param element Element to register. Registers in set of `element.name`. */ unregister(element) { const set = this.getSet(element.name); set.set.delete(element); set.ordered = null; if (set.selected == element) { set.selected = null; } } /** * Unselects other elements in element's set if element is checked. Noop * otherwise. * * @param element Element from which to calculate selection controller update. */ update(element) { if (this.updating) { return; } this.updating = true; const set = this.getSet(element.name); if (element.checked) { for (const e of set.set) { if (e == element) { continue; } e.checked = false; } set.selected = element; } // When tabbing through land focus on the checked radio in the group. if (this.isAnySelected(element)) { for (const e of set.set) { if (e.formElementTabIndex === undefined) { break; } e.formElementTabIndex = e.checked ? 0 : -1; } } this.updating = false; } }
JavaScript
class RadioBase extends FormElement { constructor() { super(...arguments); this._checked = false; this.useStateLayerCustomProperties = false; this.global = false; this.disabled = false; this.value = ''; this.name = ''; /** * Touch target extends beyond visual boundary of a component by default. * Set to `true` to remove touch target added to the component. * @see https://material.io/design/usability/accessibility.html */ this.reducedTouchTarget = false; this.mdcFoundationClass = MDCRadioFoundation; /** * input's tabindex is updated based on checked status. * Tab navigation will be removed from unchecked radios. */ this.formElementTabIndex = 0; this.focused = false; this.shouldRenderRipple = false; this.rippleElement = null; this.rippleHandlers = new RippleHandlers(() => { this.shouldRenderRipple = true; this.ripple.then((v) => { this.rippleElement = v; }); return this.ripple; }); } get checked() { return this._checked; } /** * We define our own getter/setter for `checked` because we need to track * changes to it synchronously. * * The order in which the `checked` property is set across radio buttons * within the same group is very important. However, we can't rely on * UpdatingElement's `updated` callback to observe these changes (which is * also what the `@observer` decorator uses), because it batches changes to * all properties. * * Consider: * * radio1.disabled = true; * radio2.checked = true; * radio1.checked = true; * * In this case we'd first see all changes for radio1, and then for radio2, * and we couldn't tell that radio1 was the most recently checked. */ set checked(isChecked) { var _a, _b; const oldValue = this._checked; if (isChecked === oldValue) { return; } this._checked = isChecked; if (this.formElement) { this.formElement.checked = isChecked; } (_a = this._selectionController) === null || _a === void 0 ? void 0 : _a.update(this); if (isChecked === false) { // Remove focus ring when unchecked on other radio programmatically. // Blur on input since this determines the focus style. (_b = this.formElement) === null || _b === void 0 ? void 0 : _b.blur(); } this.requestUpdate('checked', oldValue); // useful when unchecks self and wrapping element needs to synchronize // TODO(b/168543810): Remove triggering event on programmatic API call. this.dispatchEvent(new Event('checked', { bubbles: true, composed: true })); } _handleUpdatedValue(newValue) { // the observer function can't access protected fields (according to // closure compiler) because it's not a method on the class, so we need this // wrapper. this.formElement.value = newValue; } /** @soyTemplate */ renderRipple() { return this.shouldRenderRipple ? html `<mwc-ripple unbounded accent .internalUseStateLayerCustomProperties="${this.useStateLayerCustomProperties}" .disabled="${this.disabled}"></mwc-ripple>` : ''; } get isRippleActive() { var _a; return ((_a = this.rippleElement) === null || _a === void 0 ? void 0 : _a.isActive) || false; } connectedCallback() { super.connectedCallback(); // Note that we must defer creating the selection controller until the // element has connected, because selection controllers are keyed by the // radio's shadow root. For example, if we're stamping in a lit-html map // or repeat, then we'll be constructed before we're added to a root node. // // Also note if we aren't using native shadow DOM, we still need a // SelectionController, because we should update checked status of other // radios in the group when selection changes. It also simplifies // implementation and testing to use one in all cases. // // eslint-disable-next-line @typescript-eslint/no-use-before-define this._selectionController = SingleSelectionController.getController(this); this._selectionController.register(this); // Radios maybe checked before connected, update selection as soon it is // connected to DOM. Last checked radio button in the DOM will be selected. // // NOTE: If we update selection only after firstUpdate() we might mistakenly // update checked status before other radios are rendered. this._selectionController.update(this); } disconnectedCallback() { // The controller is initialized in connectedCallback, so if we are in // disconnectedCallback then it must be initialized. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._selectionController.unregister(this); this._selectionController = undefined; } focus() { this.formElement.focus(); } createAdapter() { return Object.assign(Object.assign({}, addHasRemoveClass(this.mdcRoot)), { setNativeControlDisabled: (disabled) => { this.formElement.disabled = disabled; } }); } handleFocus() { this.focused = true; this.handleRippleFocus(); } handleClick() { // Firefox has weird behavior with radios if they are not focused this.formElement.focus(); } handleBlur() { this.focused = false; this.formElement.blur(); this.rippleHandlers.endFocus(); } /** * @soyTemplate * @soyAttributes radioAttributes: input * @soyClasses radioClasses: .mdc-radio */ render() { /** @classMap */ const classes = { 'mdc-radio--touch': !this.reducedTouchTarget, 'mdc-ripple-upgraded--background-focused': this.focused, 'mdc-radio--disabled': this.disabled, }; return html ` <div class="mdc-radio ${classMap(classes)}"> <input tabindex="${this.formElementTabIndex}" class="mdc-radio__native-control" type="radio" name="${this.name}" aria-label="${ifDefined(this.ariaLabel)}" aria-labelledby="${ifDefined(this.ariaLabelledBy)}" .checked="${this.checked}" .value="${this.value}" ?disabled="${this.disabled}" @change="${this.changeHandler}" @focus="${this.handleFocus}" @click="${this.handleClick}" @blur="${this.handleBlur}" @mousedown="${this.handleRippleMouseDown}" @mouseenter="${this.handleRippleMouseEnter}" @mouseleave="${this.handleRippleMouseLeave}" @touchstart="${this.handleRippleTouchStart}" @touchend="${this.handleRippleDeactivate}" @touchcancel="${this.handleRippleDeactivate}"> <div class="mdc-radio__background"> <div class="mdc-radio__outer-circle"></div> <div class="mdc-radio__inner-circle"></div> </div> ${this.renderRipple()} </div>`; } handleRippleMouseDown(event) { const onUp = () => { window.removeEventListener('mouseup', onUp); this.handleRippleDeactivate(); }; window.addEventListener('mouseup', onUp); this.rippleHandlers.startPress(event); } handleRippleTouchStart(event) { this.rippleHandlers.startPress(event); } handleRippleDeactivate() { this.rippleHandlers.endPress(); } handleRippleMouseEnter() { this.rippleHandlers.startHover(); } handleRippleMouseLeave() { this.rippleHandlers.endHover(); } handleRippleFocus() { this.rippleHandlers.startFocus(); } changeHandler() { this.checked = this.formElement.checked; } }
JavaScript
class RadioListItemBase extends ListItemBase { constructor() { super(...arguments); this.left = false; this.graphic = 'control'; this._changeFromClick = false; } render() { const radioClasses = { 'mdc-deprecated-list-item__graphic': this.left, 'mdc-deprecated-list-item__meta': !this.left, }; const text = this.renderText(); const graphic = this.graphic && this.graphic !== 'control' && !this.left ? this.renderGraphic() : html ``; const meta = this.hasMeta && this.left ? this.renderMeta() : html ``; const ripple = this.renderRipple(); return html ` ${ripple} ${graphic} ${this.left ? '' : text} <mwc-radio global class=${classMap(radioClasses)} tabindex=${this.tabindex} name=${ifDefined(this.group === null ? undefined : this.group)} .checked=${this.selected} ?disabled=${this.disabled} @checked=${this.onChange}> </mwc-radio> ${this.left ? text : ''} ${meta}`; } onClick() { this._changeFromClick = true; super.onClick(); } async onChange(evt) { const checkbox = evt.target; const changeFromProp = this.selected === checkbox.checked; if (!changeFromProp) { this._skipPropRequest = true; this.selected = checkbox.checked; await this.updateComplete; this._skipPropRequest = false; if (!this._changeFromClick) { this.fireRequestSelected(this.selected, 'interaction'); } } this._changeFromClick = false; } }
JavaScript
class FormSubmit extends React.Component { static propTypes = { /** * The `<button/>` type */ type: PropTypes.oneOf(['button', 'submit']), /** * Specify particular fields to validate in the related form. If empty the entire form will be validated. */ triggers: PropTypes.arrayOf(PropTypes.string.isRequired), /** * Provide a render function to completely override the rendering behavior * of FormSubmit (`as` will be ignored). In addition to passing through props some * additional form submission metadata is injected to handle loading and disabled behaviors. * * ```js * <Form.Submit> * {({ errors, props, submitting, submitCount, submitAttempts }) => * <button {...props} disabled={submitCount > 1}> * submitting ? 'Saving…' : 'Submit'} * </button> * </Form.Submit> * ``` */ children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), /** * Control the rendering of the Form Submit component when not using * the render prop form of `children`. */ as: elementType, /** * A string or array of event names that trigger validation. * * @default 'onClick' */ events: PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string), ]), /** @private */ errors: PropTypes.object, /** @private */ actions: PropTypes.object, /** @private */ submits: PropTypes.object, } static defaultProps = { as: 'button', events: ['onClick'], } constructor(...args) { super(...args) this.eventHandlers = {} this.getEventHandlers = createEventHandler(event => (...args) => { this.props[event] && this.props[event](args) this.handleSubmit() }) this.memoFilterAndMapErrors = memoize( filterAndMapErrors, ([a], [b]) => a.errors === b.errors && a.names === b.names && a.maperrors === b.maperrors ) } handleSubmit(event, args) { const { actions, triggers } = this.props if (!actions) { return warning( false, 'A Form submit event ' + 'was triggered from a component outside the context of a Form. ' + 'The Button should be wrapped in a Form component' ) } if (triggers && triggers.length) actions.onValidate(triggers, event, args) else actions.onSubmit() } render() { let { events, triggers, children, errors, submits, as: Component, actions: _1, ...props } = this.props const partial = triggers && triggers.length if (partial) { errors = this.memoFilterAndMapErrors({ errors, names: triggers }) } props = Object.assign(props, this.getEventHandlers(events)) return typeof children === 'function' ? ( children({ errors, props, ...submits }) ) : ( <Component type={partial ? 'button' : 'submit'} {...props}> {children} </Component> ) } }
JavaScript
class DeserializationError extends AbstractError { /** * @param {string} message the error message * @param {Error} [rootCause] the root cause */ constructor (message, rootCause) { super(AbstractError.ErrorNames.DESERIALIZATION, message, rootCause) } }
JavaScript
class yzecoriolisActor extends Actor { /** * Augment the basic actor data with additional dynamic data. */ prepareData() { super.prepareData(); const actorData = this.data; const data = actorData.data; const flags = actorData.flags; // Make separate methods for each Actor type (character, npc, etc.) to keep // things organized. if (actorData.type === 'character') this._prepareCharacterData(actorData); } /** * Prepare Character type specific data */ _prepareCharacterData(actorData) { const data = actorData.data; // Cap attribute scores if (!data.keyArt) { data.keyArt = data.keyArt || CONFIG.YZECORIOLIS.DEFAULT_PLAYER_KEY_ART; } for (let [key, attr] of Object.entries(data.attributes)) { if (attr.value > attr.max) { attr.value = attr.max; } if (attr.value < attr.min) { attr.value = attr.min; } } //Cap Skill scores for (let [key, skl] of Object.entries(data.skills)) { if (skl.value > skl.max) { skl.value = skl.max; } if (skl.value < skl.min) { skl.value = skl.min; } } data.hitPoints.max = data.attributes.strength.value + data.attributes.agility.value; data.mindPoints.max = data.attributes.wits.value + data.attributes.empathy.value; if (data.hitPoints.value > data.hitPoints.max) { data.hitPoints.value = data.hitPoints.max; } if (data.mindPoints.value > data.mindPoints.max) { data.mindPoints.value = data.mindPoints.max; } } _prepareChatRollOptions(template, title) { let chatOptions = { speaker: { alias: this.data.token.name, actor: this.data._id, }, title: title, template: template, rollMode: game.settings.get("core", "rollMode"), sound: CONFIG.sounds.dice, flags: { img: this.data.token.randomImg ? this.data.img : this.data.token.img } // img to be displayed next to the name on the test card - if it's a wildcard img, use the actor image } // If the test is coming from a token sheet if (this.token) { chatOptions.speaker.alias = this.token.data.name; // Use the token name instead of the actor name chatOptions.speaker.token = this.token.data._id; chatOptions.speaker.scene = canvas.scene._id chatOptions.flags.img = this.token.data.img; // Use the token image instead of the actor image } else // If a linked actor - use the currently selected token's data if the actor id matches { let speaker = ChatMessage.getSpeaker() if (speaker.actor == this.data._id) { chatOptions.speaker.alias = speaker.alias chatOptions.speaker.token = speaker.token chatOptions.speaker.scene = speaker.scene chatOptions.flags.img = speaker.token ? canvas.tokens.get(speaker.token).data.img : chatOptions.flags.img } } return chatOptions } _prepareRollTitle(rollType) { } }
JavaScript
class TAARenderPass extends SSAARenderPass { constructor( scene, camera, clearColor, clearAlpha ) { super( scene, camera, clearColor, clearAlpha ); this.sampleLevel = 0; this.accumulate = false; } render( renderer, writeBuffer, readBuffer, deltaTime ) { if ( this.accumulate === false ) { super.render( renderer, writeBuffer, readBuffer, deltaTime ); this.accumulateIndex = - 1; return; } const jitterOffsets = _JitterVectors[ 5 ]; if ( this.sampleRenderTarget === undefined ) { this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, this.params ); this.sampleRenderTarget.texture.name = 'TAARenderPass.sample'; } if ( this.holdRenderTarget === undefined ) { this.holdRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, this.params ); this.holdRenderTarget.texture.name = 'TAARenderPass.hold'; } if ( this.accumulateIndex === - 1 ) { super.render( renderer, this.holdRenderTarget, readBuffer, deltaTime ); this.accumulateIndex = 0; } const autoClear = renderer.autoClear; renderer.autoClear = false; const sampleWeight = 1.0 / ( jitterOffsets.length ); if ( this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length ) { this.copyUniforms[ 'opacity' ].value = sampleWeight; this.copyUniforms[ 'tDiffuse' ].value = writeBuffer.texture; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. const numSamplesPerFrame = Math.pow( 2, this.sampleLevel ); for ( let i = 0; i < numSamplesPerFrame; i ++ ) { const j = this.accumulateIndex; const jitterOffset = jitterOffsets[ j ]; if ( this.camera.setViewOffset ) { this.camera.setViewOffset( readBuffer.width, readBuffer.height, jitterOffset[ 0 ] * 0.0625, jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16 readBuffer.width, readBuffer.height ); } renderer.setRenderTarget( writeBuffer ); renderer.clear(); renderer.render( this.scene, this.camera ); renderer.setRenderTarget( this.sampleRenderTarget ); if ( this.accumulateIndex === 0 ) renderer.clear(); this.fsQuad.render( renderer ); this.accumulateIndex ++; if ( this.accumulateIndex >= jitterOffsets.length ) break; } if ( this.camera.clearViewOffset ) this.camera.clearViewOffset(); } const accumulationWeight = this.accumulateIndex * sampleWeight; if ( accumulationWeight > 0 ) { this.copyUniforms[ 'opacity' ].value = 1.0; this.copyUniforms[ 'tDiffuse' ].value = this.sampleRenderTarget.texture; renderer.setRenderTarget( writeBuffer ); renderer.clear(); this.fsQuad.render( renderer ); } if ( accumulationWeight < 1.0 ) { this.copyUniforms[ 'opacity' ].value = 1.0 - accumulationWeight; this.copyUniforms[ 'tDiffuse' ].value = this.holdRenderTarget.texture; renderer.setRenderTarget( writeBuffer ); if ( accumulationWeight === 0 ) renderer.clear(); this.fsQuad.render( renderer ); } renderer.autoClear = autoClear; } }
JavaScript
class Timer { constructor(interval) { this.stopped = true; this.interval = interval; } start(func) { this.stopped = false; this.timer = setTimeout(func, this.interval); } stop() { if (this.timer != null) { clearTimeout(this.timer); this.stopped = true; } } isStopped() { return this.stopped; } }
JavaScript
class ActivityRouterDialog extends ComponentDialog { constructor(conversationState, luisRecognizer = undefined) { super(ACTIVITY_ROUTER_DIALOG); if (!conversationState) throw new Error('[MainDialog]: Missing parameter \'conversationState\' is required'); this.luisRecognizer = luisRecognizer; // Define the main dialog and its related components. // This is a sample "book a flight" dialog. this.addDialog(new BookingDialog()) .addDialog(new WaterfallDialog(WATERFALL_DIALOG, [ this.processActivity.bind(this) ])); this.initialDialogId = WATERFALL_DIALOG; } async processActivity(stepContext) { // A skill can send trace activities, if needed. const traceActivity = { type: ActivityTypes.Trace, timestamp: new Date(), text: 'ActivityRouterDialog.processActivity()', label: `Got activityType: ${ stepContext.context.activity.type }` }; await stepContext.context.sendActivity(traceActivity); switch (stepContext.context.activity.type) { case ActivityTypes.Event: return await this.onEventActivity(stepContext); case ActivityTypes.Message: return await this.onMessageActivity(stepContext); default: // Catch all for unhandled intents. await stepContext.context.sendActivity( `Unrecognized ActivityType: "${ stepContext.context.activity.type }".`, undefined, InputHints.IgnoringInput ); return { status: DialogTurnStatus.complete }; } } /** * This method performs different tasks based on event name. */ async onEventActivity(stepContext) { const activity = stepContext.context.activity; const traceActivity = { type: ActivityTypes.Trace, timestamp: new Date(), text: 'ActivityRouterDialog.onEventActivity()', label: `Name: ${ activity.name }, Value: ${ JSON.stringify(activity.value) }` }; await stepContext.context.sendActivity(traceActivity); // Resolve what to execute based on the event name. switch (activity.name) { case 'BookFlight': return await this.beginBookFlight(stepContext); case 'GetWeather': return await this.beginGetWeather(stepContext); default: // We didn't get an event name we can handle. await stepContext.context.sendActivity( `Unrecognized EventName: "${ stepContext.context.activity.name }".`, undefined, InputHints.IgnoringInput ); return { status: DialogTurnStatus.complete }; } } /** * This method just gets a message activity and runs it through LUIS. */ async onMessageActivity(stepContext) { const activity = stepContext.context.activity; const traceActivity = { type: ActivityTypes.Trace, timestamp: new Date(), text: 'ActivityRouterDialog.onMessageActivity()', label: `Text: ${ activity.text }, Value: ${ JSON.stringify(activity.value) }` }; await stepContext.context.sendActivity(traceActivity); if (!this.luisRecognizer || !this.luisRecognizer.isConfigured) { await stepContext.context.sendActivity( 'NOTE: LUIS is not configured. To enable all capabilities, please add \'LuisAppId\', \'LuisAPIKey\' and \'LuisAPIHostName\' to the appsettings.json file.', undefined, InputHints.IgnoringInput ); } else { // Call LUIS with the utterance. const luisResult = await this.luisRecognizer.executeLuisQuery(stepContext.context); const topIntent = LuisRecognizer.topIntent(luisResult); // Create a message showing the LUIS result. let resultString = ''; resultString += `LUIS results for "${ activity.text }":\n`; resultString += `Intent: "${ topIntent }", Score: ${ luisResult.intents[topIntent].score }\n`; await stepContext.context.sendActivity(resultString, undefined, InputHints.IgnoringInput); switch (topIntent.intent) { case 'BookFlight': return await this.beginBookFlight(stepContext); case 'GetWeather': return await this.beginGetWeather(stepContext); default: { // Catch all for unhandled intents. const didntUnderstandMessageText = `Sorry, I didn't get that. Please try asking in a different way (intent was ${ topIntent.intent })`; await stepContext.context.sendActivity(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput); break; } } } return { status: DialogTurnStatus.complete }; } async beginGetWeather(stepContext) { const activity = stepContext.context.activity; const location = activity.value || {}; // We haven't implemented the GetWeatherDialog so we just display a TODO message. const getWeatherMessageText = `TODO: get weather for here (lat: ${ location.latitude }, long: ${ location.longitude })`; await stepContext.context.sendActivity(getWeatherMessageText, getWeatherMessageText, InputHints.IgnoringInput); return { status: DialogTurnStatus.complete }; } async beginBookFlight(stepContext) { const activity = stepContext.context.activity; const bookingDetails = activity.value || {}; // Start the booking dialog. const bookingDialog = this.findDialog(BOOKING_DIALOG); return await stepContext.beginDialog(bookingDialog.id, bookingDetails); } }
JavaScript
class PinEvent { static sendPageView(pageId, delay = 2000) { return new Promise(resolve => setTimeout(() => { services.PIN.sendData(enums.PIN.EVENT.PAGE_VIEW, { type: PIN_PAGEVIEW_EVT_TYPE, pgid: pageId, }); resolve(); }, delay)); } }
JavaScript
class A11yDetails extends LitElement { /* REQUIRED FOR TOOLING DO NOT TOUCH */ /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ tag() { return "a11y-details"; } // life cycle constructor() { super(); this.closeText = ""; this.openText = ""; this.tag = A11yDetails.tag; } /** * life cycle, element is removed from the DOM */ disconnectedCallback() { if (this.observer && this.observer.disconnect) this.observer.disconnect(); super.disconnectedCallback(); } firstUpdated() { if (super.firstUpdated) super.firstUpdated(); this._updateElement(); this.observer.observe(this, { childList: true, subtree: true }); } /** * gets the details element in shadowRoot * * @readonly * @memberof A11yDetails */ get details() { return this && this.shadowRoot && this.shadowRoot.querySelector("details") ? this.shadowRoot.querySelector("details") : undefined; } /** * gets classe sfor summary to hide summary slot if open/closed text is provided * * @readonly * @memberof A11yDetails */ get summaryClasses() { return [ this.openText && this.openText.trim && this.openText.trim() !== "" ? "has-open-text" : "", this.closeText && this.closeText.trim && this.closeText.trim() !== "" ? "has-close-text" : "", ].join(" "); } /** * mutation observer for a11y-details * @readonly * @returns {object} */ get observer() { let callback = (mutationsList) => this._watchChildren(mutationsList); return new MutationObserver(callback); } /** * mutation observer for <details/> in unnamed slot * @readonly * @returns {object} */ get detailsObserver() { let callback = () => this._updateElement(); return new MutationObserver(callback); } /** * provides click for keyboard if open property is not supported by browser * * @param {event} e * @memberof A11yDetails */ _handleClick(e) { if (this.details && typeof this.details.open === "undefined") { this.toggleOpen(); e.preventDefault(); e.stopPropagation(); } } /** * provides support for keyboard if open property is not supported by browser * * @param {event} e * @memberof A11yDetails */ _handleKeyup(e) { if ( (this.details && typeof this.details.open === "undefined" && e.keyCode == 13) || e.keyCode == 32 ) { this.toggleOpen(); e.preventDefault(); e.stopPropagation(); } } /** * toggles the element */ toggleOpen() { if (this.details.hasAttribute("open")) { this.details.removeAttribute("open"); if (this.details.open) this.details.open = false; } else { this.details.setAttribute("open", ""); if (this.details.open) this.details.open = true; } } /** * updates an element based on changes in slot * * @memberof A11yDetails */ _updateElement() { let details = this.querySelector("* > details"), summary = details ? details.querySelector("* > summary") : undefined; if (summary) this._copyToSlot("summary", summary.cloneNode(true)); if (details) { let clone = details.cloneNode(true), filtered = clone.querySelectorAll("* > summary"); Object.keys(filtered || {}).forEach((i) => filtered[i].remove()); this._copyToSlot("details", clone, "div"); } } /** * watches the element's slots for a <details/> element * * @param {object} mutationsList * @memberof A11yDetails */ _watchChildren(mutationsList) { if (this._hasMutations(mutationsList)) { this._updateElement(); this.detailsObserver.observe(this.querySelector("* > details"), { childList: true, subtree: true, characterData: true, }); } else if ( this._hasMutations(mutationsList, "removedNodes") && !this.querySelector("* > details") && this.detailsObserver.disconnect ) { this.detailsObserver.disconnect(); } } /** * searches a mutations list to see if a <details/> element was added or removed * * @param {object} mutationsList * @param {string} [nodeListType="addedNodes"] "addedNodes" of "removedNodes" * @returns {boolean} * @memberof A11yDetails */ _hasMutations(mutationsList, nodeListType = "addedNodes") { return ( Object.keys(mutationsList || {}).filter((i) => { let nodes = mutationsList[i][nodeListType]; return ( Object.keys(nodes || {}).filter((j) => { let nodeName = nodes[j].tagName; return nodeName === "DETAILS"; }).length > 0 ); }).length > 0 ); } /** * moves content cloned from unnamed slot to designated named slot * * @param {string} slotName 'details' or 'summary' slot * @param {string} tagName the tag that will become a slot * @param {object} clone content cloned from unnamed slot * @memberof A11yDetails */ _copyToSlot(slotName, clone, tagName = "span") { let filteredNodes = Object.keys(clone.childNodes || {}) .filter((i) => { let node = clone.childNodes[i]; return !!node.tagName || node.textContent.trim().length > 0; }) .map((i) => clone.childNodes[parseInt(i)]); if (filteredNodes.length === 1 && filteredNodes[0].tagName) { clone = filteredNodes[0]; tagName = clone.tagName; } let slot = this._getSlot(slotName, tagName); slot.innerHTML = clone.innerHTML; clone.remove(); } /** * gets an existing named slot or makes one * * @param {string} slotName * @returns {object} * @memberof A11yDetails */ _getSlot(slotName, tagName = "span") { let slot = this.querySelector(`[slot=${slotName}]`); if (slot && slot.tagName !== tagName) slot.remove(); if (!slot) { slot = document.createElement(tagName); slot.slot = slotName; this.append(slot); } return slot; } }
JavaScript
class OrderListItem extends Base { /** * @type {OrderBook.IOrder} * @private */ _data = null; /** * @type {HTMLElement} * @private */ _root = document.createElement('w-row'); /** * @type {HTMLElement} * @private */ _parent; /** * @type {HTMLElement} * @private */ _amountNode; /** * @type {HTMLElement} * @private */ _priceNode; /** * @type {HTMLElement} * @private */ _totalNode; /** * @type {HTMLElement} * @private */ _tooltipSell; /** * @type {HTMLElement} * @private */ _tooltipBuy; /** * @type {AssetPair} * @private */ _pair; constructor(parent) { super(); this._parent = parent; this._parent.appendChild(this._root); this._createDom(); this._setHandlers(); this._draw(); } /** * @return {OrderBook.IOrder} */ getData() { return this._data; } /** * @param {OrderBook.IOrder} data * @param {OrderBook.ICrop} crop * @param {Record<string, boolean>} priceHash * @param {AssetPair} pair */ render(data, crop, priceHash, pair) { if (OrderListItem._isEqual(this._data, data)) { return null; } this._pair = pair; this._data = data; this._draw(crop, priceHash, pair); } /** * @return {number} */ getHeight() { return this._root.clientHeight; } /** * @param {OrderBook.ICrop} [crop] * @param {Record<string, boolean>} [priceHash] * @param {AssetPair} [pair] * @private */ _draw(crop, priceHash, pair) { if (this._data) { this._amountNode.innerHTML = utils.getNiceNumberTemplate(this._data.amount, pair.amountAsset.precision, true); this._priceNode.innerHTML = utils.getNiceNumberTemplate(this._data.price, pair.priceAsset.precision, true); this._totalNode.innerHTML = utils.getNiceNumberTemplate(this._data.total, pair.priceAsset.precision, true); const hasOrder = !!priceHash[this._data.price.toFixed(pair.priceAsset.precision)]; const inRange = this._data.price.gte(crop.min) && this._data.price.lte(crop.max); this._tooltip.classList.toggle('active', true); this._root.classList.toggle('active', hasOrder); this._root.classList.toggle('no-market-price', !inRange); } else { this._amountNode.innerText = '—'; this._priceNode.innerText = '—'; this._totalNode.innerText = '—'; this._tooltip.classList.toggle('active', false); this._root.classList.toggle('active', false); this._root.classList.toggle('no-market-price', false); } this._root.classList.toggle('isEmpty', !this._data); } /** * @private */ _setHandlers() { this.listenEventEmitter(this._root, 'mouseenter', () => { this._onHoverIn(); }, Base.DOM_EVENTS_METHODS); this.listenEventEmitter(this._root, 'click', () => { OrderListItem._onClickRow(this); }, Base.DOM_EVENTS_METHODS); } /** * @private */ _onHoverIn() { if (!this._pair || !this._data) { return null; } const sellTooltip = i18n.translate('orderbook.ask.tooltipText', 'app.dex', { amountAsset: this._pair.amountAsset.displayName, priceAsset: this._pair.priceAsset.displayName, price: this._data.price.toFormat(this._pair.priceAsset.precision) }); const buyTooltip = i18n.translate('orderbook.bid.tooltipText', 'app.dex', { amountAsset: this._pair.amountAsset.displayName, priceAsset: this._pair.priceAsset.displayName, price: this._data.price.toFormat(this._pair.priceAsset.precision) }); this._tooltipSell.innerText = sellTooltip; this._tooltipBuy.innerText = buyTooltip; } /** * @private */ _createDom() { this._root.appendChild( OrderListItem._createElement('div', 'table-row', [ this._tooltip = OrderListItem._createElement('div', 'tooltip-dex', [ this._tooltipSell = OrderListItem._createElement('span', 'tooltip-ask'), this._tooltipBuy = OrderListItem._createElement('span', 'tooltip-bid') ]), OrderListItem._createElement('w-cell', 'cell-0', [ this._amountNode = OrderListItem._createElement('div', 'table-cell') ]), OrderListItem._createElement('w-cell', 'cell-1', [ this._priceNode = OrderListItem._createElement('div', 'table-cell') ]), OrderListItem._createElement('w-cell', 'cell-2', [ this._totalNode = OrderListItem._createElement('div', 'table-cell') ]) ]) ); } /** * @param {OrderBook.IOrder} a * @param {OrderBook.IOrder} b * @return {boolean} * @private */ static _isEqual(a, b) { return (!a && !b) || (a && b && Object.entries(a).every(([key, value]) => utils.isEqual(value, b[key]))); } /** * @param {string} tagName * @param {string} className * @param {Array<Node>} [children] * @return {HTMLElement} * @private */ static _createElement(tagName, className, children) { const element = document.createElement(tagName); element.classList.add(className); if (children && children.length) { children.forEach(child => { element.appendChild(child); }); } return element; } /** * @param {OrderListItem} item * @private */ static _onClickRow(item) { const order = item.getData(); if (!order) { return null; } dexDataService.chooseOrderBook.dispatch({ amount: order.totalAmount.toFixed(2), price: order.price.toFixed(), type: order.type }); } }
JavaScript
class NzTabLinkDirective { constructor(elementRef, routerLink, routerLinkWithHref) { this.elementRef = elementRef; this.routerLink = routerLink; this.routerLinkWithHref = routerLinkWithHref; } }
JavaScript
class Index { /** * Create a new index for sublevel store * @param {sublevel} store - Sublevel of the base store * @param {string} name - Name of the index * @param {Function} getValue - User-passed function that returns the indexed value * @param {Function} [filter=returnTrue] - Filter for items to not index * @param {string} [delimiter=DELIMITER] - Delimiter between the index value and the base key. It may appear in the base key, but cannot appear in the index value produced by `getValue`. * @returns {Index} */ constructor (store, name, getValue, filter = returnTrue, delimiter = DELIMITER) { this.store = store this.name = name this.getValue = getValue this.filter = filter this.delimiter = delimiter this._deleted = {} this._index = this.store.sublevel(this.name) } /** * Create an index by clearing the sublevel, rebuilding for old objects, and listening for new entries * @returns {Promise<Index>} Resolves when the index is created */ async ensureIndex () { await this._clearIndex() await this._rebuildIndex() this._addIndexHook() return this } /** * Build a sublevel-compatible option range for this index * @param {Object} opts - Options from which to build a range * @returns {Object} Sublevel readStream options */ range (opts = {}) { if (opts.gt) { opts.gt = `${opts.gt}${this.delimiter}${LOWER_BOUND}` } else if (opts.gte) { opts.gte = `${opts.gte}${this.delimiter}${LOWER_BOUND}` } if (opts.lt) { opts.lt = `${opts.lt}${this.delimiter}${UPPER_BOUND}` } else if (opts.lte) { opts.lte = `${opts.lte}${this.delimiter}${UPPER_BOUND}` } return opts } /** * Create a read stream of the index, filtering out those keys marked for deletion and transforming index keys into base keys * @param {Object} opts - Sublevel readStream options * @returns {Readable} Readable stream */ createReadStream (opts) { const optionsToUpdate = Object.assign({}, opts) const updatedOptions = this.range(optionsToUpdate) const stream = this._index.createReadStream(updatedOptions) // through2 - the lib used below - overrides function context to provide access to `this.push` to push // objects into the downstream stream. In order to get access to `#_isMarkedForDeletion`, we need to // reference the Index context in a local variable const index = this return stream.pipe(through.obj(function ({ key, value }, encoding, callback) { // skip objects that are marked for deletion if (index._isMarkedForDeletion(key)) { return callback() } // give back the base key to the caller // Note: `this` is provided by the through library to give access to this function, // so we can't use a lambda here this.push({ key: index._extractBaseKey(key), value }) callback() })) } /** * Get the key corresponding to the base store from the index key * @example * // returns 'abc:123' * index._extractBaseKey('xyz:abc:123') * @example * // returns '123' * index._extractBaseKey('xyz:123') * @param {string} indexKey - Key of the object in the index * @returns {string} Key of the object in the base store */ _extractBaseKey (indexKey) { // in most cases, we will have only two chunks: the indexValue and the baseKey // However, if the base key contains `this.delimiter`, we will end up with more. // e.g. if the indexKey is `'xyz:abc:123'`, the chunks will be `['xyz', 'abc', '123']` const chunks = indexKey.split(this.delimiter) // remove the index value, which is the first value that is delimited // e.g. `['xyz', 'abc', '123']` => `['abc', '123']` const baseKeyChunks = chunks.slice(1) // rejoin the remaining chunks in case the base key contained the delimiter // e.g. `['abc', '123']` => `abc:123` return baseKeyChunks.join(this.delimiter) } /** * Create an index key * @example * // returns 'xyz:abc' * index._createIndexKey('abc', 'xyz') * // returns 'xyz:abc:123' * index._createIndexKey('abc:123', 'xyz') * @param {string} baseKey - Key of the object in the base store * @param {string} baseValue - Value of the object in the base store * @returns {string} * @throws {Error} If the derived index value contains `this.delimiter` */ _createIndexKey (baseKey, baseValue) { const indexValue = this.getValue(baseKey, baseValue) // if the index value were to contain the delimiter, we would have no way // of knowing where the index value ends and the base key begins if (indexValue && indexValue.indexOf(this.delimiter) !== -1) { throw new Error(`Index values cannot contain the delimiter (${this.delimiter}). If your index value requires it, change the delimiter of the index and rebuild it.`) } return `${indexValue}${this.delimiter}${baseKey}` } /** * Mark a base key as being deleted in this index to avoid it being returned while its being deleted * @param {string} baseKey - Key of the object in the base store * @returns {void} */ _startDeletion (baseKey) { this._deleted[baseKey] = true } /** * Base key is removed from the index store, so we can remove from our local cache * @param {string} baseKey - Key of the object in the base store * @returns {void} */ _finishDeletion (baseKey) { delete this._deleted[baseKey] } /** * Checks whether a given index key will be removed from the index * @param {string} indexKey - Key of the object in the index * @returns {boolean} */ _isMarkedForDeletion (indexKey) { const baseKey = this._extractBaseKey(indexKey) return !!this._deleted[baseKey] } /** * Queue the deletion of a base key from the index * @param {string} baseKey - Key of the object in the base store * @returns {void} */ _removeFromIndex (baseKey) { this._startDeletion(baseKey) this.store.get(baseKey, async (err, value) => { if (err) { // TODO: error handling on index removal return logger.error(`Error while removing ${baseKey} from ${this.name} index`, err) } try { if (!this.filter(baseKey, value)) { return } await promisify(this._index.del)(this._createIndexKey(baseKey, value)) this._finishDeletion(baseKey) } catch (e) { // TODO: error handling on index removal return logger.error(`Error while removing ${baseKey} from ${this.name} index`, e) } }) } /** * Create a database operation to add an object to the index * @param {string} baseKey - Key of the object in the base store * @param {string} baseValue - Value of the object in the base store * @returns {Object} Sublevel compatible database batch operation */ _addToIndexOperation (baseKey, baseValue) { const indexKey = this._createIndexKey(baseKey, baseValue) return { key: indexKey, value: baseValue, type: 'put', prefix: this._index } } /** * Add a hook to the store to add any new items in the base store to the index and * remove any objects removed from the base removed from the index * @returns {void} */ _addIndexHook () { const indexHook = (dbOperation, add) => { const { key, value, type } = dbOperation if (type === 'put' && this.filter(key, value)) { add(this._addToIndexOperation(key, value)) } else if (type === 'del') { this._removeFromIndex(key) } } // `.pre` adds a hook for before a `put` in the `store`, and returns // a function to remove that same hook. this._removeHook = this.store.pre(indexHook) } /** * Remove all objects in the index database * @returns {Promise<void>} Resolves when the database is cleared */ _clearIndex () { // reset the hook if it already exists if (this._removeHook) { this._removeHook() } return migrateStore(this._index, this._index, (key) => ({ type: 'del', key, prefix: this._index })) } /** * Rebuild the index from the base * @returns {Promise<void>} Resolves when the rebuild is complete */ _rebuildIndex () { return migrateStore(this.store, this._index, (key, value) => { if (this.filter(key, value)) { return this._addToIndexOperation(key, value) } }) } }
JavaScript
class SocialLogin extends Component { static propTypes = { disabled: PropTypes.bool.isRequired, login: PropTypes.func.isRequired }; constructor(props) { super(props); this.onButtonClick = this.onButtonClick.bind(this); } async onButtonClick(e) { const { login } = this.props; const { provider } = e.currentTarget.dataset; try { await login(provider); } catch (error) { const { reason } = error; if (reason.code === 'USER_CANCELLED') { return; } throw error; } } render() { const { disabled } = this.props; return ( <div className="social-login"> <button data-provider="facebook" disabled={disabled} onClick={this.onButtonClick} > <FormattedMessage {...messages.facebookLogin} /> </button> </div> ); } }
JavaScript
class TableMatchAssertion extends Component { render() { let columnDefs = prepareTableColumnDefs(this.props.assertion.columns); let rowData = prepareTableRowData( this.props.assertion.data, this.props.assertion.columns ); return ( <TableBaseAssertion columnDefs={columnDefs} rowData={rowData} /> ); } }
JavaScript
class CreateBoletoPaymentRequest extends BaseModel { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { super(obj); if (obj === undefined || obj === null) return; this.retries = this.constructor.getValue(obj.retries); this.bank = this.constructor.getValue(obj.bank); this.instructions = this.constructor.getValue(obj.instructions); this.dueAt = this.constructor.getValue(obj.dueAt || obj.due_at); this.billingAddress = this.constructor.getValue(obj.billingAddress || obj.billing_address); this.billingAddressId = this.constructor.getValue(obj.billingAddressId || obj.billing_address_id); this.nossoNumero = this.constructor.getValue(obj.nossoNumero || obj.nosso_numero); this.documentNumber = this.constructor.getValue(obj.documentNumber || obj.document_number); } /** * Function containing information about the fields of this model * @return {array} Array of objects containing information about the fields */ static mappingInfo() { return super.mappingInfo().concat([ { name: 'retries', realName: 'retries' }, { name: 'bank', realName: 'bank' }, { name: 'instructions', realName: 'instructions' }, { name: 'dueAt', realName: 'due_at', isDateTime: true, dateTimeValue: 'rfc3339' }, { name: 'billingAddress', realName: 'billing_address', type: 'CreateAddressRequest' }, { name: 'billingAddressId', realName: 'billing_address_id' }, { name: 'nossoNumero', realName: 'nosso_numero' }, { name: 'documentNumber', realName: 'document_number' }, ]); } /** * Function containing information about discriminator values * mapped with their corresponding model class names * * @return {object} Object containing Key-Value pairs mapping discriminator * values with their corresponding model classes */ static discriminatorMap() { return {}; } }
JavaScript
class ChatClient { constructor() { log("config", config); this.disabled = true; this.connected = false; const opts = { options: { debug: config.debug, clientId: config.clientId }, connection: { reconnect: true, secure: true }, identity: config.identity, channels: [config.channel] }; this.client = new TwitchClient(opts) .on('message', (target, context, msg, self) => this.onMessage(target, context, msg, self)) .on('connected', (addr, port) => this.onConnect(addr, port)) .on('disconnected', reason => this.onDisconnect(reason)); this.client.connect(); } /** * */ onMessage(target, context, msg, self) { if (self) return; if (config.debug) log("onMessage", target, context, msg, self); const message = msg.trim(); const isCommand = message.charAt(0) === "!"; if (isCommand) this.processCommand(context, message, self); else this.processMessage(context, message, self); } /** * tmi client connected */ onConnect(addr, port) { log(`* Connected to ${addr}:${port}`); overlays.texts.title.show(`${config.botMessagePrefix} Ready`.toUpperCase(), 5, 0, { 'font-size': '24px', color: 'green' }); this.connected = true; actions.init(); gallery.init(); } /** * tmi client disconnect, shut down */ onDisconnect(reason) { log(`onDisconnect ${reason}`); this.connected = false; overlays.texts.title.show(`${config.botMessagePrefix} Disconnected!`, 0, 0, { 'font-size': '24px', color: 'red' }); actions.stopAutoActions(); gallery.hide(); } sayFromChannel(message) { if (!this.connected || this.disabled) return; if (message != null && message.length > 0) this.client.say(config.channel, message); } sayFromChannelPrefixed(prefix, message) { sayFromChannel(`${prefix}${message}`); } sayFromChannelBot(message) { sayFromChannelPrefixed(config.botMessagePrefix, message); } /** * Delete a chat message by id, and respond via the bot in chat if responseKey is set/exists in the strings data. */ deleteMessageAndRespond(context, responseKey) { this.client .deletemessage(config.channel, context.id) .finally(() => { if (responseKey != null) { let response = utils.randomStringFromSet(responseKey, strings); if (response != null && response != responseKey) sayFromChannelBot(`${context.username} ${response}`); } }); } // TODO: implement a more useful message sanitizer/monitor and implement response messaging. // for now it only filters ALL CAPS messages sanitiseMessage(message) { if (message == null || message.length == 0) return { ok: false, reason: null, message: null }; const response = { ok: true, reason: null, message: message }; // check for shouty people const allCaps = message.toUpperCase(); if (message == allCaps) { response.ok = false; response.reason = "bot_mod_all_caps"; } // TODO: a percentage ALLCAPS check, threshold, etc return response; } /** * Takes a command string and processes it. * A command string should start with an "!" and be immediately followed by a command word. * * Further message content after the command sequence (separated by a space) will be passed to the associated action handler * see handlers.js * * Example: * `!alert Just a test.` * `!delete` */ processCommand(context, msg, self) { const spaceIndex = msg.indexOf(" "); // grab message/data after the command const parsedMessage = (spaceIndex > -1) ? msg.substring(spaceIndex + 1) : ""; let command = (spaceIndex > -1) ? msg.substring(0, spaceIndex) : msg; const sanitisedCommand = utils.sanitizeCommand(command); if (sanitisedCommand == null) return; command = `!${sanitisedCommand}`; if (actions.hasOwnProperty(command) && actions[command].security(context, command)) { actions[command].handle(context, parsedMessage); } } /** * handle a 'chat' message type */ processChatMessage(context, message) { const messageResult = sanitiseMessage(message); if (!messageResult.ok) { log("Message failed validation. Will delete", messageResult); deleteMessageAndRespond(context, messageResult.reason); // invalid messages are ignored from further processing. return; } // TODO: any message further processing/analysis } /** * Process regular message text from chat, whisper, ... */ processMessage(context, message, self) { if (self) return; const messageType = context["message-type"]; if (messageType == "action") return; // Handle different message types.. switch (messageType) { case "chat": this.processChatMessage(context, message); break; case "whisper": log(`processMessage - Someone whispered. Message: ${message}`); break; default: log(`processMessage - Unknown message type: ${messageType}, message: ${message}`); break; } } }
JavaScript
class MenuButton extends PureComponent { static Positions = Positions; static propTypes = { /** * An id to use for the menu button. This is required for a11y */ id: isRequiredForA11y(PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ])), /** * An optional id to give the button instead of the menu. */ buttonId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional id to give the list that appears in the menu. */ listId: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * An optional style to apply to the button. */ style: PropTypes.object, /** * An optional className to apply to the button. */ className: PropTypes.string, /** * An optional style to apply to the menu. */ menuStyle: PropTypes.object, /** * An optional className to apply to the menu. */ menuClassName: PropTypes.string, /** * An optional style to apply to the menu's list when it is open. */ listStyle: PropTypes.object, /** * An optional className to apply to the menu's list when it is open. */ listClassName: PropTypes.string, /** * Any children used to render icons or anything else for the button. */ buttonChildren: PropTypes.node, /** * An optional function to call when the button is clicked. */ onClick: PropTypes.func, /** * An optional function to call when the menu's visiblity is toggled. The callback * will include the next `open` state and the click event. */ onMenuToggle: PropTypes.func, /** * Boolean if the MenuButton is open by default. */ defaultOpen: PropTypes.bool, /** * The position for the menu. */ position: PropTypes.oneOf([ Positions.TOP_LEFT, Positions.TOP_RIGHT, Positions.BOTTOM_LEFT, Positions.BOTTOM_RIGHT, Positions.BELOW, ]), /** * A list of `ListItem`s to render when the Menu is toggled open. */ children: PropTypes.node, /** * Boolean if the `Menu` is displayed as full width. */ fullWidth: PropTypes.bool, /** * Boolean if the max width of the menu's list should be equal to the `Button`. */ contained: PropTypes.bool, /** * An optional transition name to use for the menu transitions. */ transitionName: PropTypes.string, /** * An optional transition leave timeout to use for the menu transitions. */ transitionEnterTimeout: PropTypes.number, /** * An optional transition leave timeout to use for the menu transitions. */ transitionLeaveTimeout: PropTypes.number, }; constructor(props) { super(props); this.state = { isOpen: props.defaultOpen || false, }; this._toggleMenu = this._toggleMenu.bind(this); this._closeMenu = this._closeMenu.bind(this); } _toggleMenu(e) { const isOpen = !this.state.isOpen; if (this.props.onClick) { this.props.onClick(e); } if (this.props.onMenuToggle) { this.props.onMenuToggle(isOpen, e); } this.setState({ isOpen }); } _closeMenu(e) { if (this.props.onMenuToggle) { this.props.onMenuToggle(false, e); } this.setState({ isOpen: false }); } render() { const { isOpen } = this.state; const { id, listId, buttonId, menuStyle, menuClassName, listStyle, listClassName, buttonChildren, children, fullWidth, position, contained, transitionName, transitionEnterTimeout, transitionLeaveTimeout, ...props } = this.props; delete props.onClick; delete props.onMenuToggle; delete props.defaultOpen; const toggle = ( <Button key="menu-button" {...props} id={buttonId} onClick={this._toggleMenu} > {buttonChildren} </Button> ); return ( <Menu id={id} listId={listId} style={menuStyle} className={menuClassName} listStyle={listStyle} listClassName={listClassName} toggle={toggle} isOpen={isOpen} onClose={this._closeMenu} contained={contained} position={position} fullWidth={fullWidth} transitionName={transitionName} transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {children} </Menu> ); } }
JavaScript
class HljsInsertLineNums { constructor() { this.shouldInsert = false; this.startNumber = 1; } "before:highlight"(data) { var match = /^linenums(:\d+)?/.exec(data.code); if (!match) { return; } var startNumber = +(match[1] || "").slice(1) || 1; this.shouldInsert = true; this.startNumber = startNumber; data.code = data.code.replace(/^linenums(:\d+)?/, ""); } "after:highlight"(result) { if (!this.shouldInsert) { return; } var startNumber = this.startNumber; var content = result.value; var lines = content.split(/\r?\n/); var output = ""; for (var i = 0; i < lines.length; i++) { output += "<div>" + (i + startNumber) + "</div>"; } var newContent = '<code class="s-code-block--line-numbers">' + output + "</code>" + content; result.value = newContent; this.shouldInsert = false; } }
JavaScript
class AcceptStakeByWorker extends StakeAndMintBase { /** * Constructor for KYC worker to accept stake and assign further work to Facilitator. * * @param {object} params * @param {number} params.tokenId * @param {string} params.amountToStake * @param {string} params.stakerAddress * @param {number} params.originChainId * @param {number} params.auxChainId * @param {string} params.requestStakeHash * @param {string} params.facilitator * * @augments StakeAndMintBase * * @constructor */ constructor(params) { super(params); const oThis = this; oThis.tokenId = params.tokenId; oThis.amountToStake = params.amountToStake; oThis.stakerAddress = params.stakerAddress; oThis.originChainId = params.originChainId; oThis.auxChainId = params.auxChainId; oThis.requestStakeHash = params.requestStakeHash; oThis.facilitator = params.facilitator; oThis.brandedTokenContract = null; oThis.secretString = null; oThis.btStakeHelper = null; } /** * Async perform. * * @return {Promise<any>} * @private */ async _asyncPerform() { const oThis = this; await oThis._validateStakeAmount(); await oThis._fetchStakerGatewayComposer(); await oThis._fetchRequiredAddresses(); await oThis._setOriginWeb3Instance(); const response = await oThis._performAcceptStake(); if (response.isSuccess()) { return Promise.resolve( responseHelper.successWithData({ taskStatus: workflowStepConstants.taskPending, transactionHash: response.data.transactionHash, taskResponseData: { chainId: oThis.originChainId, transactionHash: response.data.transactionHash, secretString: oThis.secretString } }) ); } return Promise.resolve( responseHelper.successWithData({ taskStatus: workflowStepConstants.taskPending, taskResponseData: { err: JSON.stringify(response), secretString: oThis.secretString } }) ); } /** * Validate stake amount. * * @sets oThis.amountToStake * * @return {Promise<void>} * @private */ async _validateStakeAmount() { const oThis = this; if (!oThis.amountToStake) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_smm_bt_asr_3', api_error_identifier: 'something_went_wrong', debug_options: { amountToStake: 'Stake Amount is invalid: ' + oThis.amountToStake } }) ); } oThis.amountToStake = new BigNumber(oThis.amountToStake); return oThis.amountToStake; } /** * Fetch required addresses. * * @sets oThis.gatewayContract, oThis.coGatewayContract, oThis.brandedTokenContract, oThis.originWorker * * @return {Promise<void>} * @private */ async _fetchRequiredAddresses() { const oThis = this; const tokenAddressesObj = new TokenAddressCache({ tokenId: oThis.tokenId }), addressesResp = await tokenAddressesObj.fetch(); oThis.gatewayContract = addressesResp.data[tokenAddressConstants.tokenGatewayContract]; oThis.coGatewayContract = addressesResp.data[tokenAddressConstants.tokenCoGatewayContract]; oThis.brandedTokenContract = addressesResp.data[tokenAddressConstants.brandedTokenContract]; oThis.originWorker = addressesResp.data[tokenAddressConstants.originWorkerAddressKind][0]; } /** * Get hash lock. * * @sets oThis.secretString * * @return {Promise<void>} * @private */ _getHashLock() { const oThis = this; const response = MosaicJs.Helpers.StakeHelper.createSecretHashLock(); oThis.secretString = response.secret; return response.hashLock; } /** * Get BT stake helper. * * @param {object} web3Instance * * @sets oThis.btStakeHelper * * @return {null|module:lib/stakeAndMint/brandedToken/AcceptStakeRequest.Helpers.StakeHelper} * @private */ _getBTStakeHelper(web3Instance) { const oThis = this; if (!oThis.btStakeHelper) { oThis.btStakeHelper = new BrandedToken.Helpers.StakeHelper( web3Instance, oThis.brandedTokenContract, web3Instance.utils.toChecksumAddress(oThis.gatewayComposer) ); } return oThis.btStakeHelper; } /** * Get EIP 712 Signature of worker. * * @sets oThis.provider * * @return {Promise<void>} * @private */ async _getEIP712SignedSignature() { const oThis = this; const workerAddress = oThis.originWorker, signerWeb3Instance = new SignerWeb3Provider(oThis.originShuffledProviders[0]), web3Instance = await signerWeb3Instance.getInstance(); oThis.provider = oThis.originShuffledProviders[0]; // Fetch Staker Branded Token nonce to sign. const stakerBtNonce = await oThis ._getBTStakeHelper(web3Instance) ._getStakeRequestRawTx(oThis.requestStakeHash, web3Instance); // Add worker key. const checkSumWorkerAddress = web3Instance.utils.toChecksumAddress(workerAddress); await signerWeb3Instance.addAddressKey(workerAddress); // Sign transaction. const stakeRequestTypedData = await oThis ._getBTStakeHelper() .getStakeRequestTypedData(oThis.amountToStake.toString(10), stakerBtNonce.nonce); logger.log('stakeRequestTypedData', stakeRequestTypedData); // 2. Generate EIP712 Signature. const workerAccountInstance = web3Instance.eth.accounts.wallet[checkSumWorkerAddress]; const signature = await workerAccountInstance.signEIP712TypedData(stakeRequestTypedData); // Remove worker key from web3. signerWeb3Instance.removeAddressKey(workerAddress); return signature; } /** * Perform confirm stake intent on CoGateway. * * @return {Promise<void>} * @private */ async _performAcceptStake() { const oThis = this; // Get EIP 712 signature from OST Worker. const signature = await oThis._getEIP712SignedSignature(), hashLock = oThis._getHashLock(); const txObject = await oThis ._getBTStakeHelper() ._acceptStakeRequestRawTx(oThis.requestStakeHash, signature, oThis.facilitator, hashLock), data = txObject.encodeABI(), gasPrice = await oThis._fetchGasPrice(), // Origin gas price txOptions = { gasPrice: gasPrice, gas: contractConstants.acceptStakeSTGas }; return oThis.performTransaction( oThis.originChainId, oThis.provider, oThis.facilitator, oThis.gatewayComposer, txOptions, data ); } /** * Get origin chain gas price. * * @return {Promise<*>} * @private */ async _fetchGasPrice() { const dynamicGasPriceResponse = await new DynamicGasPriceCache().fetch(); return dynamicGasPriceResponse.data; } /** * Get submit transaction parameters. * * @return {object} */ get _customSubmitTxParams() { const oThis = this; return { tokenId: oThis.tokenId, pendingTransactionKind: pendingTransactionConstants.acceptStakeKind }; } }
JavaScript
class Websocket { __construct() { /** * The websocket response (used to send data). * * @type {Jymfony.Component.HttpFoundation.Websocket.WebsocketResponse} */ this._response = undefined; } /** * The current websocket response. * * @param {Jymfony.Component.HttpFoundation.Websocket.WebsocketResponse} response */ set response(response) { this._response = response; } /** * Sends a message through the websocket. * * @param {Jymfony.Component.HttpFoundation.Websocket.Message} message * * @returns {Promise<void>} */ send(message) { const frame = new Frame(); frame.opcode = Message.TYPE_TEXT === message.type ? 0x1 : 0x2; frame.fin = true; frame.buffer = message.asBuffer(); return this._response._sendFrame(frame); } /** * Closes the websocket. * * @param {int} [reason = WebsocketResponse.CLOSE_NORMAL] * * @returns {Promise<void>} */ close(reason = WebsocketResponse.CLOSE_NORMAL) { return this._response.closeConnection(reason); } /** * Handles websocket message. * * @param {Jymfony.Component.HttpFoundation.Websocket.Message} message * * @returns {Promise<void>} */ async onMessage(message) { } // eslint-disable-line no-unused-vars /** * Handles websocket message. * * @returns {Promise<void>} */ async onClose() { } // eslint-disable-line no-unused-vars }
JavaScript
class Renderable2DGrid extends Renderable2DMultitex { /** * Constructor for Renderable2D grid. Sets up data and initializes a data texture. * * @param {string} mapTilesTextureName Name of sprite sheet texture. * @param {Array} gridData Array of indexes for each tile on the map. * @param {number} width Width of the map. * @param {number} height Height of the map. * @param {number} tileViewWidth Width of the viewport. * @param {number} tileViewHeight Height of the viewport. */ constructor(mapTilesTextureName, gridData, width, height, tileViewWidth, tileViewHeight) { super(ProgramManager.getProgram('2DGrid')); this.className = 'Renderable2DGrid'; this.dataArray = new Uint16Array(width * height); /* [0][0] = 0 = Map data tiles width. [0][1] = 1 = Map data tiles height. [0][2] = 2 = Map tiles in the texture width. [0][3] = 3 = Map tiles in the texture height. [1][0] = 4 = Map viewport width. [1][1] = 5 = Map viewport height. [1][2] = 6 = Map viewport x1. [1][3] = 7 = Map viewport y1. [2][0] = 8 = TileSize width normalized. [2][1] = 9 = TileSize height normalized. */ this.shaderTileData = []; this.mapTilesTexture = TextureManager.getTexture(mapTilesTextureName); this.addTexture(this.mapTilesTexture); this.mapTilesDataTextureName = mapTilesTextureName + 'Data' + dataTexCounter++; this.setGridData(gridData, width, height, tileViewWidth, tileViewHeight); } updateDataArray(data, x1, y1, width, height) { if (data == null) return; let dataY = 0; for (let y = y1; y < y1 + height; y++) { this.dataArray.set(data.slice(dataY * width, (dataY + 1) * width), x1 + (y * width)); dataY++; } } /** * Updates the data texture by quadrant. Quadrant is specified by the x1, y1, * width, and height parameters. * * @param {Array} data Array of values indicating the index of each sprite. * @param {number} x1 Top left x position to update. * @param {number} y1 Top left y position to update. * @param {number} width Width (in tiles) of data to update. * @param {number} height Height (in tiles) of data to update. */ updateGridData(data, x1, y1, width, height) { this.updateDataArray(data, x1, y1, width, height); this.buildShaderTileData(x1, y1, width, height); TextureManager.updateDataTexture(this.mapTilesDataTextureName, this.dataArray, x1, y1, width, height); this.requestRedraw(); } /** * * * @param {*} data * @param {*} x1 * @param {*} y1 * @param {*} width * @param {*} height */ updateGridDataViewport(data, x1, y1, width, height, viewportWidth, viewportHeight) { this.updateDataArray(data, x1, y1, width, height); this.buildShaderTileData(x1, y1, viewportWidth, viewportHeight); TextureManager.updateDataTexture(this.mapTilesDataTextureName, this.dataArray, x1, y1, width, height); this.requestRedraw(); } setGridData(data, width, height, tileViewWidth, tileViewHeight) { this.updateDataArray(data, 0, 0, width, height); let texture = TextureManager.addDataTexture(this.mapTilesDataTextureName, this.dataArray, RenderManager.GL.R16UI, RenderManager.GL.RED_INTEGER, RenderManager.GL.UNSIGNED_SHORT, -1, -1, width, height); this.addTexture(texture); /* [0][0] = 0 = Map data tiles width. [0][1] = 1 = Map data tiles height. [0][2] = 2 = Map tiles in the texture width. [0][3] = 3 = Map tiles in the texture height. [1][0] = 4 = Map viewport width. [1][1] = 5 = Map viewport height. [1][2] = 6 = Map viewport x1. [1][3] = 7 = Map viewport y1. [2][0] = 8 = TileSize width normalized. [2][1] = 9 = TileSize height normalized. */ this.shaderTileData = [ width, height, this.mapTilesTexture.framesWidth, this.mapTilesTexture.framesHeight, tileViewWidth, tileViewHeight, 0, 0, 1 / this.mapTilesTexture.framesWidth, 1 / this.mapTilesTexture.framesHeight, 1, 1, 1, 1, 1, 1 ]; } /** * Sets the viewport of the map grid to x1, y1, width, height (in tiles). * * @param {number} viewportX1 Top left x position of the viewport. * @param {number} viewportY1 Top left y position of the viewport. * @param {number} viewportWidth Width of the viewport * @param {number} viewportHeight */ buildShaderTileData(viewportX1, viewportY1, viewportWidth, viewportHeight) { this.shaderTileData[4] = viewportWidth; this.shaderTileData[5] = viewportHeight; this.shaderTileData[6] = viewportX1; this.shaderTileData[7] = viewportY1; } onEnd() { this.removeFromViewports(); TextureManager.removeTexture(this.mapTilesDataTextureName); } /** * Updates the uniforms of this renderable. Requires a position matrix for * perspective calculations by the RendererManager. * * @param {Matrix3} positionMatrix Position matrix of this renderable. */ setUniformData(positionMatrix) { if (this.textures.length < 2) return false; this.program.setUniforms({ 'u_color': this.color.color, 'u_matrix': positionMatrix, 'u_depth': this.depth, 'u_tileData': this.shaderTileData, 'u_texture': 0, 'u_mapDataTexture': 1, }); return true; } }
JavaScript
class AddCommand extends AddressableCommand { exec(state) { state.setValue(state.getValue() + this.getRegisterValue(state)); } }
JavaScript
class DefaultWeakMap extends WeakMap { constructor(createItem, items = undefined) { super(items); this.createItem = createItem; } get(key) { if (!this.has(key)) { this.set(key, this.createItem(key)); } return super.get(key); } }
JavaScript
class ReceiptItem { constructor() { } /** * Defines the metadata of ReceiptItem * * @returns {object} metadata of ReceiptItem * */ mapper() { return { required: false, serializedName: 'ReceiptItem', type: { name: 'Composite', className: 'ReceiptItem', modelProperties: { title: { required: false, serializedName: 'title', type: { name: 'String' } }, subtitle: { required: false, serializedName: 'subtitle', type: { name: 'String' } }, text: { required: false, serializedName: 'text', type: { name: 'String' } }, image: { required: false, serializedName: 'image', type: { name: 'Composite', className: 'CardImage' } }, price: { required: false, serializedName: 'price', type: { name: 'String' } }, quantity: { required: false, serializedName: 'quantity', type: { name: 'String' } }, tap: { required: false, serializedName: 'tap', type: { name: 'Composite', className: 'CardAction' } } } } }; } }
JavaScript
class Cartas { constructor(palo,valor){ if(palo>=1 && palo<=4){ this.palo = palo; }else{ this.palo = null; } if(valor>=1 && valor<=10){ this.valor = valor; }else{ this.valor = null; } } darValor(numPalo, valorCarta){ if(numPalo>=1 && numPalo<=4){ this.palo = numPalo; }else{ console.log("Dato incorrecto."); } if(valorCarta >=1 && valorCarta<=10){ this.valor = valorCarta; }else{ console.log("Dato incorrecto."); } } toString(){ let nombrePalo; let nombreValor; switch(this.palo){ case 1: {nombrePalo = "Oros"} break; case 2: {nombrePalo = "Espadas"} break; case 3: {nombrePalo = "Bastos"} break; case 4: {nombrePalo = "Copas"} break; } switch(this.valor){ case 1: {nombreValor = "As"} break; case 2: {nombreValor = "Dos"} break; case 3: {nombreValor = "Tres"} break; case 4: {nombreValor = "Cuatro"} break; case 5: {nombreValor = "Cinco"} break; case 6: {nombreValor = "Seis"} break; case 7: {nombreValor = "Siete"} break; case 8: {nombreValor = "Sota"} break; case 9: {nombreValor = "Caballo"} break; case 10: {nombreValor = "Rey"} break; } console.log(nombreValor + " de " + nombrePalo); } }
JavaScript
class Node { constructor(value) { this.value = value; this.next = null; } }
JavaScript
class Node { constructor(value) { this.value = value; this.next = null; } }
JavaScript
class TurnRenderer extends Observer { /** * Construct the TurnRenderer, making it subscribe to the game. * @param {Game} game The game to observe. * @param {HTMLElement} turnElement The div to hide/show. */ constructor(game, turnElement) { super(); this._game = game; this._turnElement = turnElement; game.subscribe(this); } /** * Show the 'robot-thinking' div if the turn is for the AI. */ update() { console.log("turn!"); if (this._game.isMyTurn(Grid.MARK_AI)) this._turnElement.style.display = "block"; else this._turnElement.style.display = "none"; } }
JavaScript
class Formula { /** * Creates a math formula object. * * @param {string} formula - A mathematical formula to parse.y */ constructor(formula) { let parser = new TapDigit.Parser(); /** * @type {object.<string, *>} */ this.tree = parser.parse(formula); /** * @type {?Builder} */ this.builder = null; } /** * The builder instance to use. * * @param {Builder} builder - The builder instance to add the formula to. */ setBuilder(builder) { this.builder = builder; } /** * Generates the processes for the formula specified in the constructor. * * Returns the last node that computes the result. * * @param {boolean} setResultNode - Set the `result` flag to `true`. * @returns {BuilderNode} * @throws {Error} */ generate(setResultNode = true) { let finalNode = this.parseTree(this.tree); if (!(finalNode instanceof BuilderNode)) { throw new Error('Invalid formula specified.'); } // Set result node if (setResultNode) { finalNode.result = true; } return finalNode; } /** * Walks through the tree generated by the TapDigit parser and generates process nodes. * * @protected * @param {object.<string, *>} tree * @returns {object.<string, *>} * @throws {Error} */ parseTree(tree) { let key = Object.keys(tree)[0]; // There's never more than one property so no loop required switch(key) { case 'Number': return parseFloat(tree.Number); case 'Identifier': return this.getRef(tree.Identifier); case 'Expression': return this.parseTree(tree.Expression); case 'FunctionCall': { let args = []; for(let i in tree.FunctionCall.args) { args.push(this.parseTree(tree.FunctionCall.args[i])); } return this.builder.process(tree.FunctionCall.name, args); } case 'Binary': return this.addOperatorProcess( tree.Binary.operator, this.parseTree(tree.Binary.left), this.parseTree(tree.Binary.right) ); case 'Unary': { let val = this.parseTree(tree.Unary.expression); if (tree.Unary.operator === '-') { if (typeof val === 'number') { return -val; } else { return this.addOperatorProcess('*', -1, val); } } else { return val; } } default: throw new Error('Operation ' + key + ' not supported.'); } } /** * Gets the reference for a value, e.g. from_node or from_parameter. * * @protected * @param {*} value * @returns {*} */ getRef(value) { // Convert native data types if (value === 'true') { return true; } else if (value === 'false') { return false; } else if (value === 'null') { return null; } // Output of a process if (typeof value === 'string' && value.startsWith('#')) { let nodeId = value.substring(1); if (nodeId in this.builder.nodes) { return { from_node: nodeId }; } } let callbackParams = this.builder.getParentCallbackParameters(); // Array labels / indices if (typeof value === 'string' && callbackParams.length > 0) { let prefix = value.match(/^\$+/); let count = prefix ? prefix[0].length : 0; if (count > 0 && callbackParams.length >= count) { let ref = value.substring(count); return callbackParams[count-1][ref]; } } // Everything else is a parameter let parameter = new Parameter(value); // Add new parameter if it doesn't exist this.builder.addParameter(parameter); return parameter; } /** * Adds a process node for an operator like +, -, *, / etc. * * @param {string} operator - The operator. * @param {number|object.<string, *>} left - The left part for the operator. * @param {number|object.<string, *>} right - The right part for the operator. * @returns {BuilderNode} * @throws {Error} */ addOperatorProcess(operator, left, right) { let processName = Formula.operatorMapping[operator]; let process = this.builder.spec(processName); if (processName && process) { let args = {}; if (!Array.isArray(process.parameters) || process.parameters.length < 2) { throw new Error("Process for operator " + operator + " must have at least two parameters"); } args[process.parameters[0].name || 'x'] = left; args[process.parameters[1].name || 'y'] = right; return this.builder.process(processName, args); } else { throw new Error('Operator ' + operator + ' not supported'); } } }
JavaScript
class FindAndReplaceUI extends Plugin { /** * @inheritDoc */ static get pluginName() { return 'FindAndReplaceUI'; } constructor( editor ) { super( editor ); this.set( 'searchText' ); this.set( 'replaceText' ); this.set( 'matchCount', null ); this.set( 'highlightOffset', null ); /** * The form view will only be assigned if the find and replace toolbar button was added. * * @member {module:find-and-replace/ui/findandreplaceformview~FindAndReplaceFormView|null} #formView */ this.formView = null; } /** * @inheritDoc */ init() { this.findAndReplacePlugin = this.editor.plugins.get( 'FindAndReplace' ); const editor = this.editor; editor.ui.componentFactory.add( 'findAndReplace', locale => { const dropdown = createDropdown( locale ); const formView = new FindAndReplaceFormView( editor.locale, this._state ); formView.delegate( 'findNext' ).to( this ); formView.delegate( 'findPrevious' ).to( this ); formView.delegate( 'replace' ).to( this ); formView.delegate( 'replaceAll' ).to( this ); formView.bind( 'matchCount' ).to( this ); formView.bind( 'highlightOffset' ).to( this ); this._createToolbarDropdown( dropdown, loupeIcon, formView ); dropdown.panelView.children.add( formView ); dropdown.on( 'change:isOpen', ( event, name, value ) => { if ( !value ) { this.fire( 'dropdown:closed' ); } } ); this.formView = formView; editor.keystrokes.set( 'Ctrl+F', ( data, cancelEvent ) => { dropdown.buttonView.fire( 'execute' ); cancelEvent(); } ); // Dropdown should be disabled when in source editing mode. See #10001. dropdown.bind( 'isEnabled' ).to( editor.commands.get( 'find' ) ); return dropdown; } ); } /** * Sets the observed state object. It is used to display search result count etc. * * @protected * @param {module:find-and-replace/findandreplacestate~FindAndReplaceState} state State object to be tracked. */ _setState( state ) { this._state = state; this.listenTo( state.results, 'change', () => { this.set( 'matchCount', state.results.length ); } ); this.bind( 'highlightOffset' ).to( state, 'highlightedResult', highlightedResult => { if ( !highlightedResult ) { return null; } const sortedResults = Array.from( state.results ).sort( ( a, b ) => { const mapping = { before: -1, same: 0, after: 1 }; return mapping[ a.marker.getStart().compareWith( b.marker.getStart() ) ]; } ); const index = sortedResults.indexOf( highlightedResult ); return index === -1 ? null : index + 1; } ); } /** * @private * @param {module:ui/dropdown/dropdownview~DropdownView} dropdown * @param {String} icon An icon to be assigned to the button. * @param {module:find-and-replace/ui/findandreplaceformview~FindAndReplaceFormView} formView A related form view. */ _createToolbarDropdown( dropdown, icon, formView ) { const t = this.editor.locale.t; const buttonView = dropdown.buttonView; // Configure the dropdown's button properties: buttonView.set( { icon, label: t( 'Find and replace' ), keystroke: 'CTRL+F', tooltip: true } ); // Each time a dropdown is opened, the search text field should get focused. // Note: Use the low priority to make sure the following listener starts working after the // default action of the drop-down is executed (i.e. the panel showed up). Otherwise, the // invisible form/input cannot be focused/selected. buttonView.on( 'open', () => { formView.disableCssTransitions(); formView.findInputView.fieldView.select(); formView.focus(); formView.enableCssTransitions(); }, { priority: 'low' } ); } }
JavaScript
class DropdownsForFiltering extends React.Component{ constructor(props){ super(props); this.state =({ courseSearch: "", uniId: "", fosId: "" }); this.handleChange = this.handleChange.bind(this); this.handleUniDropdown = this.handleUniDropdown.bind(this); this.handleFosDropdown = this.handleFosDropdown.bind(this); } showInDropdown(items) { return items.map((item, i) => { return (<MenuItem key={i} value={item._id}> {item.name} </MenuItem>); }) } handleChange(e){ const value = e.target.value; this.setState({ courseSearch: value }); this.props.handleTextField(value); } handleUniDropdown(e) { const value = e.target.value; this.setState({ uniId: value }); this.props.onUniDropdown(value); } handleFosDropdown(e) { const value = e.target.value; this.setState({ fosId: value }); this.props.onFosDropdown(value); } render() { return ( <Box m={2}> <Grid container direction="row" justify={"space-between"}> <Grid item spacing={2}> <FormControl > <InputLabel> University </InputLabel> <Select style={{minWidth: 200,maxWidth: 200}} value={this.state.uniId} onChange={this.handleUniDropdown} > {this.showInDropdown(this.props.unis)} </Select> </FormControl> </Grid> <Grid item> <FormControl> <InputLabel> Field of study </InputLabel> <Select style={{minWidth: 200,maxWidth: 200}} value={this.state.fosId} onChange={this.handleFosDropdown} > {this.showInDropdown(this.props.fos)} </Select> </FormControl> </Grid> <Box m={2}> <TextField style={{minWidth: 220,maxWidth: 200}} placeholder={"Search your course"} value={this.state.courseSearch} onChange={this.handleChange}/> </Box> </Grid> </Box> ) } }
JavaScript
class ArmorBar { constructor(element, initialValue = hero.armorHP) { this.valueEl = element.querySelector('.armor-bar-value'); this.fillEl = element.querySelector('.armor-bar-fill'); this.setValue(initialValue); // console.log('check valueEl: ', this.valueEl); // console.log('check fillEl: ', this.fillEl); } setValue(newValue) { if (newValue < 0) {//check and/or convert to 0 if value is less than 0. newValue = 0; } if (newValue > 100) {//check and/or convert to 100 if value is greater than 100. newValue = 100; } this.value = newValue; this.update(); } update() { var percentage = this.value + '%'; this.fillEl.style.width = percentage; this.valueEl.textContent = percentage; } }
JavaScript
class LegacyDeploymentsResponseDeploymentsItemPackage { /** * Create a LegacyDeploymentsResponseDeploymentsItemPackage. * @property {string} [appVersion] The version of the release * @property {boolean} [isDisabled] Flag used to determine if release is * disabled * @property {boolean} [isMandatory] Flag used to determine if release is * mandatory * @property {number} [rollout] Percentage (out of 100) that release is * deployed to * @property {string} [blobUrl] Location (URL) of release package * @property {number} [size] Size of release package * @property {string} [releaseMethod] Method used to deploy release * @property {number} [uploadTime] Release upload time as epoch Unix * timestamp * @property {string} [label] Release label (aka release name) * @property {string} [releasedByUserId] User ID that triggered most recent * release * @property {string} [manifestBlobUrl] The URL location of the package's * manifest file. * @property {object} [diffPackageMap] Object containing URL and size of * changed package hashes contained in the release */ constructor() { } /** * Defines the metadata of LegacyDeploymentsResponseDeploymentsItemPackage * * @returns {object} metadata of LegacyDeploymentsResponseDeploymentsItemPackage * */ mapper() { return { required: false, serializedName: 'LegacyDeploymentsResponse_deploymentsItem_package', type: { name: 'Composite', className: 'LegacyDeploymentsResponseDeploymentsItemPackage', modelProperties: { appVersion: { required: false, serializedName: 'appVersion', type: { name: 'String' } }, isDisabled: { required: false, serializedName: 'isDisabled', type: { name: 'Boolean' } }, isMandatory: { required: false, serializedName: 'isMandatory', type: { name: 'Boolean' } }, rollout: { required: false, serializedName: 'rollout', type: { name: 'Number' } }, blobUrl: { required: false, serializedName: 'blobUrl', type: { name: 'String' } }, size: { required: false, serializedName: 'size', type: { name: 'Number' } }, releaseMethod: { required: false, serializedName: 'releaseMethod', type: { name: 'String' } }, uploadTime: { required: false, serializedName: 'uploadTime', type: { name: 'Number' } }, label: { required: false, serializedName: 'label', type: { name: 'String' } }, releasedByUserId: { required: false, serializedName: 'releasedByUserId', type: { name: 'String' } }, manifestBlobUrl: { required: false, serializedName: 'manifestBlobUrl', type: { name: 'String' } }, diffPackageMap: { required: false, serializedName: 'diffPackageMap', type: { name: 'Object' } } } } }; } }
JavaScript
class PostDetail_button extends React.Component { render(){ const {application} = this.props // console.log("-------"+Volunteer.state) return( <div id="fh5co-blog" class="fh5co-bg-section"> <div className="button"> <span><Button variant="contained" color="secondary" style={{width:"230px", textAlign:"center"}}> Organization Profile </Button></span> <span><Link to="/volunteer/My_application"><Button variant="contained" color="secondary" style={{width:"230px", textAlign:"center"}} onClick={ addApplication.bind(this, Volunteer, application)}> Apply Now </Button></Link></span> </div> </div> ) } }
JavaScript
class mxUndoManager extends EventSource { constructor(size) { super(); this.size = size != null ? size : 100; this.clear(); } /** * Maximum command history size. 0 means unlimited history. Default is * 100. * @default 100 */ // size: number; size = null; /** * Array that contains the steps of the command history. */ // history: Array<mxUndoableEdit>; history = null; /** * Index of the element to be added next. */ // indexOfNextAdd: number; indexOfNextAdd = 0; /** * Returns true if the history is empty. */ // isEmpty(): boolean; isEmpty() { return this.history.length == 0; } /** * Clears the command history. */ // clear(): void; clear() { this.history = []; this.indexOfNextAdd = 0; this.fireEvent(new EventObject(InternalEvent.CLEAR)); } /** * Returns true if an undo is possible. */ // canUndo(): boolean; canUndo() { return this.indexOfNextAdd > 0; } /** * Undoes the last change. */ // undo(): void; undo() { while (this.indexOfNextAdd > 0) { const edit = this.history[--this.indexOfNextAdd]; edit.undo(); if (edit.isSignificant()) { this.fireEvent(new EventObject(InternalEvent.UNDO, 'edit', edit)); break; } } } /** * Returns true if a redo is possible. */ // canRedo(): boolean; canRedo() { return this.indexOfNextAdd < this.history.length; } /** * Redoes the last change. */ // redo(): void; redo() { const n = this.history.length; while (this.indexOfNextAdd < n) { const edit = this.history[this.indexOfNextAdd++]; edit.redo(); if (edit.isSignificant()) { this.fireEvent(new EventObject(InternalEvent.REDO, 'edit', edit)); break; } } } /** * Method to be called to add new undoable edits to the <history>. */ // undoableEditHappened(undoableEdit: mxUndoableEdit): void; undoableEditHappened(undoableEdit) { this.trim(); if (this.size > 0 && this.size == this.history.length) { this.history.shift(); } this.history.push(undoableEdit); this.indexOfNextAdd = this.history.length; this.fireEvent(new EventObject(InternalEvent.ADD, 'edit', undoableEdit)); } /** * Removes all pending steps after <indexOfNextAdd> from the history, * invoking die on each edit. This is called from <undoableEditHappened>. */ // trim(): void; trim() { if (this.history.length > this.indexOfNextAdd) { const edits = this.history.splice( this.indexOfNextAdd, this.history.length - this.indexOfNextAdd ); for (let i = 0; i < edits.length; i += 1) { edits[i].die(); } } } }
JavaScript
class PostsNew extends Component { renderField(field) { // ES6 Destructering const { meta: {touched, error} } = field; // Un Destructered version // const className = `form-group ${field.meta.touched && field.meta.error ? 'has-danger' : ''}` const className = `form-group ${touched && error ? 'has-danger' : ''}` return ( <div className={className}> <label>{field.label}</label> <input className="form-control" type="text" {...field.input} /> <div className="text-help"> {touched ? error : ''} </div> </div> ); } // We shoulde handle onSubmit by our self // We should send our form data to the backend // Redux Forms does not handle this for us onSubmit(values) { this.props.createPost(values, () => { this.props.history.push('/'); }); } render(){ const { handleSubmit } = this.props; return ( <div> {/* on form Submition, first redux form will call handleSubmit then handleSubmit runs the form validation after that if everything was ok will come here and runs whatever function that WE wrote for handleing form submition*/} <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <Field label="Title" name="title" component={this.renderField} /> <Field label="Tags" name="categories" component={this.renderField} /> <Field label="Post Content" name="content" component={this.renderField} /> <button type="submit" className="btn btn-primary">Submit</button> <Link to="/" className="btn btn-danger">Cancel</Link> </form> </div> ); } }
JavaScript
class NzSingletonService { constructor() { /** * This registry is used to register singleton in dev mode. * So that singletons get destroyed when hot module reload happens. * * This works in prod mode too but with no specific effect. */ this._singletonRegistry = new Map(); } get singletonRegistry() { return environment.isTestMode ? testSingleRegistry : this._singletonRegistry; } registerSingletonWithKey(key, target) { const alreadyHave = this.singletonRegistry.has(key); const item = alreadyHave ? this.singletonRegistry.get(key) : this.withNewTarget(target); if (!alreadyHave) { this.singletonRegistry.set(key, item); } } getSingletonWithKey(key) { return this.singletonRegistry.has(key) ? this.singletonRegistry.get(key).target : null; } withNewTarget(target) { return { target }; } }
JavaScript
class NzDragService { constructor(rendererFactory2) { this.draggingThreshold = 5; this.currentDraggingSequence = null; this.currentStartingPoint = null; this.handleRegistry = new Set(); this.renderer = rendererFactory2.createRenderer(null, null); } requestDraggingSequence(event) { if (!this.handleRegistry.size) { this.registerDraggingHandler(isTouchEvent(event)); } // Complete last dragging sequence if a new target is dragged. if (this.currentDraggingSequence) { this.currentDraggingSequence.complete(); } this.currentStartingPoint = getPagePosition(event); this.currentDraggingSequence = new Subject(); return this.currentDraggingSequence.pipe(map((e) => ({ x: e.pageX - this.currentStartingPoint.x, y: e.pageY - this.currentStartingPoint.y })), filter((e) => Math.abs(e.x) > this.draggingThreshold || Math.abs(e.y) > this.draggingThreshold), finalize(() => this.teardownDraggingSequence())); } registerDraggingHandler(isTouch) { if (isTouch) { this.handleRegistry.add({ teardown: this.renderer.listen('document', 'touchmove', (e) => { if (this.currentDraggingSequence) { this.currentDraggingSequence.next(e.touches[0] || e.changedTouches[0]); } }) }); this.handleRegistry.add({ teardown: this.renderer.listen('document', 'touchend', () => { if (this.currentDraggingSequence) { this.currentDraggingSequence.complete(); } }) }); } else { this.handleRegistry.add({ teardown: this.renderer.listen('document', 'mousemove', e => { if (this.currentDraggingSequence) { this.currentDraggingSequence.next(e); } }) }); this.handleRegistry.add({ teardown: this.renderer.listen('document', 'mouseup', () => { if (this.currentDraggingSequence) { this.currentDraggingSequence.complete(); } }) }); } } teardownDraggingSequence() { this.currentDraggingSequence = null; } }
JavaScript
class RCTMesh extends RCTBaseView { /** * constructor: allocates the required resources and sets defaults */ constructor(guiSys) { super(); var geometry = undefined; var material = new THREE.MeshBasicMaterial({ wireframe: false, color: 'white', side: THREE.DoubleSide, }); this.mesh = undefined; this.view = new OVRUI.UIView(guiSys); Object.defineProperty(this.props, 'source', { set: (value) => { const prevMTLKey = this._mtlCacheKey; const prevOBJKey = this._objCacheKey; this._mtlCacheKey = null; this._objCacheKey = null; // text for the url, mtl and mesh case if (value.mtl && value.mesh) { // first load the material definition const mtlURL = extractURL(value.mtl); const meshURL = extractURL(value.mesh); this._mtlCacheKey = mtlURL; this._objCacheKey = meshURL; OBJLoader.load(meshURL, mtlURL, !!value.lit).then((mesh) => { if (this.mesh) { this.view.remove(this.mesh); } this.view.add(mesh); this.mesh = mesh; if (prevOBJKey || prevMTLKey) { OBJLoader.removeReferences(prevOBJKey, prevMTLKey); } }); } else if (value.texture && value.mesh) { // alternative load path, this is designed for UI interaction objects const textureURL = extractURL(value.texture); const meshURL = extractURL(value.mesh); const loader = new THREE.TextureLoader(); this._objCacheKey = meshURL; material.map = loader.load(textureURL, (texture) => { texture.wrapS = THREE.ClampToEdgeWrapping; texture.wrapT = THREE.ClampToEdgeWrapping; texture.minFilter = THREE.LinearFilter; }); OBJLoader.load(meshURL, material, !!value.lit).then((mesh) => { if (this.mesh) { this.view.remove(this.mesh); } this.view.add(mesh); this.mesh = mesh; if (prevOBJKey || prevMTLKey) { OBJLoader.removeReferences(prevOBJKey, prevMTLKey); } }); } }}); // setup a setter so that changes to the backgroundColor style alter the default material Object.defineProperty(this.style, 'backgroundColor', { set: (value) => { material.color.set(value); }, }); } dispose() { OBJLoader.removeReferences(this._objCacheKey, this._mtlCacheKey); super.dispose(); } /** * Describes the properies representable by this view type and merges * with super type */ static describe() { return merge(super.describe(), { // register the properties sent from react to runtime NativeProps: { source: 'object', } }); } }
JavaScript
class AccountServer { constructor() { this.accounts = {}; } initialize() { this.accounts = json.parse(json.read(db.user.configs.accounts)); } saveToDisk() { json.write(db.user.configs.accounts, this.accounts); } find(sessionID) { for (let accountId of Object.keys(this.accounts)) { let account = this.accounts[accountId]; if (account.id === sessionID) { return account; } } return undefined; } isWiped(sessionID) { return this.accounts[sessionID].wipe; } setWipe(sessionID, state) { this.accounts[sessionID].wipe = state; } exists(info) { for (let accountId of Object.keys(this.accounts)) { let account = this.accounts[accountId]; if (info.email === account.email) { if(info.password === account.password) { return account.id; } else { return 0; } } } return -1; } createAccount(info) { let sessionID = (Object.keys(this.accounts).length + 1).toString(); this.accounts[sessionID] = { id: Number(sessionID), nickname: "", email: info.email, password: info.password, wipe: true, edition: "eod" } this.saveToDisk(); return sessionID; } getReservedNickname(sessionID) { return this.accounts[sessionID].nickname; } findID(data) { let buff = Buffer.from(data.token, 'base64'); let text = buff.toString('ascii'); let info = json.parse(text); let sessionID = this.exists(info); if (sessionID == -1) { return this.createAccount(info); } else { return sessionID.toString(); } } }
JavaScript
class FakeSelectionObserver extends Observer { /** * Creates new FakeSelectionObserver instance. * * @param {module:engine/view/view~View} view */ constructor( view ) { super( view ); /** * Fires debounced event `selectionChangeDone`. It uses `lodash#debounce` method to delay function call. * * @private * @param {Object} data Selection change data. * @method #_fireSelectionChangeDoneDebounced */ this._fireSelectionChangeDoneDebounced = debounce( data => this.document.fire( 'selectionChangeDone', data ), 200 ); } /** * @inheritDoc */ observe() { const document = this.document; document.on( 'keydown', ( eventInfo, data ) => { const selection = document.selection; if ( selection.isFake && _isArrowKeyCode( data.keyCode ) && this.isEnabled ) { // Prevents default key down handling - no selection change will occur. data.preventDefault(); this._handleSelectionMove( data.keyCode ); } }, { priority: 'lowest' } ); } /** * @inheritDoc */ destroy() { super.destroy(); this._fireSelectionChangeDoneDebounced.cancel(); } /** * Handles collapsing view selection according to given key code. If left or up key is provided - new selection will be * collapsed to left. If right or down key is pressed - new selection will be collapsed to right. * * This method fires {@link module:engine/view/document~Document#event:selectionChange} and * {@link module:engine/view/document~Document#event:selectionChangeDone} events imitating behaviour of * {@link module:engine/view/observer/selectionobserver~SelectionObserver}. * * @private * @param {Number} keyCode * @fires module:engine/view/document~Document#event:selectionChange * @fires module:engine/view/document~Document#event:selectionChangeDone */ _handleSelectionMove( keyCode ) { const selection = this.document.selection; const newSelection = new ViewSelection( selection.getRanges(), { backward: selection.isBackward, fake: false } ); // Left or up arrow pressed - move selection to start. if ( keyCode == keyCodes.arrowleft || keyCode == keyCodes.arrowup ) { newSelection.setTo( newSelection.getFirstPosition() ); } // Right or down arrow pressed - move selection to end. if ( keyCode == keyCodes.arrowright || keyCode == keyCodes.arrowdown ) { newSelection.setTo( newSelection.getLastPosition() ); } const data = { oldSelection: selection, newSelection, domSelection: null }; // Fire dummy selection change event. this.document.fire( 'selectionChange', data ); // Call` #_fireSelectionChangeDoneDebounced` every time when `selectionChange` event is fired. // This function is debounced what means that `selectionChangeDone` event will be fired only when // defined int the function time will elapse since the last time the function was called. // So `selectionChangeDone` will be fired when selection will stop changing. this._fireSelectionChangeDoneDebounced( data ); } }
JavaScript
class Server { constructor(perspective) { this.perspective = perspective; this._tables = {}; this._views = {}; this._callback_cache = new Map(); } /** * `Server` must be extended and the `post` method implemented before it can be initialized. */ init(msg) { this.post(msg); } post() { throw new Error("post() not implemented!"); } /** * Garbage collect un-needed views. */ clear_views(client_id) { for (let key of Object.keys(this._views)) { if (this._views[key].client_id === client_id) { try { this._views[key].delete(); } catch (e) { console.error(e); } delete this._views[key]; } } console.debug(`GC ${Object.keys(this._views).length} views in memory`); } /** * Given a message, execute its instructions. This method is the dispatcher for all Perspective actions, * including table/view creation, deletion, and all method calls to/from the table and view. * * @param {*} msg an Object containing `cmd` (a String instruction) and associated data for that instruction * @param {*} client_id */ process(msg, client_id) { switch (msg.cmd) { case "init_profile_thread": this.perspective.initialize_profile_thread(); break; case "init": this.init(msg); break; case "table": if (typeof msg.args[0] === "undefined") { this._tables[msg.name] = []; } else { const msgs = this._tables[msg.name]; this._tables[msg.name] = this.perspective.table(msg.args[0], msg.options); if (msgs) { for (const msg of msgs) { this.process(msg); } } } break; case "add_computed": let table = this._tables[msg.original]; let computed = msg.computed; // rehydrate computed column functions for (let i = 0; i < computed.length; ++i) { let column = computed[i]; eval("column.func = " + column.func); } this._tables[msg.name] = table.add_computed(computed); break; case "table_generate": let g; eval("g = " + msg.args); g(function(tbl) { this._tables[msg.name] = tbl; this.post({ id: msg.id, data: "created!" }); }); break; case "table_execute": let f; eval("f = " + msg.f); f(this._tables[msg.name]); break; case "table_method": case "view_method": this.process_method_call(msg); break; case "view": // create a new view and track it with `client_id` this._views[msg.view_name] = this._tables[msg.table_name].view(msg.config); this._views[msg.view_name].client_id = client_id; break; } } /** * Send an error to the client. */ process_error(msg, error) { this.post({ id: msg.id, error: error_to_json(error) }); } /** * Execute a subscription to a Perspective event. */ process_subscribe(msg, obj) { try { let callback; if (msg.method.slice(0, 2) === "on") { callback = ev => { let result = { id: msg.id, data: ev }; try { // post transferable data for arrow if (msg.args && msg.args[0]) { if (msg.method === "on_update" && msg.args[0]["mode"] === "row") { this.post(result, [ev]); return; } } this.post(result); } catch (e) { console.error("Removing callback after failed on_update() (presumably due to closed connection)"); obj["remove_update"](callback); } }; if (msg.callback_id) { this._callback_cache.set(msg.callback_id, callback); } } else if (msg.callback_id) { callback = this._callback_cache.get(msg.callback_id); this._callback_cache.delete(msg.callback_id); } if (callback) { obj[msg.method](callback, ...msg.args); } else { console.error(`Callback not found for remote call "${msg}"`); } } catch (error) { this.process_error(msg, error); return; } } process_method_call_response(msg, result) { if (msg.method === "delete") { delete this._views[msg.name]; } if (msg.method === "to_arrow") { this.post( { id: msg.id, data: result }, [result] ); } else { this.post({ id: msg.id, data: result }); } } /** * Given a call to a table or view method, process it. * * @param {Object} msg */ process_method_call(msg) { let obj, result; msg.cmd === "table_method" ? (obj = this._tables[msg.name]) : (obj = this._views[msg.name]); if (!obj && msg.cmd === "view_method") { // cannot have a host without a table, but can have a host without a view this.process_error(msg, {message: "View is not initialized"}); return; } if (obj && obj.push) { obj.push(msg); return; } try { if (msg.subscribe) { this.process_subscribe(msg, obj); return; } else { result = obj[msg.method].apply(obj, msg.args); if (result instanceof Promise) { result.then(result => this.process_method_call_response(msg, result)).catch(error => this.process_error(msg, error)); } else { this.process_method_call_response(msg, result); } } } catch (error) { this.process_error(msg, error); return; } } }
JavaScript
class MetricSpecification { /** * Create a MetricSpecification. * @member {string} [name] Name of metric specification. * @member {string} [displayName] Display name of metric specification. * @member {string} [displayDescription] Display description of metric * specification. * @member {string} [unit] Unit could be Bytes or Count. * @member {array} [dimensions] Dimensions of blobs, including blob type and * access tier. * @member {string} [aggregationType] Aggregation type could be Average. * @member {boolean} [fillGapWithZero] The property to decide fill gap with * zero or not. * @member {string} [category] The category this metric specification belong * to, could be Capacity. * @member {string} [resourceIdDimensionNameOverride] Account Resource Id. */ constructor() { } /** * Defines the metadata of MetricSpecification * * @returns {object} metadata of MetricSpecification * */ mapper() { return { required: false, serializedName: 'MetricSpecification', type: { name: 'Composite', className: 'MetricSpecification', modelProperties: { name: { required: false, serializedName: 'name', type: { name: 'String' } }, displayName: { required: false, serializedName: 'displayName', type: { name: 'String' } }, displayDescription: { required: false, serializedName: 'displayDescription', type: { name: 'String' } }, unit: { required: false, serializedName: 'unit', type: { name: 'String' } }, dimensions: { required: false, serializedName: 'dimensions', type: { name: 'Sequence', element: { required: false, serializedName: 'DimensionElementType', type: { name: 'Composite', className: 'Dimension' } } } }, aggregationType: { required: false, serializedName: 'aggregationType', type: { name: 'String' } }, fillGapWithZero: { required: false, serializedName: 'fillGapWithZero', type: { name: 'Boolean' } }, category: { required: false, serializedName: 'category', type: { name: 'String' } }, resourceIdDimensionNameOverride: { required: false, serializedName: 'resourceIdDimensionNameOverride', type: { name: 'String' } } } } }; } }
JavaScript
class Compiler { constructor(resolve, meta, appConfigs, scheduler) { this.current = meta.current; this.resolve = resolve; this.meta = meta; this.appConfigs = appConfigs; this.$scheduer = scheduler; } destroy() { this.appConfigs = null; this.$scheduer = null; } async parse(mdl) { debug('module to parse %O', mdl); let children = []; let content = mdl.code; // generate empty string is allowed. content = content == null ? mdl.content || readFile(mdl.src) : content; let type = path.extname(mdl.meta.source); type = type.replace(/^\.*/, ''); const options = { 'js': jsOptions, }; let {kind, ...rest} = await this.$parse(content, options[type], mdl.meta.source, type, mdl); debug('kind %s, rest %o', kind, rest); mdl.kind = kind; switch (kind) { case 'wxa': { mdl.rst = rest.wxa; // app.wxa do not have template to compile. if (mdl.category && mdl.category.toUpperCase() === 'APP') delete mdl.rst.template; children = children.concat(this.$$parseRST(mdl)); break; } case 'xml': { mdl.xml = rest.xml; children = children.concat(this.$$parseXML(mdl)); break; } case 'js': { // only allow babel-ast mdl.ast = rest.ast; children = children.concat(this.$$parseAST(mdl)); break; } case 'css': { mdl.css = rest.css; children = children.concat(this.$$parseCSS(mdl)); break; } case 'json': { mdl.json = rest.json; children = children.concat(this.$$parseJSON(mdl)); break; } } return children; } $parse(code, configs={}, filepath, type, mdl) { switch (type) { case 'wxa': { mdl.isAbstract = true; return new WxaCompiler(this.resolve, this.meta).parse(filepath, code); } case 'js': { return new ScriptCompiler().parse(filepath, code, configs); } case 'css': case 'wxss': { return Promise.resolve({css: code, kind: 'css'}); } case 'wxml': { return new XmlCompiler().parse(filepath, code); } case 'json': case 'config': { return new ConfigCompiler().parse(filepath, code); } case 'png': case 'jpg': case 'jpeg': case 'webp': case 'eot': case 'woff': case 'woff2': case 'ttf': case 'file': { // just copy. mdl.isFile = true; return Promise.resolve({kind: 'file'}); } default: { // unknown type, can be define by other compiler. return Promise.resolve({kind: mdl.sourceType || 'other'}); } } } $$parseRST(mdl) { // spread mdl with child nodes return Object.keys(mdl.rst).map((key)=>{ let dep = Object.assign({}, mdl.rst[key]); // wxa file pret object should as same as his parent node. dep.content = mdl.rst[key].code; dep.pret = mdl.pret || defaultPret; dep.category = mdl.category || ''; dep.pagePath = mdl.pagePath || void(0); return dep; }); } $$parseAST(mdl) { let deps = new ASTManager(this.resolve||{}, this.meta).parse(mdl); // analysis deps; return deps; } $$parseXML(mdl) { let deps = new XMLManager(this.resolve||{}, this.meta).parse(mdl); debug('xml dependencies %o', deps); // analysis deps; return deps; } $$parseCSS(mdl) { let deps = new CSSManager(this.resolve || {}, this.meta).parse(mdl); debug('css dependencies %o', deps); return deps; } $$parseJSON(mdl) { let children = []; let category = mdl.category ? mdl.category.toLowerCase() : ''; // normal json file or empty json file doesn't need to be resolved. if ( ~['app', 'component', 'page'].indexOf(category) ) { // Page or Component resolve children = new ComponentManager(this.resolve, this.meta, this.appConfigs).parse(mdl); } if (mdl.src === this.$scheduer.APP_CONFIG_PATH) { this.$scheduer.appConfigs = Object.assign({}, mdl.json); // global components in wxa; // delete custom field in app.json or wechat devtool will get wrong. delete mdl.json['wxa.globalComponents']; } mdl.code = JSON.stringify(mdl.json, void(0), 4); return children; } }
JavaScript
class ReactiveElement extends HTMLElement { constructor() { super(); this.__instanceProperties = new Map(); this.__pendingConnectionPromise = undefined; this.__enableConnection = undefined; /** * @category updates */ this.isUpdatePending = false; /** * @category updates */ this.hasUpdated = false; /** * Name of currently reflecting property */ this.__reflectingProperty = null; this._initialize(); } /** * @nocollapse */ static addInitializer(initializer) { var _a; (_a = this._initializers) !== null && _a !== void 0 ? _a : (this._initializers = []); this._initializers.push(initializer); } /** * Returns a list of attributes corresponding to the registered properties. * @nocollapse * @category attributes */ static get observedAttributes() { // note: piggy backing on this to ensure we're finalized. this.finalize(); const attributes = []; // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this.elementProperties.forEach((v, p) => { const attr = this.__attributeNameForProperty(p, v); if (attr !== undefined) { this.__attributeToPropertyMap.set(attr, p); attributes.push(attr); } }); return attributes; } /** * Creates a property accessor on the element prototype if one does not exist * and stores a PropertyDeclaration for the property with the given options. * The property setter calls the property's `hasChanged` property option * or uses a strict identity check to determine whether or not to request * an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * * @nocollapse * @category properties */ static createProperty(name, options = defaultPropertyDeclaration) { // if this is a state property, force the attribute to false. if (options.state) { // Cast as any since this is readonly. // eslint-disable-next-line @typescript-eslint/no-explicit-any options.attribute = false; } // Note, since this can be called by the `@property` decorator which // is called before `finalize`, we ensure finalization has been kicked off. this.finalize(); this.elementProperties.set(name, options); // Do not generate an accessor if the prototype already has one, since // it would be lost otherwise and that would never be the user's intention; // Instead, we expect users to call `requestUpdate` themselves from // user-defined accessors. Note that if the super has an accessor we will // still overwrite it if (!options.noAccessor && !this.prototype.hasOwnProperty(name)) { const key = typeof name === 'symbol' ? Symbol() : `__${name}`; const descriptor = this.getPropertyDescriptor(name, key, options); if (descriptor !== undefined) { Object.defineProperty(this.prototype, name, descriptor); } } } /** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * * @nocollapse * @category properties */ static getPropertyDescriptor(name, key, options) { return { // eslint-disable-next-line @typescript-eslint/no-explicit-any get() { return this[key]; }, set(value) { const oldValue = this[name]; this[key] = value; this.requestUpdate(name, oldValue, options); }, configurable: true, enumerable: true, }; } /** * Returns the property options associated with the given property. * These options are defined with a PropertyDeclaration via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override `createProperty`. * * @nocollapse * @final * @category properties */ static getPropertyOptions(name) { return this.elementProperties.get(name) || defaultPropertyDeclaration; } /** * Creates property accessors for registered properties, sets up element * styling, and ensures any superclasses are also finalized. Returns true if * the element was finalized. * @nocollapse */ static finalize() { if (this.hasOwnProperty(finalized)) { return false; } this[finalized] = true; // finalize any superclasses const superCtor = Object.getPrototypeOf(this); superCtor.finalize(); this.elementProperties = new Map(superCtor.elementProperties); // initialize Map populated in observedAttributes this.__attributeToPropertyMap = new Map(); // make any properties // Note, only process "own" properties since this element will inherit // any properties defined on the superClass, and finalization ensures // the entire prototype chain is finalized. if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) { const props = this.properties; // support symbols in properties (IE11 does not support this) const propKeys = [ ...Object.getOwnPropertyNames(props), ...Object.getOwnPropertySymbols(props), ]; // This for/of is ok because propKeys is an array for (const p of propKeys) { // note, use of `any` is due to TypeScript lack of support for symbol in // index types // eslint-disable-next-line @typescript-eslint/no-explicit-any this.createProperty(p, props[p]); } } this.elementStyles = this.finalizeStyles(this.styles); // DEV mode warnings if (DEV_MODE) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const warnRemoved = (obj, name) => { if (obj[name] !== undefined) { console.warn(`\`${name}\` is implemented. It ` + `has been removed from this version of ReactiveElement.` + ` See the changelog at https://github.com/lit/lit/blob/main/packages/reactive-element/CHANGELOG.md`); } }; [`initialize`, `requestUpdateInternal`, `_getUpdateComplete`].forEach((name) => // eslint-disable-next-line @typescript-eslint/no-explicit-any warnRemoved(this.prototype, name)); } return true; } /** * Takes the styles the user supplied via the `static styles` property and * returns the array of styles to apply to the element. * Override this method to integrate into a style management system. * * Styles are deduplicated preserving the _last_ instance in the list. This * is a performance optimization to avoid duplicated styles that can occur * especially when composing via subclassing. The last item is kept to try * to preserve the cascade order with the assumption that it's most important * that last added styles override previous styles. * * @nocollapse * @category styles */ static finalizeStyles(styles) { const elementStyles = []; if (Array.isArray(styles)) { // Dedupe the flattened array in reverse order to preserve the last items. // TODO(sorvell): casting to Array<unknown> works around TS error that // appears to come from trying to flatten a type CSSResultArray. const set = new Set(styles.flat(Infinity).reverse()); // Then preserve original order by adding the set items in reverse order. for (const s of set) { elementStyles.unshift((0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.getCompatibleStyle)(s)); } } else if (styles !== undefined) { elementStyles.push((0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.getCompatibleStyle)(styles)); } return elementStyles; } /** * Returns the property name for the given attribute `name`. * @nocollapse */ static __attributeNameForProperty(name, options) { const attribute = options.attribute; return attribute === false ? undefined : typeof attribute === 'string' ? attribute : typeof name === 'string' ? name.toLowerCase() : undefined; } /** * Internal only override point for customizing work done when elements * are constructed. * * @internal */ _initialize() { var _a; this.__updatePromise = new Promise((res) => (this.enableUpdating = res)); this._$changedProperties = new Map(); this.__saveInstanceProperties(); // ensures first update will be caught by an early access of // `updateComplete` this.requestUpdate(); (_a = this.constructor._initializers) === null || _a === void 0 ? void 0 : _a.forEach((i) => i(this)); } /** * @category controllers */ addController(controller) { var _a, _b; ((_a = this.__controllers) !== null && _a !== void 0 ? _a : (this.__controllers = [])).push(controller); // If a controller is added after the element has been connected, // call hostConnected. Note, re-using existence of `renderRoot` here // (which is set in connectedCallback) to avoid the need to track a // first connected state. if (this.renderRoot !== undefined && this.isConnected) { (_b = controller.hostConnected) === null || _b === void 0 ? void 0 : _b.call(controller); } } /** * @category controllers */ removeController(controller) { var _a; // Note, if the indexOf is -1, the >>> will flip the sign which makes the // splice do nothing. (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.splice(this.__controllers.indexOf(controller) >>> 0, 1); } /** * Fixes any properties set on the instance before upgrade time. * Otherwise these would shadow the accessor and break these properties. * The properties are stored in a Map which is played back after the * constructor runs. Note, on very old versions of Safari (<=9) or Chrome * (<=41), properties created for native platform properties like (`id` or * `name`) may not have default values set in the element constructor. On * these browsers native properties appear on instances and therefore their * default value will overwrite any element default (e.g. if the element sets * this.id = 'id' in the constructor, the 'id' will become '' since this is * the native platform default). */ __saveInstanceProperties() { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays this.constructor.elementProperties.forEach((_v, p) => { if (this.hasOwnProperty(p)) { this.__instanceProperties.set(p, this[p]); delete this[p]; } }); } /** * Returns the node into which the element should render and by default * creates and returns an open shadowRoot. Implement to customize where the * element's DOM is rendered. For example, to render into the element's * childNodes, return `this`. * * @return Returns a node into which to render. * @category rendering */ createRenderRoot() { var _a; const renderRoot = (_a = this.shadowRoot) !== null && _a !== void 0 ? _a : this.attachShadow(this.constructor.shadowRootOptions); (0,_css_tag_js__WEBPACK_IMPORTED_MODULE_0__.adoptStyles)(renderRoot, this.constructor.elementStyles); return renderRoot; } /** * On first connection, creates the element's renderRoot, sets up * element styling, and enables updating. * @category lifecycle */ connectedCallback() { var _a; // create renderRoot before first update. if (this.renderRoot === undefined) { this.renderRoot = this.createRenderRoot(); } this.enableUpdating(true); (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostConnected) === null || _a === void 0 ? void 0 : _a.call(c); }); // If we were disconnected, re-enable updating by resolving the pending // connection promise if (this.__enableConnection) { this.__enableConnection(); this.__pendingConnectionPromise = this.__enableConnection = undefined; } } /** * Note, this method should be considered final and not overridden. It is * overridden on the element instance with a function that triggers the first * update. * @category updates */ enableUpdating(_requestedUpdate) { } /** * Allows for `super.disconnectedCallback()` in extensions while * reserving the possibility of making non-breaking feature additions * when disconnecting at some point in the future. * @category lifecycle */ disconnectedCallback() { var _a; (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostDisconnected) === null || _a === void 0 ? void 0 : _a.call(c); }); this.__pendingConnectionPromise = new Promise((r) => (this.__enableConnection = r)); } /** * Synchronizes property values when attributes change. * @category attributes */ attributeChangedCallback(name, _old, value) { this._$attributeToProperty(name, value); } __propertyToAttribute(name, value, options = defaultPropertyDeclaration) { var _a, _b; const attr = this .constructor.__attributeNameForProperty(name, options); if (attr !== undefined && options.reflect === true) { const toAttribute = (_b = (_a = options.converter) === null || _a === void 0 ? void 0 : _a.toAttribute) !== null && _b !== void 0 ? _b : defaultConverter.toAttribute; const attrValue = toAttribute(value, options.type); if (DEV_MODE && this.constructor.enabledWarnings.indexOf('migration') >= 0 && attrValue === undefined) { console.warn(`The attribute value for the ` + `${name} property is undefined. The attribute will be ` + `removed, but in the previous version of ReactiveElement, the ` + `attribute would not have changed.`); } // Track if the property is being reflected to avoid // setting the property again via `attributeChangedCallback`. Note: // 1. this takes advantage of the fact that the callback is synchronous. // 2. will behave incorrectly if multiple attributes are in the reaction // stack at time of calling. However, since we process attributes // in `update` this should not be possible (or an extreme corner case // that we'd like to discover). // mark state reflecting this.__reflectingProperty = name; if (attrValue == null) { this.removeAttribute(attr); } else { this.setAttribute(attr, attrValue); } // mark state not reflecting this.__reflectingProperty = null; } } /** @internal */ _$attributeToProperty(name, value) { var _a, _b, _c; const ctor = this.constructor; // Note, hint this as an `AttributeMap` so closure clearly understands // the type; it has issues with tracking types through statics const propName = ctor.__attributeToPropertyMap.get(name); // Use tracking info to avoid reflecting a property value to an attribute // if it was just set because the attribute changed. if (propName !== undefined && this.__reflectingProperty !== propName) { const options = ctor.getPropertyOptions(propName); const converter = options.converter; const fromAttribute = (_c = (_b = (_a = converter) === null || _a === void 0 ? void 0 : _a.fromAttribute) !== null && _b !== void 0 ? _b : (typeof converter === 'function' ? converter : null)) !== null && _c !== void 0 ? _c : defaultConverter.fromAttribute; // mark state reflecting this.__reflectingProperty = propName; // eslint-disable-next-line @typescript-eslint/no-explicit-any this[propName] = fromAttribute(value, options.type); // mark state not reflecting this.__reflectingProperty = null; } } /** * Requests an update which is processed asynchronously. This should be called * when an element should update based on some state not triggered by setting * a reactive property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. * * @param name name of requesting property * @param oldValue old value of requesting property * @param options property options to use instead of the previously * configured options * @category updates */ requestUpdate(name, oldValue, options) { let shouldRequestUpdate = true; // If we have a property key, perform property update steps. if (name !== undefined) { options = options || this.constructor.getPropertyOptions(name); const hasChanged = options.hasChanged || notEqual; if (hasChanged(this[name], oldValue)) { if (!this._$changedProperties.has(name)) { this._$changedProperties.set(name, oldValue); } // Add to reflecting properties set. // Note, it's important that every change has a chance to add the // property to `_reflectingProperties`. This ensures setting // attribute + property reflects correctly. if (options.reflect === true && this.__reflectingProperty !== name) { if (this.__reflectingProperties === undefined) { this.__reflectingProperties = new Map(); } this.__reflectingProperties.set(name, options); } } else { // Abort the request if the property should not be considered changed. shouldRequestUpdate = false; } } if (!this.isUpdatePending && shouldRequestUpdate) { this.__updatePromise = this.__enqueueUpdate(); } // Note, since this no longer returns a promise, in dev mode we return a // thenable which warns if it's called. return DEV_MODE ? requestUpdateThenable : undefined; } /** * Sets up the element to asynchronously update. */ async __enqueueUpdate() { this.isUpdatePending = true; try { // Ensure any previous update has resolved before updating. // This `await` also ensures that property changes are batched. await this.__updatePromise; // If we were disconnected, wait until re-connected to flush an update while (this.__pendingConnectionPromise) { await this.__pendingConnectionPromise; } } catch (e) { // Refire any previous errors async so they do not disrupt the update // cycle. Errors are refired so developers have a chance to observe // them, and this can be done by implementing // `window.onunhandledrejection`. Promise.reject(e); } const result = this.performUpdate(); // If `performUpdate` returns a Promise, we await it. This is done to // enable coordinating updates with a scheduler. Note, the result is // checked to avoid delaying an additional microtask unless we need to. if (result != null) { await result; } return !this.isUpdatePending; } /** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * You can override this method to change the timing of updates. If this * method is overridden, `super.performUpdate()` must be called. * * For instance, to schedule updates to occur just before the next frame: * * ``` * protected async performUpdate(): Promise<unknown> { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.performUpdate(); * } * ``` * @category updates */ performUpdate() { var _a; // Abort any update if one is not pending when this is called. // This can happen if `performUpdate` is called early to "flush" // the update. if (!this.isUpdatePending) { return; } // create renderRoot before first update. if (!this.hasUpdated) { // Produce warning if any class properties are shadowed by class fields if (DEV_MODE) { const shadowedProperties = []; this.constructor.elementProperties.forEach((_v, p) => { var _a; if (this.hasOwnProperty(p) && !((_a = this.__instanceProperties) === null || _a === void 0 ? void 0 : _a.has(p))) { shadowedProperties.push(p); } }); if (shadowedProperties.length) { // TODO(sorvell): Link to docs explanation of this issue. console.warn(`The following properties will not trigger updates as expected ` + `because they are set using class fields: ` + `${shadowedProperties.join(', ')}. ` + `Native class fields and some compiled output will overwrite ` + `accessors used for detecting changes. To fix this issue, ` + `either initialize properties in the constructor or adjust ` + `your compiler settings; for example, for TypeScript set ` + `\`useDefineForClassFields: false\` in your \`tsconfig.json\`.`); } } } // Mixin instance properties once, if they exist. if (this.__instanceProperties) { // Use forEach so this works even if for/of loops are compiled to for loops // expecting arrays // eslint-disable-next-line @typescript-eslint/no-explicit-any this.__instanceProperties.forEach((v, p) => (this[p] = v)); this.__instanceProperties = undefined; } let shouldUpdate = false; const changedProperties = this._$changedProperties; try { shouldUpdate = this.shouldUpdate(changedProperties); if (shouldUpdate) { this.willUpdate(changedProperties); (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostUpdate) === null || _a === void 0 ? void 0 : _a.call(c); }); this.update(changedProperties); } else { this.__markUpdated(); } } catch (e) { // Prevent `firstUpdated` and `updated` from running when there's an // update exception. shouldUpdate = false; // Ensure element can accept additional updates after an exception. this.__markUpdated(); throw e; } // The update is no longer considered pending and further updates are now allowed. if (shouldUpdate) { this._$didUpdate(changedProperties); } } /** * @category updates */ willUpdate(_changedProperties) { } // Note, this is an override point for polyfill-support. // @internal _$didUpdate(changedProperties) { var _a; (_a = this.__controllers) === null || _a === void 0 ? void 0 : _a.forEach((c) => { var _a; return (_a = c.hostUpdated) === null || _a === void 0 ? void 0 : _a.call(c); }); if (!this.hasUpdated) { this.hasUpdated = true; this.firstUpdated(changedProperties); } this.updated(changedProperties); if (DEV_MODE && this.isUpdatePending && this.constructor.enabledWarnings.indexOf('change-in-update') >= 0) { console.warn(`An update was requested (generally because a property was set) ` + `after an update completed, causing a new update to be scheduled. ` + `This is inefficient and should be avoided unless the next update ` + `can only be scheduled as a side effect of the previous update.`); } } __markUpdated() { this._$changedProperties = new Map(); this.isUpdatePending = false; } /** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super.getUpdateComplete()`, then any subsequent state. * * @return A promise of a boolean that indicates if the update resolved * without triggering another update. * @category updates */ get updateComplete() { return this.getUpdateComplete(); } /** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * class MyElement extends LitElement { * async getUpdateComplete() { * await super.getUpdateComplete(); * await this._myChild.updateComplete; * } * } * @category updates */ getUpdateComplete() { return this.__updatePromise; } /** * Controls whether or not `update` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values * @category updates */ shouldUpdate(_changedProperties) { return true; } /** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values * @category updates */ update(_changedProperties) { if (this.__reflectingProperties !== undefined) { // Use forEach so this works even if for/of loops are compiled to for // loops expecting arrays this.__reflectingProperties.forEach((v, k) => this.__propertyToAttribute(k, this[k], v)); this.__reflectingProperties = undefined; } this.__markUpdated(); } /** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ updated(_changedProperties) { } /** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ firstUpdated(_changedProperties) { } }
JavaScript
class LitElement extends _lit_reactive_element__WEBPACK_IMPORTED_MODULE_0__.ReactiveElement { constructor() { super(...arguments); /** * @category rendering */ this.renderOptions = { host: this }; this.__childPart = undefined; } /** * @category rendering */ createRenderRoot() { var _a; var _b; const renderRoot = super.createRenderRoot(); // When adoptedStyleSheets are shimmed, they are inserted into the // shadowRoot by createRenderRoot. Adjust the renderBefore node so that // any styles in Lit content render before adoptedStyleSheets. This is // important so that adoptedStyleSheets have precedence over styles in // the shadowRoot. (_a = (_b = this.renderOptions).renderBefore) !== null && _a !== void 0 ? _a : (_b.renderBefore = renderRoot.firstChild); return renderRoot; } /** * Updates the element. This method reflects property values to attributes * and calls `render` to render DOM via lit-html. Setting properties inside * this method will *not* trigger another update. * @param changedProperties Map of changed properties with old values * @category updates */ update(changedProperties) { // Setting properties in `render` should not trigger an update. Since // updates are allowed after super.update, it's important to call `render` // before that. const value = this.render(); super.update(changedProperties); this.__childPart = (0,lit_html__WEBPACK_IMPORTED_MODULE_1__.render)(value, this.renderRoot, this.renderOptions); } // TODO(kschaaf): Consider debouncing directive disconnection so element moves // do not thrash directive callbacks // https://github.com/lit/lit/issues/1457 /** * @category lifecycle */ connectedCallback() { var _a; super.connectedCallback(); (_a = this.__childPart) === null || _a === void 0 ? void 0 : _a.setConnected(true); } /** * @category lifecycle */ disconnectedCallback() { var _a; super.disconnectedCallback(); (_a = this.__childPart) === null || _a === void 0 ? void 0 : _a.setConnected(false); } /** * Invoked on each update to perform rendering tasks. This method may return * any value renderable by lit-html's `ChildPart` - typically a * `TemplateResult`. Setting properties inside this method will *not* trigger * the element to update. * @category rendering */ render() { return lit_html__WEBPACK_IMPORTED_MODULE_1__.noChange; } }
JavaScript
class TemplateInstance { constructor(template, parent) { /** @internal */ this._parts = []; /** @internal */ this._$disconnectableChildren = undefined; this._$template = template; this._$parent = parent; } // This method is separate from the constructor because we need to return a // DocumentFragment and we don't want to hold onto it with an instance field. _clone(options) { var _a; const { el: { content }, parts: parts, } = this._$template; const fragment = ((_a = options === null || options === void 0 ? void 0 : options.creationScope) !== null && _a !== void 0 ? _a : d).importNode(content, true); walker.currentNode = fragment; let node = walker.nextNode(); let nodeIndex = 0; let partIndex = 0; let templatePart = parts[0]; while (templatePart !== undefined) { if (nodeIndex === templatePart.index) { let part; if (templatePart.type === CHILD_PART) { part = new ChildPart(node, node.nextSibling, this, options); } else if (templatePart.type === ATTRIBUTE_PART) { part = new templatePart.ctor(node, templatePart.name, templatePart.strings, this, options); } else if (templatePart.type === ELEMENT_PART) { part = new ElementPart(node, this, options); } this._parts.push(part); templatePart = parts[++partIndex]; } if (nodeIndex !== (templatePart === null || templatePart === void 0 ? void 0 : templatePart.index)) { node = walker.nextNode(); nodeIndex++; } } return fragment; } _update(values) { let i = 0; for (const part of this._parts) { if (part !== undefined) { if (part.strings !== undefined) { part._$setValue(values, part, i); // The number of values the part consumes is part.strings.length - 1 // since values are in between template spans. We increment i by 1 // later in the loop, so increment it by part.strings.length - 2 here i += part.strings.length - 2; } else { part._$setValue(values[i]); } } i++; } } }
JavaScript
class Task { /** * Id of the task * @type {number} * @memberof Task */ Id /** * The name of the task * @type {string} * @memberof Task */ TaskName /** * The FQND or Hostname of the Server hosting the task * @type {string} * @memberof Task */ Server /** * The start time of the task in minutes since midnight * @type {number} * @memberof Task */ StartTime /** * The end time of the task in minutes since midnight * @type {number | undefined} * @memberof Task */ EndTime /** * The interval in minutes in which the task will be repeated * @type {number} * @memberof Task */ Interval /** * True indicates the task also runs in the weekend * @type {boolean} * @memberof Task */ Weekend /** * The normal duration in minutes of the task * @type {number} * @memberof Task */ NormalDuration /** * Discord ID of persons responible for this task * @type {string} * @memberof Task */ Responsible /** * Status of the task * -1 = DISABLED * 0 = NEW * 1 = RUNNING * 2 = OK * 3 = FAILED * 4 = FAILED NOTIF SEND * @type {-1 | 0 | 1 | 2 | 3 | 4} * @memberof Task */ Status /** * Last time the task has been executed * @type {Date | undefined} * @memberof Task */ LastRun /** * Last time the task has completed execution sucessfully * @type {Date | undefined} * @memberof Task */ LastSuccess /** * Command the task has executed * @type {string} * @memberof Task */ Command }
JavaScript
class Socket { constructor ( socketFactory, roomEvents ) { "ngInject"; Object.assign(this, { socketFactory, roomEvents }); } sit(options) { let {placeId, success, failure} = options; options.emit = { eventName: this.roomEvents.reqTakePlace, data: { placeId: placeId } }; options.events = [ { eventName: this.roomEvents.resTakePlaceSuccess, callback: data => { success(data); success = null; failure = null; // this.listenAskForStart(); } }, { eventName: this.roomEvents.resTakePlaceFailure, callback: data => { failure(data); success = null; failure = null; // this.listenAskForStart(); } } ]; this.socketFactory.emitHandler(options); } }
JavaScript
class VerifierCodelab extends VerifierBase { /** * @param {Object} data - data to be used for execution of verification. * @param {Array} [data.input] - An array that contains environment * variable key value pairs. */ async _runVerification (data) { const result = await this._createVerifyProcess(data) return result } static verifyTargetFilePath (targetDef, filename) { if (!_.isString(filename)) { const message = 'target file definition must have a String property "file"' throw new VerifierConfigError(message) } const targetFileNamePath = join(targetDef.global.appDirectory, filename) const makefilestat = statSync(targetFileNamePath) if (!makefilestat.isFile()) { const message = 'specified tempMakefile in target definition is not found' throw new VerifierConfigError(message) } return targetFileNamePath } /** NOTE: Using Sync functions is only allowed within verifyTargetDef * Function is called before the Codelab verification actually takes place. */ static verifyTargetDef (targetDef) { super.verifyTargetDef(targetDef) super.verifyLanguageDef(targetDef) } /** Creates temporary directory for the workshop user. **/ async _prepareUserTempDir () { try { this.tempDir = join(this.targetDef.global.tempDirectory, `temp/${this.username}/`) await ensureDir(this.tempDir) logger.debug(`Created directory ${this.tempDir}`) } catch (e) { logger.debug('Internal Error : Failed to create a temporary directory. Please try again') throw e } } /** Grabs filelist that author provided in book.json and copies every file into temporary directory * made for user. * @param tempDir * @returns {Promise<void>} * @private */ async _copyCodelabResources (tempDir) { let i try { for (i = 0; i < this.targetDef.files.length; i++) { const newFilePath = join(tempDir, this.targetDef.files[i]) const filePath = VerifierCodelab.verifyTargetFilePath(this.targetDef, this.targetDef.files[i]) await copy(filePath, newFilePath) logger.debug(`Copied ${this.targetDef.files[i]}.`) } const currFiles = await readdir(tempDir) logger.debug(`Files now available in temp user dir: ${currFiles}`) } catch (e) { logger.debug('An error occurred while copying files') throw e } } /** Creates a file into temporary directory made with the code that user wrote into workshop * text editor UI. * @param inputData * @returns {Promise<void>} * @private */ async _createUserDataFile (inputData) { try { const userInputFile = join(this.tempDir, this.targetDef.userInputFile) await writeFile(userInputFile, inputData) logger.debug('Added user input file into directory.') } catch (e) { logger.debug('Error occurred when saving code into file') throw e } } /** Executes command provided by author in book.json in the user directory created. * Returns standard output and error. */ async _runCodelab () { const cmdOptions = { cwd: this.tempDir, timeout: this.targetDef.timeout, stdio: 'inherit' } logger.debug(cmdOptions) const command = this.targetDef.command logger.debug(command) const debugMessage = `Creating a child process for verifier target "${this.targetDef.name}"` logger.debug({ message: debugMessage, command: command, option: cmdOptions }) let error = null let stdout = '' let stderr = '' try { const result = await exec(command, cmdOptions) stdout = result.stdout stderr = result.stderr } catch (err) { if (err && _.isObject(err) && err.killed) { const message = `Timeout Error, message: ${err.message}` error = new VerifierTimeoutError(message) } else if (err && !err.stderr) { const message = `Unexpected Error, message: ${err.message}` error = new errors.LevelError(message) } else { error = new VerifierUserError(err.stderr) } stdout = err.stdout stderr = err.stderr } if (this.targetDef.global.debug) { console.log('\n\n==============================================') console.log('Dumping STDOUT and STDERR from script verifier') console.log('----------------------------------------------') if (stdout) { console.log('STDOUT:') console.log(stdout) } if (stderr) { console.log('STDERR') console.log(stderr) } console.log('==============================================\n\n') } const passed = stdout.split(os.EOL).filter((str) => { return !!str }) if (error) { error.passed = passed throw error } else { return passed } } /** Deletes temporary directory made for the user recursively. */ async _deleteUserTmpDir () { try { logger.debug(`Now deleting temp directory: ${this.tempDir}`) logger.debug('Files in directory before deleting:') logger.debug(await readdir(this.tempDir)) await remove(this.tempDir) } catch (e) { logger.debug('An error occurred while deleting temp directory') throw e } } async _createVerifyProcess (data) { try { await this._prepareUserTempDir() logger.debug(this.tempDir) // Copy files into temp directory await this._copyCodelabResources(this.tempDir) // Creating a file with code that user typed into UI editor await this._createUserDataFile(data.input) // Creating child process const result = {} result.passed = await this._runCodelab() await this._deleteUserTmpDir() return result } catch (e) { logger.debug(e) logger.debug('Deleting any files made after catching error') await this._deleteUserTmpDir() // Rethrow exception because caller of this function catches error throw e } } }
JavaScript
class Spawner extends Engine.Actor { constructor(x, y) { super({}); this.positionX = x this.positionY = y this.realx = 0//(x + 1) * 50; this.realy = 0//(y + 1) * 50; this.path = []; this.mobs = []; this.spawned = []; this.startTime = 0.0; this.distance = 0 this.scaleFunction = null this.scale = 1 } setScaleFunction(func){ this.scaleFunction = func } updateScale(n){ this.scale = this.scaleFunction(n) } mobsExhausted(){ if (this.mobs.length == 0){ for(let i = 0; i < this.spawned.length; i++){ if (this.spawned[i].isActive()){//!(this.spawned[i].isDead() || this.spawned[i].hasReachedGoal())){ //console.log("not exhausted") //console.log(this.spawned[i].id) return false } } return true } return false } update = (dt) => { this.spawnMobs(dt) } getPosition(){ return [this.positionX, this.positionY] } isEmpty(){ return this.mobs.length == 0 } setPath(path){ this.path = path this.distance = this.sumPath(path) } sumPath(path){ let total = 0 for(let i = 1; i < path.length; i++){ total += Math.sqrt(Math.pow(path[i-1][0] - path[i][0], 2) + Math.pow(path[i-1][1] - path[i][1], 2)) } return total } /* *uses realx and realy not x, y, which are virtual representations, not graphical */ render = (dt) => { this.realX = this.positionX * this.stage.blockWidth + this.stage.startX this.realY = this.positionY * this.stage.blockHeight + this.stage.startY this.ctx.fillStyle = "red"; this.ctx.fillRect(this.realX, this.realY, this.stage.blockWidth, this.stage.blockHeight); //console.log(this.realX) this.ctx.fillStyle = "white"; this.ctx.font = "20px Arial"; this.ctx.textAlign = "center"; this.ctx.fillText("S", this.realX + this.stage.blockWidth/2, this.realY + this.stage.blockHeight/2 + 8); } /* * takes a list of lists where the inner list is * [timing, mob] * the list must be sorted in order of increasing timing */ setMobs(mobs) { this.mobs = mobs this.startTime = 0.0 this.spawned = [] } spawnMobs(deltaTime) { this.startTime += deltaTime while (this.mobs.length > 0 && this.mobs[0][0] <= this.startTime) { let toSpawn = this.mobs[0][1] this.mobs.shift() this.spawn(toSpawn) } } /* * adds mob to world, sets coordinates to the spawner's, copies the path to the mob */ spawn(mobType) { //console.log(mobType) let mob = new mobType({ x: 0, y: 0, width: 0, height: 0 }) mob.scaleStats(this.scale) mob.setDistance(this.distance) mob.setPath(this.path) this.stage.addActor(mob, 9) mob.updatePosition([this.positionY, this.positionX]) this.stage.addActive(mob) //console.log(mob) if(mob instanceof Monster) { //console.log("YEAH BITCH") mob.ctx = this.stage.fCanvas.getContext('2d') } this.spawned.push(mob) //console.log(mob) } mobsRemaining() { return this.mobs.length } }
JavaScript
class VoiceState extends Base { constructor(guild, data) { super(guild.client); /** * The guild of this voice state * @type {Guild} */ this.guild = guild; /** * The id of the member of this voice state * @type {Snowflake} */ this.id = data.user_id; this._patch(data); } _patch(data) { if ('deaf' in data) { /** * Whether this member is deafened server-wide * @type {?boolean} */ this.serverDeaf = data.deaf; } else { this.serverDeaf ??= null; } if ('mute' in data) { /** * Whether this member is muted server-wide * @type {?boolean} */ this.serverMute = data.mute; } else { this.serverMute ??= null; } if ('self_deaf' in data) { /** * Whether this member is self-deafened * @type {?boolean} */ this.selfDeaf = data.self_deaf; } else { this.selfDeaf ??= null; } if ('self_mute' in data) { /** * Whether this member is self-muted * @type {?boolean} */ this.selfMute = data.self_mute; } else { this.selfMute ??= null; } if ('self_video' in data) { /** * Whether this member's camera is enabled * @type {?boolean} */ this.selfVideo = data.self_video; } else { this.selfVideo ??= null; } if ('session_id' in data) { /** * The session id for this member's connection * @type {?string} */ this.sessionId = data.session_id; } else { this.sessionId ??= null; } // The self_stream is property is omitted if false, check for another property // here to avoid incorrectly clearing this when partial data is specified if ('self_video' in data) { /** * Whether this member is streaming using "Screen Share" * @type {?boolean} */ this.streaming = data.self_stream ?? false; } else { this.streaming ??= null; } if ('channel_id' in data) { /** * The {@link VoiceChannel} or {@link StageChannel} id the member is in * @type {?Snowflake} */ this.channelId = data.channel_id; } else { this.channelId ??= null; } if ('suppress' in data) { /** * Whether this member is suppressed from speaking. This property is specific to stage channels only. * @type {?boolean} */ this.suppress = data.suppress; } else { this.suppress ??= null; } if ('request_to_speak_timestamp' in data) { /** * The time at which the member requested to speak. This property is specific to stage channels only. * @type {?number} */ this.requestToSpeakTimestamp = data.request_to_speak_timestamp && Date.parse(data.request_to_speak_timestamp); } else { this.requestToSpeakTimestamp ??= null; } return this; } /** * The member that this voice state belongs to * @type {?GuildMember} * @readonly */ get member() { return this.guild.members.cache.get(this.id) ?? null; } /** * The channel that the member is connected to * @type {?(VoiceChannel|StageChannel)} * @readonly */ get channel() { return this.guild.channels.cache.get(this.channelId) ?? null; } /** * Whether this member is either self-deafened or server-deafened * @type {?boolean} * @readonly */ get deaf() { return this.serverDeaf || this.selfDeaf; } /** * Whether this member is either self-muted or server-muted * @type {?boolean} * @readonly */ get mute() { return this.serverMute || this.selfMute; } /** * Mutes/unmutes the member of this voice state. * @param {boolean} [mute=true] Whether or not the member should be muted * @param {string} [reason] Reason for muting or unmuting * @returns {Promise<GuildMember>} */ setMute(mute = true, reason) { return this.guild.members.edit(this.id, { mute }, reason); } /** * Deafens/undeafens the member of this voice state. * @param {boolean} [deaf=true] Whether or not the member should be deafened * @param {string} [reason] Reason for deafening or undeafening * @returns {Promise<GuildMember>} */ setDeaf(deaf = true, reason) { return this.guild.members.edit(this.id, { deaf }, reason); } /** * Disconnects the member from the channel. * @param {string} [reason] Reason for disconnecting the member from the channel * @returns {Promise<GuildMember>} */ disconnect(reason) { return this.setChannel(null, reason); } /** * Moves the member to a different channel, or disconnects them from the one they're in. * @param {GuildVoiceChannelResolvable|null} channel Channel to move the member to, or `null` if you want to * disconnect them from voice. * @param {string} [reason] Reason for moving member to another channel or disconnecting * @returns {Promise<GuildMember>} */ setChannel(channel, reason) { return this.guild.members.edit(this.id, { channel }, reason); } /** * Data to edit the logged in user's own voice state with, when in a stage channel * @typedef {Object} VoiceStateEditData * @property {boolean} [requestToSpeak] Whether or not the client is requesting to become a speaker. * <info>Only available to the logged in user's own voice state.</info> * @property {boolean} [suppressed] Whether or not the user should be suppressed. */ /** * Edits this voice state. Currently only available when in a stage channel * @param {VoiceStateEditData} data The data to edit the voice state with * @returns {Promise<VoiceState>} */ async edit(data) { if (this.channel?.type !== ChannelType.GuildStageVoice) throw new Error('VOICE_NOT_STAGE_CHANNEL'); const target = this.client.user.id === this.id ? '@me' : this.id; if (target !== '@me' && typeof data.requestToSpeak !== 'undefined') { throw new Error('VOICE_STATE_NOT_OWN'); } if (!['boolean', 'undefined'].includes(typeof data.requestToSpeak)) { throw new TypeError('VOICE_STATE_INVALID_TYPE', 'requestToSpeak'); } if (!['boolean', 'undefined'].includes(typeof data.suppressed)) { throw new TypeError('VOICE_STATE_INVALID_TYPE', 'suppressed'); } await this.client.rest.patch(Routes.guildVoiceState(this.guild.id, target), { body: { channel_id: this.channelId, request_to_speak_timestamp: data.requestToSpeak ? new Date().toISOString() : data.requestToSpeak === false ? null : undefined, suppress: data.suppressed, }, }); return this; } /** * Toggles the request to speak in the channel. * Only applicable for stage channels and for the client's own voice state. * @param {boolean} [requestToSpeak=true] Whether or not the client is requesting to become a speaker. * @example * // Making the client request to speak in a stage channel (raise its hand) * guild.me.voice.setRequestToSpeak(true); * @example * // Making the client cancel a request to speak * guild.me.voice.setRequestToSpeak(false); * @returns {Promise<VoiceState>} */ setRequestToSpeak(requestToSpeak = true) { return this.edit({ requestToSpeak }); } /** * Suppress/unsuppress the user. Only applicable for stage channels. * @param {boolean} [suppressed=true] Whether or not the user should be suppressed. * @example * // Making the client a speaker * guild.me.voice.setSuppressed(false); * @example * // Making the client an audience member * guild.me.voice.setSuppressed(true); * @example * // Inviting another user to speak * voiceState.setSuppressed(false); * @example * // Moving another user to the audience, or cancelling their invite to speak * voiceState.setSuppressed(true); * @returns {Promise<VoiceState>} */ setSuppressed(suppressed = true) { return this.edit({ suppressed }); } toJSON() { return super.toJSON({ id: true, serverDeaf: true, serverMute: true, selfDeaf: true, selfMute: true, sessionId: true, channelId: 'channel', }); } }
JavaScript
class NetworkClient { /** * Create an instance of NetworkClient. * @param networkEndPoint The endpoint to use for the client. * @param logger Logger to send communication info to. * @param timeoutMs The timeout in ms before aborting. * @param httpClientRequest The client request object, usually not required. */ constructor(networkEndPoint, logger, timeoutMs = 0, httpClientRequest) { if (objectHelper_1.ObjectHelper.isEmpty(networkEndPoint)) { throw new networkError_1.NetworkError("The networkEndPoint must be defined"); } if (!numberHelper_1.NumberHelper.isInteger(timeoutMs) || timeoutMs < 0) { throw new networkError_1.NetworkError("The timeoutMs must be >= 0"); } this._networkEndPoint = networkEndPoint; this._timeoutMs = timeoutMs; this._logger = logger || new nullLogger_1.NullLogger(); this._httpClientRequest = httpClientRequest || (networkEndPoint.getProtocol() === "http" ? http.request : https.request); this._logger.banner("Network Client", { endPoint: this._networkEndPoint }); } /** * Get data asynchronously. * @param data The data to send. * @param additionalPath An additional path append to the endpoint path. * @param additionalHeaders Extra headers to send with the request. * @returns Promise which resolves to the object returned or rejects with error. */ async get(data, additionalPath, additionalHeaders) { this._logger.info("===> NetworkClient::GET Send"); const resp = await this.doRequest("GET", this.objectToParameters(data), additionalPath, additionalHeaders); this._logger.info("<=== NetworkClient::GET Received", resp); return resp; } /** * Post data asynchronously. * @param data The data to send. * @param additionalPath An additional path append to the endpoint path. * @param additionalHeaders Extra headers to send with the request. * @returns Promise which resolves to the object returned or rejects with error. */ async post(data, additionalPath, additionalHeaders) { this._logger.info("===> NetworkClient::POST Send", data); const resp = await this.doRequest("POST", data, additionalPath, additionalHeaders); this._logger.info("<=== NetworkClient::POST Received", resp); return resp; } /** * Request data as JSON asynchronously. * @typeparam T The generic type for the object to send. * @typeparam U The generic type for the returned object. * @param data The data to send as the JSON body. * @param method The method to send with the request. * @param additionalPath An additional path append to the endpoint path. * @param additionalHeaders Extra headers to send with the request. * @returns Promise which resolves to the object returned or rejects with error. */ async json(data, method, additionalPath, additionalHeaders) { this._logger.info(`===> NetworkClient::${method} Send`); const headers = additionalHeaders || {}; let localData; if (method === "GET" || method === "DELETE") { localData = this.objectToParameters(data); } else { headers["Content-Type"] = "application/json"; localData = JSON.stringify(data); } return this.doRequest(method, localData, additionalPath, headers) .then((responseData) => { try { const response = JSON.parse(responseData); this._logger.info(`===> NetworkClient::${method} Received`, response); return response; } catch (err) { this._logger.info(`===> NetworkClient::${method} Parse Failed`, responseData); throw (new networkError_1.NetworkError(`Failed ${method} request, unable to parse response`, { endPoint: this._networkEndPoint.getUri(), response: responseData })); } }); } /** * Perform a request asynchronously. * @param method The method to send the data with. * @param data The data to send. * @param additionalPath An additional path append to the endpoint path. * @param additionalHeaders Extra headers to send with the request. * @returns Promise which resolves to the object returned or rejects with error. */ async doRequest(method, data, additionalPath, additionalHeaders) { return new Promise((resolve, reject) => { const headers = additionalHeaders || {}; let uri = this._networkEndPoint.getUri(); let path = this._networkEndPoint.getRootPath(); if (!stringHelper_1.StringHelper.isEmpty(additionalPath)) { const stripped = `/${additionalPath.replace(/^\/*/, "")}`; path += stripped; uri += stripped; } const options = { protocol: `${this._networkEndPoint.getProtocol()}:`, hostname: this._networkEndPoint.getHost(), port: this._networkEndPoint.getPort(), path: path, method: method, headers, timeout: this._timeoutMs > 0 ? this._timeoutMs : undefined }; if ((method === "GET" || method === "DELETE") && !objectHelper_1.ObjectHelper.isEmpty(data)) { options.path += data; } const req = this._httpClientRequest(options, (res) => { let responseData = ""; res.setEncoding("utf8"); res.on("data", (responseBody) => { responseData += responseBody; }); res.on("end", () => { if (res.statusCode === 200) { resolve(responseData); } else { this._logger.info("<=== NetworkClient::Received Fail", { code: res.statusCode, data: responseData }); reject(new networkError_1.NetworkError(`Failed ${method} request`, { endPoint: uri, errorResponseCode: res.statusCode, errorResponse: responseData || res.statusMessage })); } }); }); req.on("error", (err) => { this._logger.error("<=== NetworkClient::Errored"); reject(new networkError_1.NetworkError(`Failed ${method} request`, { endPoint: uri, errorResponse: err })); }); req.on("timeout", (err) => { this._logger.error("<=== NetworkClient::Timed Out"); reject(new networkError_1.NetworkError(`Failed ${method} request, timed out`, { endPoint: uri })); }); if (method !== "GET" && method !== "DELETE" && !objectHelper_1.ObjectHelper.isEmpty(data)) { req.write(data); } req.end(); }); } /* @internal */ objectToParameters(data) { let localUri = ""; if (data) { const keys = Object.keys(data); if (keys.length > 0) { const parms = []; for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = data[key] ? data[key].toString() : ""; parms.push(`${encodeURIComponent(keys[i])}=${encodeURIComponent(value)}`); } localUri += `?${parms.join("&")}`; } } return localUri; } }
JavaScript
class Scheduler extends EventEmitter { /** * Create an instance of Scheduler class * @param {Object} configOptions - the global config * @param {String} configOptions.scheduler.collection - the name of the collection to store jobs * @param {Object[]} configOptions.scheduler.jobs - the jobs array. see [documentation]{@link https://www.npmjs.com/package/cron} */ constructor(configOptions) { super(); this.store = configOptions.$store; this.logger = configOptions.$logger; this.collection = AppImport('.util') .lastValue(configOptions, 'scheduler', 'collection') || 'cron'; let jobsMap = AppImport('.util').lastValue(configOptions, 'scheduler', 'jobs'); if (typeof jobsMap !== 'object' || jobsMap === null || Array.isArray(jobsMap)) { jobsMap = {}; } this.jobsMap = jobsMap; this.jobsInstance = {}; } /** * Call one cron * @param {Object} cron - the cron object */ async callOneCron(cron) { await this.store.write(this.collection, cron._id, { status: 2 }); try { await FunctionsMap[cron.name](this.store, this.logger, ...cron.params); } catch (er) { return this.store.write(this.collection, cron._id, { status: 0, error: er }); } return this.store.write(this.collection, cron._id, { status: 1 }); } /** * To be called when the cron completes * @param {String} name - the job name to complete with */ async completeCron(name) { this.logger.info(`Job ${name} completed at ${new Date()}.`); } /** * Call the crons that are in queue or yet to be executed * @param {String} name - the job name to run with */ async callCron(name) { const docs = await this.store.listAll(this.collection, { name, enabled: true, status: { $lt: 1 }, // to execute failed or the ones in queue }, { params: 1 }); await Promise.all(docs.map(this.callOneCron.bind(this))); } /** * Init the scheduler to assign a collection * @chainable */ init() { this.store.mkcoll(this.collection); Object.keys(this.jobsMap).forEach((jb) => { if (typeof FunctionsMap[jb] === 'function') { this.jobsInstance[jb] = new CronJob(Object.assign({}, this.jobsMap[jb], { onTick: this.callCron.bind(this, jb), onComplete: this.onComplete.bind(this, jb), start: true, })); } else { delete this.jobsMap[jb]; } }); return this; } /** * Enable the scheduler * @param {String} jobName - the job to start * @chainable */ enable(jobName) { this.jobsInstance[jobName].start(); return this; } /** * Disable the scheduler * @param {String} jobName - the job to start * @chainable */ disable(jobName) { this.jobsInstance[jobName].stop(); return this; } /** * Enable a job * @param {String} jobId - the job id to enable * @chainable */ enableJob(jobId) { return this.store.write(this.collection, jobId, { enabled: true }); } /** * Disable a job * @param {String} jobId - the job id to disable * @chainable */ disableJob(jobId) { return this.store.write(this.collection, jobId, { enabled: false }); } /** * create a job to schedule * @param {String} name - the key name of the subscribers * @param {*} params - the array of parameters to pass on tick. */ add(name, params) { if (!this.jobsMap[name]) throw new Error('Incorrect job name.'); this.store.write(this.collection, null, { name, params, enabled: true, status: -1, // 0 means, to be executed }); } }
JavaScript
class Payload { /** * Creates a new Payload. You can only supply either data or error. The url has to be valid. * * @param isFetching {boolean} Whether we're currently fetching from requestUrl * @param data {object|null} The data which has been fetched or null * @param error {string|null} The error message which has occurred or null * @param requestUrl {string|null} The url from which to fetch or null if we're not sure yet * @param fetchDate {number|null} The date when the last fetch has been started * @throws {Error} If you supply data and error or the url is invalid. */ constructor (isFetching, data = null, error = null, requestUrl = null, fetchDate = null) { this._isFetching = isFetching this._fetchDate = fetchDate this._error = error this._requestUrl = requestUrl this._data = data if (requestUrl !== null && !isUrl(requestUrl)) { throw new Error('requestUrl must be a valid URL') } if (error && data) { throw new Error('data and error can not be set at the same time') } } /** * @return {number} The date the fetch was initiated as serializable number */ get fetchDate () { return this._fetchDate } /** * @return {boolean} If a fetch is going on */ get isFetching () { return this._isFetching } /** * @return {*} The data which has been fetched or null */ get data () { return this._data } /** * @return {boolean} If the {@link data} is ready to be used */ ready () { return !!this._data } /** * @return {string} The error message if the fetch failed or null */ get error () { return this._error } /** * @return {string} The url which was used to initiate the fetch */ get requestUrl () { return this._requestUrl } }
JavaScript
class Votes extends Component { state = { savedVotes: [], }; //default method when page loads componentDidMount() { this.fetchVotes(); } //fetch vote details fetchVotes = () => { API.getVotes().then(res => { console.log(res.data); this.setState({ savedVotes: res.data }); }); } render() { return ( <> <VoteResult savedVotes={this.state.savedVotes} /> </> ); } }
JavaScript
class ColumnSorting extends BasePlugin { constructor(hotInstance) { super(hotInstance); this.sortIndicators = []; this.lastSortedColumn = null; } /** * Check if the plugin is enabled in the handsontable settings. * * @returns {Boolean} */ isEnabled() { return !!(this.hot.getSettings().columnSorting); } /** * Enable plugin for this Handsontable instance. */ enablePlugin() { if (this.enabled) { return; } const _this = this; this.hot.sortIndex = []; this.hot.sort = function() { let args = Array.prototype.slice.call(arguments); return _this.sortByColumn.apply(_this, args); }; if (typeof this.hot.getSettings().observeChanges === 'undefined') { this.enableObserveChangesPlugin(); } this.addHook('afterTrimRow', (row) => this.sort()); this.addHook('afterUntrimRow', (row) => this.sort()); this.addHook('modifyRow', (row) => this.translateRow(row)); this.addHook('unmodifyRow', (row) => this.untranslateRow(row)); this.addHook('afterUpdateSettings', () => this.onAfterUpdateSettings()); this.addHook('afterGetColHeader', (col, TH) => this.getColHeader(col, TH)); this.addHook('afterOnCellMouseDown', (event, target) => this.onAfterOnCellMouseDown(event, target)); this.addHook('afterCreateRow', function() { _this.afterCreateRow.apply(_this, arguments); }); this.addHook('afterRemoveRow', function() { _this.afterRemoveRow.apply(_this, arguments); }); this.addHook('afterInit', () => this.sortBySettings()); this.addHook('afterLoadData', () => { this.hot.sortIndex = []; if (this.hot.view) { this.sortBySettings(); } }); if (this.hot.view) { this.sortBySettings(); } super.enablePlugin(); } /** * Disable plugin for this Handsontable instance. */ disablePlugin() { this.hot.sort = void 0; super.disablePlugin(); } /** * afterUpdateSettings callback. * * @private */ onAfterUpdateSettings() { this.sortBySettings(); } sortBySettings() { let sortingSettings = this.hot.getSettings().columnSorting; let loadedSortingState = this.loadSortingState(); let sortingColumn; let sortingOrder; if (typeof loadedSortingState === 'undefined') { sortingColumn = sortingSettings.column; sortingOrder = sortingSettings.sortOrder; } else { sortingColumn = loadedSortingState.sortColumn; sortingOrder = loadedSortingState.sortOrder; } if (typeof sortingColumn === 'number') { this.lastSortedColumn = sortingColumn; this.sortByColumn(sortingColumn, sortingOrder); } } /** * Set sorted column and order info * * @param {number} col Sorted column index. * @param {boolean|undefined} order Sorting order (`true` for ascending, `false` for descending). */ setSortingColumn(col, order) { if (typeof col == 'undefined') { this.hot.sortColumn = void 0; this.hot.sortOrder = void 0; return; } else if (this.hot.sortColumn === col && typeof order == 'undefined') { if (this.hot.sortOrder === false) { this.hot.sortOrder = void 0; } else { this.hot.sortOrder = !this.hot.sortOrder; } } else { this.hot.sortOrder = typeof order === 'undefined' ? true : order; } this.hot.sortColumn = col; } sortByColumn(col, order) { this.setSortingColumn(col, order); if (typeof this.hot.sortColumn == 'undefined') { return; } let allowSorting = Handsontable.hooks.run(this.hot, 'beforeColumnSort', this.hot.sortColumn, this.hot.sortOrder); if (allowSorting !== false) { this.sort(); } this.updateOrderClass(); this.updateSortIndicator(); Handsontable.hooks.run(this.hot, 'afterColumnSort', this.hot.sortColumn, this.hot.sortOrder); this.hot.render(); this.saveSortingState(); } /** * Save the sorting state */ saveSortingState() { let sortingState = {}; if (typeof this.hot.sortColumn != 'undefined') { sortingState.sortColumn = this.hot.sortColumn; } if (typeof this.hot.sortOrder != 'undefined') { sortingState.sortOrder = this.hot.sortOrder; } if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) { Handsontable.hooks.run(this.hot, 'persistentStateSave', 'columnSorting', sortingState); } } /** * Load the sorting state. * * @returns {*} Previously saved sorting state. */ loadSortingState() { let storedState = {}; Handsontable.hooks.run(this.hot, 'persistentStateLoad', 'columnSorting', storedState); return storedState.value; } /** * Update sorting class name state. */ updateOrderClass() { let orderClass; if (this.hot.sortOrder === true) { orderClass = 'ascending'; } else if (this.hot.sortOrder === false) { orderClass = 'descending'; } this.sortOrderClass = orderClass; } enableObserveChangesPlugin() { let _this = this; this.hot._registerTimeout( setTimeout(function() { _this.hot.updateSettings({ observeChanges: true }); }, 0)); } /** * Default sorting algorithm. * * @param {Boolean} sortOrder Sorting order - `true` for ascending, `false` for descending. * @param {Object} columnMeta Column meta object. * @returns {Function} The comparing function. */ defaultSort(sortOrder, columnMeta) { return function(a, b) { if (typeof a[1] == 'string') { a[1] = a[1].toLowerCase(); } if (typeof b[1] == 'string') { b[1] = b[1].toLowerCase(); } if (a[1] === b[1]) { return 0; } if (a[1] === null || a[1] === '') { return 1; } if (b[1] === null || b[1] === '') { return -1; } if (isNaN(a[1]) && !isNaN(b[1])) { return sortOrder ? 1 : -1; } else if (!isNaN(a[1]) && isNaN(b[1])) { return sortOrder ? -1 : 1; } else if (!(isNaN(a[1]) || isNaN(b[1]))) { a[1] = parseFloat(a[1]); b[1] = parseFloat(b[1]); } if (a[1] < b[1]) { return sortOrder ? -1 : 1; } if (a[1] > b[1]) { return sortOrder ? 1 : -1; } return 0; }; } /** * Date sorting algorithm * @param {Boolean} sortOrder Sorting order (`true` for ascending, `false` for descending). * @param {Object} columnMeta Column meta object. * @returns {Function} The compare function. */ dateSort(sortOrder, columnMeta) { return function(a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null || a[1] === '') { return 1; } if (b[1] === null || b[1] === '') { return -1; } var aDate = moment(a[1], columnMeta.dateFormat); var bDate = moment(b[1], columnMeta.dateFormat); if (!aDate.isValid()) { return 1; } if (!bDate.isValid()) { return -1; } if (bDate.isAfter(aDate)) { return sortOrder ? -1 : 1; } if (bDate.isBefore(aDate)) { return sortOrder ? 1 : -1; } return 0; }; } /** * Numeric sorting algorithm. * * @param {Boolean} sortOrder Sorting order (`true` for ascending, `false` for descending). * @param {Object} columnMeta Column meta object. * @returns {Function} The compare function. */ numericSort(sortOrder, columnMeta) { return function(a, b) { let parsedA = parseFloat(a[1]); let parsedB = parseFloat(b[1]); if (parsedA === parsedB || (isNaN(parsedA) && isNaN(parsedB))) { return 0; } if (isNaN(parsedA)) { return 1; } if (isNaN(parsedB)) { return -1; } if (parsedA < parsedB) { return sortOrder ? -1 : 1; } else if (parsedA > parsedB) { return sortOrder ? 1 : -1; } return 0; }; } /** * Perform the sorting. */ sort() { if (typeof this.hot.sortOrder == 'undefined') { this.hot.sortIndex.length = 0; return; } let colMeta, sortFunction; this.hot.sortingEnabled = false; // this is required by translateRow plugin hook this.hot.sortIndex.length = 0; let nrOfRows; const emptyRows = this.hot.countEmptyRows(); if (this.hot.getSettings().maxRows === Number.POSITIVE_INFINITY) { nrOfRows = this.hot.countRows() - this.hot.getSettings().minSpareRows; } else { nrOfRows = this.hot.countRows() - emptyRows; } for (let i = 0, ilen = nrOfRows; i < ilen; i++) { this.hot.sortIndex.push([i, this.hot.getDataAtCell(i, this.hot.sortColumn)]); } colMeta = this.hot.getCellMeta(0, this.hot.sortColumn); if (colMeta.sortFunction) { sortFunction = colMeta.sortFunction; } else { switch (colMeta.type) { case 'date': sortFunction = this.dateSort; break; case 'numeric': sortFunction = this.numericSort; break; default: sortFunction = this.defaultSort; } } this.hot.sortIndex.sort(sortFunction(this.hot.sortOrder, colMeta)); // Append spareRows for (let i = this.hot.sortIndex.length; i < this.hot.countRows(); i++) { this.hot.sortIndex.push([i, this.hot.getDataAtCell(i, this.hot.sortColumn)]); } this.hot.sortingEnabled = true; // this is required by translateRow plugin hook } /** * Update indicator states. */ updateSortIndicator() { if (typeof this.hot.sortOrder == 'undefined') { return; } const colMeta = this.hot.getCellMeta(0, this.hot.sortColumn); this.sortIndicators[this.hot.sortColumn] = colMeta.sortIndicator; } /** * `modifyRow` hook callback. Translates physical row index to the sorted row index. * * @param {Number} row Row index. * @returns {Number} Sorted row index. */ translateRow(row) { if (this.hot.sortingEnabled && (typeof this.hot.sortOrder !== 'undefined') && this.hot.sortIndex && this.hot.sortIndex.length && this.hot.sortIndex[row]) { return this.hot.sortIndex[row][0]; } return row; } /** * Translates sorted row index to physical row index. * * @param {Number} row Sorted row index. * @returns {number} Physical row index. */ untranslateRow(row) { if (this.hot.sortingEnabled && this.hot.sortIndex && this.hot.sortIndex.length) { for (var i = 0; i < this.hot.sortIndex.length; i++) { if (this.hot.sortIndex[i][0] == row) { return i; } } } } /** * `afterGetColHeader` callback. Adds column sorting css classes to clickable headers. * * @private * @param {Number} col Column index. * @param {Element} TH TH HTML element. */ getColHeader(col, TH) { if (col < 0 || !TH.parentNode) { return false; } let headerLink = TH.querySelector('.colHeader'); let colspan = TH.getAttribute('colspan'); let TRs = TH.parentNode.parentNode.childNodes; let headerLevel = Array.prototype.indexOf.call(TRs, TH.parentNode); headerLevel = headerLevel - TRs.length; if (!headerLink) { return; } if (this.hot.getSettings().columnSorting && col >= 0 && headerLevel === -1) { addClass(headerLink, 'columnSorting'); } removeClass(headerLink, 'descending'); removeClass(headerLink, 'ascending'); if (this.sortIndicators[col]) { if (col === this.hot.sortColumn) { if (this.sortOrderClass === 'ascending') { addClass(headerLink, 'ascending'); } else if (this.sortOrderClass === 'descending') { addClass(headerLink, 'descending'); } } } } /** * Check if any column is in a sorted state. * * @returns {Boolean} */ isSorted() { return typeof this.hot.sortColumn != 'undefined'; } /** * `afterCreateRow` callback. Updates the sorting state after a row have been created. * * @private * @param {Number} index * @param {Number} amount */ afterCreateRow(index, amount) { if (!this.isSorted()) { return; } for (var i = 0; i < this.hot.sortIndex.length; i++) { if (this.hot.sortIndex[i][0] >= index) { this.hot.sortIndex[i][0] += amount; } } for (var i = 0; i < amount; i++) { this.hot.sortIndex.splice(index + i, 0, [index + i, this.hot.getSourceData()[index + i][this.hot.sortColumn + this.hot.colOffset()]]); } this.saveSortingState(); } /** * `afterRemoveRow` hook callback. * * @private * @param {Number} index * @param {Number} amount */ afterRemoveRow(index, amount) { if (!this.isSorted()) { return; } let removedRows = this.hot.sortIndex.splice(index, amount); removedRows = arrayMap(removedRows, (row) => row[0]); function countRowShift(logicalRow) { // Todo: compare perf between reduce vs sort->each->brake return arrayReduce(removedRows, (count, removedLogicalRow) => { if (logicalRow > removedLogicalRow) { count++; } return count; }, 0); } this.hot.sortIndex = arrayMap(this.hot.sortIndex, (logicalRow, physicalRow) => { let rowShift = countRowShift(logicalRow[0]); if (rowShift) { logicalRow[0] -= rowShift; } return logicalRow; }); this.saveSortingState(); } /** * `onAfterOnCellMouseDown` hook callback. * * @private * @param {Event} event Event which are provided by hook. * @param {WalkontableCellCoords} coords Coords of the selected cell. */ onAfterOnCellMouseDown(event, coords) { if (coords.row > -1) { return; } if (hasClass(event.realTarget, 'columnSorting')) { // reset order state on every new column header click if (coords.col !== this.lastSortedColumn) { this.hot.sortOrder = true; } this.lastSortedColumn = coords.col; this.sortByColumn(coords.col); } } }
JavaScript
class NameResolver { // This function is called ONLY by the UserInfo plugin to pass its db setDb(db) { log.verbose("Name resolution database initialized."); this.db = db; } // For a given username, retrieve the user ID. getUserIDFromUsername(username) { username = username.replace(/^@/, ""); if (!this.db) { log.error("NameResolver: database is uninitialized"); throw new Error("Database uninitialized"); } return Object.keys(this.db).find(userID => this.db[userID] === username); } // For a given user ID, get the latest username. getUsernameFromUserID(userID) { if (!this.db) { log.error("NameResolver: database is uninitialized"); throw new Error("Database uninitialized"); } return this.db[userID]; } }
JavaScript
class McDatepickerContent { constructor(changeDetectorRef) { this.changeDetectorRef = changeDetectorRef; /** Emits when an animation has finished. */ this.animationDone = new Subject(); this.subscriptions = new Subscription(); } ngAfterViewInit() { this.subscriptions.add(this.datepicker.stateChanges.subscribe(() => { this.changeDetectorRef.markForCheck(); })); } ngOnDestroy() { this.subscriptions.unsubscribe(); this.animationDone.complete(); } startExitAnimation() { this.animationState = 'void'; this.changeDetectorRef.markForCheck(); } }