language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class WebDriverExtension { static bindTo(childTokens) { var res = [ bind(_CHILDREN) .toFactory((injector) => childTokens.map(token => injector.get(token)), [Injector]), bind(WebDriverExtension) .toFactory((children, capabilities) => { var delegate; children.forEach(extension => { if (extension.supports(capabilities)) { delegate = extension; } }); if (isBlank(delegate)) { throw new BaseException('Could not find a delegate for given capabilities!'); } return delegate; }, [_CHILDREN, Options.CAPABILITIES]) ]; return res; } gc() { throw new BaseException('NYI'); } timeBegin(name) { throw new BaseException('NYI'); } timeEnd(name, restartName) { throw new BaseException('NYI'); } /** * Format: * - cat: category of the event * - name: event name: 'script', 'gc', 'render', ... * - ph: phase: 'B' (begin), 'E' (end), 'b' (nestable start), 'e' (nestable end), 'X' (Complete *event) * - ts: timestamp in ms, e.g. 12345 * - pid: process id * - args: arguments, e.g. {heapSize: 1234} * * Based on [Chrome Trace Event *Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit) **/ readPerfLog() { throw new BaseException('NYI'); } perfLogFeatures() { throw new BaseException('NYI'); } supports(capabilities) { return true; } }
JavaScript
class InputOption extends HeroOption { constructor( origin, key, placeholder, val, settings = { addValues: false, type: 'text' }, ) { super(); this.origin = origin; this.key = key; this.val = val; this.placeholder = placeholder; this.settings = settings; } $elem; render($parent, settings) { const $container = $('<div class="hct-option">'); const min = this.settings.min ? `min="${this.settings.min}"` : ''; const max = this.settings.max ? `max="${this.settings.max}"` : ''; const wrapped = !!this.settings.postLabel; if (this.settings.preLabel) { const $preLabel = $(`<span class="hct-option-label">${this.settings.preLabel}</span>`); $container.append($preLabel); } const data = this.settings.data; if (wrapped) { const $wrapper = $(`<div class="hct-flex ${this.settings.class ?? ''}">`); this.$elem = $(`<input type="${this.settings.type}" placeholder="${this.placeholder}" ${data ?? ''} value=${this.val} ${this.settings.type == 'number' ? `${min} ${max}` : ''}>`); $wrapper.append(this.$elem); if (this.settings.postLabel) { const $postLabel = $(`<p class='hct-postlabel'>${this.settings.postLabel}</p>`); $wrapper.append($postLabel); } $container.append($wrapper); } else { this.$elem = $(`<input class="${this.settings.class ?? ''}" type="${this.settings.type}" placeholder="${this.placeholder}" ${data ?? ''} value=${this.val} ${this.settings.type == 'number' ? `${min} ${max}` : ''}>`); $container.append(this.$elem); } if (settings?.beforeParent) { $parent.before($container); } else { $parent.append($container); } } value() { const val = this.$elem.val(); if (this.settings.type == 'number') return val; return val; } isFulfilled() { return !!this.$elem.val(); } applyToHero(actor) { apply(actor, this.key, this.value(), this.settings.addValues, this.settings.type === 'number'); } }
JavaScript
class ScrollToTop extends Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { const excludePages = [ROUTES.VIEW_PAPER, ROUTES.FEATURED_COMPARISONS, ROUTES.SMART_REVIEW]; let preventScrollTop = false; for (const page of excludePages) { const matchPage = match(page); if (matchPage(this.props.location.pathname) && matchPage(prevProps.location.pathname)) { preventScrollTop = true; break; } } if (!preventScrollTop) { window.scrollTo(0, 0); } } } render() { return this.props.children; } }
JavaScript
class DragAndDropPanel { /** * Create a new style panel in the given element. * @param {HTMLElement} div The element that will display the palette items. * @param {boolean} passiveSupported Whether or not the browser supports active and passive event listeners. */ constructor(div, passiveSupported) { this.divField = div this.$maxItemWidth = 150 this.passiveSupported = !!passiveSupported this.$copyNodeLabels = true } /** * The main element of this panel. */ get div() { return this.divField } set div(div) { this.divField = div } /** * The desired maximum width of each item. This value is used to decide whether or not a * visualization must be scaled down. */ get maxItemWidth() { return this.$maxItemWidth } set maxItemWidth(width) { this.$maxItemWidth = width } /** * A callback that is called then the user presses the mouse button on an item. * It should start the actual drag and drop operation. */ get beginDragCallback() { return this.$beginDragCallback } set beginDragCallback(callback) { this.$beginDragCallback = callback } /** * Whether the labels of the DnD node visual should be transferred to the created node or discarded. * @returns {Boolean} */ get copyNodeLabels() { return this.$copyNodeLabels } set copyNodeLabels(value) { this.$copyNodeLabels = value } /** * Adds the items provided by the given factory to this palette. * This method delegates the creation of the visualization of each node * to createNodeVisual. */ populatePanel(itemFactory) { if (!itemFactory) { return } // Create the nodes that specify the visualizations for the panel. const items = itemFactory // Convert the nodes into plain visualizations const graphComponent = new GraphComponent() for (let i = 0; i < items.length; i++) { const item = items[i] const modelItem = INode.isInstance(item) || IEdge.isInstance(item) ? item : item.element const visual = INode.isInstance(modelItem) ? this.createNodeVisual(item, graphComponent) : this.createEdgeVisual(item, graphComponent) this.addPointerDownListener(modelItem, visual, this.beginDragCallback) this.div.appendChild(visual) } } /** * Creates an element that contains the visualization of the given node. * This method is used by populatePanel to create the visualization * for each node provided by the factory. * @return {HTMLDivElement} */ createNodeVisual(original, graphComponent) { const graph = graphComponent.graph graph.clear() const originalNode = INode.isInstance(original) ? original : original.element const node = graph.createNode( new Rect(0,0,100,50), // enable instead of new Rect to show the whole Node //originalNode.layout.toRect(), originalNode.style, originalNode.tag ) originalNode.labels.forEach(label => { graph.addLabel( node, label.text, label.layoutParameter, label.style, label.preferredSize, label.tag ) }) originalNode.ports.forEach(port => { graph.addPort(node, port.locationParameter, port.style, port.tag) }) this.updateViewport(graphComponent) return this.exportAndWrap(graphComponent, original.tooltip) } /** * Creates an element that contains the visualization of the given edge. * @return {HTMLDivElement} */ createEdgeVisual(original, graphComponent) { const graph = graphComponent.graph graph.clear() const originalEdge = IEdge.isInstance(original) ? original : original.element const n1 = graph.createNode(new Rect(0, 10, 0, 0), VoidNodeStyle.INSTANCE) const n2 = graph.createNode(new Rect(50, 40, 0, 0), VoidNodeStyle.INSTANCE) const edge = graph.createEdge(n1, n2, originalEdge.style) graph.addBend(edge, new Point(25, 10)) graph.addBend(edge, new Point(25, 40)) this.updateViewport(graphComponent) // provide some more insets to account for the arrow heads graphComponent.updateContentRect(new Insets(5)) return this.exportAndWrap(graphComponent, original.tooltip) } updateViewport(graphComponent) { const graph = graphComponent.graph let viewport = Rect.EMPTY graph.nodes.forEach(node => { viewport = Rect.add(viewport, node.layout.toRect()) node.labels.forEach(label => { viewport = Rect.add(viewport, label.layout.bounds) }) }) graph.edges.forEach(edge => { viewport = viewport.add(edge.sourcePort.location) viewport = viewport.add(edge.targetPort.location) edge.bends.forEach(bend => { viewport = viewport.add(bend.location.toPoint()) }) }) viewport = viewport.getEnlarged(5) graphComponent.contentRect = viewport graphComponent.zoomTo(viewport) } /** * Exports and wraps the original visualization in an HTML element. * @return {HTMLDivElement} */ exportAndWrap(graphComponent, tooltip) { const exporter = new SvgExport(graphComponent.contentRect) exporter.margins = new Insets(5) exporter.scale = exporter.calculateScaleForWidth( Math.min(this.maxItemWidth, graphComponent.contentRect.width) ) const visual = exporter.exportSvg(graphComponent) // Firefox does not display the SVG correctly because of the clip - so we remove it. visual.removeAttribute('clip-path') const div = document.createElement('div') div.setAttribute('class', 'dndPanelItem') div.appendChild(visual) div.style.setProperty('width', visual.getAttribute('width'), '') div.style.setProperty('height', visual.getAttribute('height'), '') div.style.setProperty('touch-action', 'none') try { div.style.setProperty('cursor', 'grab', '') } catch (e) { /* IE9 doesn't support grab cursor */ } if (tooltip) { div.title = tooltip } return div } /** * Adds a mousedown listener to the given element that starts the drag operation. */ addPointerDownListener(item, element, callback) { if (!callback) { return } // the actual drag operation const doDragOperation = () => { if (typeof IStripe !== 'undefined' && IStripe.isInstance(item.tag)) { // If the dummy node has a stripe as its tag, we use the stripe directly // This allows StripeDropInputMode to take over callback(element, item.tag) } else if (ILabel.isInstance(item.tag) || IPort.isInstance(item.tag)) { callback(element, item.tag) } else if (IEdge.isInstance(item)) { callback(element, item) } else { // Otherwise, we just use the node itself and let (hopefully) NodeDropInputMode take over const simpleNode = new SimpleNode() simpleNode.layout = item.layout simpleNode.style = item.style.clone() simpleNode.tag = item.tag simpleNode.labels = this.$copyNodeLabels ? item.labels : IListEnumerable.EMPTY if (item.ports.size > 0) { simpleNode.ports = new ListEnumerable(item.ports) } callback(element, simpleNode) } } element.addEventListener( 'mousedown', evt => { if (evt.button !== 0) { return } doDragOperation() evt.preventDefault() }, false ) const touchStartListener = evt => { doDragOperation() evt.preventDefault() } if (window.PointerEvent !== undefined) { element.addEventListener( 'pointerdown', evt => { if (evt.pointerType === 'touch' || evt.pointerType === 'pen') { touchStartListener(evt) } }, true ) } else if (window.MSPointerEvent !== undefined) { element.addEventListener( 'MSPointerDown', evt => { if ( evt.pointerType === evt.MSPOINTER_TYPE_TOUCH || evt.pointerType === evt.MSPOINTER_TYPE_PEN ) { touchStartListener(evt) } }, true ) } else { element.addEventListener( 'touchstart', touchStartListener, this.passiveSupported ? { passive: false } : false ) } } }
JavaScript
class Base64 { /** * Calculate length in bytes required to hold an encoded base64 string. */ static encodedLen(dataLen) { precondition.ensureNumber('dataLen', dataLen); let proxyResult; proxyResult = Module._vscf_base64_encoded_len(dataLen); return proxyResult; } /** * Encode given data to the base64 format. * Note, written buffer is NOT null-terminated. */ static encode(data) { precondition.ensureByteArray('data', data); // Copy bytes from JS memory to the WASM memory. const dataSize = data.length * data.BYTES_PER_ELEMENT; const dataPtr = Module._malloc(dataSize); Module.HEAP8.set(data, dataPtr); // Create C structure vsc_data_t. const dataCtxSize = Module._vsc_data_ctx_size(); const dataCtxPtr = Module._malloc(dataCtxSize); // Point created vsc_data_t object to the copied bytes. Module._vsc_data(dataCtxPtr, dataPtr, dataSize); const strCapacity = modules.Base64.encodedLen(data.length); const strCtxPtr = Module._vsc_buffer_new_with_capacity(strCapacity); try { Module._vscf_base64_encode(dataCtxPtr, strCtxPtr); const strPtr = Module._vsc_buffer_bytes(strCtxPtr); const strPtrLen = Module._vsc_buffer_len(strCtxPtr); const str = Module.HEAPU8.slice(strPtr, strPtr + strPtrLen); return str; } finally { Module._free(dataPtr); Module._free(dataCtxPtr); Module._vsc_buffer_delete(strCtxPtr); } } /** * Calculate length in bytes required to hold a decoded base64 string. */ static decodedLen(strLen) { precondition.ensureNumber('strLen', strLen); let proxyResult; proxyResult = Module._vscf_base64_decoded_len(strLen); return proxyResult; } /** * Decode given data from the base64 format. */ static decode(str) { precondition.ensureByteArray('str', str); // Copy bytes from JS memory to the WASM memory. const strSize = str.length * str.BYTES_PER_ELEMENT; const strPtr = Module._malloc(strSize); Module.HEAP8.set(str, strPtr); // Create C structure vsc_data_t. const strCtxSize = Module._vsc_data_ctx_size(); const strCtxPtr = Module._malloc(strCtxSize); // Point created vsc_data_t object to the copied bytes. Module._vsc_data(strCtxPtr, strPtr, strSize); const dataCapacity = modules.Base64.decodedLen(str.length); const dataCtxPtr = Module._vsc_buffer_new_with_capacity(dataCapacity); try { const proxyResult = Module._vscf_base64_decode(strCtxPtr, dataCtxPtr); modules.FoundationError.handleStatusCode(proxyResult); const dataPtr = Module._vsc_buffer_bytes(dataCtxPtr); const dataPtrLen = Module._vsc_buffer_len(dataCtxPtr); const data = Module.HEAPU8.slice(dataPtr, dataPtr + dataPtrLen); return data; } finally { Module._free(strPtr); Module._free(strCtxPtr); Module._vsc_buffer_delete(dataCtxPtr); } } }
JavaScript
class StorageInterface { /** * @param {string|Symbol} storeId * @param {TYPE} data * @returns {StorageInterface<TYPE>} */ set(storeId, data) { throw NotOverrideException.FROM_INTERFACE('StorageInterface') } /** * @returns {?StoreState<TYPE>} */ get() { throw NotOverrideException.FROM_INTERFACE('StorageInterface') } }
JavaScript
class Manipulator { constructor(objectDiff, arrayDiff) { this.objectDiff = objectDiff; this.arrayDiff = arrayDiff; } apply() { throw new Error('This method should be implemented in the child class'); } }
JavaScript
class ViewInterface { /** * Constructs a view interface * @param elem - the root element to draw the interface in * @param nav - the navbar element */ constructor(elem, nav, rangeCount) { if (rangeCount == null) rangeCount = 10; this.elem = $(elem); this.nav = $(nav); // The range of elements to render. this.range = [0, rangeCount]; // The total number of elements. this.count = 0; } init() { // Hook up callbacks. this._setupCallbacks(); this.updateCount(); const [lower, upper] = this.range; const count = upper - lower; this.updateRange(lower, count); } _setupCallbacks() { const self = this; this.nav.find("#nav-prev").on("click", () => self.prev()); this.nav.find("#nav-next").on("click", () => self.next()); this.nav.find("#nav-range").on("change", (evt) => { const value = evt.target.value; const parts = value.split("-"); console.assert(parts === 2); const [lower, upper] = [Number.parseInt(parts[0])-1, Number.parseInt(parts[1])]; const count = upper - lower; self.updateRange(lower, count); }); $('body').on("keydown", evt => { console.log(evt.key); if (evt.key === "ArrowLeft") self.prev(); else if (evt.key === "ArrowRight") self.next(); }); } next() { const self = this; const [lower, upper] = self.range; const count = upper - lower; const newUpper = Math.min(self.count, upper+count); self.updateRange(Math.max(0, newUpper-count), count); } prev() { const self = this; const [lower, upper] = self.range; const count = upper - lower; const newLower = Math.max(0, lower - count); self.updateRange(newLower, count); } updateCount() { // Set up count in nav interface. const self = this; $.ajax({ url: "/count/", contentType: "application/json", method: "GET", success: function(data) { // Clear root. self.count = data.value; self.nav.find("#nav-count").text("of " + self.count); } }); } renderTemplate(idx, body) { const ret = $("#templates").find("div.card").clone(); ret.attr("id", "obj-" + idx); ret.find("h6.card-header").text("Element: " + (idx+1)); ret.find("div.card-body").html(body); return ret; } updateRange(start, count) { const self = this; // Handle arguments. if (count == null) count = 10; if (start == null) start = 0; // Get renderables from the server. $.ajax({ url: "/render/", contentType: "application/json", method: "GET", data: {start: start, count: count}, success: function(data) { // Clear root. self.elem.empty(); for (let i = 0; i < data.html.length; i++) { const html = self.renderTemplate(start + i, data.html[i]); self.elem.append(html); } self.nav.find("#nav-range").val((start+1) + "-" + (start+count)); self.range = [start, start+count]; } }); } }
JavaScript
class SelectDropdown extends React.Component { static propTypes = { id: PropTypes.string.isRequired, options: PropTypes.array.isRequired, value: PropTypes.string, onChange: PropTypes.func.isRequired } render() { const { id, onChange, options, value } = this.props let selectedValue = value; const listing = []; for (let i = 0; i < options.length; i++) { const entry = options[i]; // Check whether the entry is a structired value or a string if (typeof entry === 'object') { // A structured value is expected to have at least a .value // element. Other optional elements are .key and .isDefault let entryKey = null; if (entry.key) { entryKey = entry.key; } else { entryKey = entry.value; } if ((entry.isDefault) && (selectedValue == null)) { selectedValue = entry.value; } listing.push({ key: entryKey, text: entry.value, value: entryKey }) } else { // Assumes entry to be a scalar (string) value listing.push({ key: entry, text: entry, value: entry }) } } return <Dropdown text={selectedValue} name={id} selection scrolling fluid options={listing} onChange={onChange} />; } }
JavaScript
class PolygonTesselator { constructor({polygons, IndexType}) { // Normalize all polygons polygons = polygons.map(polygon => Polygon.normalize(polygon)); // Count all polygon vertices const pointCount = getPointCount(polygons); this.polygons = polygons; this.pointCount = pointCount; this.IndexType = IndexType; // TODO: dynamically decide IndexType in tesselator? // Check if the vertex count excedes index type limit if (IndexType === Uint16Array && pointCount > 65535) { throw new Error("Vertex count exceeds browser's limit"); } this.attributes = { pickingColors: calculatePickingColors({polygons, pointCount}) }; } updatePositions({fp64, extruded}) { const {attributes, polygons, pointCount} = this; attributes.positions = attributes.positions || new Float32Array(pointCount * 3); attributes.nextPositions = attributes.nextPositions || new Float32Array(pointCount * 3); if (fp64) { // We only need x, y component attributes.positions64xyLow = attributes.positions64xyLow || new Float32Array(pointCount * 2); attributes.nextPositions64xyLow = attributes.nextPositions64xyLow || new Float32Array(pointCount * 2); } updatePositions({cache: attributes, polygons, extruded, fp64}); } indices() { const {polygons, IndexType} = this; return calculateIndices({polygons, IndexType}); } positions() { return this.attributes.positions; } positions64xyLow() { return this.attributes.positions64xyLow; } nextPositions() { return this.attributes.nextPositions; } nextPositions64xyLow() { return this.attributes.nextPositions64xyLow; } elevations({key = 'elevations', getElevation = x => 100} = {}) { const {attributes, polygons, pointCount} = this; const values = updateElevations({cache: attributes[key], polygons, pointCount, getElevation}); attributes[key] = values; return values; } colors({key = 'colors', getColor = x => DEFAULT_COLOR} = {}) { const {attributes, polygons, pointCount} = this; const values = updateColors({cache: attributes[key], polygons, pointCount, getColor}); attributes[key] = values; return values; } pickingColors() { return this.attributes.pickingColors; } }
JavaScript
class ToolRunner extends events.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(os.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + os.EOL.length); n = s.indexOf(os.EOL); } strBuffer = s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); } } _getSpawnFileName() { if (IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse .split('') .reverse() .join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return __awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes('/') || (IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve, reject) => { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); const fileName = this._getSpawnFileName(); const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); const stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } const errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } }); }); } }
JavaScript
class Node { static addStringTerminator(src, offset, str) { if (str[str.length - 1] === '\n') return str; const next = Node.endOfWhiteSpace(src, offset); return next >= src.length || src[next] === '\n' ? str + '\n' : str; } // ^(---|...) static atDocumentBoundary(src, offset, sep) { const ch0 = src[offset]; if (!ch0) return true; const prev = src[offset - 1]; if (prev && prev !== '\n') return false; if (sep) { if (ch0 !== sep) return false; } else { if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; } const ch1 = src[offset + 1]; const ch2 = src[offset + 2]; if (ch1 !== ch0 || ch2 !== ch0) return false; const ch3 = src[offset + 3]; return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; } static endOfIdentifier(src, offset) { let ch = src[offset]; const isVerbatim = ch === '<'; const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; if (isVerbatim && ch === '>') offset += 1; return offset; } static endOfIndent(src, offset) { let ch = src[offset]; while (ch === ' ') ch = src[offset += 1]; return offset; } static endOfLine(src, offset) { let ch = src[offset]; while (ch && ch !== '\n') ch = src[offset += 1]; return offset; } static endOfWhiteSpace(src, offset) { let ch = src[offset]; while (ch === '\t' || ch === ' ') ch = src[offset += 1]; return offset; } static startOfLine(src, offset) { let ch = src[offset - 1]; if (ch === '\n') return offset; while (ch && ch !== '\n') ch = src[offset -= 1]; return offset + 1; } /** * End of indentation, or null if the line's indent level is not more * than `indent` * * @param {string} src * @param {number} indent * @param {number} lineStart * @returns {?number} */ static endOfBlockIndent(src, indent, lineStart) { const inEnd = Node.endOfIndent(src, lineStart); if (inEnd > lineStart + indent) { return inEnd; } else { const wsEnd = Node.endOfWhiteSpace(src, inEnd); const ch = src[wsEnd]; if (!ch || ch === '\n') return wsEnd; } return null; } static atBlank(src, offset, endAsBlank) { const ch = src[offset]; return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; } static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { if (!ch || indentDiff < 0) return false; if (indentDiff > 0) return true; return indicatorAsIndent && ch === '-'; } // should be at line or string end, or at next non-whitespace char static normalizeOffset(src, offset) { const ch = src[offset]; return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); } // fold single newline into space, multiple newlines to N - 1 newlines // presumes src[offset] === '\n' static foldNewline(src, offset, indent) { let inCount = 0; let error = false; let fold = ''; let ch = src[offset + 1]; while (ch === ' ' || ch === '\t' || ch === '\n') { switch (ch) { case '\n': inCount = 0; offset += 1; fold += '\n'; break; case '\t': if (inCount <= indent) error = true; offset = Node.endOfWhiteSpace(src, offset + 2) - 1; break; case ' ': inCount += 1; offset += 1; break; } ch = src[offset + 1]; } if (!fold) fold = ' '; if (ch && inCount <= indent) error = true; return { fold, offset, error }; } constructor(type, props, context) { Object.defineProperty(this, 'context', { value: context || null, writable: true }); this.error = null; this.range = null; this.valueRange = null; this.props = props || []; this.type = type; this.value = null; } getPropValue(idx, key, skipKey) { if (!this.context) return null; const { src } = this.context; const prop = this.props[idx]; return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; } get anchor() { for (let i = 0; i < this.props.length; ++i) { const anchor = this.getPropValue(i, Char.ANCHOR, true); if (anchor != null) return anchor; } return null; } get comment() { const comments = []; for (let i = 0; i < this.props.length; ++i) { const comment = this.getPropValue(i, Char.COMMENT, true); if (comment != null) comments.push(comment); } return comments.length > 0 ? comments.join('\n') : null; } commentHasRequiredWhitespace(start) { const { src } = this.context; if (this.header && start === this.header.end) return false; if (!this.valueRange) return false; const { end } = this.valueRange; return start !== end || Node.atBlank(src, end - 1); } get hasComment() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] === Char.COMMENT) return true; } } return false; } get hasProps() { if (this.context) { const { src } = this.context; for (let i = 0; i < this.props.length; ++i) { if (src[this.props[i].start] !== Char.COMMENT) return true; } } return false; } get includesTrailingLines() { return false; } get jsonLike() { const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; return jsonLikeTypes.indexOf(this.type) !== -1; } get rangeAsLinePos() { if (!this.range || !this.context) return undefined; const start = getLinePos(this.range.start, this.context.root); if (!start) return undefined; const end = getLinePos(this.range.end, this.context.root); return { start, end }; } get rawValue() { if (!this.valueRange || !this.context) return null; const { start, end } = this.valueRange; return this.context.src.slice(start, end); } get tag() { for (let i = 0; i < this.props.length; ++i) { const tag = this.getPropValue(i, Char.TAG, false); if (tag != null) { if (tag[1] === '<') { return { verbatim: tag.slice(2, -1) }; } else { // eslint-disable-next-line no-unused-vars const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); return { handle, suffix }; } } } return null; } get valueRangeContainsNewline() { if (!this.valueRange || !this.context) return false; const { start, end } = this.valueRange; const { src } = this.context; for (let i = start; i < end; ++i) { if (src[i] === '\n') return true; } return false; } parseComment(start) { const { src } = this.context; if (src[start] === Char.COMMENT) { const end = Node.endOfLine(src, start + 1); const commentRange = new Range(start, end); this.props.push(commentRange); return end; } return start; } /** * Populates the `origStart` and `origEnd` values of all ranges for this * node. Extended by child classes to handle descendant nodes. * * @param {number[]} cr - Positions of dropped CR characters * @param {number} offset - Starting index of `cr` from the last call * @returns {number} - The next offset, matching the one found for `origStart` */ setOrigRanges(cr, offset) { if (this.range) offset = this.range.setOrigRange(cr, offset); if (this.valueRange) this.valueRange.setOrigRange(cr, offset); this.props.forEach(prop => prop.setOrigRange(cr, offset)); return offset; } toString() { const { context: { src }, range, value } = this; if (value != null) return value; const str = src.slice(range.start, range.end); return Node.addStringTerminator(src, range.end, str); } }
JavaScript
class Alarm extends alarm_base_1.AlarmBase { /** * @stability stable */ constructor(scope, id, props) { super(scope, id, { physicalName: props.alarmName, }); const comparisonOperator = props.comparisonOperator || ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD; // Render metric, process potential overrides from the alarm // (It would be preferable if the statistic etc. was worked into the metric, // but hey we're allowing overrides...) const metricProps = this.renderMetric(props.metric); if (props.period) { metricProps.period = props.period.toSeconds(); } if (props.statistic) { // Will overwrite both fields if present Object.assign(metricProps, { statistic: renderIfSimpleStatistic(props.statistic), extendedStatistic: renderIfExtendedStatistic(props.statistic), }); } const alarm = new cloudwatch_generated_1.CfnAlarm(this, 'Resource', { // Meta alarmDescription: props.alarmDescription, alarmName: this.physicalName, // Evaluation comparisonOperator, threshold: props.threshold, datapointsToAlarm: props.datapointsToAlarm, evaluateLowSampleCountPercentile: props.evaluateLowSampleCountPercentile, evaluationPeriods: props.evaluationPeriods, treatMissingData: props.treatMissingData, // Actions actionsEnabled: props.actionsEnabled, alarmActions: core_1.Lazy.list({ produce: () => this.alarmActionArns }), insufficientDataActions: core_1.Lazy.list({ produce: (() => this.insufficientDataActionArns) }), okActions: core_1.Lazy.list({ produce: () => this.okActionArns }), // Metric ...metricProps, }); this.alarmArn = this.getResourceArnAttribute(alarm.attrArn, { service: 'cloudwatch', resource: 'alarm', resourceName: this.physicalName, sep: ':', }); this.alarmName = this.getResourceNameAttribute(alarm.ref); this.metric = props.metric; const datapoints = props.datapointsToAlarm || props.evaluationPeriods; this.annotation = { // eslint-disable-next-line max-len label: `${this.metric} ${OPERATOR_SYMBOLS[comparisonOperator]} ${props.threshold} for ${datapoints} datapoints within ${describePeriod(props.evaluationPeriods * metric_util_1.metricPeriod(props.metric).toSeconds())}`, value: props.threshold, }; } /** * Import an existing CloudWatch alarm provided an ARN. * * @param scope The parent creating construct (usually `this`). * @param id The construct's name. * @param alarmArn Alarm ARN (i.e. arn:aws:cloudwatch:<region>:<account-id>:alarm:Foo). * @stability stable */ static fromAlarmArn(scope, id, alarmArn) { class Import extends alarm_base_1.AlarmBase { constructor() { super(...arguments); this.alarmArn = alarmArn; this.alarmName = core_1.Stack.of(scope).parseArn(alarmArn, ':').resourceName; } } return new Import(scope, id); } /** * Turn this alarm into a horizontal annotation. * * This is useful if you want to represent an Alarm in a non-AlarmWidget. * An `AlarmWidget` can directly show an alarm, but it can only show a * single alarm and no other metrics. Instead, you can convert the alarm to * a HorizontalAnnotation and add it as an annotation to another graph. * * This might be useful if: * * - You want to show multiple alarms inside a single graph, for example if * you have both a "small margin/long period" alarm as well as a * "large margin/short period" alarm. * * - You want to show an Alarm line in a graph with multiple metrics in it. * * @stability stable */ toAnnotation() { return this.annotation; } /** * Trigger this action if the alarm fires. * * Typically the ARN of an SNS topic or ARN of an AutoScaling policy. * * @stability stable */ addAlarmAction(...actions) { if (this.alarmActionArns === undefined) { this.alarmActionArns = []; } this.alarmActionArns.push(...actions.map(a => this.validateActionArn(a.bind(this, this).alarmActionArn))); } validateActionArn(actionArn) { var _b, _c, _d; const ec2ActionsRegexp = /arn:aws:automate:[a-z|\d|-]+:ec2:[a-z]+/; if (ec2ActionsRegexp.test(actionArn)) { // Check per-instance metric const metricConfig = this.metric.toMetricConfig(); if (((_c = (_b = metricConfig.metricStat) === null || _b === void 0 ? void 0 : _b.dimensions) === null || _c === void 0 ? void 0 : _c.length) != 1 || ((_d = metricConfig.metricStat) === null || _d === void 0 ? void 0 : _d.dimensions[0].name) != 'InstanceId') { throw new Error(`EC2 alarm actions requires an EC2 Per-Instance Metric. (${JSON.stringify(metricConfig)} does not have an 'InstanceId' dimension)`); } } return actionArn; } renderMetric(metric) { const self = this; return metric_util_1.dispatchMetric(metric, { withStat(stat, conf) { var _b, _c, _d; self.validateMetricStat(stat, metric); const canRenderAsLegacyMetric = ((_b = conf.renderingProperties) === null || _b === void 0 ? void 0 : _b.label) == undefined && (stat.account == undefined || core_1.Stack.of(self).account == stat.account); // Do this to disturb existing templates as little as possible if (canRenderAsLegacyMetric) { return object_1.dropUndefined({ dimensions: stat.dimensions, namespace: stat.namespace, metricName: stat.metricName, period: (_c = stat.period) === null || _c === void 0 ? void 0 : _c.toSeconds(), statistic: renderIfSimpleStatistic(stat.statistic), extendedStatistic: renderIfExtendedStatistic(stat.statistic), unit: stat.unitFilter, }); } return { metrics: [ { metricStat: { metric: { metricName: stat.metricName, namespace: stat.namespace, dimensions: stat.dimensions, }, period: stat.period.toSeconds(), stat: stat.statistic, unit: stat.unitFilter, }, id: 'm1', accountId: stat.account, label: (_d = conf.renderingProperties) === null || _d === void 0 ? void 0 : _d.label, returnData: true, }, ], }; }, withExpression() { // Expand the math expression metric into a set const mset = new rendering_1.MetricSet(); mset.addTopLevel(true, metric); let eid = 0; function uniqueMetricId() { return `expr_${++eid}`; } return { metrics: mset.entries.map(entry => metric_util_1.dispatchMetric(entry.metric, { withStat(stat, conf) { var _b; self.validateMetricStat(stat, entry.metric); return { metricStat: { metric: { metricName: stat.metricName, namespace: stat.namespace, dimensions: stat.dimensions, }, period: stat.period.toSeconds(), stat: stat.statistic, unit: stat.unitFilter, }, id: entry.id || uniqueMetricId(), accountId: stat.account, label: (_b = conf.renderingProperties) === null || _b === void 0 ? void 0 : _b.label, returnData: entry.tag ? undefined : false, }; }, withExpression(expr, conf) { var _b; const hasSubmetrics = mathExprHasSubmetrics(expr); if (hasSubmetrics) { assertSubmetricsCount(expr); } return { expression: expr.expression, id: entry.id || uniqueMetricId(), label: (_b = conf.renderingProperties) === null || _b === void 0 ? void 0 : _b.label, period: hasSubmetrics ? undefined : expr.period, returnData: entry.tag ? undefined : false, }; }, })), }; }, }); } /** * Validate that if a region is in the given stat config, they match the Alarm */ validateMetricStat(stat, metric) { const stack = core_1.Stack.of(this); if (definitelyDifferent(stat.region, stack.region)) { throw new Error(`Cannot create an Alarm in region '${stack.region}' based on metric '${metric}' in '${stat.region}'`); } } }
JavaScript
class CreateNetworkMappingInput { /** * Create a CreateNetworkMappingInput. * @member {object} [properties] Input properties for creating network * mapping. * @member {string} [properties.recoveryFabricName] Recovery fabric Name. * @member {string} [properties.recoveryNetworkId] Recovery network Id. * @member {object} [properties.fabricSpecificDetails] Fabric specific input * properties. * @member {string} [properties.fabricSpecificDetails.instanceType] * Polymorphic Discriminator */ constructor() { } /** * Defines the metadata of CreateNetworkMappingInput * * @returns {object} metadata of CreateNetworkMappingInput * */ mapper() { return { required: false, serializedName: 'CreateNetworkMappingInput', type: { name: 'Composite', className: 'CreateNetworkMappingInput', modelProperties: { properties: { required: false, serializedName: 'properties', type: { name: 'Composite', className: 'CreateNetworkMappingInputProperties' } } } } }; } }
JavaScript
class Page2 extends React.Component { constructor(props) { super(props); this.state={ username: '', email: '', // modalIsOpen: false, }; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); const data = new FormData(e.target); const curUsername = data.get('username'), curEmail = data.get('email'); // On submit of the form, send a POST request with the data to the server. fetch(`signupparticipant`,{ method: 'POST', body:JSON.stringify({ username: curUsername, email: curEmail, // modalIsOpen: true }), headers: {"Content-Type": "application/json"} }) .then(function(response){ return response.json() }).then(function(body){ // console.log(body); alert(curEmail); }) .catch(err => console.log(err)); this.username.value =""; this.email.value=""; this.checkbox1.checked=false; this.checkbox2.checked=false; this.props.history.push('/ParticipantSignUpPending'); } render() { let email = this.state.email; return ( <div className="mainpage"> {!email && <div className="wrappermainpage"> <div className="wrapperpage2"> <div style={{width: 'auto', margin: 'auto', color:"dimgray"}}> <Step.Group ordered size="mini" > <Step active > <Step.Content> <Step.Title>Enrolling</Step.Title> <Step.Description>Insert your email </Step.Description> </Step.Content> </Step> <Step disabled > <Step.Content> <Step.Title>Confirmed Email </Step.Title> <Step.Description>Welcome to our Survey</Step.Description> </Step.Content> </Step> <Step disabled > <Step.Content> <Step.Title>Survey Questions</Step.Title> <Step.Description>Please answer questions</Step.Description> </Step.Content> </Step> <Step disabled > <Step.Content> <Step.Title>Rating and Further Experiences</Step.Title> <Step.Description>Please rate our survey</Step.Description> </Step.Content> </Step> <Step disabled > <Step.Content> <Step.Title>Survey Submitted</Step.Title> <Step.Description>Thanks for your participation</Step.Description> </Step.Content> </Step> </Step.Group> </div> <Segment > <form onSubmit={this.handleSubmit}> <table> <p className="ppage2" > Please insert your name and email address(Name just used as alias) </p> <div className="form-group-p2"> <Icon name='user' style={{color:"black"}}/> <input placeholder= "Name" type="username" name="username" className="form-control-2" ref={(a) => this.username = a} required/> </div> <div className="form-group-p2"> <Icon name='mail' style={{color:"black"}} /> <input placeholder= "Email" type="email" name="email" className="form-control-2" ref={(a) => this.email = a} required/> </div> <div className="form-group-pag2"> <label className="labelpage1" style={{fontFamily: "sans-serif", fontSize:'15px'}}> <input type="checkbox" name="checkbox1" className="form-control-12" ref={(a) => this.checkbox1 = a} required /> I agree to the <Modal trigger={<a style={{fontFamily: "sans-serif", fontSize:'15px', color:"blue"}}> {' '}Terms & Use </a>} header='Pollinator Insect Online Survey' content={<p style={{ padding: '15px', textAlign:'justify'}}>Thank you for interest in participating in this survey. This survey is run by the University of New England ... <br/> In this survey you will be shown a series of images of insect pollinators, and will be asked to identify the type of insect shown in each by selecting multiple choice answers. </p>} actions={[ { key: 'done', content: 'Agree', positive: true }, ]} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', textAlign:'justify'}} /> , including our Cookie use </label> </div> <div className="form-group-pag2"> <input type="checkbox" name="checkbox2" className="form-control-12" ref={(a) => this.checkbox2 = a} required /> <label className="labelpage1" style={{fontFamily: "sans-serif", fontSize:'15px'}}> I have not undertaken</label> </div> <button type="submit" className="btn-primary21" style={{fontFamily: "sans-serif", fontSize:'15px', paddingLeft:"40px"}} > Send Email </button> </table> </form> </Segment> </div> </div> } </div> ); } }
JavaScript
class PathsClass extends BaseClass { getSplineFromCoords (coords) { const startLat = coords[0] const startLng = coords[1] const endLat = coords[2] const endLng = coords[3] // start and end points const start = latLongToCartesian(startLat, startLng, this.config.scene.globeRadius) const end = latLongToCartesian(endLat, endLng, this.config.scene.globeRadius) // altitude const altitude = clamp(start.distanceTo(end) * 0.75, this.config.curveMinAltitude, this.config.curveMaxAltitude) // 2 control points const interpolate = geoInterpolate([startLng, startLat], [endLng, endLat]) const midCoord1 = interpolate(0.25 + (Math.random() * 0.1)) const midCoord2 = interpolate(0.75 + (Math.random() * 0.1)) const mid1 = latLongToCartesian(midCoord1[1], midCoord1[0], this.config.scene.globeRadius + altitude) const mid2 = latLongToCartesian(midCoord2[1], midCoord2[0], this.config.scene.globeRadius + altitude) return { start, end, spline: new CubicBezierCurve3(start, mid1, mid2, end) } } init (data) { this.coords = data this.material = new MeshBasicMaterial({ blending: AdditiveBlending, opacity: 0.4, transparent: true, depthWrite: false, color: new Color(0x003a62) }) this.mesh = new Mesh() this.lineCount = 700 this.counters = [] for (let index = 0; index < this.lineCount; index++) { const randIndex1 = Math.floor(Math.random() * this.coords.length) const randIndex2 = Math.floor(Math.random() * this.coords.length) this.addLine(randIndex1, randIndex2) } super.init() } addLine (index1, index2) { this.counters.push(Math.floor(Math.random() * this.config.curveSegments)) const start = this.coords[index1] const end = this.coords[index2] if (typeof start === 'undefined' || typeof end === 'undefined') { return } const { spline } = this.getSplineFromCoords([ start.lat, start.long, end.lat, end.long ]) // add curve geometry const curveGeometry = new BufferGeometry() const points = new Float32Array(this.config.curveSegments * 3) const vertices = spline.getPoints(this.config.curveSegments - 1) for (let i = 0, j = 0; i < vertices.length; i++) { const vertex = vertices[i] points[j++] = vertex.x points[j++] = vertex.y points[j++] = vertex.z } curveGeometry.setAttribute('position', new BufferAttribute(points, 3)) curveGeometry.setDrawRange(0, 0) let mesh = new Line(curveGeometry, this.material) this.mesh.add(mesh) } addNode (data) { this.coords.push(data) for (let index = 0; index < 10; index++) { this.addLine(this.coords.length - 1, Math.floor(Math.random() * this.coords.length)) } } renderFrame (args) { this.mesh.children.forEach((line, index) => { this.counters[index] += (args.dt * 30.0) if (this.counters[index] > this.config.curveSegments) { this.counters[index] = Math.floor(Math.random() * this.config.curveSegments) } line.geometry.setDrawRange(0, this.counters[index]) }) super.renderFrame() } }
JavaScript
class _Text { // Y.Text: insert(position,string) delete(position,length) get(i) toString() bindTextarea(htmlElement) observe({insert|delete}) constructor(ytext) { this.ytext = ytext } init(jso) { this.ytext.insert(0, jso) } overwrite(s) { this.ytext.delete(0, this.ytext.toString().length) this.ytext.insert(0, s) } toJs() { return this.ytext.toString() } yText() { return this.ytext } }
JavaScript
class ExtendedSearch { constructor( pattern, { isCaseSensitive = Config.isCaseSensitive, includeMatches = Config.includeMatches, minMatchCharLength = Config.minMatchCharLength, ignoreLocation = Config.ignoreLocation, findAllMatches = Config.findAllMatches, location = Config.location, threshold = Config.threshold, distance = Config.distance } = {} ) { this.query = null; this.options = { isCaseSensitive, includeMatches, minMatchCharLength, findAllMatches, ignoreLocation, location, threshold, distance }; this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); this.query = parseQuery(this.pattern, this.options); } static condition(_, options) { return options.useExtendedSearch } searchIn(text) { const query = this.query; if (!query) { return { isMatch: false, score: 1 } } const { includeMatches, isCaseSensitive } = this.options; text = isCaseSensitive ? text : text.toLowerCase(); let numMatches = 0; let allIndices = []; let totalScore = 0; // ORs for (let i = 0, qLen = query.length; i < qLen; i += 1) { const searchers = query[i]; // Reset indices allIndices.length = 0; numMatches = 0; // ANDs for (let j = 0, pLen = searchers.length; j < pLen; j += 1) { const searcher = searchers[j]; const { isMatch, indices, score } = searcher.search(text); if (isMatch) { numMatches += 1; totalScore += score; if (includeMatches) { const type = searcher.constructor.type; if (MultiMatchSet.has(type)) { allIndices = [...allIndices, ...indices]; } else { allIndices.push(indices); } } } else { totalScore = 0; numMatches = 0; allIndices.length = 0; break } } // OR condition, so if TRUE, return if (numMatches) { let result = { isMatch: true, score: totalScore / numMatches }; if (includeMatches) { result.indices = allIndices; } return result } } // Nothing was matched return { isMatch: false, score: 1 } } }
JavaScript
class EntitySet { constructor(collection, entities) { this.collection = collection; this.set = new Set(entities); } // Return a new set containing only the entities from this set which // have the given tag. and(tag) { return this.filter((entity) => entity.tags.has(tag)); } // Return a new set containing only the entities from this set which // do not have the given tag. andNot(tag) { return this.filter((entity) => !entity.tags.has(tag)); } // Return a new set containing a union between this set and the set of // entities which have the given tag. or(tag) { return new EntitySet(this.collection, [ ...this.set, ...this.collection.get(tag), ]); } // Return a new set filtered in a similar way to `Array.prototype.filter`. filter(callback) { const filtered = new EntitySet(this.collection); this.forEach((entity) => { if (callback(entity)) filtered.set.add(entity); }); return filtered; } // See `Set.prototype.forEach`. forEach(callback) { this.set.forEach(callback); } // Allow iteration of this object. [Symbol.iterator]() { return this.set.values(); } }
JavaScript
class RepoHome extends Component { constructor(props) { super(props); this.state = { isLoaded: false, error: null, repo: null }; this.repoId = this.props.match.params.repoId; this.goToCreate = this.goToCreate.bind(this); this.handleSearch = this.handleSearch.bind(this); } goToCreate() { this.props.history.push(`/${this.repoId}/create`); } handleSearch(query) { this.props.history.push({ pathname: `/${this.repoId}/results`, search: '?query_name=' + encodeURIComponent(query), }); } componentDidMount() { const apiUrl = `/${this.repoId}/d/repo`; fetch(apiUrl) .then(res => res.json()) .then( (repo) => { this.setState({ isLoaded: true, repo: repo }); }, (error) => { this.setState({ isLoaded: true, error: error }); } ); } render() { if (this.state.error) { return <div>An error occurred</div> } if (!this.state.isLoaded) { return <LoadingIndicator />; } var recordCountContent = null; if (this.state.repo.recordCount > 0) { recordCountContent = ( <p className='mdc-typography--body1 repohome-recordcount'> <FormattedMessage {...MESSAGES.repoRecordCount} values={{ 'recordCount': this.state.repo.recordCount }} /> </p> ); } return ( <div> <RepoHeader repo={this.state.repo} backButtonTarget={'/'} /> <div className='repohome-body'> <SearchBar repoId={this.repoId} initialValue='' onSearch={this.handleSearch} /> {recordCountContent} <EndBarHeader> <FormattedMessage {...MESSAGES.or} /> </EndBarHeader> <Button className='pf-button-secondary' raised onClick={this.goToCreate} > {this.props.intl.formatMessage(MESSAGES.provideInfoAboutSomeone)} </Button> </div> <Footer /> </div>); } }
JavaScript
class ControladorJogo { static inicializar() { ControladorJogo._previaJogo = previaJogo; //PREVIA JOGO: se eh previaJogo, vai ter apenas um level com todos os diferenciais (vai mostrar a estrutura de interseccao de X de tempo ateh o final, vai ter soh as pocoes mais legais, o level vai acabar depois de um certo tempo e falar quais sao os diferenciais desse jogo) //ps: ver se da pra mostrar as formasGeometricas de Interseccao.vaiIntersectar(...) (printar de outra cor) //ps2: colocar texto na tela explicando que vao aparecer figuras na tela pra demonstrar como a estrutura de Colisao eh feita //ps3: deixar o personagem com muito mais vida (pra ele nao morrer antes de acabar o tempo) ControladorJogo._estadoJogo = EstadoJogo.NaoComecou; //quando personagem mudar estado do jogo (pausar), novo atributo: ControladorJogo._estadoJogoAnterior //arrumar background inicio const medidasPadrao = { width: 2880, height: 1800 }; //img.width e img.height nao estah funcionando const img = ArmazenadorInfoObjetos.getImagem("Outros/background_inicio"); const medidas = { height: height, width: medidasPadrao.width * height / medidasPadrao.height/*calcular width da imagem a partir do height*/ }; const ponto = new Ponto((width - medidas.width) / 2, 0); ControladorJogo._infoBackgroundInicio = { img: img, medidas: medidas, ponto: ponto }; } //GETTER // Atributos de Estado static get estadoJogo() { return ControladorJogo._estadoJogo; } static get criandoLevel() { return ControladorJogo._criandoLevel; } static get level() { return ControladorJogo._level; } static get previaJogo() { return ControladorJogo._previaJogo; } static get conjuntoDrawsEspeciais() { return ControladorJogo._conjuntoDrawsEspeciais; } // ObjetosTela static get pers() { return ControladorJogo._personagemPrincipal; } static get controladoresInimigos() { return ControladorJogo._controladoresInimigos; } static get controladorSuportesAereos() { return ControladorJogo._controladorSuportesAereos; } static get controladoresObstaculos() { return ControladorJogo._controladoresObstaculos; } static get controladorOutrosTirosNaoPers() { return ControladorJogo._controladorOutrosTirosNaoPers; } static get controladorPocaoTela() { return ControladorJogo._controladorPocaoTela; } static get oficina() { return ControladorJogo._oficina; } static get escuridao() { return ControladorJogo._escuridao; } //inicializacao static comecarJogo() { //para setar tamanho dos objetos corretamente e ser proporcional ao width ArmazenadorInfoObjetos.inicializar(); //para draws especiais ControladorJogo._conjuntoDrawsEspeciais = new ConjuntoDrawsEspeciaisJogo(); //personagem original if (ControladorJogo._previaJogo) //se eh a previa ControladorJogo._personagemPrincipal = new PersonagemPrincipal(ArmazenadorInfoObjetos.infoAviaoMasterPers); else ControladorJogo._personagemPrincipal = new PersonagemPrincipal(ArmazenadorInfoObjetos.infoAviaoOriginalPers); ControladorJogo._personagemPrincipal.colocarLugarInicial(); //controlador pocao (1 pra todos os levels) ControladorJogo._controladorPocaoTela = new ControladorPocaoTela(); //controladorOutrosTirosNaoPers: para os tiros dos inimigos e dos suportes aereos que forem retirados do vetor nao sumirem ControladorJogo._controladorOutrosTirosNaoPers = new ControladorTiros(null, false); //let's start baby... ControladorJogo._level = 1; ControladorJogo._iniciarLevel(); ControladorJogo._estadoJogo = EstadoJogo.Jogando; } //inicializar level static _iniciarLevel() // retorna se ainda tem levels { ControladorJogo._criandoLevel = true; //Para tiros de inimigos e suportes aereos do level anterior nao sumirem: //concatenar tiros dos inimigos e do jogo em controladorTiros[0] quando for passar de level (antes de deletar os controladoresTirosJogo e controladoresInimigos) //se jah estah no 2o level em diante (antes do 1o level nao tinha nenhum tiro sem dono) if (ControladorJogo._level > 1) { let concatTirosEmSemDono = objComArmas => /*cada um dos objetos com armas*/ { objComArmas.armas.forEach(arma => /*cada uma das armas do objeto com armas atual*/ ControladorJogo._controladorOutrosTirosNaoPers.concatenarTiros(arma.controlador) // concatenar todos os tiros dessa arma em controladorOutrosTirosNaoPers ); } ControladorJogo._controladorSuportesAereos.suportesAereos.forEach(concatTirosEmSemDono); ControladorJogo._controladoresInimigos.forEach(controladorInims => /*cada um dos controladores*/ controladorInims.inimigos.forEach(concatTirosEmSemDono)); } //zerar tudo ControladorJogo._controladoresInimigos = []; ControladorJogo._controladoresObstaculos = []; ControladorJogo._controladorSuportesAereos = null; //soh os dos inimigos delete ControladorJogo._escuridao; //mudar : ControladorJogo._controladoresInimigos, ControladorJogo._controladoresObstaculos, ControladorJogo._controladorSuportesAereos (opcional) // ATENCAO: NENHUM DESSES MEMBROS PODEM SER NULOS, POREM PODEM SER UM ARRAY DE ZERO POSICOES if (ControladorJogo._previaJogo) { //PREVIA JOGO: fazer dois levels (pra poder ver a Oficina) //obs: quando comecar o segundo level, depois de um certo tempo, mostrar o Sistema de Colisao! let length; switch (ControladorJogo._level) { case 1: { // inimigos //Aviao Master Inim (parado no meio) const infoAviaoMaster = ArmazenadorInfoObjetos.infoInim("AviaoMaster", { ficarParado: true }); const infoAparecAviaoMaster = new InfoObjetoTelaAparecendo(true, true); length = ControladorJogo._controladoresInimigos.push(new ControladorInimigos(infoAviaoMaster, true, infoAparecAviaoMaster)); const yAviaoMaster = 0.45 * height - infoAviaoMaster.formaGeometrica.height / 2; ControladorJogo._controladoresInimigos[length - 1].indexContr = length - 1; ControladorJogo._controladoresInimigos[length - 1].adicionarInimigo({ posicaoX: PosicaoX.Meio, y: yAviaoMaster }); //Aviao Bruto SemHel const infoAviaoBruto = ArmazenadorInfoObjetos.infoInim("AviaoBrutoSemHel"); const yAviaoBruto = 20; const infoAparecAviaoBruto = new InfoObjetoTelaAparecendo(false, false, new Ponto(0, -(infoAviaoBruto.formaGeometrica.height + yAviaoBruto))); length = ControladorJogo._controladoresInimigos.push(new ControladorInimigos(infoAviaoBruto, false, infoAparecAviaoBruto)); ControladorJogo._controladoresInimigos[length - 1].indexContr = length - 1; const qtdAfastadoParede = 40; const porcWidthRetBrutoAndar = 0.4; ControladorJogo._controladoresInimigos[length - 1].adicionarInimigoDif({ posicaoX: PosicaoX.ParedeEsquerda, x: qtdAfastadoParede, y: yAviaoBruto }, { direcao: Direcao.Direita }, { infoAndar: { outrasInformacoes: { retangulo: { x: 0, width: porcWidthRetBrutoAndar } } } }); ControladorJogo._controladoresInimigos[length - 1].adicionarInimigoDif({ posicaoX: PosicaoX.ParedeDireita, x: -qtdAfastadoParede, y: yAviaoBruto }, { direcao: Direcao.Esquerda }, { infoAndar: { outrasInformacoes: { retangulo: { x: -porcWidthRetBrutoAndar, width: porcWidthRetBrutoAndar } } } }); //obstaculos //ComLaserA const porcWidthRetObstAndar = 0.18; const infoObstComLaser = ArmazenadorInfoObjetos.infoObst("ComLaserA", { direcao: Direcao.Baixo }, TipoAndar.PermanecerEmRetangulo, { retangulo: { y: 0, height: porcWidthRetObstAndar } }); const infoAparecObstComLaser = new InfoObjetoTelaAparecendo(true, true); length = ControladorJogo._controladoresObstaculos.push(new ControladorObstaculos(infoObstComLaser, infoAparecObstComLaser)); ControladorJogo._controladoresObstaculos[length - 1].indexContr = length - 1; const yObstComLaser = 0.6 * height; const qtdAfastadoParedeObstComLaser = width * 0.15; ControladorJogo._controladoresObstaculos[length - 1].adicionarObstaculoDif({ posicaoX: PosicaoX.ParedeEsquerda, x: qtdAfastadoParedeObstComLaser, y: yObstComLaser }); ControladorJogo._controladoresObstaculos[length - 1].adicionarObstaculoDif({ posicaoX: PosicaoX.ParedeDireita, x: -qtdAfastadoParedeObstComLaser, y: yObstComLaser }); } break; //se tiver mais levels colocar aqui, mudar em: ControladorJogo.tempoEstimadoLevel(), ControladorJogo._acabouLevel(), ControladorPocaoTela.pocoesPossiveisFromLevel(...), ControladorPocaoTela.probabilidadeFromLevel(...) default: return false; //acabaram os levels } } else { let length; switch (ControladorJogo._level) { case 1: case 2: { // inimigos //Inimigo Normal Medio (essencial) const infoInimMedio = ArmazenadorInfoObjetos.infoInim("HelicopteroBom", { ficarParado: true }); const infoInimMedioAparec = new InfoObjetoTelaAparecendo(false, false, new Ponto(0, -70)); //ObjetoAparecendo length = ControladorJogo._controladoresInimigos.push(new ControladorInimigos(infoInimMedio, true, infoInimMedioAparec)); ControladorJogo._controladoresInimigos[length - 1].indexContr = length - 1; ControladorJogo._controladoresInimigos[length - 1].adicionarInimigo({ posicaoX: PosicaoX.Meio, y: 15 }); // obstaculos } break; case 10: { //ganha nave espacial ControladorJogo._personagemPrincipal = ControladorJogo._personagemPrincipal.novaNave(ArmazenadorInfoObjetos.infoAviaoMasterPers); } break; //se tiver mais levels colocar aqui, mudar em: ControladorJogo.tempoEstimadoLevel(), ControladorJogo._acabouLevel(), ControladorPocaoTela.pocoesPossiveisFromLevel(...), ControladorPocaoTela.probabilidadeFromLevel(...) default: console.log("Acabaram as fases... vishh Luca tá fraco!!"); return false; //acabaram os levels } } //para nao ter que ficar verificando se eh undefined toda hora: if (ControladorJogo._controladorSuportesAereos === null) ControladorJogo._controladorSuportesAereos = new ControladorSuportesAereos(); ControladorJogo._criandoLevel = false; // programar para o "Level X" da tela desaparecer //programar para colocar "Level X" na tela ControladorJogo._conjuntoDrawsEspeciais.adicionarMetodoDraw(() => { push(); textSize(40); fill(0); textAlign(CENTER, CENTER); text("Level " + ControladorJogo._level, width / 2, (height - heightVidaUsuario) / 2); pop(); }, 3000); //adicionar timers do level atual depois que os ObjetosTela criados acabarem de aparecer new Timer(() => { ControladorJogo._adicionarTimersLevel(); }, tempoObjetoAparecerAntesIniciarLv); return true; //ainda tem mais levels } static _adicionarTimersLevel() { if (ControladorJogo._previaJogo) { //PREVIA JOGO switch (ControladorJogo._level) { case 1: { // inimigos const infoMostrarVida = { mostrarVidaSempre: false }; const tempoAddCadaInimigo = 27000; //Aviao Normal Bom Escuro (seguindo pers) //criar controlador const infoAviaoBom = ArmazenadorInfoObjetos.infoInim("AviaoNormalBomEscuro", undefined/*alteracoesAndarRotacionar*/, undefined/*outrasInformacoesAndar*/, TipoAndar.SeguirPers, infoMostrarVida); const infoAparecAviaoBom = new InfoObjetoTelaAparecendo(true, true); const lengthBom = ControladorJogo._controladoresInimigos.push(new ControladorInimigos(infoAviaoBom, false, infoAparecAviaoBom)); ControladorJogo._controladoresInimigos[lengthBom - 1].indexContr = lengthBom - 1; //adicionar inimigo new Timer(() => { new Timer(() => { const surgirEsquerda = Probabilidade.chance(1, 2); //ponto inicial const qtdAfastadoParede = 20; const pontoInicial = { posicaoX: (surgirEsquerda) ? PosicaoX.ParedeEsquerda : PosicaoX.ParedeDireita, x: qtdAfastadoParede * (surgirEsquerda) ? 1 : -1, y: 25 }; //mudar qtdAndar e rotacao const anguloAponta = PI / 4 * ((surgirEsquerda) ? -1 : 1); const alteracoesAndarRotacionar = { direcaoAnguloAponta: anguloAponta, ehAngulo: true, angulo: -Angulo.angRotacaoParaAngCicloTrig(PI + anguloAponta) }; ControladorJogo._controladoresInimigos[lengthBom - 1].adicionarInimigoDif(pontoInicial, alteracoesAndarRotacionar); }, tempoAddCadaInimigo, Timer.ehIntervalFazerAoCriar); }, tempoAddCadaInimigo * 0.5, false) //Aviao Supersonico Rapido (se movimentando) //criar controlador const infoAviaoSupersonico = ArmazenadorInfoObjetos.infoInim("AviaoSupersonicoRapido", undefined/*alteracoesAndarRotacionar*/, undefined/*outrasInformacoesAndar*/, TipoAndar.PermanecerEmRetangulo/*permanecer dentro da tela, pois nao tem nenhuma*/, infoMostrarVida); const infoAparecAviaoSupersonico = new InfoObjetoTelaAparecendo(true, true); const lengthSupersonico = ControladorJogo._controladoresInimigos.push(new ControladorInimigos(infoAviaoSupersonico, false, infoAparecAviaoSupersonico)); ControladorJogo._controladoresInimigos[lengthSupersonico - 1].indexContr = lengthSupersonico - 1; //adicionar inimigo new Timer(() => { const surgirEsquerda = Probabilidade.chance(1, 2); const qtdAfastadoParede = 20; ControladorJogo._controladoresInimigos[lengthSupersonico - 1].adicionarInimigo({ posicaoX: (surgirEsquerda) ? PosicaoX.ParedeEsquerda : PosicaoX.ParedeDireita, x: qtdAfastadoParede * (surgirEsquerda) ? 1 : -1, y: 200 }); }, tempoAddCadaInimigo, Timer.ehIntervalNaoFazerAoCriar); // obstaculos // escuridao let infoEscuridao = new InfoEscuridao(); //repeticoes: de 2 a 3 infoEscuridao.qtdRepeticoes = 2.5; infoEscuridao.desvioQtdRep = 0.5; //tempo infoEscuridao.tempoEscurecendo = 600; infoEscuridao.tempoEscuroTotal = 200; infoEscuridao.intervaloEntreEscClarMsmBloco = 200; //tempo entre cada escurecer-clarear do mesmo bloco infoEscuridao.intervalo = 15000; //tempo sem escuridao //desvios infoEscuridao.desvioTempoEscurec = 0; infoEscuridao.desvioEscuroTotal = 20; infoEscuridao.desvioIntervalo = 0; ControladorJogo._escuridao = new Escuridao(infoEscuridao); } break; } } else { //criar: // - todos os controladores que soh terao objetos adicionados por Timers e esses Timers // - outros Timers que vao ser usados no Level // - Escuridao (tambem tem um Timer dentro dele) switch (ControladorJogo._level) { case 1: { const infoObstRotatorio = ArmazenadorInfoObjetos.infoObst("Rotatorio"); const yObstRotatorio = 25; const lengthObstRotatorio = ControladorJogo._controladoresObstaculos.push(new ControladorObstaculos(infoObstRotatorio, new InfoObjetoTelaAparecendo(true, true))); ControladorJogo._controladoresObstaculos[lengthObstRotatorio - 1].indexContr = lengthObstRotatorio - 1; new Timer(() => { // y const y = height * 0.5; // x const xDir = width * 0.6; const xEsq = width * 0.4; //ADICIONAR ControladorJogo._controladoresObstaculos[lengthObstRotatorio - 1].adicionarObstaculoDif({ x: xEsq, y: y }, { direcao: Direcao.Direita }); ControladorJogo._controladoresObstaculos[lengthObstRotatorio - 1].adicionarObstaculoDif({ x: xDir, y: y }, { direcao: Direcao.Esquerda }); }, 3000, Timer.ehIntervalFazerAoCriar); // escuridao /* let infoEscuridao = new InfoEscuridao(); infoEscuridao.tempoEscurecendo = 800; infoEscuridao.desvioTempoEscurec = 0; infoEscuridao.tempoEscuroTotal = 0; infoEscuridao.desvioEscuroTotal = 0; infoEscuridao.intervaloEntreEscClarMsmBloco = 200; infoEscuridao.intervalo = 10000; infoEscuridao.desvioIntervalo = 0; infoEscuridao.qtdRepeticoes = 2; infoEscuridao.desvioQtdRep = 0; ControladorJogo._escuridao = new Escuridao(infoEscuridao); */ } break; } } //POCAO (pode ter mais de uma pocao por level, mas apenas uma na tela de cada vez) //esse metodo vai programar para adicionar quantas pocoes o level permita (se Probabilidade.chance()) //e jah vai programar para tira-lo caso ele nao seja pego dentro do tempo ControladorJogo._controladorPocaoTela.programarPocoesLevel(); } //passar de level static _passarLevel() //retorna se pers ganhou { ControladorJogo._level++; //passa de level ConjuntoTimers.excluirTimersDoLevel(); //finaliza timers antigos atrelacados ao level e os exclui ControladorJogo._conjuntoDrawsEspeciais.procPassouLevel(); //remove funcoes draw que nao transcendem o level const aindaTemLevel = ControladorJogo._iniciarLevel(); //proximo level if (aindaTemLevel === false) return true; // pers ganhou //cria oficina ControladorJogo._oficina = new Oficina(ControladorJogo._level); //programar para tirar oficina new Timer(() => { delete ControladorJogo._oficina; }, 5000); return false; //pers nao ganhou } static tempoEstimadoLevel(level) //retornar tempo em segundos { if (ControladorJogo.previaJogo) return 50; // TODO: ajeitar tempo cada level switch (level) { case 1: return 25; case 2: return 40; case 3: return 60; case 4: return 65; case 5: return 70; case 6: return 75; case 7: return 80; case 8: return 85; case 9: return 90; case 10: return 95; case 11: return 100; case 12: return 105; case 13: return 110; case 14: return 115; case 15: return 120; } } //FUNCIONALIDADES PROGRAMA FAZ SOZINHO //andar tiros static _andarTiros() { //tiros do personagem ControladorJogo._personagemPrincipal.andarTiros(); //tiros sem dono ControladorJogo._controladorOutrosTirosNaoPers.andarTiros(); //tiros dos suportes aereos ControladorJogo._controladorSuportesAereos.suportesAereos.forEach(suporteAereo => suporteAereo.andarTiros()); //tiros dos inimigos ControladorJogo._controladoresInimigos.forEach(controladorInims => controladorInims.andarTirosTodosInim()); } //andar inimigos e obstaculos static _andarInimObst() { //andar obstaculos ControladorJogo._controladoresObstaculos.forEach(controladorObsts => controladorObsts.andarObstaculos()); //andar inimigos ControladorJogo._controladoresInimigos.forEach(controladorInims => controladorInims.andarInimigos()); } //atirar automatico static _atirarAutomatico() { //personagem ControladorJogo._personagemPrincipal.atirar(); //inimigos ControladorJogo._controladoresInimigos.forEach(controladorInims => controladorInims.atirarTodosInim()); //suportes aereos ControladorJogo._controladorSuportesAereos.suportesAereos.forEach(suporteAereo => suporteAereo.atirar()); } //FUNCINALIDADES PERSONAGEM //andar static andarPers(direcaoX, direcaoY) //setinhas ou WASD { //se estah jogando (jah comecou, nao estah pausado e o personagem nao morreu) if (ControladorJogo._estadoJogo === EstadoJogo.Jogando) ControladorJogo._personagemPrincipal.andar(direcaoX, direcaoY); } //tiro nao automatico static persPuxouGatilho() //E { // para o aviao especial... (arma do index zero o personagem que atira manualmente) if (ControladorJogo._estadoJogo === EstadoJogo.Jogando && ControladorJogo._personagemPrincipal.ehAviaoMaster) ControladorJogo._personagemPrincipal.puxarGatilho(indexArmaNaoAutomaticaAviaoMasterPers); } //POCAO static ativarPocaoPers() //Q { //se estah jogando (jah comecou, nao estah pausado e o personagem nao morreu) if (ControladorJogo._estadoJogo === EstadoJogo.Jogando) ControladorJogo._personagemPrincipal.controladorPocoesPegou.usarPocaoAtual(); } //pausado/despausado static mudarPausado() //enter { // pra pausar, o jogo jah tem que ter comecado if (ControladorJogo._estadoJogo === EstadoJogo.NaoComecou) return; if (ControladorJogo._estadoJogo === EstadoJogo.Pausado) { ControladorJogo._estadoJogo = ControladorJogo._estadoJogoAnterior; delete ControladorJogo._estadoJogoAnterior; } else ControladorJogo._pausarJogo(); } static pausar() //quando a janela perder o foco { if (ControladorJogo._estadoJogo !== EstadoJogo.NaoComecou || ControladorJogo._estadoJogo !== EstadoJogo.Pausado) // se da pra pausar e nao estah pausado jah ControladorJogo._pausarJogo(); } static _pausarJogo() { ControladorJogo._estadoJogoAnterior = ControladorJogo._estadoJogo; ControladorJogo._estadoJogo = EstadoJogo.Pausado; } //para saber se painel personagem vai ser printado normal ou um pouco opaco static algumObjetoImportanteNesseEspaco(retanguloEspaco) // ObjetosImportantes: PersonagemPrincipal, Pocao, Inimigos (normal ou aparecendo), Obstaculos (normal ou aparecendo) { //se jogo ainda nao comecou ou jah acabou, nao tem nenhum objeto importante no espaco if (ControladorJogo._estadoJogo !== EstadoJogo.Jogando && ControladorJogo._estadoJogo !== EstadoJogo.Morto) return false; //PersonagemPrincipal if (ControladorJogo._personagemPrincipal.formaGeometrica !== undefined && //se jah morreu e acabou imgs morto Interseccao.interseccaoComoRetangulos(retanguloEspaco, ControladorJogo._personagemPrincipal.formaGeometrica)) return true; //Pocao if (ControladorJogo._controladorPocaoTela.temObjPocao && Interseccao.interseccaoComoRetangulos(retanguloEspaco, ControladorJogo._controladorPocaoTela.objPocao.formaGeometrica)) return true; //Inimigos const interseccaoAlgumInim = ControladorJogo._controladoresInimigos.some(controladorInims => controladorInims.algumInimNesseEspaco(retanguloEspaco)); if (interseccaoAlgumInim) return true; //SuportesAereos const interseccaoAlgumSuporteAereo = ControladorJogo._controladorSuportesAereos.suportesAereos.some(suporteAereo => Interseccao.interseccaoComoRetangulos(retanguloEspaco, suporteAereo.formaGeometrica)); if (interseccaoAlgumSuporteAereo) return true; //Obstaculos const interseccaoAlgumObst = ControladorJogo._controladoresObstaculos.some(controladorObsts => controladorObsts.algumObstNesseEspaco(retanguloEspaco)); if (interseccaoAlgumObst) return true; // nao tem nenhum objeto importante nesse espaco return false; } //acabar jogo //perdeu static persMorreu() { ControladorJogo._estadoJogo = EstadoJogo.Morto; } static _persPerdeu() { //mudar estado jogo ControladorJogo._estadoJogo = EstadoJogo.Perdeu; //setar reiniciar do jogo const tempoAntesReiniciar = 3000; ControladorJogo._tempoFaltaRecomecarJogo = []; new Timer(() => { //acabar jogo //apagar Timers ConjuntoTimers.excluirTimers(); //zerar propriedades for (let key in ControladorJogo) if (typeof ControladorJogo[key] !== 'function') delete ControladorJogo[key]; //recomecar jogo ControladorJogo.inicializar(); //se demorar muito, jah comeca o jogo sozinho (verificar se ainda nao comecou) const tempoAntesComecarJogoAutomatico = 500; setTimeout(() => { if (ControladorJogo._estadoJogo === EstadoJogo.NaoComecou) ControladorJogo.comecarJogo(); }, tempoAntesComecarJogoAutomatico); }, tempoAntesReiniciar, undefined, undefined, undefined, { obj: ControladorJogo._tempoFaltaRecomecarJogo, atr: "tempo" }); //avisar personagem e fazer procedimentos necessarios ControladorJogo._personagemPrincipal.procAcabouImgsMorto(); } //ganhou static _persGanhou() { ControladorJogo._estadoJogo = EstadoJogo.Ganhou; ControladorJogo._personagemPrincipal.procGanhou(); //setar andar do personagem: quando ganhar vai andando para o meio const qtdPersAndar = 5.5; const pontoSeguir = ControladorJogo._getPontoCentralGanhou(); const infoAndar = new InfoAndar(qtdPersAndar, 0, TipoAndar.SeguirPonto, { pontoSeguir: pontoSeguir }); const formaGeomPers = ControladorJogo._personagemPrincipal.formaGeometrica; ControladorJogo._classeAndarPersGanhou = new ClasseAndar(infoAndar, formaGeomPers); //para ir deixando mais branco //calcular quantas vezes o personagem vai andar ateh chegar no meio const qtdTemQueAndarX = pontoSeguir.x - formaGeomPers.centroMassa.x; const qtdTemQueAndarY = pontoSeguir.y - formaGeomPers.centroMassa.y; const qtdVezesDemoraTotalmenteBranco = Operacoes.hipotenusa(qtdTemQueAndarX, qtdTemQueAndarY) / qtdPersAndar; //para parar no meio no mesmo tempo em que fica totalmente branco // ControladorJogo._qtdMudaOpacidadeBranco = 255 / qtdVezesDemoraTotalmenteBranco; ControladorJogo._qtOpacidadeBrancoAtual = 0; } static _getPontoCentralGanhou() { return new Ponto(0.5 * width, (height - heightVidaUsuario) * 0.5); } //draw static draw() { const estadoJogoAntesDraw = ControladorJogo._estadoJogo; ControladorJogo._draw(); ControladorJogo._ultimoDraw = estadoJogoAntesDraw; } static _draw() { if (ControladorJogo._estadoJogo === EstadoJogo.NaoComecou) { //desenhar imagem de fundo const infoImg = ControladorJogo._infoBackgroundInicio; image(infoImg.img, infoImg.ponto.x, infoImg.ponto.y, infoImg.medidas.width, infoImg.medidas.height); push(); //desenhar texto textAlign(CENTER, CENTER); //NomeJogo push(); textStyle(BOLD); textSize(60); text("Aviões em Combate", width * 0.5, height * 0.7); pop(); //instrucoes para jogar textSize(35); text("Pressione [ESC] para começar a jogar", width / 2, height * 0.8); pop(); return; } if (ControladorJogo._estadoJogo === EstadoJogo.Pausado) //pausa-se com [ENTER] { if (ControladorJogo._ultimoDraw !== EstadoJogo.Pausado) //se jah desenhou { // TODO : design //deixa o que estava na tela de fundo mesmo //Retangulo tela inteira push(); const corRetMaior = color(0, 0, 0, 100); stroke(corRetMaior); fill(corRetMaior); rect(0, 0, width, height); pop(); //Retangulo menor push(); const corRetMenos = color(0, 0, 0, 220); stroke(corRetMenos); fill(corRetMenos); const porcSobraLadosHoriz = 0.15; const porcSobraLadosVert = 0.15; rect(porcSobraLadosHoriz * width, porcSobraLadosVert * height, (1 - 2 * porcSobraLadosHoriz) * width, (1 - 2 * porcSobraLadosVert) * height); pop(); //PAUSE e PLAY push(); textAlign(CENTER, CENTER); //PAUSE const corPause = color(247, 120, 101); stroke(corPause); fill(corPause); textSize(80); text("PAUSE", width * 0.5, height * 0.3); //Pressione para PLAY const corPlay = color(77, 148, 255); stroke(corPlay); fill(corPlay); textSize(30); text("Pressione [ENTER] para dar PLAY", width * 0.5, height * 0.4); pop(); push(); //REGRAS const numCor = 190; fill(numCor); stroke(numCor); //cabecalho const textSizeCabecRegras = 25; textSize(textSizeCabecRegras); const yCabecRegras = 0.61 * height; text("Regras:", (0.028 + porcSobraLadosHoriz) * width, yCabecRegras); //regras em si noStroke(); textSize(13); const qtdEntreCadaLinha = 21; const xRegras = (0.04 + porcSobraLadosHoriz) * width; const yPrimRegra = yCabecRegras + textSizeCabecRegras + 4; let regras = []; if (ControladorJogo._personagemPrincipal.ehAviaoMaster) { regras.push("- Mira da arma giratária: mouse"); regras.push("- Atirar míssel: tecla E"); } regras.push("- Ativar poder/poção: tecla Q"); regras.push("- Movimento da nave: teclas AWDS"); regras.push("- Mate os inimigos mais importantes de cada level para passsar de fase"); regras.forEach((regra, index) => text(regra, xRegras, yPrimRegra + index * qtdEntreCadaLinha)); pop(); } return; } else if (ControladorJogo._estadoJogo === EstadoJogo.Ganhou) { // TODO : design (falar que ele passou todas as fases ateh ultima fase existente) // ir colocando fundo branco, indo com o personagem para o meio //andar com o personagem e desenhar ele if (ControladorJogo._classeAndarPersGanhou !== undefined) //se ainda estah andando { const formaGeomPers = ControladorJogo._personagemPrincipal.formaGeometrica; //anda const qtdAndar = ControladorJogo._classeAndarPersGanhou.procAndar(formaGeomPers); ControladorJogo._personagemPrincipal.moverSemColisao(qtdAndar.x, qtdAndar.y); if (formaGeomPers.centroMassa.equals(ControladorJogo._getPontoCentralGanhou())) //quando jah chegou no meio eh soh parar de andar delete ControladorJogo._classeAndarPersGanhou; } else //aumentar tamanho personagem { if (ControladorJogo._personagemPrincipal.formaGeometrica.height < 0.37 * height) ControladorJogo._personagemPrincipal.mudarTamanhoSemColisao(1.02); } if (ControladorJogo._qtOpacidadeBrancoAtual !== 255) ControladorJogo._qtOpacidadeBrancoAtual = Math.min(255, ControladorJogo._qtdMudaOpacidadeBranco + ControladorJogo._qtOpacidadeBrancoAtual); push(); background(55); background(color(255, 255, 255, ControladorJogo._qtOpacidadeBrancoAtual)); stroke(0); fill(0); textSize(40); text("VOCE GANHOU!!", 50, 50); pop(); //desenhar pers ControladorJogo._personagemPrincipal.draw(); return; } if (ControladorJogo._criandoLevel) //quando enquanto estiver no processo de criar o level (ainda estah dentro do procedimento ControladorJogo._iniciarLevel), nao faz nada return; //daqui pra baixo ControladorJogo._estadoJogo === EstadoJogo.Jogando OU EstadoJogo.Morto (printa tudo normal apenas existe essa opcao diferente para nao deixar que personagem se mova ou atire enquanto estah morto) // ou EstadoJogo.Perdeu (continua printando por certo tempo ateh voltar do comeco) //procedimento dos Timers (antes de tudo) const antigoEstadoJogo = ControladorJogo._estadoJogo; ConjuntoTimers.procDraws(); //se reiniciou o jogo durante o procDraw, nao desenhar nada (tanto porque, os objetos tela nao existem ainda) if (antigoEstadoJogo !== ControladorJogo._estadoJogo && ControladorJogo._estadoJogo === EstadoJogo.NaoComecou) return; // TODO: SE ESTAH COM POCAO DE DEIXAR TEMPO MAIS DEVAGAR, COLOCAR PLANO DE FUNDO DIFERENTE OU MEIO OPACO POR CIMA background(55); //nessa ordem especificamente ControladorJogo._andarInimObst(); ControladorJogo._personagemPrincipal.procPerdeVidaColidiuObjs(); ControladorJogo._andarTiros(); ControladorJogo._atirarAutomatico(); if (ControladorJogo._oficina !== undefined) { ControladorJogo._oficina.draw(); ControladorJogo._oficina.procVerificarConsertando(ControladorJogo._level); } //desenha Inimigos e Obstaculos SURGINDO (ObjetosTela surgindo ficam atras dos que jah surgiram) ControladorJogo._controladorSuportesAereos.drawSurgindo(); for (let i = ControladorJogo._controladoresInimigos.length - 1; i >= 0; i--) ControladorJogo._controladoresInimigos[i].drawSurgindo(); for (let i = ControladorJogo._controladoresObstaculos.length - 1; i >= 0; i--) ControladorJogo._controladoresObstaculos[i].drawSurgindo(); // OBJETOS JAH INTERAGEM COM O MEIO: // Tiros sem dono ControladorJogo._controladorOutrosTirosNaoPers.draw(); //Suportes Aereos ControladorJogo._controladorSuportesAereos.draw(); // tambem desenha os tiros // Inimigos (do ultimo para o primeiro pois o primeiro eh mais importante) for (let i = ControladorJogo._controladoresInimigos.length - 1; i >= 0; i--) ControladorJogo._controladoresInimigos[i].draw(); // tambem desenha os tiros dos inimigos // Obstaculos (do ultimo pro primeiro pois o primeiro eh mais importante) for (let i = ControladorJogo._controladoresObstaculos.length - 1; i >= 0; i--) ControladorJogo._controladoresObstaculos[i].draw(); //Pocao ControladorJogo._controladorPocaoTela.draw(); //desenha o personagem e os tiros dele (sua vida e suas pocoes ainda nao) const acabouImgsMorreuPers = ControladorJogo._personagemPrincipal.draw(TipoDrawPersonagem.ParteDoCeu); if (acabouImgsMorreuPers) ControladorJogo._persPerdeu(); //desenha os tiros mortos (eles tem que ficar por cima de todos os ObjetosTela) ControladorJogo._controladorOutrosTirosNaoPers.drawMortos(); //sem dono ControladorJogo._controladorSuportesAereos.suportesAereos.forEach(suporteAereo => suporteAereo.drawTirosMortos()); //de Suportes Aereos ControladorJogo._controladoresInimigos.forEach(contrInims => contrInims.drawTirosMortosInims()); //de Inimigos ControladorJogo._personagemPrincipal.drawTirosMortos(); //de PersonagemPrincipal //desenha a mira arma giratoria (nao podia desenhar junto com a parte do ceu porque dessa forma os tiros mortos ficariam por cima da mira) ControladorJogo._personagemPrincipal.draw(TipoDrawPersonagem.MiraArmaGiratoria); if (ControladorJogo._escuridao !== undefined) ControladorJogo._escuridao.draw(); //desenha a escuridao por cima de tudo a nao ser da vida do personagem, de suas pocoes e do level //desenha a vida e as pocoes do personagem ControladorJogo._personagemPrincipal.draw(TipoDrawPersonagem.Painel); //desenha draws especiais (informacoes em texto normalmente) ControladorJogo._conjuntoDrawsEspeciais.draw(); if (ControladorJogo._personagemPrincipal.vivo && ControladorJogo._acabouLevel()) { const persGanhou = ControladorJogo._passarLevel(); if (persGanhou) ControladorJogo._persGanhou(); } if (ControladorJogo._estadoJogo === EstadoJogo.Perdeu) //animacao dele morrendo { // TODO : animacao dele morrendo (ideia: acabar com os tiros dele e continuar o jogo "normal" com uma animacao dele morrendo e colocar na tela depois que ele MORREU) push(); textAlign(CENTER, TOP); //Voce morreu... o jogo serah reiniciado em: const yLinha1 = 0.17 * height; const textSizeLinha1 = 100; textSize(textSizeLinha1); text("Você morreu...", 0.5 * width, yLinha1); // O jogo será reiniciado em: const yLinha2 = yLinha1 + textSizeLinha1 + 4; const textSizeLinha2 = 50; textSize(textSizeLinha2); text(" O jogo será reiniciado em:", 0.5 * width, yLinha2); //tempo textSize(300); text((Math.round(ControladorJogo._tempoFaltaRecomecarJogo.tempo / 1000)).toFixed(0) + "s", 0.5 * width, yLinha2 + textSizeLinha2 + 7); pop(); } } static _acabouLevel() { //verificar se o level jah acabou switch (ControladorJogo._level) { default: //se nao tem nenhum inimigo essencial na tela return ControladorJogo._controladoresInimigos.every(controladorInims => !controladorInims.ehDeInimigosEssenciais || !controladorInims.algumInimNaTela()); } return false; } }
JavaScript
class GameMap { constructor(config){ const { id, name = 'default-map-name', description = '-', width, data } = config this.id = id this.name = name this.description = description this.width = width this.data = data this.dataRendered = [] this.rooms = [] } }
JavaScript
class FirebaseLoginbutton extends LitElement { static get is() { return 'firebase-loginbutton'; } static get properties() { return { id: { type: String, reflect: true }, appName:{ type: String, }, dataUser: { type: Object }, displayName: { type: String }, email: { type: String }, uid: { type: String }, apiKey: { type: String, attribute: 'api-key' }, domain: { type: String }, zone: { type: String }, messagingSenderId: { type: String, attribute: 'messaging-sender-id' }, appId: { type: String, attribute: 'app-id' }, showPhoto: { type: Boolean, attribute: 'show-photo' }, showEmail: { type: Boolean, attribute: 'show-email' }, showUser: { type: Boolean, attribute: 'show-user' }, showIcon: { type: Boolean, attribute: 'show-icon' }, hasParams: { type: Boolean, attribute: false }, iconLogout: { type: String, attribute: false }, infobtn: { type: String, attribute: false }, hideIfLogin: { type: Boolean, attribute: 'hide-if-login' }, firebaseApp: { type: Object } }; } static get styles() { return [firebaseLoginbuttonStyles]; } constructor() { super(); if (typeof initializeApp === 'undefined') { throw new Error('To work firebase-loginbutton: Please, import firebase-app and firebase-auth first'); } this.showEmail = false; this.showUser = false; this.showIcon = false; this.showPhoto = false; this.hideIfLogin = false; this.name = 'NAME'; // TODO: generate a random Name to identify the component from others. this.dataUser = null; this.zone = null; // OPTIONAL. Old projects dont have a zone this.signedIn = false; this.signedOut = false; this.isMobile = navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i) !== null; this._dispatchSigninEvent = this._dispatchSigninEvent.bind(this); } _dispatchSigninEvent() { if (this.signedIn) { document.dispatchEvent(new CustomEvent('firebase-signin', {detail: {user: this.dataUser, firebaseApp: this.firebaseApp, firebaseStorage: this.firebaseStorage, name: this.appName, id: this.id}})); } } _checkIfCallMe(event) { const { detail } = event; if (detail.id === this.id) { this._dispatchSigninEvent(); } } firstUpdated() { this.id = this.id || `firebase-loginbutton-${ Math.random().toString(36).substring(2, 9)}`; this.appName = `firebase-loginbutton-${this.id}`; this.firebaseInitialize(); document.addEventListener('are-it-logged-into-firebase', this._checkIfCallMe.bind(this)); const componentCreatedEvent = new CustomEvent('wc-ready', { detail: { id: this.id, componentName: this.tagName, component: this, }, }); document.dispatchEvent(componentCreatedEvent); } attributeChangedCallback(name, oldval, newval) { if (super.attributeChangedCallback) { super.attributeChangedCallback(name, oldval, newval); } this.hasParams = !!(this.apiKey && this.domain && this.messagingSenderId && this.appId); } async firebaseInitialize() { if (!this.firebaseApp) { const firebaseConfig = { apiKey: this.apiKey, authDomain: `${this.domain }.firebaseapp.com`, databaseURL: (this.zone === null) ? `https://${this.domain}.firebaseio.com` : `https://${this.domain}-default-rtdb.${this.zone}.firebasedatabase.app`, projectId: this.domain, storageBucket: `${this.domain }.appspot.com`, messagingSenderId: this.messagingSenderId, appId: this.appId }; this.firebaseApp = await initializeApp(firebaseConfig, this.appName); this.firebaseStorage = getStorage(this.firebaseApp); this.authStateChangedListener(); } else { console.warn('firebaseApp not found'); } } _checkEventsLogin(user) { if (user) { if (!this.signedIn) { this.dataUser = user; // document.dispatchEvent(new CustomEvent('firebase-signin', {detail: {user, name: this.name, id: this.id, firebaseApp: this.firebaseApp }})); document.dispatchEvent(new CustomEvent('firebase-signin', {detail: {user: this.dataUser, firebaseApp: this.firebaseApp, firebaseStorage: this.firebaseStorage, name: this.appName, id: this.id}})); this.signedIn = true; this.signedOut = false; } } else if (!this.signedOut) { document.dispatchEvent(new CustomEvent('firebase-signout', {detail: {user: this.email, name: this.name, id: this.id, firebaseApp: this.firebaseApp }})); this.signedIn = false; this.signedOut = true; } } _getUserInfo(user) { if (user) { this.displayName = user.displayName; this.email = user.email; this.uid = user.uid; this.photo = user.photoURL; } } _drawButtonLogin() { const sR = this.shadowRoot; if (!this.isMobile) { sR.querySelector('.button-photo').innerHTML = (this.showPhoto) ? `<img src="${this.photo}" alt="${this.displayName} photo"/>` : ''; sR.querySelector('.button-text').innerText = 'Sign out'; sR.querySelector('.button-icon').innerHTML = (this.showIcon) ? `${this.iconLogout}` : ''; sR.querySelector('.button-user').textContent = (this.showUser) ? `${this.displayName}` : ''; sR.querySelector('.button-email').textContent = (this.showEmail) ? `${this.email}` : ''; if (this.hideIfLogin) { sR.querySelector('.wrapper__layer--login').classList.add('hide'); } sR.querySelector('#quickstart-sign-in').classList.add('wrapper__login--button'); sR.querySelector('#quickstart-sign-in').classList.remove('wrapper__login--button-mobile'); } else { sR.querySelector('.button-icon').innerHTML = `${this.iconLogout}`; if (this.hideIfLogin) { sR.querySelector('.wrapper__layer--login').classList.add('hide'); } sR.querySelector('#quickstart-sign-in').classList.remove('wrapper__login--button'); sR.querySelector('#quickstart-sign-in').classList.add('wrapper__login--button-mobile'); } if (this.showIcon) { sR.querySelector('.button-icon svg').classList.remove('signin'); sR.querySelector('.button-icon svg').classList.add('signout'); } this.shadowRoot.querySelector('#quickstart-sign-in').classList.add('border-logged-in'); this.shadowRoot.querySelector('#quickstart-sign-in').classList.remove('border-logged-out'); } _drawButtonLogout() { const sR = this.shadowRoot; if (!this.isMobile) { sR.querySelector('.button-photo').textContent = ''; sR.querySelector('.button-text').textContent = 'Sign in'; sR.querySelector('.button-icon').innerHTML = (this.showIcon) ? `${this.iconLogout}` : ''; sR.querySelector('.button-user').textContent = ''; sR.querySelector('.button-email').textContent = ''; sR.querySelector('#quickstart-sign-in').classList.add('wrapper__login--button'); sR.querySelector('#quickstart-sign-in').classList.remove('wrapper__login--button-mobile'); } else { sR.querySelector('.button-icon').innerHTML = `${this.iconLogout}`; sR.querySelector('#quickstart-sign-in').classList.remove('wrapper__login--button'); sR.querySelector('#quickstart-sign-in').classList.add('wrapper__login--button-mobile'); } sR.querySelector('.wrapper__layer--login').classList.remove('hide'); if (this.showIcon) { sR.querySelector('.button-icon svg').classList.add('signin'); sR.querySelector('.button-icon svg').classList.remove('signout'); } this.displayName = undefined; this.email = undefined; this.uid = undefined; this.shadowRoot.querySelector('#quickstart-sign-in').classList.add('border-logged-out'); this.shadowRoot.querySelector('#quickstart-sign-in').classList.remove('border-logged-in'); } authStateChangedListener() { this.auth = getAuth(this.firebaseApp); onAuthStateChanged(this.auth, (user) => { this.dataUser = user; this.iconLogout = '<svg id="logout-icon" width="23" height="21" class="signout"><path d="M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z"/></svg>'; this._getUserInfo(user); this.shadowRoot.querySelector('#quickstart-sign-in').disabled = false; if (user) { this._drawButtonLogin(); } else { this._drawButtonLogout(); } this._checkEventsLogin(user); }); } async toggleSignIn() { if (!this.auth.currentUser) { const provider = new GoogleAuthProvider(); provider.addScope('profile'); provider.addScope('email'); const result = await signInWithPopup(this.auth, provider); // The signed-in user info. this.dataUser = result.user; console.log(`Logged user ${this.dataUser.displayName}`); this.shadowRoot.querySelector('#quickstart-sign-in').classList.add('border-logged-in'); this._dispatchSigninEvent(); } else { this.shadowRoot.querySelector('#quickstart-sign-in').classList.remove('border-logged-in'); this.auth.signOut(); } } render() { return html` <section class="wrapper__layer--login"> ${this.hasParams ? html` <div id="user" class="wrapper__user"></div> <button disabled id="quickstart-sign-in" @click="${this.toggleSignIn}" title="${this.infobtn}"> <div class="button-photo"></div> <div class="button-icon"></div> <div class="button-user"></div> <div class="button-email"></div> <div class="button-text"></div> </button> ` : html` <p>Faltan parámetros en la definición del componente</p> ` } </section> `; } }
JavaScript
class UiLoadedVersion { constructor(editorScreen) { this.el = cloneDomTemplate("#editor-loaded-version"); this.thumbnailBar = new UiThumbnailBar(this); this.contentCenter = new UiContentCenter(this); this.rightSideBar = new UiRightSidebar(this, editorScreen); } terminate() { this.rightSideBar.terminate(); this.contentCenter.terminate(); this.thumbnailBar.terminate(); } }
JavaScript
class GoogleConversions { /** * Maps an IBox object to a GoogleMapTypes.LatLngBoundsLiteral object. * * \@memberof GoogleConversions * @param {?} bounds - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateBounds(bounds) { /** @type {?} */ const b = { east: bounds.maxLongitude, north: bounds.maxLatitude, south: bounds.minLatitude, west: bounds.minLongitude, }; return b; } /** * Maps an IInfoWindowOptions object to a GoogleMapTypes.InfoWindowOptions object. * * \@memberof GoogleConversions * @param {?} options - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateInfoWindowOptions(options) { /** @type {?} */ const o = {}; Object.keys(options) .filter(k => GoogleConversions._infoWindowOptionsAttributes.indexOf(k) !== -1) .forEach((k) => { if (k === 'htmlContent') { o.content = (/** @type {?} */ (options))[k]; } else { o[k] = (/** @type {?} */ (options))[k]; } }); if (o.content == null || o.content === '') { if (options.title !== '' && options.description !== '') { o.content = `${options.title}: ${options.description}`; } else if (options.description !== '') { o.content = options.description; } else { o.content = options.title; } } return o; } /** * Maps an ILatLong object to a GoogleMapTypes.LatLngLiteral object. * * \@memberof GoogleConversions * @param {?} latlong - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateLocation(latlong) { /** @type {?} */ const l = { lat: latlong.latitude, lng: latlong.longitude }; return l; } /** * Maps an GoogleMapTypes.LatLngLiteral object to a ILatLong object. * * \@memberof GoogleConversions * @param {?} latlng - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateLatLng(latlng) { /** @type {?} */ const l = { latitude: latlng.lat, longitude: latlng.lng }; return l; } /** * Maps an ILatLong object to a GoogleMapTypes.LatLng object. * * \@memberof GoogleConversions * @param {?} latlong - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateLocationObject(latlong) { /** @type {?} */ const l = new google.maps.LatLng(latlong.latitude, latlong.longitude); return l; } /** * Maps an GoogleMapTypes.LatLng object to a ILatLong object. * * \@memberof GoogleConversions * @param {?} latlng - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateLatLngObject(latlng) { /** @type {?} */ const l = { latitude: latlng.lat(), longitude: latlng.lng() }; return l; } /** * Maps an ILatLong array to a array of GoogleMapTypes.LatLng object. * * \@memberof GoogleConversions * @param {?} latlongArray - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateLocationObjectArray(latlongArray) { /** @type {?} */ const p = new Array(); for (let i = 0; i < latlongArray.length; i++) { p.push(GoogleConversions.TranslateLocationObject(latlongArray[i])); } return p; } /** * Maps a MapTypeId object to a Google maptype string. * * \@memberof GoogleConversions * @param {?} mapTypeId - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateMapTypeId(mapTypeId) { switch (mapTypeId) { case MapTypeId.road: return GoogleMapTypes.MapTypeId[GoogleMapTypes.MapTypeId.roadmap]; case MapTypeId.grayscale: return GoogleMapTypes.MapTypeId[GoogleMapTypes.MapTypeId.terrain]; case MapTypeId.hybrid: return GoogleMapTypes.MapTypeId[GoogleMapTypes.MapTypeId.hybrid]; case MapTypeId.ordnanceSurvey: return GoogleMapTypes.MapTypeId[GoogleMapTypes.MapTypeId.terrain]; default: return GoogleMapTypes.MapTypeId[GoogleMapTypes.MapTypeId.satellite]; } } /** * Maps an IMarkerOptions object to a GoogleMapTypes.MarkerOptions object. * * \@memberof GoogleConversions * @param {?} options - Object to be mapped. * @return {?} - Promise that when resolved contains the mapped object. * */ static TranslateMarkerOptions(options) { /** @type {?} */ const o = {}; Object.keys(options) .filter(k => GoogleConversions._markerOptionsAttributes.indexOf(k) !== -1) .forEach((k) => { if (k === 'position') { /** @type {?} */ const latlng = GoogleConversions.TranslateLocationObject(options[k]); o.position = latlng; } else { o[k] = (/** @type {?} */ (options))[k]; } }); return o; } /** * Maps an IMapOptions object to a GoogleMapTypes.MapOptions object. * * \@memberof GoogleConversions * @param {?} options - Object to be mapped. * @return {?} - Mapped object. * */ static TranslateOptions(options) { /** @type {?} */ const o = {}; Object.keys(options) .filter(k => GoogleConversions._mapOptionsAttributes.indexOf(k) !== -1) .forEach((k) => { if (k === 'center') { o.center = GoogleConversions.TranslateLocation(options.center); } else if (k === 'mapTypeId') { o.mapTypeId = GoogleConversions.TranslateMapTypeId(options.mapTypeId); } else if (k === 'disableZooming') { o.gestureHandling = 'none'; o.zoomControl = false; } else if (k === 'showMapTypeSelector') { o.mapTypeControl = false; } else if (k === 'customMapStyleGoogle') { o.styles = /** @type {?} */ (/** @type {?} */ (options.customMapStyleGoogle)); } else { (/** @type {?} */ (o))[k] = (/** @type {?} */ (options))[k]; } }); return o; } /** * Translates an array of locations or an array or arrays of location to and array of arrays of Bing Map Locations * * \@memberof GoogleConversions * @param {?} paths - ILatLong based locations to convert. * @return {?} - converted locations. * */ static TranslatePaths(paths) { /** @type {?} */ const p = new Array(); if (paths == null || !Array.isArray(paths) || paths.length === 0) { p.push(new Array()); } else if (Array.isArray(paths[0])) { /** @type {?} */ const p1 = /** @type {?} */ (paths); for (let i = 0; i < p1.length; i++) { p.push(GoogleConversions.TranslateLocationObjectArray(p1[i])); } } else { // parameter is a simple array.... p.push(GoogleConversions.TranslateLocationObjectArray(/** @type {?} */ (paths))); } return p; } /** * Maps an IPolygonOptions object to a GoogleMapTypes.PolygonOptions. * * \@memberof GoogleConversions * @param {?} options - Object to be mapped. * @return {?} - Mapped object. * */ static TranslatePolygonOptions(options) { /** @type {?} */ const o = {}; Object.keys(options) .filter(k => GoogleConversions._polygonOptionsAttributes.indexOf(k) !== -1) .forEach((k) => { if (k === 'paths') { if (!Array.isArray(options.paths)) { return; } if (options.paths.length === 0) { o.paths = new Array(); } else if (Array.isArray(options.paths[0])) { o.paths = new Array(); /** @type {?} */ const p1 = /** @type {?} */ (options.paths); for (let i = 0; i < p1.length; i++) { o.paths[i] = new Array(); for (let j = 0; j < p1[i].length; j++) { o.paths[i][j] = { lat: p1[i][j].latitude, lng: p1[i][j].longitude }; } } } else { o.paths = new Array(); /** @type {?} */ const p1 = /** @type {?} */ (options.paths); for (let i = 0; i < p1.length; i++) { o.paths[i] = { lat: p1[i].latitude, lng: p1[i].longitude }; } } } else { o[k] = (/** @type {?} */ (options))[k]; } }); return o; } /** * Maps an IPolylineOptions object to a GoogleMapTypes.PolylineOptions. * * \@memberof GoogleConversions * @param {?} options - Object to be mapped. * @return {?} - Mapped object. * */ static TranslatePolylineOptions(options) { /** @type {?} */ const o = {}; Object.keys(options) .filter(k => GoogleConversions._polylineOptionsAttributes.indexOf(k) !== -1) .forEach((k) => { o[k] = (/** @type {?} */ (options))[k]; }); return o; } }
JavaScript
class TextInlines { /** * @param {object} pdfDocument object is instance of PDFDocument */ constructor(pdfDocument) { this.pdfDocument = pdfDocument; } /** * Converts an array of strings (or inline-definition-objects) into a collection * of inlines and calculated minWidth/maxWidth and their min/max widths * * @param {Array} textArray an array of inline-definition-objects (or strings) * @param {StyleContextStack} styleContextStack current style stack * @returns {object} collection of inlines, minWidth, maxWidth */ buildInlines(textArray, styleContextStack) { const getTrimmedWidth = item => { return Math.max(0, item.width - item.leadingCut - item.trailingCut); }; let minWidth = 0; let maxWidth = 0; let currentLineWidth; let flattenedTextArray = flattenTextArray(textArray); const textBreaker = new _TextBreaker.default(); let breakedText = textBreaker.getBreaks(flattenedTextArray, styleContextStack); let measuredText = this.measure(breakedText, styleContextStack); measuredText.forEach(inline => { minWidth = Math.max(minWidth, getTrimmedWidth(inline)); if (!currentLineWidth) { currentLineWidth = { width: 0, leadingCut: inline.leadingCut, trailingCut: 0 }; } currentLineWidth.width += inline.width; currentLineWidth.trailingCut = inline.trailingCut; maxWidth = Math.max(maxWidth, getTrimmedWidth(currentLineWidth)); if (inline.lineEnd) { currentLineWidth = null; } }); if (_StyleContextStack.default.getStyleProperty({}, styleContextStack, 'noWrap', false)) { minWidth = maxWidth; } return { items: measuredText, minWidth: minWidth, maxWidth: maxWidth }; } measure(array, styleContextStack) { if (array.length) { let leadingIndent = _StyleContextStack.default.getStyleProperty(array[0], styleContextStack, 'leadingIndent', 0); if (leadingIndent) { array[0].leadingCut = -leadingIndent; array[0].leadingIndent = leadingIndent; } } array.forEach(item => { let font = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'font', 'Roboto'); let bold = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'bold', false); let italics = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'italics', false); item.font = this.pdfDocument.provideFont(font, bold, italics); item.alignment = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'alignment', 'left'); item.fontSize = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'fontSize', 12); item.fontFeatures = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'fontFeatures', null); item.characterSpacing = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'characterSpacing', 0); item.color = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'color', 'black'); item.decoration = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'decoration', null); item.decorationColor = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'decorationColor', null); item.decorationStyle = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'decorationStyle', null); item.background = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'background', null); item.link = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'link', null); item.linkToPage = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'linkToPage', null); item.linkToDestination = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'linkToDestination', null); item.noWrap = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'noWrap', null); item.opacity = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'opacity', 1); let lineHeight = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'lineHeight', 1); item.width = this.widthOfText(item.text, item); item.height = item.font.lineHeight(item.fontSize) * lineHeight; if (!item.leadingCut) { item.leadingCut = 0; } let preserveLeadingSpaces = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'preserveLeadingSpaces', false); if (!preserveLeadingSpaces) { let leadingSpaces = item.text.match(LEADING); if (leadingSpaces) { item.leadingCut += this.widthOfText(leadingSpaces[0], item); } } item.trailingCut = 0; let preserveTrailingSpaces = _StyleContextStack.default.getStyleProperty(item, styleContextStack, 'preserveTrailingSpaces', false); if (!preserveTrailingSpaces) { let trailingSpaces = item.text.match(TRAILING); if (trailingSpaces) { item.trailingCut = this.widthOfText(trailingSpaces[0], item); } } }, this); return array; } /** * Width of text * * @param {string} text * @param {object} inline * @returns {number} */ widthOfText(text, inline) { return inline.font.widthOfString(text, inline.fontSize, inline.fontFeatures) + (inline.characterSpacing || 0) * (text.length - 1); } /** * Returns size of the specified string (without breaking it) using the current style * * @param {string} text text to be measured * @param {object} styleContextStack current style stack * @returns {object} size of the specified string */ sizeOfText(text, styleContextStack) { //TODO: refactor - extract from measure let fontName = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'font', 'Roboto'); let fontSize = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'fontSize', 12); let fontFeatures = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'fontFeatures', null); let bold = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'bold', false); let italics = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'italics', false); let lineHeight = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'lineHeight', 1); let characterSpacing = _StyleContextStack.default.getStyleProperty({}, styleContextStack, 'characterSpacing', 0); let font = this.pdfDocument.provideFont(fontName, bold, italics); return { width: this.widthOfText(text, { font: font, fontSize: fontSize, characterSpacing: characterSpacing, fontFeatures: fontFeatures }), height: font.lineHeight(fontSize) * lineHeight, fontSize: fontSize, lineHeight: lineHeight, ascender: font.ascender / 1000 * fontSize, descender: font.descender / 1000 * fontSize }; } /** * Returns size of the specified rotated string (without breaking it) using the current style * * @param {string} text text to be measured * @param {number} angle * @param {object} styleContextStack current style stack * @returns {object} size of the specified string */ sizeOfRotatedText(text, angle, styleContextStack) { let size = this.sizeOfText(text, styleContextStack); return { width: size.height * Math.sin(angle * Math.PI / -180) + size.width * Math.cos(angle * Math.PI / -180), height: size.width * Math.sin(angle * Math.PI / -180) + size.height * Math.cos(angle * Math.PI / -180) }; } }
JavaScript
class PinyinSort { /** * Constructor. * * @param {boolean} checkPolyphone - Whether to check for polyphonic words. * @param {number} charCase - Output pinyin case mode, 0- first letter capitalization; 1- All lowercase; 2 - all uppercase. */ constructor(checkPolyphone = false, charCase = 1) { this.pinyin = new Pinyin({ checkPolyphone: checkPolyphone, charCase: charCase }); } /** * Sort data for appinfo,compared by appName. * * @param {object} a - appinfo for compare. * @return {object} b - appinfo for compare. */ sortByAppName(a, b) { return this.getChar(a.appName) - this.getChar(b.appName); } getChar (str) { return this.pinyin.getFullChars(str).charCodeAt(0); } }
JavaScript
class SearchField extends Component { constructor({ store }) { super(); this.store = Ext.create('Ext.data.ChainedStore', { source: store }); this.itemTpl = createTpl({ getQuery: this.getQuery, showTime: true }) } /** * Needed to highlight text matching the query in the itemTpl */ getQuery = () => { return this.query; } /** * Filters the combobox by event title and speaker name */ search = (queryPlan) => { let { query } = queryPlan; query = (query || '').toLowerCase(); this.query = query; this.store.clearFilter(); this.store.filterBy(record => { const { title, speakers } = record.data; return query.trim().split(/\s+/).some(token => { return title.toLowerCase().indexOf(token) >= 0 || (speakers && speakers.some(speaker => speaker.name.toLowerCase().indexOf(token) >= 0)); }) }); this.field.expand(); return false; // cancel the built-in search and run our own } /** * Navigate to the event when an item is selected in the list */ onSelect = (combo, record) => { if (record) { location.hash = `/schedule/${record.getId()}` } } render() { return ( <ComboBox { ...this.props } ui="alt" placeholder="Search" ref={field => this.field = field} itemTpl={this.itemTpl} store={this.store} queryMode="local" onBeforeQuery={this.search} clearable hideTrigger onSelect={this.onSelect} valueField='id' matchFieldWidth={false} floatedPicker={{ width: 500 }} triggers={{ search: { type: 'search', side: 'left' }, expand: null }} /> ) } }
JavaScript
class t extends e { static get version() { return "1.11.1"; } get html() { return "\n<style>:host{position:relative;display:inline-block;width:100%;line-height:1.5em;font-weight:400;text-align:left;text-rendering:optimizelegibility;border-top:1px solid #f0f0f0;border-top:var(--pfe-select--BorderTop,var(--pfe-select--BorderWidth,var(--pfe-theme--ui--border-width,1px)) var(--pfe-theme--ui--border-style,solid) var(--pfe-select--BorderColor,var(--pfe-theme--color--surface--lighter,#f0f0f0)));border-right:1px solid #f0f0f0;border-right:var(--pfe-select--BorderRight,var(--pfe-select--BorderWidth,var(--pfe-theme--ui--border-width,1px)) var(--pfe-theme--ui--border-style,solid) var(--pfe-select--BorderColor,var(--pfe-theme--color--surface--lighter,#f0f0f0)));border-bottom:1px solid #3c3f42;border-bottom:var(--pfe-select--BorderBottom,var(--pfe-select--BorderBottomWidth,var(--pfe-theme--ui--border-width,1px)) var(--pfe-theme--ui--border-style,solid) var(--pfe-select--BorderBottomColor,var(--pfe-theme--color--surface--darker,#3c3f42)));border-left:1px solid #f0f0f0;border-left:var(--pfe-select--BorderLeft,var(--pfe-select--BorderWidth,var(--pfe-theme--ui--border-width,1px)) var(--pfe-theme--ui--border-style,solid) var(--pfe-select--BorderColor,var(--pfe-theme--color--surface--lighter,#f0f0f0)));background-color:#fff;background-color:var(--pfe-select--BackgroundColor,var(--pfe-theme--color--surface--lightest,#fff));color:#151515;color:var(--pfe-select--Color,var(--pfe-theme--color--text,#151515))}:host *,:host ::after,:host ::before{-webkit-box-sizing:border-box;box-sizing:border-box}:host::after{border-style:solid;border-style:var(--pfe-theme--surface--border-style,solid);border-width:6px 6px 0;border-color:transparent;border-top-color:#3c3f42;-webkit-transform:rotate(0);transform:rotate(0);display:inline-block;content:\"\";position:absolute;top:calc(1rem * .875);top:calc(var(--pfe-theme--container-padding,1rem) * .875);right:calc(1rem * .75);right:calc(var(--pfe-theme--container-padding,1rem) * .75)}:host([hidden]){display:none}:host(:hover){border-bottom:1px solid #06c;border-bottom:var(--pfe-select--BorderBottom--hover,var(--pfe-select--BorderBottomWidth,var(--pfe-theme--ui--border-width,1px)) var(--pfe-theme--ui--border-style,solid) var(--pfe-select--BorderBottomColor--hover,var(--pfe-theme--color--link,#06c)))}:host(:focus-within){border-bottom-width:calc(4px / 2);border-bottom-width:calc(var(--pfe-theme--surface--border-width--heavy,4px)/ 2);border-bottom-color:#06c;border-bottom-color:var(--pfe-select--BorderBottomColor--hover,var(--pfe-theme--color--link,#06c))}:host(:focus-within) ::slotted(select){padding-bottom:calc(1rem * .438);padding-bottom:calc(var(--pfe-theme-container-padding,1rem) * .438)}:host ::slotted(select){text-rendering:auto!important;background-color:#fff;background-color:var(--pfe-select--BackgroundColor,var(--pfe-theme--color--surface--lightest,#fff));color:#151515;color:var(--pfe-select--Color,var(--pfe-theme--color--text,#151515));border-radius:0;width:100%;min-width:100%;font-size:1rem;font-size:var(--pfe-theme--font-size,1rem);font-weight:400;font-weight:var(--pfe-theme--font-weight--normal,400);font-family:\"Red Hat Text\",RedHatText,Overpass,Overpass,Arial,sans-serif;font-family:var(--pfe-select--FontFamily, var(--pfe-theme--font-family, \"Red Hat Text\", \"RedHatText\", \"Overpass\", Overpass, Arial, sans-serif));-webkit-appearance:none;-moz-appearance:none;appearance:none;-webkit-box-shadow:none;box-shadow:none;border:none;padding:calc(1rem * .5);padding:calc(var(--pfe-theme--container-padding,1rem) * .5);padding-right:calc(1rem * 1.5);padding-right:calc(var(--pfe-theme--container-padding,1rem) * 1.5)}:host([invalid]){border-bottom-width:calc(4px / 2);border-bottom-width:calc(var(--pfe-theme--surface--border-width--heavy,4px)/ 2);border-bottom-color:#a30000;border-bottom-color:var(--pfe-select--BorderBottomColor--error,var(--pfe-theme--color--feedback--critical,#a30000))}:host([invalid]) ::slotted(select){padding-bottom:calc(1rem * .438);padding-bottom:calc(var(--pfe-theme--container-padding,1rem) * .438);background-image:url(\"data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath fill='%23c9190b' d='M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z'/%3E%3C/svg%3E\");background-size:.875rem;background-repeat:no-repeat;background-position:calc(100% - calc(1rem * 2)) center;background-position:calc(100% - calc(var(--pfe-theme--container-padding,1rem) * 2)) center}:host([invalid]){border-bottom-width:calc(4px / 2);border-bottom-width:calc(var(--pfe-theme--surface--border-width--heavy,4px)/ 2);border-bottom-color:#a30000;border-bottom-color:var(--pfe-select--BorderBottomColor--error,var(--pfe-theme--color--feedback--critical,#a30000))}:host([invalid]) ::slotted(select){padding-bottom:calc(1rem * .438);padding-bottom:calc(var(--pfe-theme--container-padding,1rem) * .438);background-image:url(\"data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath fill='%23c9190b' d='M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z'/%3E%3C/svg%3E\");background-size:.875rem;background-repeat:no-repeat;background-position:calc(100% - calc(1rem * 2)) center;background-position:calc(100% - calc(var(--pfe-theme--container-padding,1rem) * 2)) center} /*# sourceMappingURL=pfe-select.min.css.map */</style>\n<slot></slot>"; } static get tag() { return "pfe-select"; } get templateUrl() { return "pfe-select.html"; } get styleUrl() { return "pfe-select.scss"; } get pfeOptions() { return this._pfeOptions; } set pfeOptions(e) { this._pfeOptions = e.filter((e) => e.selected).length > 1 ? this._handleMultipleSelectedValues(e) : e, this._modifyDOM(); } static get events() { return { change: this.tag + ":change" }; } static get properties() { return { invalid: { type: Boolean, observer: "_handleInvalid", default: !1 }, oldInvalid: { type: Boolean, alias: "invalid", attr: "pfe-invalid" }, }; } _handleInvalid(e, t) { const r = t ? "true" : "false"; this.querySelector("select").setAttribute("aria-invalid", r); } constructor() { super(t), this._pfeOptions = null, this._init = this._init.bind(this), this._inputChanged = this._inputChanged.bind(this), this.observer = new MutationObserver(this._init); } connectedCallback() { super.connectedCallback(), customElements.whenDefined(t.tag).then(() => { this.pfeOptions ? (this._modifyDOM(), this._init()) : this.hasLightDOM() ? this._init() : this.warn( "The first child in the light DOM must be a supported select tag", ); }), this.observer.observe(this, { childList: !0 }); } disconnectedCallback() { super.disconnectedCallback(), this.observer.disconnect(), this._input && this._input.removeEventListener("input", this._inputChanged); } addOptions(e) { this._pfeOptions = this._pfeOptions ? this._pfeOptions.concat(e) : e; } _handleMultipleSelectedValues(e) { this.warn( "The first 'selected' option will take precedence over others in case of multiple 'selected' options", ); const t = e.findIndex((e) => e.selected); return e.map((e, r) => (e.selected = t == r, e)); } _init() { this._input = this.querySelector("select"), this._input ? this._input.addEventListener("change", this._inputChanged) : this.warn("The first child needs to be a select element"); } _inputChanged() { this.emitEvent(t.events.change, { detail: { value: this._input.value } }); } _modifyDOM() { let e = document.createElement("select"); if ( this._pfeOptions.map((t) => { const r = Object.assign(document.createElement("option"), t); e.add(r, null); }), this.hasLightDOM() ) { const t = this.querySelector("select"); t.parentNode.replaceChild(e, t); } else this.appendChild(e); } }
JavaScript
class ImageDiffer { constructor({imageCache}) { /** * @type {!ImageCache} * @private */ this.imageCache_ = imageCache; } /** * @param {!SnapshotSuiteJson} actualSuite * @param {!SnapshotSuiteJson} expectedSuite * @return {!Promise<!Array<!ImageDiffJson>>} */ async compareAllPages({ actualSuite, expectedSuite, }) { /** @type {!Array<!Promise<!Array<!ImageDiffJson>>>} */ const pagePromises = []; for (const [htmlFilePath, actualPage] of Object.entries(actualSuite)) { // HTML file is not present in `golden.json` on `master` const expectedPage = expectedSuite[htmlFilePath]; if (!expectedPage) { continue; } pagePromises.push( this.compareOnePage_({ htmlFilePath, goldenPageUrl: expectedPage.publicUrl, snapshotPageUrl: actualPage.publicUrl, actualPage, expectedPage, }) ); } // Flatten the array of arrays const diffResults = [].concat(...(await Promise.all(pagePromises))); // Filter out images with no diffs return diffResults.filter((diffResult) => Boolean(diffResult.diffImageBuffer)); } /** * @param {string} htmlFilePath * @param {string} goldenPageUrl * @param {string} snapshotPageUrl * @param {!SnapshotPageJson} actualPage * @param {!SnapshotPageJson} expectedPage * @return {!Promise<!Array<!ImageDiffJson>>} * @private */ async compareOnePage_({ htmlFilePath, goldenPageUrl, snapshotPageUrl, actualPage, expectedPage, }) { /** @type {!Array<!Promise<!ImageDiffJson>>} */ const imagePromises = []; const actualScreenshots = actualPage.screenshots; const expectedScreenshots = expectedPage.screenshots; for (const [browserKey, actualImageUrl] of Object.entries(actualScreenshots)) { // Screenshot image for this browser is not present in `golden.json` on `master` const expectedImageUrl = expectedScreenshots[browserKey]; if (!expectedImageUrl) { continue; } imagePromises.push( this.compareOneImage_({actualImageUrl, expectedImageUrl}) .then( (diffImageBuffer) => ({ htmlFilePath, goldenPageUrl, snapshotPageUrl, browserKey, expectedImageUrl, actualImageUrl, diffImageUrl: null, // populated by `Controller` diffImageBuffer, }), (err) => Promise.reject(err) ) ); } return Promise.all(imagePromises); } /** * @param {string} actualImageUrl * @param {string} expectedImageUrl * @return {!Promise<?Buffer>} * @private */ async compareOneImage_({ actualImageUrl, expectedImageUrl, }) { console.log(`➡ Comparing snapshot to golden: "${actualImageUrl}" vs. "${expectedImageUrl}"...`); const [actualImageBuffer, expectedImageBuffer] = await Promise.all([ this.imageCache_.getImageBuffer(actualImageUrl), this.imageCache_.getImageBuffer(expectedImageUrl), ]); const diffResult = await this.computeDiff_({ actualImageBuffer, expectedImageBuffer, }); if (diffResult.rawMisMatchPercentage < 0.01) { console.log(`✔ No diffs found for "${actualImageUrl}"!`); return null; } console.log(`✗︎ Image "${actualImageUrl}" has changed!`); return diffResult.getBuffer(); } /** * @param {!Buffer} actualImageBuffer * @param {!Buffer} expectedImageBuffer * @return {!Promise<!ResembleApiComparisonResult>} * @private */ async computeDiff_({ actualImageBuffer, expectedImageBuffer, }) { const options = require('../resemble.json'); return await compareImages( actualImageBuffer, expectedImageBuffer, options ); } }
JavaScript
class CCAWindow { /** * @param {!WindowEventCallbacks} callbacks * @param {?WindowTestEventCallbacks} testingCallbacks * @param {?PerfLogger} perfLogger The logger for perf events. If it * is null, we will create a new one for the window. * @param {?Intent=} intent Intent to be handled by the app window. * Set to null for app window not launching from intent. */ constructor(callbacks, testingCallbacks, perfLogger, intent = null) { /** * @type {!WindowEventCallbacks} */ this.callbacks_ = callbacks; /** * @type {?WindowTestEventCallbacks} */ this.testingCallbacks_ = testingCallbacks; /** * @type {?Intent} * @private */ this.intent_ = intent; /** * @type {!PerfLogger} * @private */ this.perfLogger_ = perfLogger || new PerfLogger(); /** * @type {?chrome.app.window.AppWindow} * @private */ this.appWindow_ = null; /** * @type {?ForegroundOps} * @private */ this.foregroundOps_ = null; /** * @type {!WindowState} * @private */ this.state_ = WindowState.UNINIT; } /** * Gets state of the window. * @return {!WindowState} */ get state() { return this.state_; } /** * Creates app window and launches app. * @return {!Promise} */ async launch() { // Disables the metrics sending if it is testing window. if (this.testingCallbacks_ !== null) { await setMetricsEnabled(false); } this.state_ = WindowState.LAUNCHING; // The height will be later calculated to match video aspect ratio once the // stream is available. const initialHeight = Math.round(MIN_WIDTH / INITIAL_ASPECT_RATIO); const windowId = this.intent_ !== null ? `main-${this.intent_.intentId}` : 'main'; const windowUrl = 'views/main.html' + (this.intent_ !== null ? this.intent_.url.search : ''); chrome.app.window.create( windowUrl, { id: windowId, frame: {color: TOPBAR_COLOR}, hidden: true, // Will be shown from main.js once loaded. innerBounds: { width: MIN_WIDTH, height: initialHeight, minWidth: MIN_WIDTH, left: Math.round((window.screen.availWidth - MIN_WIDTH) / 2), top: Math.round((window.screen.availHeight - initialHeight) / 2), }, }, (appWindow) => { this.perfLogger_.start(PerfEvent.LAUNCHING_FROM_WINDOW_CREATION); this.appWindow_ = appWindow; this.appWindow_.onClosed.addListener(() => { browserProxy.localStorageSet({maximized: appWindow.isMaximized()}); browserProxy.localStorageSet( {fullscreen: appWindow.isFullscreen()}); this.state_ = WindowState.CLOSED; if (this.intent_ !== null && !this.intent_.done) { this.intent_.cancel(); } this.callbacks_.onClosed(this); if (this.testingCallbacks_ !== null) { this.testingCallbacks_.onClosed(windowUrl); } }); appWindow.contentWindow.backgroundOps = this; if (this.testingCallbacks_ !== null) { this.testingCallbacks_.onCreated(windowUrl); } }); } /** * @override */ bindForegroundOps(ops) { this.foregroundOps_ = ops; } /** * @override */ getIntent() { return this.intent_; } /** * @override */ notifyActivation() { this.state_ = WindowState.ACTIVE; // For intent only requiring open camera with specific mode without // returning the capture result, called onIntentHandled() right // after app successfully launched. if (this.intent_ !== null && !this.intent_.shouldHandleResult) { this.intent_.finish(); } this.callbacks_.onActive(this); } /** * @override */ notifySuspension() { this.state_ = WindowState.SUSPENDED; this.callbacks_.onSuspended(this); } /** * @override */ getPerfLogger() { return this.perfLogger_; } /** * @override */ getTestingErrorCallback() { return this.testingCallbacks_ ? this.testingCallbacks_.onError : null; } /** * Suspends the app window. */ suspend() { if (this.state_ === WindowState.LAUNCHING) { console.error('Call suspend() while window is still launching.'); return; } this.state_ = WindowState.SUSPENDING; this.foregroundOps_.suspend(); } /** * Resumes the app window. */ resume() { this.state_ = WindowState.RESUMING; this.foregroundOps_.resume(); } /** * Closes the app window. */ close() { this.state_ = WindowState.CLOSING; this.appWindow_.close(); } /** * Minimize or restore the app window. */ minimizeOrRestore() { if (this.appWindow_.isMinimized()) { this.appWindow_.restore(); this.appWindow_.focus(); } else { this.appWindow_.minimize(); } } }
JavaScript
class Background { /** * @public */ constructor() { /** * Launch window handles launch event triggered from app launcher. * @type {?CCAWindow} * @private */ this.launcherWindow_ = null; /** * Intent window handles launch event triggered from ARC++ intent. * @type {?CCAWindow} * @private */ this.intentWindow_ = null; /** * The pending intent arrived when foreground window is busy. * @type {?Intent} */ this.pendingIntent_ = null; // By default, we enable the metrics sending on background page and will // turn it off when launching testing windows. initMetrics(); } /** * Checks and logs any violation of background transition logic. * @param {boolean} assertion Condition to be asserted. * @param {string|function(): string} message Logged message. * @private */ assert_(assertion, message) { if (!assertion) { console.error(typeof message === 'string' ? message : message()); } // TODO(inker): Cleans up states and starts over after any violation. } /** * Processes the pending intent. * @private */ processPendingIntent_() { if (!this.pendingIntent_) { console.error('Call processPendingIntent_() without intent present.'); return; } this.intentWindow_ = this.createIntentWindow_(this.pendingIntent_); this.pendingIntent_ = null; this.intentWindow_.launch(); } /** * Returns a Window object handling launch event triggered from app launcher. * @return {!CCAWindow} * @private */ createLauncherWindow_() { const onActive = (wnd) => { this.assert_(wnd === this.launcherWindow_, 'Wrong active launch window.'); this.assert_( !this.intentWindow_, 'Launch window is active while handling intent window.'); if (this.pendingIntent_ !== null) { wnd.suspend(); } }; const onSuspended = (wnd) => { this.assert_( wnd === this.launcherWindow_, 'Wrong suspended launch window.'); this.assert_( !this.intentWindow_, 'Launch window is suspended while handling intent window.'); if (this.pendingIntent_ === null) { this.assert_( false, 'Launch window is not suspended by some pending intent'); wnd.resume(); return; } this.processPendingIntent_(); }; const onClosed = (wnd) => { this.assert_(wnd === this.launcherWindow_, 'Wrong closed launch window.'); this.launcherWindow_ = null; if (this.pendingIntent_ !== null) { this.processPendingIntent_(); } }; const wnd = new CCAWindow( {onActive, onSuspended, onClosed}, windowTestEventCallbacks, perfLoggerForTesting); windowTestEventCallbacks = null; perfLoggerForTesting = null; return wnd; } /** * Returns a Window object handling launch event triggered from ARC++ intent. * @param {!Intent} intent Intent forwarding from ARC++. * @return {!CCAWindow} * @private */ createIntentWindow_(intent) { const onActive = (wnd) => { this.assert_(wnd === this.intentWindow_, 'Wrong active intent window.'); this.assert_( !this.launcherWindow_ || this.launcherWindow_.state === WindowState.SUSPENDED, () => `Launch window is ${ this.launcherWindow_.state} when intent window is active.`); if (this.pendingIntent_) { wnd.close(); } }; const onSuspended = (wnd) => { this.assert_( wnd === this.intentWindow_, 'Wrong suspended intent window.'); this.assert_(false, 'Intent window should not be suspended.'); }; const onClosed = (wnd) => { this.assert_(wnd === this.intentWindow_, 'Wrong closed intent window.'); this.assert_( !this.launcherWindow_ || this.launcherWindow_.state === WindowState.SUSPENDED, () => `Launch window is ${ this.launcherWindow_.state} when intent window is closed.`); this.intentWindow_ = null; if (this.pendingIntent_) { this.processPendingIntent_(); } else if (this.launcherWindow_) { this.launcherWindow_.resume(); } }; const wnd = new CCAWindow( {onActive, onSuspended, onClosed}, windowTestEventCallbacks, perfLoggerForTesting, intent); windowTestEventCallbacks = null; perfLoggerForTesting = null; return wnd; } /** * Handles launch event triggered from app launcher. */ launchApp() { if (this.launcherWindow_ || this.intentWindow_) { const activeWindow = [this.launcherWindow_, this.intentWindow_].find( (wnd) => wnd !== null && wnd.state_ === WindowState.ACTIVE); if (activeWindow !== undefined) { activeWindow.minimizeOrRestore(); } return; } this.assert_( !this.pendingIntent_, 'Pending intent is not processed when launch new window.'); this.launcherWindow_ = this.createLauncherWindow_(); this.launcherWindow_.launch(); } /** * Closes the existing pending intent and replaces it with a new incoming * intent. * @param {!Intent} intent New incoming intent. * @private */ replacePendingIntent_(intent) { if (this.pendingIntent_) { this.pendingIntent_.cancel(); } this.pendingIntent_ = intent; } /** * Handles launch event triggered from ARC++ intent. * @param {!Intent} intent Intent forwarding from ARC++. */ launchIntent(intent) { if (this.intentWindow_) { switch (this.intentWindow_.state) { case WindowState.LAUNCHING: case WindowState.CLOSING: this.replacePendingIntent_(intent); break; case WindowState.ACTIVE: this.replacePendingIntent_(intent); this.intentWindow_.close(); break; default: this.assert_( false, `Intent window is ${ this.intentWindow_.state} when launch new intent window.`); } } else if (this.launcherWindow_) { switch (this.launcherWindow_.state) { case WindowState.LAUNCHING: case WindowState.SUSPENDING: case WindowState.RESUMING: case WindowState.CLOSING: this.replacePendingIntent_(intent); break; case WindowState.ACTIVE: this.assert_( !this.pendingIntent_, 'Pending intent is not processed when launch window is active.'); this.replacePendingIntent_(intent); this.launcherWindow_.suspend(); break; default: this.assert_( false, `Launch window is ${ this.launcherWindow_.state} when launch new intent window.`); } } else { this.intentWindow_ = this.createIntentWindow_(intent); this.intentWindow_.launch(); } } }
JavaScript
class AbstractCartItem { constructor() { this.ref = generateRef(); } /** * Updates this item with the serialized object * @param {object} data */ update(data) { merge(this, data); } /** * Returns the price of this item as a BigNumber * @return {BigNumber} */ getPrice() {} /** * Returns a serialized version of this instance * * @return {object} */ serialize() { return { id: this.id, type: this.type, }; } }
JavaScript
class DecodedBitStreamParser { static decode(bytes, version, ecLevel, hints) { const bits = new BitSource(bytes); let result = new StringBuilder(); const byteSegments = new Array(); // 1 // TYPESCRIPTPORT: I do not use constructor with size 1 as in original Java means capacity and the array length is checked below let symbolSequence = -1; let parityData = -1; try { let currentCharacterSetECI = null; let fc1InEffect = false; let mode; do { // While still another segment to read... if (bits.available() < 4) { // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here mode = Mode.TERMINATOR; } else { const modeBits = bits.readBits(4); mode = Mode.forBits(modeBits); // mode is encoded by 4 bits } switch (mode) { case Mode.TERMINATOR: break; case Mode.FNC1_FIRST_POSITION: case Mode.FNC1_SECOND_POSITION: // We do little with FNC1 except alter the parsed result a bit according to the spec fc1InEffect = true; break; case Mode.STRUCTURED_APPEND: if (bits.available() < 16) { throw new FormatException(); } // sequence number and parity is added later to the result metadata // Read next 8 bits (symbol sequence #) and 8 bits (data: parity), then continue symbolSequence = bits.readBits(8); parityData = bits.readBits(8); break; case Mode.ECI: // Count doesn't apply to ECI const value = DecodedBitStreamParser.parseECIValue(bits); currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value); if (currentCharacterSetECI === null) { throw new FormatException(); } break; case Mode.HANZI: // First handle Hanzi mode which does not start with character count // Chinese mode contains a sub set indicator right after mode indicator const subset = bits.readBits(4); const countHanzi = bits.readBits(mode.getCharacterCountBits(version)); if (subset === DecodedBitStreamParser.GB2312_SUBSET) { DecodedBitStreamParser.decodeHanziSegment(bits, result, countHanzi); } break; default: // "Normal" QR code modes: // How many characters will follow, encoded in this mode? const count = bits.readBits(mode.getCharacterCountBits(version)); switch (mode) { case Mode.NUMERIC: DecodedBitStreamParser.decodeNumericSegment(bits, result, count); break; case Mode.ALPHANUMERIC: DecodedBitStreamParser.decodeAlphanumericSegment(bits, result, count, fc1InEffect); break; case Mode.BYTE: DecodedBitStreamParser.decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints); break; case Mode.KANJI: DecodedBitStreamParser.decodeKanjiSegment(bits, result, count); break; default: throw new FormatException(); } break; } } while (mode !== Mode.TERMINATOR); } catch (iae /*: IllegalArgumentException*/) { // from readBits() calls throw new FormatException(); } return new DecoderResult(bytes, result.toString(), byteSegments.length === 0 ? null : byteSegments, ecLevel === null ? null : ecLevel.toString(), symbolSequence, parityData); } /** * See specification GBT 18284-2000 */ static decodeHanziSegment(bits, result, count /*int*/) { // Don't crash trying to read more bits than we have available. if (count * 13 > bits.available()) { throw new FormatException(); } // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as GB2312 afterwards const buffer = new Uint8Array(2 * count); let offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character const twoBytes = bits.readBits(13); let assembledTwoBytes = (((twoBytes / 0x060) << 8) & 0xFFFFFFFF) | (twoBytes % 0x060); if (assembledTwoBytes < 0x003BF) { // In the 0xA1A1 to 0xAAFE range assembledTwoBytes += 0x0A1A1; } else { // In the 0xB0A1 to 0xFAFE range assembledTwoBytes += 0x0A6A1; } buffer[offset] = /*(byte) */ ((assembledTwoBytes >> 8) & 0xFF); buffer[offset + 1] = /*(byte) */ (assembledTwoBytes & 0xFF); offset += 2; count--; } try { result.append(StringEncoding.decode(buffer, StringUtils.GB2312)); // TYPESCRIPTPORT: TODO: implement GB2312 decode. StringView from MDN could be a starting point } catch (ignored /*: UnsupportedEncodingException*/) { throw new FormatException(ignored); } } static decodeKanjiSegment(bits, result, count /*int*/) { // Don't crash trying to read more bits than we have available. if (count * 13 > bits.available()) { throw new FormatException(); } // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards const buffer = new Uint8Array(2 * count); let offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character const twoBytes = bits.readBits(13); let assembledTwoBytes = (((twoBytes / 0x0C0) << 8) & 0xFFFFFFFF) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = /*(byte) */ (assembledTwoBytes >> 8); buffer[offset + 1] = /*(byte) */ assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: try { result.append(StringEncoding.decode(buffer, StringUtils.SHIFT_JIS)); // TYPESCRIPTPORT: TODO: implement SHIFT_JIS decode. StringView from MDN could be a starting point } catch (ignored /*: UnsupportedEncodingException*/) { throw new FormatException(ignored); } } static decodeByteSegment(bits, result, count /*int*/, currentCharacterSetECI, byteSegments, hints) { // Don't crash trying to read more bits than we have available. if (8 * count > bits.available()) { throw new FormatException(); } const readBytes = new Uint8Array(count); for (let i = 0; i < count; i++) { readBytes[i] = /*(byte) */ bits.readBits(8); } let encoding; if (currentCharacterSetECI === null) { // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. encoding = StringUtils.guessEncoding(readBytes, hints); } else { encoding = currentCharacterSetECI.getName(); } try { result.append(StringEncoding.decode(readBytes, encoding)); } catch (ignored /*: UnsupportedEncodingException*/) { throw new FormatException(ignored); } byteSegments.push(readBytes); } static toAlphaNumericChar(value /*int*/) { if (value >= DecodedBitStreamParser.ALPHANUMERIC_CHARS.length) { throw new FormatException(); } return DecodedBitStreamParser.ALPHANUMERIC_CHARS[value]; } static decodeAlphanumericSegment(bits, result, count /*int*/, fc1InEffect) { // Read two characters at a time const start = result.length(); while (count > 1) { if (bits.available() < 11) { throw new FormatException(); } const nextTwoCharsBits = bits.readBits(11); result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(nextTwoCharsBits / 45))); result.append(DecodedBitStreamParser.toAlphaNumericChar(nextTwoCharsBits % 45)); count -= 2; } if (count === 1) { // special case: one character left if (bits.available() < 6) { throw new FormatException(); } result.append(DecodedBitStreamParser.toAlphaNumericChar(bits.readBits(6))); } // See section 6.4.8.1, 6.4.8.2 if (fc1InEffect) { // We need to massage the result a bit if in an FNC1 mode: for (let i = start; i < result.length(); i++) { if (result.charAt(i) === '%') { if (i < result.length() - 1 && result.charAt(i + 1) === '%') { // %% is rendered as % result.deleteCharAt(i + 1); } else { // In alpha mode, % should be converted to FNC1 separator 0x1D result.setCharAt(i, String.fromCharCode(0x1D)); } } } } } static decodeNumericSegment(bits, result, count /*int*/) { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits if (bits.available() < 10) { throw new FormatException(); } const threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw new FormatException(); } result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 100))); result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 10) % 10)); result.append(DecodedBitStreamParser.toAlphaNumericChar(threeDigitsBits % 10)); count -= 3; } if (count === 2) { // Two digits left over to read, encoded in 7 bits if (bits.available() < 7) { throw new FormatException(); } const twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw new FormatException(); } result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(twoDigitsBits / 10))); result.append(DecodedBitStreamParser.toAlphaNumericChar(twoDigitsBits % 10)); } else if (count === 1) { // One digit left over to read if (bits.available() < 4) { throw new FormatException(); } const digitBits = bits.readBits(4); if (digitBits >= 10) { throw new FormatException(); } result.append(DecodedBitStreamParser.toAlphaNumericChar(digitBits)); } } static parseECIValue(bits) { const firstByte = bits.readBits(8); if ((firstByte & 0x80) === 0) { // just one byte return firstByte & 0x7F; } if ((firstByte & 0xC0) === 0x80) { // two bytes const secondByte = bits.readBits(8); return (((firstByte & 0x3F) << 8) & 0xFFFFFFFF) | secondByte; } if ((firstByte & 0xE0) === 0xC0) { // three bytes const secondThirdBytes = bits.readBits(16); return (((firstByte & 0x1F) << 16) & 0xFFFFFFFF) | secondThirdBytes; } throw new FormatException(); } }
JavaScript
class EditableOutline extends _litElement.LitElement { //styles function static get styles() { return [(0, _litElement.css)` :host { display: block; font-family: "Noto Serif", serif; } :host([hidden]) { display: none; } .button-wrapper { line-height: 36px; position: -webkit-sticky; position: sticky; top: 0px; background-color: white; display: block; justify-content: space-evenly; } @media (max-width: 1000px) { button span { opacity: 0; visibility: hidden; position: absolute; left: -9999px; } } button { height: 32px; font-size: 10px; margin: 0; padding: 0 8px; } button span { padding-left: 4px; pointer-events: none; } #outline { margin: 0; } ul { font-size: 16px; line-height: 32px; padding-left: 32px; visibility: visible; opacity: 1; overflow: hidden; height: auto; transition: 0.2s ease-in-out all; } li { font-size: 16px; line-height: 32px; padding: 4px; transition: 0.2s linear all; } ul:hover { outline: 1px solid #eeeeee; } li.collapsed-title { background-color: #dddddd; } li.collapsed-title:after { content: " ( Double-click to expand )"; } li:after { transition: 0.4s ease-in-out all; opacity: 0; font-size: 11px; visibility: hidden; } li.collapsed-title:hover:after { font-style: italic; opacity: 1; visibility: visible; } ul.collapsed-content { visibility: hidden; opacity: 0; height: 0; } li:focus, li:active, li:hover { background-color: #eeeeee; outline: 1px solid #cccccc; } iron-icon { pointer-events: none; } `]; } // render function render() { return (0, _litElement.html)` <iron-a11y-keys keys="enter" @keys-pressed="${this._enterPressed}" stop-keyboard-event-propagation ></iron-a11y-keys> <iron-a11y-keys keys="up" @keys-pressed="${this._upPressed}" stop-keyboard-event-propagation ></iron-a11y-keys> <iron-a11y-keys keys="down" @keys-pressed="${this._downPressed}" stop-keyboard-event-propagation ></iron-a11y-keys> <div class="button-wrapper"> <button @click="${this.buttonEvents}" id="add" title="Add a new node"> <iron-icon icon="icons:add"></iron-icon><span>Add</span> </button> <button @click="${this.buttonEvents}" id="collapse" title="Toggle active node collapsed status" > <iron-icon icon="icons:swap-vert"></iron-icon ><span>Toggle active</span> </button> <button @click="${this.buttonEvents}" id="collapseall" title="Collapse all nodes" > <iron-icon icon="icons:swap-vert"></iron-icon ><span>Collapse all</span> </button> <button @click="${this.buttonEvents}" id="expandall" title="Expand all nodes" > <iron-icon icon="icons:swap-vert"></iron-icon><span>Expand all</span> </button> <button @click="${this.buttonEvents}" id="down" title="Move active node down" > <iron-icon icon="icons:arrow-downward"></iron-icon ><span>Move down</span> </button> <button @click="${this.buttonEvents}" id="up" title="Move active node up" > <iron-icon icon="icons:arrow-upward"></iron-icon><span>Move up</span> </button> <button @click="${this.buttonEvents}" id="outdent" title="Outdent active node" > <iron-icon icon="editor:format-indent-decrease"></iron-icon ><span>Outdent</span> </button> <button @click="${this.buttonEvents}" id="indent" title="Indent active node" > <iron-icon icon="editor:format-indent-increase"></iron-icon ><span>Indent</span> </button> <button @click="${this.buttonEvents}" id="duplicate" title="Duplicate active node tree" > <iron-icon icon="icons:content-copy"></iron-icon ><span>Duplicate</span> </button> </div> <ul id="outline"></ul> `; } // properties available to the custom element for data binding static get properties() { return { ...super.properties, /** * A items list of JSON Outline Schema Items */ items: { type: Array }, /** * Edit mode */ editMode: { type: Boolean, attribute: "edit-mode" }, /** * Outline node for keyboard key binding */ __outlineNode: { type: Object } }; } constructor() { super(); this.items = []; this.editMode = false; this.jos = window.JSONOutlineSchema.requestAvailability(); new Promise((res, rej) => _require.default(["../../@polymer/iron-icon/iron-icon.js"], res, rej)); new Promise((res, rej) => _require.default(["../../@polymer/iron-icons/iron-icons.js"], res, rej)); new Promise((res, rej) => _require.default(["../../@polymer/iron-icons/editor-icons.js"], res, rej)); setTimeout(() => { this.addEventListener("dblclick", this._collapseClickHandler.bind(this)); }, 0); } /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ static get tag() { return "editable-outline"; } /** * Collapse button callback */ _collapse(e) { let node = this.getSelectionNode(); if (node && node.tagName === "LI" && node.nextElementSibling && node.nextElementSibling.tagName === "UL") { node.classList.toggle("collapsed-title"); node.nextElementSibling.classList.toggle("collapsed-content"); } } /** * Expand all items */ _expandall(e) { this.shadowRoot.querySelectorAll("li").forEach(el => { el.classList.remove("collapsed-title"); }); this.shadowRoot.querySelectorAll("ul").forEach(el => { el.classList.remove("collapsed-content"); }); } /** * Collapse all items */ _collapseall(e) { this.shadowRoot.querySelectorAll("li").forEach(el => { if (el.nextElementSibling && el.nextElementSibling.tagName === "UL") { el.classList.add("collapsed-title"); el.nextElementSibling.classList.add("collapsed-content"); } }); } _onKeyDown(e) { if (this.editMode) { switch (e.key) { case "Tab": if (e.shiftKey) { this._tabBackKeyPressed(e); } else { this._tabKeyPressed(e); } break; } } } /** * Click handler method needs to walk a little different then normal collapse */ _collapseClickHandler(e) { let el; let i = 0; let notFound = true; while (notFound && e.path.length > i + 1) { el = e.path[i]; if (el.tagName === "LI" && el.nextElementSibling && el.nextElementSibling.tagName === "UL") { el.classList.toggle("collapsed-title"); el.nextElementSibling.classList.toggle("collapsed-content"); notFound = false; } i++; } } firstUpdated() { this.__outlineNode = this.shadowRoot.querySelector("#outline"); this.shadowRoot.querySelectorAll("iron-a11y-keys").forEach(el => { el.target = this.__outlineNode; }); this.__outlineNode.addEventListener("keydown", this._onKeyDown.bind(this)); this._observer = new MutationObserver(this._observeRecord.bind(this)); this._observer.observe(this.__outlineNode, { childList: true, subtree: true }); } updated(changedProperties) { changedProperties.forEach((oldValue, propName) => { let notifiedProps = ["editMode", "items"]; if (notifiedProps.includes(propName)) { // notify let eventName = `${propName.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase()}-changed`; this.dispatchEvent(new CustomEvent(eventName, { detail: { value: this[propName] } })); } }); } /** * Mutation observer callback * @todo current issue if you copy and paste into the same node */ _observeRecord(record) { for (var index in record) { let info = record[index]; // if we've got new nodes to react to that were not imported if (info.addedNodes.length > 0) { // special rules for an outdent event for (let i in info.addedNodes) { if (info.addedNodes[i].tagName) { if (info.addedNodes[i].tagName === "LI") { if (this.__blockScrub) { info.addedNodes[i].setAttribute("contenteditable", "true"); } else { this.jos.scrubElementJOSData(info.addedNodes[i]); info.addedNodes[i].setAttribute("contenteditable", "true"); } } // we have an unknown hest of items, scrub em all if we are in scrub mode else if (info.addedNodes[i].tagName === "UL") { if (!this.__blockScrub) { this.jos.scrubElementJOSData(info.addedNodes[i]); } } } } } } setTimeout(() => { this.__blockScrub = false; }, 100); } /** * Disconnected life cycle */ disconnectedCallback() { this.__outlineNode.removeEventListener("keydown", this._onKeyDown.bind(this)); this._observer.disconnect(); super.disconnectedCallback(); } /** * Button events internally */ buttonEvents(e) { switch (e.target.id) { case "add": this._add(e); break; case "collapse": this._collapse(e); break; case "collapseall": this._collapseall(e); break; case "expandall": this._expandall(e); break; case "indent": this._indent(); break; case "outdent": this._outdent(); break; case "up": this._move("up"); break; case "down": this._move("down"); break; case "duplicate": this._duplicate(); break; } } /** * Duplicate whatever has selection */ _duplicate() { // get active item from where cursor is try { this.__blockScrub = false; let activeItem = this.getSelectionNode(); if (activeItem && activeItem.tagName === "LI") { // clone the item's hierarchy as well if (activeItem.nextElementSibling !== null && activeItem.nextElementSibling.tagName === "UL") { // copy the UL and all children and insert it after the UL it's duplicating const clone2 = activeItem.nextElementSibling.cloneNode(true); activeItem.parentNode.insertBefore(clone2, activeItem.nextElementSibling.nextElementSibling); // clone the LI, placing it before the UL we just made const clone = activeItem.cloneNode(true); activeItem.parentNode.insertBefore(clone, activeItem.nextElementSibling.nextElementSibling); } else { const clone = activeItem.cloneNode(true); // insert the clone AFTER the current selection activeItem.parentNode.insertBefore(clone, activeItem.nextElementSibling); } } } catch (e) { console.log(e); } } /** * Move whatever has selection up or down */ _move(direction) { // get active item from where cursor is try { let activeItem = this.getSelectionNode(); let test = activeItem; let valid = false; if (activeItem == null) { return false; } // ensure this operation is executed in scope while (!valid && test.parentNode) { if (test.id === "outline") { valid = true; } test = test.parentNode; } // ensure from all that, we have something if (valid && activeItem && activeItem.tagName === "LI") { // move the things above us, below us if (direction === "up") { // ensure there's something above us if (activeItem.previousElementSibling !== null) { // see if we are moving us, or us and the hierarchy if (activeItem.nextElementSibling && activeItem.nextElementSibling.tagName === "UL") { // see if the thing we have to move above has it's own structure if (activeItem.previousElementSibling.tagName === "UL") { // ensure we don't lose our metadata this.__blockScrub = true; // insert the element currently above us, just before 2 places back; so behind our UL activeItem.parentNode.insertBefore(activeItem.previousElementSibling, activeItem.nextElementSibling.nextElementSibling); } this.__blockScrub = true; // now insert the LI above us, 2 places back so it is in front of the UL activeItem.parentNode.insertBefore(activeItem.previousElementSibling, activeItem.nextElementSibling.nextElementSibling); activeItem.focus(); } else { // easier use case, we are moving ourselves only but above us is a UL if (activeItem.previousElementSibling.tagName === "UL") { this.__blockScrub = true; // move the UL after us activeItem.parentNode.insertBefore(activeItem.previousElementSibling, activeItem.nextElementSibling); } this.__blockScrub = true; // now move the LI after us activeItem.parentNode.insertBefore(activeItem.previousElementSibling, activeItem.nextElementSibling); activeItem.focus(); } } } else if (direction === "down") { // if nothing after us, we can't move if (activeItem.nextElementSibling !== null) { // account for having to hop over children if (activeItem.nextElementSibling && activeItem.nextElementSibling.tagName === "UL" && activeItem.nextElementSibling.nextElementSibling !== null) { // an outline is just below us if (activeItem.nextElementSibling.nextElementSibling.tagName === "LI" && activeItem.nextElementSibling.nextElementSibling.nextElementSibling !== null && activeItem.nextElementSibling.nextElementSibling.nextElementSibling.tagName === "UL") { this.__blockScrub = true; // move the thing 2 down to just before us; so the UL activeItem.parentNode.insertBefore(activeItem.nextElementSibling.nextElementSibling, activeItem); } this.__blockScrub = true; // now move the LI that is 2 below us just above us activeItem.parentNode.insertBefore(activeItem.nextElementSibling.nextElementSibling, activeItem); activeItem.focus(); } else if (activeItem.nextElementSibling.tagName === "LI") { // just moving 1 tag, see if we need to move 2 things about us or 1 if (activeItem.nextElementSibling.nextElementSibling !== null && activeItem.nextElementSibling.nextElementSibling.tagName === "UL") { this.__blockScrub = true; activeItem.parentNode.insertBefore(activeItem.nextElementSibling, activeItem); } this.__blockScrub = true; // work on the LI activeItem.parentNode.insertBefore(activeItem.nextElementSibling, activeItem); activeItem.focus(); } } } } } catch (e) { console.log(e); } } /** * Take the current manifest and import it into an HTML outline */ importJsonOutlineSchemaItems() { this.__blockScrub = true; setTimeout(() => { // wipe out the outline while (this.__outlineNode.firstChild) { this.__outlineNode.removeChild(this.__outlineNode.firstChild); } if (this.items.length === 0) { // get from JOS items if we have none currently this.items = [...this.jos.items]; } let outline = this.jos.itemsToNodes(this.items); // rebuild the outline w/ children we just found while (outline.firstChild) { this.__blockScrub = true; this.__outlineNode.appendChild(outline.firstChild); } this.shadowRoot.querySelectorAll("li").forEach(el => { el.setAttribute("contenteditable", "true"); }); }, 0); return outline; } /** * Take what's currently in the area and get JSON Outline Schema; optionally save */ exportJsonOutlineSchemaItems(save = false) { return this.jos.nodesToItems(this.__outlineNode, save); } _upPressed(e) { let node = this.getSelectionNode(); if (node && node.previousSibling && node.previousSibling.tagName === "LI") { node.previousSibling.focus(); } else if (node && node.previousSibling && node.previousSibling.tagName === "UL" && node.previousSibling.firstChild && node.previousSibling.firstChild.tagName === "LI") { node.previousSibling.firstChild.focus(); } else if (node && node.previousSibling == null && node.parentNode.tagName === "UL" && node.parentNode.previousSibling && node.parentNode.previousSibling.tagName === "LI") { node.parentNode.previousSibling.focus(); } } _downPressed(e) { let node = this.getSelectionNode(); if (node && node.nextSibling && node.nextSibling.tagName === "LI") { node.nextSibling.focus(); } else if (node && node.nextSibling && node.nextSibling.tagName === "UL" && node.nextSibling.firstChild && node.nextSibling.firstChild.tagName === "LI") { node.nextSibling.firstChild.focus(); } else if (node && node.nextSibling == null && node.parentNode.tagName === "UL" && node.parentNode.nextSibling && node.parentNode.nextSibling.tagName === "LI") { node.parentNode.nextSibling.focus(); } } /** * Find the next thing to tab forward to. */ _tabKeyPressed(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); if (e.detail.keyboardEvent) { e.detail.keyboardEvent.preventDefault(); e.detail.keyboardEvent.stopPropagation(); e.detail.keyboardEvent.stopImmediatePropagation(); } try { this._indent(); } catch (e) {} } /** * Move back through things when tab back pressed */ _tabBackKeyPressed(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); if (e.detail.keyboardEvent) { e.detail.keyboardEvent.preventDefault(); e.detail.keyboardEvent.stopPropagation(); e.detail.keyboardEvent.stopImmediatePropagation(); } try { this._outdent(); } catch (e) {} } _enterPressed(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); // prevent the contenteditable stuff if (e.detail.keyboardEvent) { e.detail.keyboardEvent.preventDefault(); e.detail.keyboardEvent.stopPropagation(); e.detail.keyboardEvent.stopImmediatePropagation(); } this._add(); } _add() { let li = document.createElement("li"); li.setAttribute("contenteditable", "true"); let node = this.getSelectionNode(); if (this.__outlineNode.querySelector("li") == null || !node || node.tagName && node.tagName != "UL" && node.tagName != "LI") { this.__outlineNode.appendChild(li); } else { if ((node.tagName == null || node.tagName != "LI") && node.parentNode) { node = node.parentNode; } if (node.nextSibling == null) { node.parentNode.appendChild(li); } else { node.parentNode.insertBefore(li, node.nextSibling); } try { li.focus(); } catch (e) {// prevent issue on polyfill browsers potentially } } } _outdent() { this.__blockScrub = true; try { let node = this.getSelectionNode(); if (node == null) { return false; } // need to hold this in case it's empty at the end const parent = node.parentNode; if (node.parentNode && node.parentNode != this.__outlineNode && node.parentNode.nextSibling != null) { node.parentNode.parentNode.insertBefore(node, node.parentNode.nextSibling); if (parent.children.length == 0) { parent.remove(); } } else if (node.parentNode && node.parentNode != this.__outlineNode && node.parentNode.nextSibling == null) { node.parentNode.parentNode.appendChild(node); if (parent.children.length == 0) { parent.remove(); } } node.focus(); } catch (e) { console.warn(e); } } _indent() { this.__blockScrub = true; try { let node = this.getSelectionNode(); if (node == null) { return false; } // see if the previous tag is a LI, if so we can indent if (node.previousSibling != null && node.previousSibling.tagName === "LI") { let ul; if (node.nextSibling && node.nextSibling.tagName === "UL") { ul = node.nextSibling; } else { ul = document.createElement("ul"); node.parentNode.insertBefore(ul, node); } // append a new list inside the child before the active node position // now append into that list the node that was active ul.appendChild(node); node.focus(); } else if (node.previousSibling != null && node.previousSibling.tagName === "UL") { node.previousSibling.appendChild(node); node.focus(); } } catch (e) { console.warn(e); } } getSelectionNode() { let node = this.getDeepSelection().anchorNode; if (node && (node.tagName == null || node.tagName != "LI") && node.parentNode) { node = node.parentNode; } return node; } /** * Selection normalizer */ getDeepSelection() { // try and obtain the selection from the nearest shadow // which would give us the selection object when running native ShadowDOM // with fallback support for the entire window which would imply Shady // native API if (this.shadowRoot.getSelection) { return this.shadowRoot.getSelection(); } // ponyfill from google else if ((0, _utils.getRange)(this.__outlineNode.parentNode)) { return (0, _utils.getRange)(this.__outlineNode.parentNode); } // missed on both, hope the normal one will work return window.getSelection(); } /** * Get a normalized range based on current selection */ getDeepRange() { let sel = this.getDeepSelection(); if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); } else if (sel) { return sel; } else false; } }
JavaScript
class Calculator extends Component { constructor(props) { super(props); this.handleCelsiusChange = this.handleCelsiusChange.bind(this); this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this); this.state = { temp: '', scale: 'c' }; } handleCelsiusChange(temp) { this.setState({ scale: 'c', temp }); } handleFahrenheitChange(temp) { this.setState({ scale: 'f', temp }) } render() { const scale = this.state.scale; const temp = this.state.temp; const c = scale === 'f' ? convert(temp, toCelsius) : temp; const f = scale === 'c' ? convert(temp, toFahrenheit) : temp; return ( <div className={'w-4/5 my-2 rounded mx-auto p-3 bg-secondary md:flex md:flex-row filter drop-shadow-xl'}> <TempInput scale="f" temp={f} onChange={this.handleFahrenheitChange} /> <img src={Convert} alt="convert temperature" className={'mx-auto my-2 transform rotate-90 md:rotate-0'} /> <TempInput scale="c" temp={c} onChange={this.handleCelsiusChange} /> </div> ); } }
JavaScript
class DiscussionComposer extends ComposerBody { init() { super.init(); /** * The value of the title input. * * @type {Function} */ this.title = m.prop(''); } static initProps(props) { super.initProps(props); props.placeholder = props.placeholder || extractText(app.translator.trans('core.forum.composer_discussion.body_placeholder')); props.submitLabel = props.submitLabel || app.translator.trans('core.forum.composer_discussion.submit_button'); props.confirmExit = props.confirmExit || extractText(app.translator.trans('core.forum.composer_discussion.discard_confirmation')); props.titlePlaceholder = props.titlePlaceholder || extractText(app.translator.trans('core.forum.composer_discussion.title_placeholder')); props.className = 'ComposerBody--discussion'; } headerItems() { const items = super.headerItems(); items.add('title', <h3>{app.translator.trans('core.forum.composer_discussion.title')}</h3>, 100); items.add( 'discussionTitle', <h3> <input className="FormControl" value={this.title()} oninput={m.withAttr('value', this.title)} placeholder={this.props.titlePlaceholder} disabled={!!this.props.disabled} onkeydown={this.onkeydown.bind(this)} /> </h3> ); return items; } /** * Handle the title input's keydown event. When the return key is pressed, * move the focus to the start of the text editor. * * @param {Event} e */ onkeydown(e) { if (e.which === 13) { // Return e.preventDefault(); this.editor.setSelectionRange(0, 0); } m.redraw.strategy('none'); } preventExit() { return (this.title() || this.content()) && this.props.confirmExit; } /** * Get the data to submit to the server when the discussion is saved. * * @return {Object} */ data() { return { title: this.title(), content: this.content(), }; } onsubmit() { this.loading = true; const data = this.data(); app.store .createRecord('discussions') .save(data) .then((discussion) => { app.composer.hide(); app.discussions.refresh(); m.route(app.route.discussion(discussion)); }, this.loaded.bind(this)); } }
JavaScript
class DefaultConfig { constructor(config=null) { /** * Language of parsed Wiki text (default `en`). * * @type {String} */ this.language = 'en'; this.contentLanguage = new LanguageSetup( config && config.language? config.language : 'en', config && config.projectName? config.projectName : ''); /** * project name (like `$wgSitename`, e.g. used for namespaces * `Title.NS_PROJECT` and `Title.NS_PROJECT_TALK`). * * @type {String} */ this.projectName = ''; /** * This page title. Currently used for edit section links in **TOC** and * for some **Magic Variables** (e.g `{{PAGENAME}}`, `{{FULLPAGENAME}}`, * `{{NAMESPACE}}`). * * @type {String} */ this.pageTitle = 'Main page'; /** * Base template for wiki page URL with query. * Template params: * * `$PROTOCOL` - protocol scheme (e.g. '`https://`') * * `$QUERY` - query part of url * * @type {String} */ this.baseUrlForQuery = `$PROTOCOL${ this.language }.wikipedia.org/w/index.php?$QUERY`; /** * Base template for wiki page URL only (without query). * Template params: * * `$PROTOCOL` - protocol scheme (e.g. '`https://`') * * `$TITLE` - title * * `$QUERY` - query part of url (optional; don't use with $TITLE) * * @type {String} */ this.baseUrlForTitle = this.baseUrlForQuery; /** * Base template for wiki URLs. Template params: * * `$PROTOCOL` - protocol scheme (e.g. '`https://`') * * `$LANGUAGE` - interwiki language * * `$QUERY` - query part of url * * @type {String} */ this.interwikiUrl = `$PROTOCOL$LANGUAGE.wikipedia.org/w/index.php?$QUERY`; this.validInterwikiNames = []; this.externalLinkTarget = false; // setting to _blank may represent a security risk this.defaultThumbSize = 300; this.thumbUpright = 0.75; this.wgResponsiveImages = true; this.uploadMissingFileUrl = true; // override default config with user defined if(config) Object.entries(config).forEach(([k, v]) => this[k] = v); } /** * Check if title exists (also test if file exists) * * @param {Title|String} title * @return {Boolean} */ titleExists(title) { return true; } /** * Overrides Title.getFullURL if return truthy. Use for generate your own * url for title. * * @param {Title} title * @param {URLSearchParams|Object|Array|String} [query] * @param {String} [proto='//'] Protocol type to use in URL ('//' - relative, 'http://', 'https://') * @return {String} */ getFullURL(title, query=null, proto='//') { return false; } /** * Function is checking if image can be displayed * (false - display image page link instead) * * @param {Title} title * @return {Boolean} */ allowImageDisplay(title) { return true; } /** * Make thumb image (or thumb image information). * */ makeThumb(title, width=false, height=false, doNotZoomIn=false) { return false; // return { // url: '', // width: 0, // height: 0 // }; } /** * Get url for image (ie. /images/a/af/LoremIpsum.png). Overrides Title.getImageURL if return truthy. * * @return {String} */ getImageURL(title) { return false; } /** * Get relative url for image thumb (ie. /images/thumb/a/af/LoremIpsum.png/150px-LoremIpsum.png). Overrides Title.getThumbURL if return truthy. * * @param {Number} width thumb width * @return {String} */ getThumbURL(width) { return false; } /** * Allow display external image as <img> tag */ allowExternalImage(url) { return false; } /** * Get template source for title * * @param String title * @return String */ getTemplate(title) { return false; } /** * Registers new Magic Variables * * @return [{{id: String, synonyms: String[], caseSensitive: Boolean}}] */ registerNewMagicVariables() { return []; } /** * Changes the output for a given Magic Variable * */ changeMagicVariableOutput(variableId, defaultOutput) { return defaultOutput; } /** * Called by parser when parser function needed (eg. {{sum:1|2|3}}). Return * parser function result text or false, when function in unknown. * * @param String funcName * @param Object args * @return String|false */ callParserFunction(funcName, args) { return false; } }
JavaScript
class Pow extends Component { static propTypes = { /** @ignore */ remotePoW: PropTypes.bool.isRequired, /** @ignore */ t: PropTypes.func.isRequired, /** @ignore */ changePowSettings: PropTypes.func.isRequired, /** @ignore */ setSetting: PropTypes.func.isRequired, /** @ignore */ theme: PropTypes.object.isRequired, }; constructor() { super(); this.onChange = this.onChange.bind(this); } componentDidMount() { leaveNavigationBreadcrumb('Pow'); } onChange() { this.props.changePowSettings(); } render() { const { t, remotePoW, theme: { body, primary } } = this.props; const textColor = { color: body.color }; return ( <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <View style={styles.container}> <View style={styles.topContainer}> <View style={{ flex: 2 }} /> <InfoBox> <Text style={[styles.infoText, textColor]}>{t('feeless')}</Text> <Text style={[styles.infoText, textColor, { paddingTop: height / 50 }]}> {t('localOrRemote')} </Text> </InfoBox> <View style={{ flex: 1.1 }} /> <TouchableWithoutFeedback onPress={this.onChange} hitSlop={{ top: height / 55, bottom: height / 55, left: width / 70, right: width / 35 }} > <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}> <View style={styles.toggleTextContainer}> <Text style={[styles.toggleText, textColor, { marginRight: width / 45 }]}> {t('local')} </Text> </View> <Toggle active={remotePoW} bodyColor={body.color} primaryColor={primary.color} scale={1.3} /> <View style={styles.toggleTextContainer}> <Text style={[styles.toggleText, textColor, { marginLeft: width / 45 }]}> {t('remote')} </Text> </View> </View> </TouchableWithoutFeedback> <View style={{ flex: 1.5 }} /> </View> <View style={styles.bottomContainer}> <TouchableOpacity onPress={() => this.props.setSetting('advancedSettings')} hitSlop={{ top: height / 55, bottom: height / 55, left: width / 55, right: width / 55 }} > <View style={styles.itemLeft}> <Icon name="chevronLeft" size={width / 28} color={body.color} /> <Text style={[styles.titleTextLeft, textColor]}>{t('global:back')}</Text> </View> </TouchableOpacity> </View> </View> </TouchableWithoutFeedback> ); } }
JavaScript
class Agent extends EggApplication { /** * @constructor * @param {Object} options - see {@link EggApplication} */ constructor(options = {}) { options.type = 'agent'; super(options); this._wrapMessenger(); this.loader.load(); // dump config after loaded, ensure all the dynamic modifications will be recorded this.dumpConfig(); // keep agent alive even it don't have any io tasks setInterval(() => {}, 24 * 60 * 60 * 1000); this._uncaughtExceptionHandler = this._uncaughtExceptionHandler.bind(this); process.on('uncaughtException', this._uncaughtExceptionHandler); } _uncaughtExceptionHandler(err) { if (!(err instanceof Error)) { err = new Error(String(err)); } /* istanbul ignore else */ if (err.name === 'Error') { err.name = 'unhandledExceptionError'; } this.coreLogger.error(err); } get [EGG_LOADER]() { return AgentWorkerLoader; } get [EGG_PATH]() { return path.join(__dirname, '..'); } _wrapMessenger() { for (const methodName of [ 'broadcast', 'sendTo', 'sendToApp', 'sendToAgent', 'sendRandom' ]) { wrapMethod(methodName, this.messenger, this.coreLogger); } function wrapMethod(methodName, messenger, logger) { const originMethod = messenger[methodName]; messenger[methodName] = function() { const stack = new Error().stack.split('\n').slice(1).join('\n'); logger.warn('agent can\'t call %s before server started\n%s', methodName, stack); originMethod.apply(this, arguments); }; messenger.once('egg-ready', () => { messenger[methodName] = originMethod; }); } } close() { process.removeListener('uncaughtException', this._uncaughtExceptionHandler); return super.close(); } }
JavaScript
class RedisFeature extends Feature { static shortcut = 'redis' subscribers = new Map() commands = REDIS_COMMANDS featureWasEnabled(options) { this.hide('client', (this.client = redis.createClient(options))) } stopSubscribtion(channel) { const client = this.subscribers.get(channel) if (client) { this.subscribers.delete(channel) client.unsubscribe() client.quit() } return channel } publish(channel, message) { this.client.publish(channel, message) } subscribe(channel, handler) { let subscriber = this.subscribers.get(channel) if (!subscriber) { subscriber = this.client.duplicate() this.subscribers.set(channel, subscriber) } subscriber.on('message', (channel, message) => { console.log({ message, channel }) }) subscriber.subscribe(channel) return subscriber } get async() { if (this._async) { return this._async } this.hide('_async', this.createAsyncInterface(this.featureSettings)) return this._async } createAsyncInterface(options = {}) { const { isFunction } = this.lodash const { commands = REDIS_COMMANDS } = options const { client } = this return commands .filter(cmd => isFunction(client[cmd])) .reduce( (memo, method) => ({ ...memo, [method]: promisify(client[method]).bind(client), }), {} ) } }
JavaScript
class GameObject extends Physical { /** * Creates a new GameObject. * * @param {number} posX Initial x position * @param {number} posY {number} Initial y position * @param {Area} area Initial y position * @param {boolean} collidable If the object can collide with other collidable objects */ constructor(posX, posY, area, collidable) { super(); this.position = new Vec2(posX, posY); this.direction = new Vec2(0, 0); this.speed = 0; //pixel per second /** @property {Area} */ this.area = area; this.collidable = collidable; } update(dtime) { super.update(dtime); return this._update(dtime); } rollback(dtime) { super.rollback(dtime); return this._update(dtime, true); } /** * Calculates and updates the position of the object with its direction and speed. * * @param dtime Time since last call [s] * @param invert If the direction should be inverted * @private */ _update(dtime, invert = false) { if (this.speed === 0) return false; let len = this.direction.length(); let multiplier = this.speed / len; let velocity = this.direction.clone().multiply(multiplier * dtime); velocity.y = -velocity.y; //because (0, 0) is left top if(invert){ velocity.multiply(-1); } this.position.addVec(velocity); this.area.move(velocity.x, velocity.y); return velocity.length()!=0; } /** * Sets the new position of the game object. * * @param posX New x position * @param posY New y position */ setPosition(posX, posY){ this.area.moveTo(posX, posY); this.position.set(posX, posY); } /** * Returns the current position of the game object * * @returns {Vec2} Current position */ getPosition(){ return this.position; } /** * Sets the speed of the object. * * @param {number} speed Pixel per second */ setSpeed(speed) { this.speed = speed; } /** * Returns the speed of the object. * * @returns {number} Pixel per second */ getSpeed() { return this.speed; } /** * Returns if the object's speed is >= 0. * * @returns {boolean} If the object is movable */ isMovable() { return this.speed > 0; } /** * Sets the direction of the object. * * @param {Vec2} direction Direction as Vec2 */ setDirection(direction) { this.direction = direction; } /** * Returns the direction of the game object. * * @returns {Vec2} A clone of the direction */ getDirection() { return this.direction.clone(); } isCollidable() { return this.collidable; } /** * Called whenever this object collides with an other collidable gameobject. * Physics handling can be denied if the method returns false. * * @param gameObject * @returns {boolean} If physics sould be ignored in this individual case */ onCollideWith(gameObject) { return false; } }
JavaScript
class AppMain extends Component { componentDidMount() { // this.checkValid(this.props); } componentWillReceiveProps(nextProps) { // or componentDidUpdate // this.checkValid(nextProps); } checkValid = (props) => { //TODO check if menu has items // var locationToCheck = props.location.pathname.split('/'); // if (props.app.appMenu.state.menu) { // var exists = lodash.find(props.app.appMenu.state.menu, (o) => { // var comparison = stringSimilarity.compareTwoStrings(o.url, "/" + locationToCheck[1]); // // console.log(o.url + "->" + comparison); // return comparison > 0.8 // }); // if (!exists && props.location.pathname !== '/403' && props.location.pathname !== '/') { // this.props.history.replace('/403'); // } // } } render() { const defaultProps = { app: this.props.app }; return ( <Content style={{ padding: '10px 40px' }}> <Switch> <Route exact path='/' render={({ match }) => <Projects match={match} menuActive='home' {...defaultProps} />} /> {/* <Route exact path='/projects' render={({ match }) => <Projects match={match} menuActive='projects' {...defaultProps} />} /> */} <Route exact path='/config' render={({ match }) => <Configuration match={match} menuActive='config' {...defaultProps} />} /> <Route exact path='/project/:id' render={({ match }) => <ProjectDetail match={match} menuActive='config' {...defaultProps} />} /> <Route exact path='/project/:id/job/:jobId' render={({ match }) => <ProjectDetail match={match} menuActive='config' {...defaultProps} />} /> </Switch> </Content > ); } }
JavaScript
class Search extends Command { /** * @param {Client} client The instantiating client * @param {CommandData} data The data for the command */ constructor(bot) { super(bot, { name: 'search', guildOnly: true, dirname: __dirname, botPermissions: ['SEND_MESSAGES', 'EMBED_LINKS', 'CONNECT', 'SPEAK'], description: 'Searches for a song.', usage: 'search <link / song name>', cooldown: 3000, examples: ['search palaye royale'], slash: true, options: [{ name: 'track', description: 'track to search for.', type: 'STRING', required: true, autocomplete: true, }], }); } /** * Function for recieving message. * @param {bot} bot The instantiating client * @param {message} message The message that ran the command * @readonly */ async run(bot, message, settings) { // Check if the member has role to interact with music plugin if (message.guild.roles.cache.get(settings.MusicDJRole)) { if (!message.member.roles.cache.has(settings.MusicDJRole)) { return message.channel.error('misc:MISSING_ROLE').then(m => m.timedDelete({ timeout: 10000 })); } } // make sure user is in a voice channel if (!message.member.voice.channel) return message.channel.error('music/play:NOT_VC').then(m => m.timedDelete({ timeout: 10000 })); // Check that user is in the same voice channel if (bot.manager?.players.get(message.guild.id)) { if (message.member.voice.channel.id != bot.manager?.players.get(message.guild.id).voiceChannel) return message.channel.error('misc:NOT_VOICE').then(m => m.timedDelete({ timeout: 10000 })); } // Check if VC is full and bot can't join doesn't have (MANAGE_CHANNELS) if (message.member.voice.channel.full && !message.member.voice.channel.permissionsFor(message.guild.me).has('MOVE_MEMBERS')) { return message.channel.error('music/play:VC_FULL').then(m => m.timedDelete({ timeout: 10000 })); } // Make sure that a song/url has been entered if (!message.args) return message.channel.error('music/search:NO_INPUT'); // Create player let player; try { player = bot.manager.create({ guild: message.guild.id, voiceChannel: message.member.voice.channel.id, textChannel: message.channel.id, selfDeafen: true, }); } catch (err) { if (message.deletable) message.delete(); bot.logger.error(`Command: '${this.help.name}' has error: ${err.message}.`); return message.channel.error('misc:ERROR_MESSAGE', { ERROR: err.message }).then(m => m.timedDelete({ timeout: 5000 })); } const search = message.args.join(' '); let res; // Search for track try { res = await player.search(search, message.author); if (res.loadType === 'LOAD_FAILED') { if (!player.queue.current) player.destroy(); throw res.exception; } } catch (err) { return message.channel.error('music/search:ERROR', { ERROR: err.message }).then(m => m.timedDelete({ timeout: 5000 })); } // Workout what to do with the results if (res.loadType == 'NO_MATCHES') { // An error occured or couldn't find the track if (!player.queue.current) player.destroy(); return message.channel.error('music/search:NO_SONG'); } else { // Display the options for search let max = 10, collected; const filter = (m) => m.author.id === message.author.id && /^(\d+|cancel)$/i.test(m.content); if (res.tracks.length < max) max = res.tracks.length; const results = res.tracks.slice(0, max).map((track, index) => `${++index} - \`${track.title}\``).join('\n'); const embed = new Embed(bot, message.guild) .setTitle('music/search:TITLE', { TITLE: message.args.join(' ') }) .setColor(message.member.displayHexColor) .setDescription(message.translate('music/search:DESC', { RESULTS: results })); message.channel.send({ embeds: [embed] }); try { collected = await message.channel.awaitMessages({ filter, max: 1, time: 30e3, errors: ['time'] }); } catch (e) { if (!player.queue.current) player.destroy(); return message.reply(message.translate('misc:WAITED_TOO_LONG')); } const first = collected.first().content; if (first.toLowerCase() === 'cancel') { if (!player.queue.current) player.destroy(); return message.channel.send(message.translate('misc:CANCELLED')); } const index = Number(first) - 1; if (index < 0 || index > max - 1) return message.reply(message.translate('music/search:INVALID', { NUM: max })); const track = res.tracks[index]; if (player.state !== 'CONNECTED') player.connect(); player.queue.add(track); if (!player.playing && !player.paused && !player.queue.size) { player.play(); } else { message.channel.send(message.translate('music/search:ADDED', { TITLE: track.title })); } } } /** * Function for recieving interaction. * @param {bot} bot The instantiating client * @param {interaction} interaction The interaction that ran the command * @param {guild} guild The guild the interaction ran in * @param {args} args The options provided in the command, if any * @readonly */ async callback(bot, interaction, guild, args) { const channel = guild.channels.cache.get(interaction.channelId), member = guild.members.cache.get(interaction.user.id), search = args.get('track').value; // Check if the member has role to interact with music plugin if (guild.roles.cache.get(guild.settings.MusicDJRole)) { if (!member.roles.cache.has(guild.settings.MusicDJRole)) { return interaction.reply({ ephemeral: true, embeds: [channel.error('misc:MISSING_ROLE', { }, true)] }); } } // make sure user is in a voice channel if (!member.voice.channel) return interaction.reply({ ephemeral: true, embeds: [channel.error('misc:MISSING_ROLE', { }, true)] }); // Check that user is in the same voice channel if (bot.manager?.players.get(guild.id)) { if (member.voice.channel.id != bot.manager?.players.get(guild.id).voiceChannel) return interaction.reply({ ephemeral: true, embeds: [channel.error('misc:NOT_VOICE', { }, true)] }); } // Check if VC is full and bot can't join doesn't have (MANAGE_CHANNELS) if (member.voice.channel.full && !member.voice.channel.permissionsFor(guild.me).has('MOVE_MEMBERS')) { return interaction.reply({ ephemeral: true, embeds: [channel.error('music/play:VC_FULL', { }, true)] }); } // Create player let player; try { player = bot.manager.create({ guild: guild.id, voiceChannel: member.voice.channel.id, textChannel: channel.id, selfDeafen: true, }); } catch (err) { console.log(err); bot.logger.error(`Command: '${this.help.name}' has error: ${err.message}.`); return interaction.reply({ embeds: [channel.error('misc:ERROR_MESSAGE', { ERROR: err.message }, true)] }); } // Search for track let res; try { res = await player.search(search, member.user); if (res.loadType === 'LOAD_FAILED') { if (!player.queue.current) player.destroy(); throw res.exception; } } catch (err) { return interaction.reply({ embeds: [channel.error('misc:ERROR_MESSAGE', { ERROR: err.message }, true)] }); } // Workout what to do with the results if (res.loadType == 'NO_MATCHES') { // An error occured or couldn't find the track if (!player.queue.current) player.destroy(); return interaction.reply({ embeds: [channel.error('music/search:NO_SONG', {}, true)] }); } else { // Display the options for search let max = 10, collected; const filter = (m) => m.author.id === member.user.id && /^(\d+|cancel)$/i.test(m.content); if (res.tracks.length < max) max = res.tracks.length; const results = res.tracks.slice(0, max).map((track, index) => `${++index} - \`${track.title}\``).join('\n'); const embed = new Embed(bot, guild) .setTitle('music/search:TITLE', { TITLE: search }) .setColor(member.displayHexColor) .setDescription(guild.translate('music/search:DESC', { RESULTS: results })); interaction.reply({ embeds: [embed] }); try { collected = await channel.awaitMessages(filter, { max: 1, time: 30e3, errors: ['time'] }); } catch (e) { if (!player.queue.current) player.destroy(); return interaction.reply({ content:guild.translate('misc:WAITED_TOO_LONG') }); } const first = collected.first().content; if (first.toLowerCase() === 'cancel') { if (!player.queue.current) player.destroy(); return interaction.reply({ content:guild.translate('misc:CANCELLED') }); } const index = Number(first) - 1; if (index < 0 || index > max - 1) return interaction.reply({ content:guild.translate('music/search:INVALID', { NUM: max }) }); const track = res.tracks[index]; if (player.state !== 'CONNECTED') player.connect(); player.queue.add(track); if (!player.playing && !player.paused && !player.queue.size) { player.play(); } else { interaction.reply({ content:guild.translate('music/search:ADDED', { TITLE: track.title }) }); } } } }
JavaScript
class StreamingPolicyWidevineConfiguration { /** * Create a StreamingPolicyWidevineConfiguration. * @property {string} [customLicenseAcquisitionUrlTemplate] Template for the * URL of the custom service delivering licenses to end user players. Not * required when using Azure Media Services for issuing licenses. The * template supports replaceable tokens that the service will update at * runtime with the value specific to the request. The currently supported * token values are {AlternativeMediaId}, which is replaced with the value of * StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is * replaced with the value of identifier of the key being requested. */ constructor() { } /** * Defines the metadata of StreamingPolicyWidevineConfiguration * * @returns {object} metadata of StreamingPolicyWidevineConfiguration * */ mapper() { return { required: false, serializedName: 'StreamingPolicyWidevineConfiguration', type: { name: 'Composite', className: 'StreamingPolicyWidevineConfiguration', modelProperties: { customLicenseAcquisitionUrlTemplate: { required: false, serializedName: 'customLicenseAcquisitionUrlTemplate', type: { name: 'String' } } } } }; } }
JavaScript
class ComboBox extends React.PureComponent { state = { value: this.props.value, inputValue: this.props.inputValue || '' } /** * Update input value if it's provided from outside. * * @param {object} props * @param {string} [props.inputValue] */ componentWillReceiveProps (props) { if (props.inputValue != null && this.state.inputValue !== props.inputValue) { this.setState({ inputValue: props.inputValue }) } if (props.value !== this.state.value && props.value !== undefined) { this.setState({ value: props.value }) } } /** * Check if this input is disabled. * * @param {object} [props] * @param {boolean} [props.disabled] * @param {boolean} [props.readOnly] * @returns {boolean} */ isDisabled (props) { const { disabled, readOnly } = props || this.props return disabled || readOnly } /** * Reduce state change of Downshift. * This function handles side effects of reducing state. * * @param {object} state * @param {object} changes * @returns {object} */ stateReducer = (state, changes) => { const nextState = this._stateReducer(state, changes) if (this.props.inputValue == null && nextState.inputValue !== undefined) { const nextInputValue = nextState.inputValue == null ? '' : nextState.inputValue if (nextInputValue !== this.state.inputValue) { this.setState({ inputValue: nextInputValue }) } } return nextState } /** * Handle state changes inside of Downshift component. * We need it to not close menu after element is clicked in multi-select. * * @param {object} state * @param {object} changes * @returns {object} */ _stateReducer (state, changes) { const { multi } = this.props switch (changes.type) { case Downshift.stateChangeTypes.clickItem: case Downshift.stateChangeTypes.keyDownEnter: // Remove input value when item has been selected, // And keep list open if it's multi-select const nextChanges = { ...changes, inputValue: '', isOpen: multi } // Keep selected item still highlighted, when it's multi-select if (multi && this.state.inputValue === '') { nextChanges.highlightedIndex = state.highlightedIndex } return nextChanges default: return changes } } /** * Get props which should be passed through our components below Downshift. * * @param {object} data * @returns {object} */ getStateProps (data) { const { footer, icon, options, multi, placeholder, buildItemId, renderItem, renderValue, onFocus, onBlur } = this.props const { value } = this.state return { ...data, ...{ footer, icon, options, multi, placeholder, buildItemId, renderItem }, inputValue: this.state.inputValue, renderValue: renderValue || renderItem, getInputProps: props => data.getInputProps(this.getInputProps(props)), getRemoveButtonProps: this.getRemoveButtonProps, getClearButtonProps: this.getClearButtonProps, selectedItems: value == null ? [] : [].concat(value), onInputFocus: onFocus, onInputBlur: onBlur } } /** * Build props for 'remove' button. * * @param {object} props * @returns {object|{ onClick: function }} */ getRemoveButtonProps = (props) => { const { onClick, item } = props || {} return { ...props, onClick: event => { // Do not propagate click on 'remove' button - it may cause strange operations on Downshift event.stopPropagation() // Select again (= unselect) current element this.select(item) if (onClick) { onClick(event) } } } } /** * Build props for 'clear' button. * * @param {object} props * @returns {object|{ onClick: function }} */ getClearButtonProps = (props) => { const onClick = props ? props.onClick : null return { ...props, onClick: event => { // Do not propagate click on 'clear' button - it may cause strange operations on Downshift event.stopPropagation() // Unselect current element this.select(null) if (onClick) { onClick(event) } } } } /** * Build props for input, to handle keyboard events. * * @param {object} props * @returns {object|{ onClick: function }} */ getInputProps (props) { const { onFocus, onBlur } = this.props const onKeyDown = props ? props.onKeyDown : null return { ...props, onFocus, onBlur, disabled: this.isDisabled(), onKeyDown: event => { this.handleInputKeyDown(event) if (onKeyDown) { onKeyDown(event) } } } } /** * Handle keyboard events on input. * * @param {SyntheticEvent|Event} event */ handleInputKeyDown (event) { const { inputValue, value } = this.state const { multi, onNewValue } = this.props // Don't handle it when it's disabled if (this.isDisabled()) { return } // Do not propagate space in input, as it will cause removing value if (event.which === SPACE_KEY) { event.stopPropagation() return } // Rest of handlers is for multi-select combo-boxes only if (!multi) { return } // Remove last value in multi-select on backspace if (event.which === BACKSPACE_KEY && inputValue === '' && value.length) { event.stopPropagation() // Unselect last value this.select(value[value.length - 1]) } // Handle adding new value if ((event.which === COMMA_KEY || event.which === TAB_KEY) && inputValue !== '') { event.preventDefault() event.stopPropagation() this.setState({ inputValue: '' }) if (this.props.value === undefined) { this.setState({ value: (value || []).concat(inputValue) }) } if (onNewValue) { onNewValue(inputValue) } } } /** * Handle item (un)selection. * * @param {object} item */ select = (item) => { const { onChange, multi } = this.props const { value } = this.state // Don't handle it when it's disabled if (this.isDisabled()) { return } // Handle simple selection for single select-box if (!multi) { if (this.props.value === undefined) { this.setState({ value: item }) } if (onChange) { onChange(item) } return } // Build array of current values const _value = value == null ? [] : [].concat(value) // Remove existing or add new item to value const nextValue = _value.indexOf(item) !== -1 ? _value.filter(x => x !== item) : _value.concat(item) if (this.props.value === undefined) { this.setState({ value: nextValue }) } // Trigger event with new value if (onChange) { onChange(nextValue) } } /** * Render component in Downshift flow * * @param {object} _data * @returns {React.Element} */ renderComponent = (_data) => { // Compose Downshift & our properties const data = this.getStateProps(_data) // Get required data to render component const { className } = this.props const { isOpen, options, multi, icon } = data // Check if menu should be visible const open = isOpen && options.length > 0 // Build class name for wrapper const clsName = buildClassName(moduleName, className, { open, multi, 'with-info': icon }) // Build value component const value = multi ? <ComboBoxMultiValue {...data} /> : <ComboBoxValue {...data} /> // Build menu component const menu = open ? <Menu {...data} /> : null // Render component return ( <div className={clsName}> {value} {menu} </div> ) } /** * Render Downshift component with our wrappers. * * @returns {React.Element} */ render () { const { id, icon, multi, placeholder, value, options, onChange, readOnly, disabled, buildItemId, renderItem, renderValue, children, ...passedProps } = this.props const idProps = {} if (id) { idProps.id = 'container_' + id idProps.inputId = id } return ( <Downshift stateReducer={this.stateReducer} onChange={this.select} selectedItem={null} disabled={this.isDisabled()} {...passedProps} {...idProps} > {this.renderComponent} </Downshift> ) } }
JavaScript
class SVGContainer extends wgl.Element { /** * @param {SVGGElement} groupElement where transformation should be applied * @param {Function} drawCallback a function that is called after each * `draw()` */ constructor(groupElement, drawCallback) { super(); this.g = groupElement; this.dx = 0; this.dy = 0; this.scale = 0; this.drawCallback = drawCallback || noop; } draw() { let transform = this.worldTransform; if (transformsAreSame(this.worldTransform, this)) { // Avoid DOM updates if possible. return; } let pixelRatio = this.scene.getPixelRatio(); let scale = transform.scale / pixelRatio; let dx = transform.dx / pixelRatio; let dy = transform.dy / pixelRatio; // console.log(`matrix(${scale}, 0, 0, ${scale}, ${dx}, ${dy})`); this.g.setAttributeNS(null, 'transform', `matrix(${scale}, 0, 0, ${scale}, ${dx}, ${dy})`); this.scale = transform.scale; this.dx = transform.dx; this.dy = transform.dy; this.drawCallback(this); } }
JavaScript
class limitreport { /** * @constructor */ constructor() { this.creds = new AWS.EnvironmentCredentials('AWS'); // Lambda provided credentials this.sqs = new AWS.SQS(); this.dynamoConfig = { credentials: this.creds, region: process.env.AWS_REGION, }; this.docClient = new AWS.DynamoDB.DocumentClient(this.dynamoConfig); this.ddbTable = process.env.LIMIT_REPORT_TBL; this.queueURL = process.env.SQS_URL; this.max_messages = process.env.MAX_MESSAGES; this.max_loops = process.env.MAX_LOOPS; this.anonymous_data = process.env.ANONYMOUS_DATA; this.solution = process.env.SOLUTION; this.uuid = process.env.UUID; } /** * Updates Dynamo DB table * @param {CWEvent} event [description] * @param {function} cb [callback function] * @return {limitreport~callback} [callback to handle response] */ updateReport(event, cb) { const _self = this; let queueParams = { AttributeNames: ['SentTimestamp'], MaxNumberOfMessages: this.max_messages, MessageAttributeNames: ['All'], QueueUrl: this.queueURL, }; async.each( _.range(this.max_loops), function(i, callback_p) { _self.sqs.receiveMessage(queueParams, function(err, rcv_payload) { if (err) { LOGGER.log('ERROR', err); //🔥 callback_p(); } else if (rcv_payload.Messages && rcv_payload.Messages.length > 0) { async.each( rcv_payload.Messages, function(message, callback_e) { _self.updateTable(message, function(err, data) { if (err) { LOGGER.log('ERROR', JSON.stringify(err)); callback_e(); } else { LOGGER.log('INFO', JSON.stringify(data)); //calling sendMetrics and removeMessage in parallel async.parallel( { remove_mssg: function(callback) { _self.removeMessage(message, function(data) { callback(null, data); }); }, send_metric: function(callback) { _self.sendMetrics(message, function(data) { callback(null, data); }); }, }, function(err, results) { // results LOGGER.log( 'INFO', `results: ${JSON.stringify(results, null, 2)}` ); callback_e(); } ); } }); }, function(err) { if ( err //if any iteration callback called with error ); else callback_p(); //executed after all iterations are done } ); } else { callback_p(); } //no messages }); }, function(err) { return cb(null, { Result: 'TA messages read', }); } ); } /** * [updateTable description] * @param {[type]} payload [description] * @param {Function} cb [description] * @return {[type]} [description] */ updateTable(payload, cb) { let ta_mssg = JSON.parse(payload.Body); let params = { TableName: this.ddbTable, Item: { MessageId: payload.MessageId, AccountId: ta_mssg.account, TimeStamp: ta_mssg.time, Region: ta_mssg.detail['check-item-detail']['Region'], Service: ta_mssg.detail['check-item-detail']['Service'], LimitName: ta_mssg.detail['check-item-detail']['Limit Name'], CurrentUsage: ta_mssg.detail['check-item-detail']['Current Usage'], LimitAmount: ta_mssg.detail['check-item-detail']['Limit Amount'], Status: ta_mssg.detail['status'], ExpiryTime: new Date().getTime() + 15 * 24 * 3600 * 1000, //1️⃣5️⃣ days }, }; LOGGER.log('DEBUG', `DDB put item: ${JSON.stringify(params)}`); this.docClient.put(params, function(err, data) { if (err) { return cb( { TableUpdate: { status: err, }, }, null ); //🔥 } else { return cb(null, { TableUpdate: { status: 'success', //receipthandle: payload.ReceiptHandle }, }); } }); } /** * [sendMetrics description] * @type {[type]} */ sendMetrics(message, cb) { if (this.anonymous_data != 'Yes') return cb({ Status: 'Customer chose not to send anonymous metrics to AWS', }); let _metricsHelper = new MetricsHelper(); let metrics = JSON.parse(message.Body); let metricData = { Region: metrics.detail['check-item-detail']['Region'], Service: metrics.detail['check-item-detail']['Service'], LimitName: metrics.detail['check-item-detail']['Limit Name'], Status: metrics.detail['status'], //include itemsize from ddb }; let _anonymousmetric = { Solution: this.solution, UUID: this.uuid, TimeStamp: moment() .utc() .format('YYYY-MM-DD HH:mm:ss.S'), Data: metricData, }; LOGGER.log( 'DEBUG', `anonymous metric: ${JSON.stringify(_anonymousmetric)}` ); _metricsHelper.sendAnonymousMetric(_anonymousmetric, function(err, data) { let responseData; if (err) { responseData = { Error: 'Sending anonymous metric failed', }; } else { responseData = { Success: 'Anonymous metrics sent to AWS', }; } return cb(responseData); }); } /** * [removeMessage description] * @param {[type]} message [description] * @param {Function} cb [description] * @return {[type]} [description] */ removeMessage(message, cb) { let _deleteParams = { QueueUrl: this.queueURL, ReceiptHandle: message.ReceiptHandle, }; this.sqs.deleteMessage(_deleteParams, function(err, data) { if (err) { return cb({ Status: { table_update: 'success', sqs_delete: err, }, }); //🔥 } else { return cb({ Status: { table_update: 'success', sqs_delete: 'success', }, }); } }); } }
JavaScript
class Row extends Component { layout = layout; @argument @required @type(Component) parent; @argument @required @type(arrayOf(Component)) columns; @argument @type('boolean') sortable = true; @argument @type(optional('string')) sort = null; @argument @type(unionOf('string', arrayOf('string'))) sortSequence; @argument @required @type(Action) onColumnClick; cells = A(); registerCell(cell) { let columns = this.get('columns'); let prop = cell.get('prop'); if (prop) { let column = columns.findBy('prop', prop); cell.set('column', column); } else { let index = this.get('cells.length'); let column = columns.objectAt(index); cell.set('column', column); } this.get('cells').addObject(cell); } unregisterCell(cell) { this.get('cells').removeObject(cell); } }
JavaScript
class SetSimpleTokenAdmin extends SetupSimpleTokenBase { /** * Constructor to set admin address in simple token contract. * * @param {object} params * @param {string} params.signerAddress: address who signs Tx * @param {string} params.signerKey: private key of signerAddress * @param {string} params.adminAddress: address which is to be made admin * @param {string} params.simpleTokenContractAddress: simple token contract address * * @augments SetupSimpleTokenBase * * @constructor */ constructor(params) { super(params); const oThis = this; oThis.adminAddress = params.adminAddress; oThis.simpleTokenContractAddress = params.simpleTokenContractAddress; } /** * Async perform. * * @ignore * * @return {Promise} */ async asyncPerform() { const oThis = this; await oThis.setGasPrice(); oThis.addKeyToWallet(); const setAdminRsp = await oThis._setAdminAddress(); oThis.removeKeyFromWallet(); await oThis._insertIntoChainSetupLogs(chainSetupConstants.setBaseContractAdminStepKind, setAdminRsp); return setAdminRsp; } /** * Set admin address. * * @return {Promise} * @private */ async _setAdminAddress() { const oThis = this; const nonceRsp = await oThis.fetchNonce(oThis.signerAddress); const params = { from: oThis.signerAddress, nonce: nonceRsp.data.nonce, gasPrice: oThis.gasPrice, gas: contractConstants.setAdminSimpleTokenGas }; const simpleTokenContractObj = new oThis.web3Instance.eth.Contract(CoreAbis.simpleToken); simpleTokenContractObj.options.address = oThis.simpleTokenContractAddress; const transactionReceipt = await simpleTokenContractObj.methods .setAdminAddress(oThis.adminAddress) .send(params) .catch(function(errorResponse) { logger.error(errorResponse); return responseHelper.error({ internal_error_identifier: 't_cs_o_ag_st_saa_1', api_error_identifier: 'unhandled_catch_response', debug_options: { error: errorResponse } }); }); const setAdminRsp = responseHelper.successWithData({ transactionHash: transactionReceipt.transactionHash, transactionReceipt: transactionReceipt }); setAdminRsp.debugOptions = { inputParams: { signerAddress: oThis.signerAddress }, processedParams: { adminAddress: oThis.adminAddress, simpleTokenContractAddress: simpleTokenContractObj.options.address } }; return setAdminRsp; } }
JavaScript
class SpeakerStats { /** * Initializes a new SpeakerStats instance. * * @constructor * @param {string} userId - The id of the user being tracked. * @param {string} displayName - The name of the user being tracked. * @param {boolean} isLocalStats - True if the stats model tracks * the local user. * @returns {void} */ constructor(userId, displayName, isLocalStats) { this._userId = userId; this.setDisplayName(displayName); this._isLocalStats = isLocalStats || false; this.setIsDominantSpeaker(false); this.totalDominantSpeakerTime = 0; this._dominantSpeakerStart = null; this._hasLeft = false; } /** * Get the user id being tracked. * * @returns {string} The user id. */ getUserId() { return this._userId; } /** * Get the name of the user being tracked. * * @returns {string} The user name. */ getDisplayName() { return this.displayName; } /** * Updates the last known name of the user being tracked. * * @param {string} - The user name. * @returns {void} */ setDisplayName(newName) { this.displayName = newName; } /** * Returns true if the stats are tracking the local user. * * @returns {boolean} */ isLocalStats() { return this._isLocalStats; } /** * Returns true if the tracked user is currently a dominant speaker. * * @returns {boolean} */ isDominantSpeaker() { return this._isDominantSpeaker; } /** * Returns true if the tracked user is currently a dominant speaker. * * @param {boolean} - If true, the user will being accumulating time * as dominant speaker. If false, the user will not accumulate time * and will record any time accumulated since starting as dominant speaker. * @returns {void} */ setIsDominantSpeaker(isNowDominantSpeaker) { if (!this._isDominantSpeaker && isNowDominantSpeaker) { this._dominantSpeakerStart = Date.now(); } else if (this._isDominantSpeaker && !isNowDominantSpeaker) { const now = Date.now(); const timeElapsed = now - (this._dominantSpeakerStart || 0); this.totalDominantSpeakerTime += timeElapsed; this._dominantSpeakerStart = null; } this._isDominantSpeaker = isNowDominantSpeaker; } /** * Get how long the tracked user has been dominant speaker. * * @returns {number} - The speaker time in milliseconds. */ getTotalDominantSpeakerTime() { let total = this.totalDominantSpeakerTime; if (this._isDominantSpeaker) { total += Date.now() - this._dominantSpeakerStart; } return total; } /** * Get whether or not the user is still in the meeting. * * @returns {boolean} True if the user is no longer in the meeting. */ hasLeft() { return this._hasLeft; } /** * Set the user as having left the meeting. * * @returns {void} */ markAsHasLeft() { this._hasLeft = true; this.setIsDominantSpeaker(false); } }
JavaScript
class Colormaker { /** * Create a colormaker instance * @param {ColormakerParameters} params - colormaker parameter */ constructor(params = {}) { this.parameters = createParams(params, ScaleDefaultParameters); if (typeof this.parameters.value === 'string') { this.parameters.value = tmpColor.set(this.parameters.value).getHex(); } if (this.parameters.structure) { this.atomProxy = this.parameters.structure.getAtomProxy(); } } getScale(params = {}) { const p = createParams(params, this.parameters); if (p.scale === 'rainbow') { p.scale = ['red', 'orange', 'yellow', 'green', 'blue']; } else if (p.scale === 'rwb') { p.scale = ['red', 'white', 'blue']; } if (p.reverse) { p.domain.reverse(); } return chroma .scale(p.scale) // TODO .mode(p.mode) .domain(p.domain) .out('num'); // TODO } /** * safe a color to an array * @param {Integer} color - hex color value * @param {Array|TypedArray} array - destination * @param {Integer} offset - index into the array * @return {Array} the destination array */ colorToArray(color, array = [], offset = 0) { array[offset] = (color >> 16 & 255) / 255; array[offset + 1] = (color >> 8 & 255) / 255; array[offset + 2] = (color & 255) / 255; return array; } /** * safe a atom color to an array * @param {AtomProxy} atom - atom to get color for * @param {Array|TypedArray} array - destination * @param {Integer} offset - index into the array * @return {Array} the destination array */ atomColorToArray(atom, array, offset) { return this.colorToArray(this.atomColor ? this.atomColor(atom) : 0x000000, array, offset); } /** * return the color for an bond * @param {BondProxy} bond - bond to get color for * @param {Boolean} fromTo - whether to use the first or second atom of the bond * @return {Integer} hex bond color */ bondColor(bond, fromTo) { if (this.atomProxy && this.atomColor) { this.atomProxy.index = fromTo ? bond.atomIndex1 : bond.atomIndex2; return this.atomColor(this.atomProxy); } else { return 0x000000; } } /** * safe a bond color to an array * @param {BondProxy} bond - bond to get color for * @param {Boolean} fromTo - whether to use the first or second atom of the bond * @param {Array|TypedArray} array - destination * @param {Integer} offset - index into the array * @return {Array} the destination array */ bondColorToArray(bond, fromTo, array, offset) { return this.colorToArray(this.bondColor(bond, fromTo), array, offset); } /** * safe a volume cell color to an array * @param {Integer} index - volume cell index * @param {Array|TypedArray} array - destination * @param {Integer} offset - index into the array * @return {Array} the destination array */ volumeColorToArray(index, array, offset) { return this.colorToArray(this.volumeColor ? this.volumeColor(index) : 0x000000, array, offset); } /** * safe a color for coordinates in space to an array * @param {Vector3} coords - xyz coordinates * @param {Array|TypedArray} array - destination * @param {Integer} offset - index into the array * @return {Array} the destination array */ positionColorToArray(coords, array, offset) { return this.colorToArray(this.positionColor ? this.positionColor(coords) : 0x000000, array, offset); } }
JavaScript
class DamageChat { static fullRegex = /^(?<roll>\d+(?<D>d\d*)?(?<adds1>[+-]\d+)?(?<adds2>[+-]\d+)?)(?:[×xX\*](?<mult>\d+))?(?: ?\((?<divisor>-?\d+(?:\.\d+)?)\))?/ static initSettings() { Hooks.on('renderChatMessage', async (app, html, msg) => { let isDamageChatMessage = !!html.find('.damage-chat-message').length if (isDamageChatMessage) { let transfer = JSON.parse(app.data.flags.transfer) // for each damage-message, set the drag-and-drop events and data let damageMessages = html.find('.damage-message') if (!!damageMessages && damageMessages.length > 0) { for (let index = 0; index < damageMessages.length; index++) { let message = damageMessages[index] message.setAttribute('draggable', true) message.addEventListener('dragstart', ev => { $(ev.currentTarget).addClass('dragging') ev.dataTransfer.setDragImage(game.GURPS.damageDragImage, 30, 30) let data = { type: 'damageItem', payload: transfer.payload[index], } return ev.dataTransfer.setData('text/plain', JSON.stringify(data)) }) message.addEventListener('dragend', ev => { $(ev.currentTarget).removeClass('dragging') }) } } // end-if (!!damageMessages && damageMessages.length) // for the damage-all-message, set the drag-and-drop events and data let allDamageMessage = html.find('.damage-all-message') if (!!allDamageMessage && allDamageMessage.length == 1) { let transfer = JSON.parse(app.data.flags.transfer) let message = allDamageMessage[0] message.setAttribute('draggable', true) message.addEventListener('dragstart', ev => { $(ev.currentTarget).addClass('dragging') ev.dataTransfer.setDragImage(game.GURPS.damageDragImage, 30, 30) let data = { type: 'damageItem', payload: transfer.payload, } return ev.dataTransfer.setData('text/plain', JSON.stringify(data)) }) message.addEventListener('dragend', ev => { $(ev.currentTarget).removeClass('dragging') }) } // If there was a target, enable the GM's apply button let button = html.find('button', '.apply-all') button.hide() if (!!transfer.userTarget && transfer.userTarget != null) { if (game.user.isGM) { button.show() button.click(ev => { // get actor from id let token = canvas.tokens.get(transfer.userTarget) // ... // get payload; its either the "all damage" payload or ... if (!!token) token.actor.handleDamageDrop(payload) else ui.notifications.warn("Unable to find token with ID:" + transfer.userTarget); }) } } } // end-if (damageChatMessage) }) } /** * Create the damage chat message. * @param {Actor} actor that rolled the damage. * @param {String} diceText such as '3d-1(2)' * @param {String} damageType text from DamageTables.damageTypeMap * @param {Event} event that triggered this action * @param {String} overrideDiceText ?? */ static async create(actor, diceText, damageType, event, overrideDiceText, tokenNames) { let message = new DamageChat() const targetmods = await game.GURPS.ModifierBucket.applyMods() // append any global mods let dice = message._getDiceData(diceText, damageType, targetmods, overrideDiceText) if (!tokenNames) tokenNames = [] if (tokenNames.length == 0) tokenNames.push('') let draggableData = [] await tokenNames.forEach(async tokenName => { let data = await message._createDraggableSection(actor, dice, tokenName, targetmods) draggableData.push(data) }) message._createChatMessage(actor, dice, targetmods, draggableData, event) // Resolve any modifier descriptors (such as *Costs 1FP) targetmods .filter(it => !!it.desc) .map(it => it.desc) .forEach(it => game.GURPS.applyModifierDesc(actor, it)) } /** * This method is all about interpreting the die roll text. * * Returns { * formula: String, -- Foundry Dice formula * modifier: num, -- sum of modifiers * diceText: String, -- GURPS die text * multiplier: num, -- any multiplier (1 if none) * divisor: num, -- any armor divisor (0 if none) * adds1: num, -- first add * adds2: num, -- second add * min: num, -- minimum value of the die roll (0, 1) * } * @param {String} diceText * @param {*} damageType * @param {*} overrideDiceText */ _getDiceData(diceText, damageType, targetmods, overrideDiceText) { // format for diceText: // // '<dice>d+<adds1>+<adds2>x<multiplier>(<divisor>)' // // - Multipliers are integers that appear after a multiplication sign (x, X, *, or ×). // // - Armor divisors are decimal numbers in parentheses: (2), (5), (0.2), (0.5). (Accept // an optional space between the armor divisor and the preceding characters.) // // Examples: 3d, 1d-1, 3dx5, 3d-1x5, 2d(2), 5d-1(0.2), 3dx2(5), 4d-1x4(5). // // Added support for a second add, such as: 1d-2+3 -- this was to support damage expressed // using basic damage syntax, such as "sw+3" (which could translate to '1d-2+3', for exmaple). let result = DamageChat.fullRegex.exec(diceText) if (!result) { ui.notifications.warn(`Invalid Dice formula: "${diceText}"`) return null } diceText = result.groups.roll diceText = diceText.replace('−', '-') // replace minus (&#8722;) with hyphen let multiplier = !!result.groups.mult ? parseInt(result.groups.mult) : 1 let divisor = !!result.groups.divisor ? parseFloat(result.groups.divisor) : 0 let adds1 = 0 let temp = !!result.groups.adds1 ? result.groups.adds1 : '' if (!!temp && temp !== '') { temp = temp.startsWith('+') ? temp.slice(1) : temp adds1 = parseInt(temp) } let adds2 = 0 temp = !!result.groups.adds2 ? result.groups.adds2 : '' if (!!temp && temp !== '') { temp = temp.startsWith('+') ? temp.slice(1) : temp adds2 = parseInt(temp) } let formula = diceText let verb = '' if (!!result.groups.D) { verb = 'Rolling ' if (result.groups.D === 'd') formula = d6ify(diceText) // GURPS dice (assume 6) } let displayText = overrideDiceText || diceText // overrideDiceText used when actual formula isn't 'pretty' SW+2 vs 1d6+1+2 let min = 1 if (damageType === '') damageType = 'dmg' if (damageType === 'cr') min = 0 if (formula.slice(-1) === '!') { formula = formula.slice(0, -1) min = 1 } let modifier = 0 for (let m of targetmods) { modifier += m.modint } let additionalText = '' if (multiplier > 1) { additionalText += `×${multiplier}` } if (divisor != 0) { additionalText += ` (${divisor})` } let diceData = { formula: formula, verb: verb, // Rolling (if we have dice) or nothing modifier: modifier, diceText: displayText + additionalText, damageType: damageType, multiplier: multiplier, divisor: divisor, adds1: adds1, adds2: adds2, min: min, } console.log(diceData) return diceData } /** * This method creates the content of each draggable section with * damage rolled for a single target. * @param {*} actor * @param {*} diceData * @param {*} tokenName * @param {*} targetmods */ async _createDraggableSection(actor, diceData, tokenName, targetmods) { let roll = Roll.create(diceData.formula + `+${diceData.modifier}`) roll.roll() let diceValue = roll.results[0] let dicePlusAdds = diceValue + diceData.adds1 + diceData.adds2 let rollTotal = roll.total let b378 = false if (rollTotal < diceData.min) { rollTotal = diceData.min if (diceData.damageType !== 'cr') { b378 = true } } let damage = rollTotal * diceData.multiplier let explainLineOne = null if ((roll.dice.length > 0 && roll.dice[0].results.length > 1) || diceData.adds1 !== 0) { let tempString = '' if (roll.dice.length > 0) { tempString = roll.dice[0].results.map(it => it.result).join() tempString = `Rolled (${tempString})` } else { tempString = diceValue } if (diceData.adds1 !== 0) { let sign = diceData.adds1 < 0 ? '−' : '+' let value = Math.abs(diceData.adds1) tempString = `${tempString} ${sign} ${value}` } if (diceData.adds2 !== 0) { let sign = diceData.adds2 < 0 ? '-' : '+' let value = Math.abs(diceData.adds2) tempString = `${tempString} ${sign} ${value}` } explainLineOne = `${tempString} = ${dicePlusAdds}.` } let explainLineTwo = null let sign = diceData.modifier < 0 ? '−' : '+' let value = Math.abs(diceData.modifier) if (targetmods.length > 0 && diceData.multiplier > 1) { explainLineTwo = `Total = (${dicePlusAdds} ${sign} ${value}) × ${diceData.multiplier} = ${damage}.` } else if (targetmods.length > 0) { explainLineTwo = `Total = ${dicePlusAdds} ${sign} ${value} = ${damage}.` } else if (diceData.multiplier > 1) { explainLineTwo = `Total = ${dicePlusAdds} × ${diceData.multiplier} = ${damage}.` } let hasExplanation = explainLineOne || explainLineTwo if (hasExplanation && b378) { if (explainLineTwo) explainLineTwo = `${explainLineTwo}*` else explainLineOne = `${explainLineOne}*` } let contentData = { id: generateUniqueId(), attacker: actor._id, dice: diceData.diceText, damageType: diceData.damageType, damageTypeText: diceData.damageType === 'dmg' ? ' ' : `'${diceData.damageType}' `, armorDivisor: diceData.divisor, damage: damage, hasExplanation: hasExplanation, explainLineOne: explainLineOne, explainLineTwo: explainLineTwo, isB378: b378, roll: roll, target: tokenName, } console.log(contentData) return contentData } async _createChatMessage(actor, diceData, targetmods, draggableData, event) { let userTarget = null if (!!game.user.targets.size) { userTarget = game.user.targets.values().next().value } const damageType = diceData.damageType let html = await renderTemplate('systems/gurps/templates/damage-message-wrapper.html', { draggableData: draggableData, verb: diceData.verb, dice: diceData.diceText, damageTypeText: damageType === 'dmg' ? ' ' : `'${damageType}' `, modifiers: targetmods.map(it => `${it.mod} ${it.desc.replace(/^dmg/, 'damage')}`), userTarget: userTarget, }) const speaker = { alias: actor.name, _id: actor._id, actor: actor } let messageData = { user: game.user._id, speaker: speaker, content: html, type: CONST.CHAT_MESSAGE_TYPES.ROLL, roll: draggableData[0].roll, } if (event?.shiftKey) { messageData.whisper = [game.user._id] } messageData['flags.transfer'] = JSON.stringify({ type: 'damageItem', payload: draggableData, userTarget: !!userTarget ? userTarget.id : null, }) if (isNiceDiceEnabled()) { let rolls = draggableData.map(d => d.roll) let throws = [] let dice = [] rolls.shift() // The first roll will be handled by DSN's chat handler... the rest we will manually roll rolls.forEach(r => { r.dice.forEach(d => { let type = 'd' + d.faces d.results.forEach(s => dice.push({ result: s.result, resultLabel: s.result, type: type, vectors: [], options: {}, }) ) }) }) throws.push({ dice: dice }) if (dice.length > 0) { // The user made a "multi-damage" roll... let them see the dice! game.dice3d.show({ throws: throws }) } } else { messageData.sound = CONFIG.sounds.dice } CONFIG.ChatMessage.entityClass.create(messageData).then(arg => { console.log(arg) let messageId = arg.data._id // 'qHz1QQuzpJiavH3V' $(`[data-message-id='${messageId}']`).click(ev => game.GURPS.handleOnPdf(ev)) }) } }
JavaScript
class Srcset { /** * @param {!Array<!SrcsetSourceDef>} sources */ constructor(sources) { user().assert(sources.length > 0, 'Srcset must have at least one source'); /** @private @const {!Array<!SrcsetSourceDef>} */ this.sources_ = sources; // Only one type of source specified can be used - width or DPR. let hasWidth = false; let hasDpr = false; for (let i = 0; i < sources.length; i++) { const source = sources[i]; hasWidth = hasWidth || !!source.width; hasDpr = hasDpr || !!source.dpr; } user().assert(!!(hasWidth ^ hasDpr), 'Srcset must have width or dpr sources, but not both'); // Source and assert duplicates. sources.sort(hasWidth ? sortByWidth : sortByDpr); /** @private @const {boolean} */ this.widthBased_ = hasWidth; } /** * Performs selection for specified width and DPR. Here, width is the width * in screen pixels and DPR is the device-pixel-ratio or pixel density of * the device. Depending on the circumstances, such as low network conditions, * it's possible to manipulate the result of this method by passing a lower * DPR value. * * The source selection depends on whether this is width-based or DPR-based * srcset. * * In a width-based source, the source's width is the physical width of a * resource (e.g. an image). Depending on the provided DPR, this width is * converted to the screen pixels as following: * pixelWidth = sourceWidth / DPR * * Then, the source closest to the requested "width" is selected using * the "pixelWidth". The slight preference is given to the bigger sources to * ensure the most optimal quality. * * In a DPR-based source, the source's DPR is used to return the source that * is closest to the requested DPR. * * Based on * http://www.w3.org/html/wg/drafts/html/master/semantics.html#attr-img-srcset. * @param {number} width * @param {number} dpr * @return {string} */ select(width, dpr) { dev().assert(width, 'width=%s', width); dev().assert(dpr, 'dpr=%s', dpr); let index = 0; if (this.widthBased_) { index = this.selectByWidth_(width * dpr); } else { index = this.selectByDpr_(dpr); } return this.sources_[index].url; } /** * @param {number} width * @return {number} * @private */ selectByWidth_(width) { const sources = this.sources_; let minIndex = 0; let minScore = Infinity; let minWidth = Infinity; for (let i = 0; i < sources.length; i++) { const sWidth = sources[i].width; const score = Math.abs(sWidth - width); // Select the one that is closer with a slight preference toward larger // widths. If smaller size is closer, enforce minimum ratio to ensure // image isn't too distorted. if (score <= minScore * 1.1 || width / minWidth > 1.2) { minIndex = i; minScore = score; minWidth = sWidth; } else { break; } } return minIndex; } /** * @param {number} dpr * @return {number} * @private */ selectByDpr_(dpr) { const sources = this.sources_; let minIndex = 0; let minScore = Infinity; for (let i = 0; i < sources.length; i++) { const score = Math.abs(sources[i].dpr - dpr); if (score <= minScore) { minIndex = i; minScore = score; } else { break; } } return minIndex; } /** * Returns all URLs in the srcset. * @return {!Array<string>} */ getUrls() { return this.sources_.map(s => s.url); } /** * Reconstructs the string expression for this srcset. * @param {function(string):string=} opt_mapper * @return {string} */ stringify(opt_mapper) { const res = []; const sources = this.sources_; for (let i = 0; i < sources.length; i++) { const source = sources[i]; let src = source.url; if (opt_mapper) { src = opt_mapper(src); } if (this.widthBased_) { src += ` ${source.width}w`; } else { src += ` ${source.dpr}x`; } res.push(src); } return res.join(', '); } }
JavaScript
class AtomicFunction extends _function_mjs__WEBPACK_IMPORTED_MODULE_1__.AbstractFunction { constructor(arity) { super(); /** * The input arity of the function */ this.arity = arity; } evaluate() { var values = []; for (var i = 0; i < arguments.length; i++) { values[i] = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(arguments[i]); } return this.compute(...values); } /** * Computes the return value of the function from its input arguments. * @param arguments A variable number of {@link Values}, whose number * must match the input arity of the function. * @return The resulting {@link Value} */ compute() { if (arguments.length !== this.arity) { throw "Invalid number of arguments"; } var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i].getValue()); } var o = this.getValue(...args); if (o instanceof _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value) { return o; } return new AtomicFunctionReturnValue(this, o, ...arguments); } getValue() { // To be overridden by descendants return null; } set() { return this; } }
JavaScript
class AtomicFunctionReturnValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { /** * Creates a new value * @param arguments An output value followed by the function's input arguments */ constructor() { super(); /** * The function instance this value comes from */ this.referenceFunction = arguments[0]; /** * The output value produced by the function */ this.outputValue = arguments[1]; /** * The function's input arguments */ this.inputValues = []; for (var i = 2; i < arguments.length; i++) { this.inputValues.push(arguments[i]); } } getValue() { return this.outputValue; } toString() { return this.outputValue.toString(); } /* @Override */ query(type, d, root, factory) { var leaves = []; var n = factory.getAndNode(); for (var i = 0; i < this.inputValues.length; i++) { if (this.inputValues[i] === null) { continue; } var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(d.tail(), new _function_mjs__WEBPACK_IMPORTED_MODULE_1__.InputArgument(i)); var sub_root = factory.getObjectNode(new_d, this.referenceFunction); var sub_leaves = []; sub_leaves = this.inputValues[i].query(type, _function_mjs__WEBPACK_IMPORTED_MODULE_1__.ReturnValue.instance, sub_root, factory); leaves.push(...sub_leaves); n.addChild(sub_root); } var f_root = factory.getObjectNode(d, this.referenceFunction); if (n.getChildren().length === 1) { f_root.addChild(n.getChildren()[0]); } else { f_root.addChild(n); } root.addChild(f_root); return leaves; } }
JavaScript
class Identity extends AtomicFunction { constructor() { super(1); } getValue() { return arguments[0]; } }
JavaScript
class BooleanConnective extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_1__.AtomicFunction { constructor() { super("arity"); } compute() { var false_values = []; var false_positions = []; var true_values = []; var true_positions = []; for (var i = 0; i < arguments.length; i++) { var o = arguments[i].getValue(); if (typeof o !== "boolean") { throw "Invalid argument type"; } if (o === true) { true_values.push(arguments[i]); true_positions.push(i); } else { false_values.push(arguments[i]); false_positions.push(i); } } return this.getBooleanValue(false_values, true_values, false_positions, true_positions); } }
JavaScript
class NaryDisjunctiveVerdict extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.NaryValue { query(q, d, root, factory) { var leaves = []; var n = factory.getOrNode(); for (var i = 0; i < this.values.length; i++) { var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_3__.CompoundDesignator.create(d.tail(), new _function_mjs__WEBPACK_IMPORTED_MODULE_0__.InputArgument(this.positions[i])); var sub_root = factory.getObjectNode(new_d, this.referenceFunction); var sub_leaves = []; sub_leaves = this.values[i].query(q, _function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, sub_root, factory); leaves.push(...sub_leaves); n.addChild(sub_root); } if (n.getChildren().length === 1) { root.addChild(n.getChildren()[0]); } else { root.addChild(n); } return leaves; } }
JavaScript
class NaryConjunctiveVerdict extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.NaryValue { constructor(value, values = [], positions = []) { super(value, values, positions); } query(q, d, root, factory) { var leaves = []; var n = factory.getAndNode(); for (var i = 0; i < this.values.length; i++) { var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_3__.CompoundDesignator.create(d.tail(), new _function_mjs__WEBPACK_IMPORTED_MODULE_0__.InputArgument(this.positions[i])); var sub_root = factory.getObjectNode(new_d, this.referenceFunction); var sub_leaves = []; sub_leaves = this.values[i].query(q, _function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, sub_root, factory); leaves.push(...sub_leaves); n.addChild(sub_root); } if (n.getChildren().length === 1) { root.addChild(n.getChildren()[0]); } else { root.addChild(n); } return leaves; } }
JavaScript
class BooleanAnd extends BooleanConnective { constructor(arity = 2) { super(arity); } /** * Gets the Boolean value. * @param false_values * @param true_values * @param false_positions * @param true_positions */ getBooleanValue(false_values = [], true_values = [], false_positions = [], true_positions = []) { if (false_values.length === 0) { return new NaryConjunctiveVerdict(true, true_values, true_positions); } return new NaryDisjunctiveVerdict(false, false_values, false_positions); } toString() { return "And"; } }
JavaScript
class BooleanOr extends BooleanConnective { constructor(arity = 2) { super(arity); } getBooleanValue(false_values = [], true_values = [], false_positions = [], true_positions = []) { if (true_values.length === 0) { return new NaryConjunctiveVerdict(false, false_values, false_positions); } return new NaryDisjunctiveVerdict(true, true_values, true_positions); } toString() { return "Or"; } }
JavaScript
class BooleanNot extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_1__.AtomicFunction { constructor() { super(1); } getValue() { if (typeof arguments[0] !== "boolean") { throw "Invalid argument type"; } return !arguments[0]; } toString() { return "Not"; } }
JavaScript
class ComposedFunction extends _function_mjs__WEBPACK_IMPORTED_MODULE_1__.AbstractFunction { /** * Creates a new instance of the function. * @param operator The top-level operator this function composes * @param operands The operands of this function. These operands * can themselves be other functions. */ constructor(operator, ...operands) { super(); this.operator = operator; this.operands = []; for (var i = 0; i < operands.length; i++) { if (typeof operands[i] === "string") { var op = operands[i]; if (op.startsWith("@")) { var index = op.substring(1).trim(); this.operands.push(new Argument(index)); continue; } if (op.startsWith("$")) { this.operands.push(new NamedArgument(this, op.substring(1).trim())); continue; } } else { this.operands.push(_function_mjs__WEBPACK_IMPORTED_MODULE_1__.AbstractFunction.lift(operands[i])); } } } setName(name) { this.name = name; return this; } set(variable, value) { var cf = new ComposedFunction(this.operator); var operands = []; for (var i = 0; i < this.operands.length; i++) { operands.push(this.operands[i].set(variable, value)); } cf.operands = operands; return cf; } getArity() { var args = []; this.getArguments(args); return args.length; } getArguments(args) { for (var i = 0; i < this.operands.length; i++) { var f = this.operands[i]; if (f instanceof ComposedFunction) { f.getArguments(args); } if (f instanceof Argument) { args.push(f.index); } if (f instanceof NamedArgument) { args.push(i); } } } evaluate() { var values = []; for (var i = 0; i < this.operands.length; i++) { values.push(this.operands[i].evaluate(...arguments)); } var v = this.operator.evaluate(...values); return new ComposedFunctionValue(this, v, ...values); } toString() { if (this.name != null) { return this.name; } return "F(" + this.operator.toString() + ")"; } }
JavaScript
class ComposedFunctionValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { constructor(f, return_value, ...values) { super(); this.referenceFunction = f; this.inputValues = values; this.returnValue = return_value; } query(q, d, root, factory) { var leaves = []; if (!(d.head() instanceof _function_mjs__WEBPACK_IMPORTED_MODULE_1__.ReturnValue)) { return leaves; } var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(_function_mjs__WEBPACK_IMPORTED_MODULE_1__.ReturnValue.instance, d.tail()); var sub_root = factory.getObjectNode(new_d, this.referenceFunction.operator); var sub_leaves = this.returnValue.query(q, d, sub_root, factory); var new_sub_leaves = []; for (var i = 0; i < sub_leaves.length; i++) { var sub_leaf = sub_leaves[i]; if (sub_leaf instanceof _tracer_mjs__WEBPACK_IMPORTED_MODULE_3__.ObjectNode) { var o_sl = sub_leaf; var des = o_sl.getDesignatedObject().getDesignator(); if (des.head() instanceof _function_mjs__WEBPACK_IMPORTED_MODULE_1__.InputArgument) { var fia = des.head(); var index = fia.getIndex(); new_sub_leaves.push(...this.inputValues[index].query(q, new_d, sub_leaf, factory)); continue; } } new_sub_leaves.push(sub_leaf); } leaves.push(...new_sub_leaves); root.addChild(sub_root); return leaves; } getValue() { return this.returnValue.getValue(); } toString() { return this.returnValue.toString(); } }
JavaScript
class NamedArgument extends _function_mjs__WEBPACK_IMPORTED_MODULE_1__.AbstractFunction { constructor(f, name) { super(); this.name = name; this.value = null; this.referenceFunction = f; this.isSet = false; } /* @Override */ set(name, value) { if (this.name === name || "$" + this.name === name) { this.value = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(value); } this.isSet = true; return this; } evaluate() { if (this.isSet) { return new NamedArgumentValue(this.name, this.value); } for (var i = 0; i < this.referenceFunction.operands.length; i++) { if (this.referenceFunction.operands[i] instanceof NamedArgument) { if (this.name === this.referenceFunction.operands[i].getName()) { return new NamedArgumentValue(this.name, _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(arguments[i])); } } } return new NamedArgumentValue(this.name, this.value); } toString() { return "$" + this.name; } getArity() { return 0; } getName() { return this.name; } }
JavaScript
class NamedArgumentValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { constructor(name, v) { super(); this.value = v; this.name = name; } query(q, d, root, factory) { var leaves = []; var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(d.tail(), new FunctionNamedArgument(this.name, this.value)); var n = factory.getObjectNode(new_d, this.value); var sub_leaves = this.value.query(q, d, n, factory); leaves.push(...sub_leaves); root.addChild(n); return leaves; } getValue() { return this.value.getValue(); } toString() { return this.value.getValue().toString(); } }
JavaScript
class FunctionNamedArgument extends _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Designator { /** * Creates a new named argument. * @param name The name of the argument * @param v The value of the argument */ constructor(name, v) { super(); this.name = name; this.value = v; } appliesTo(o) { return o instanceof Function; } head() { return this; } tail() { return null; } toString() { return "$" + this.name + "/" + this.value; } }
JavaScript
class Argument extends _function_mjs__WEBPACK_IMPORTED_MODULE_1__.AbstractFunction { /** * Creates a new instance of the function. * @param index The position of the argument in the composed * function */ constructor(index) { super(); this.index = index; } /* @Override */ set(name, value) { return this; } evaluate() { var v = _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value.lift(arguments[this.index]); return new ArgumentValue(this, v, this.index); } toString() { return "@" + this.index; } }
JavaScript
class ArgumentValue extends _value_mjs__WEBPACK_IMPORTED_MODULE_2__.Value { /** * Creates a new argument value. * @param f The function to which this value is an argument * @param v The value * @param index The position of the value in the arguments of the * function */ constructor(f, v, index) { super(); this.value = v; this.index = index; this.referenceFunction = f; } query(q, d, root, factory) { var leaves = []; var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(d.tail(), new _function_mjs__WEBPACK_IMPORTED_MODULE_1__.InputArgument(this.index, this.value)); var n = factory.getObjectNode(new_d, this.value); var sub_leaves = this.value.query(q, d, n, factory); leaves.push(...sub_leaves); root.addChild(n); return leaves; } getValue() { return this.value.getValue(); } }
JavaScript
class Designator { /** * Creates a new instance of designator. */ constructor() {// Nothing to do } /** * Extracts the designator at the head of a composition. For designators that * are atomic, returns the designator itself. */ head() { return this; } /** * Extracts the designator made of the tail of a composition. For designators * that are atomic, returns null. */ tail() { return null; } equals(o) { if (o == null || !(o instanceof Designator)) { return false; } return o == this; } }
JavaScript
class Nothing extends Designator { constructor() { super(); } toString() { return "Nothing"; } equals(o) { if (o == null || !(o instanceof Nothing)) { return false; } return true; } }
JavaScript
class AbstractFunction { constructor() {// Nothing to do } /** * Converts an arbitrary object into a {@link Function}. * @param o The object to convert. If o is a function, it is returned as is. * Otherwise, o is converted into a {@link ConstantFunction} that returns * the {@link Value} lifted from o. * @return The converted function */ static lift(o) { if (o instanceof AbstractFunction) { return o; } return new ConstantFunction(_value_mjs__WEBPACK_IMPORTED_MODULE_1__.Value.lift(o)); } /** * Computes the return value of the function from its provided input * arguments. * @param arguments A variable number of input arguments * @return The return value of the function */ evaluate() { // To be overridden by descendants return null; } /** * Binds a variable name to a specific value. * @param variable The name of the variable * @param value The value to bind this variable to */ setTo(variable, value) {// To be overridden by descendants } /** * Gets the arity of the function. * @return The arity */ getArity() { return 0; } equals(o) { if (o == null || !(o instanceof AbstractFunction)) { return false; } return o == this; } // d is a deserializer and j is a JSON structure // static deserialize(d, j) { // var instance = new this(); // var descendant = [] // var getDescendants = instance.extractJSON(j, descendant) // for (const descendant in getDescendants) { // //we can obtain j' with descendants[d] // d.deserialize(getDescendants[descendant]); // } // return instance // } static deserialize(d, j) { const params = []; for (const serializedParam of j.contents) { if (typeof serializedParam == "object" && Object.keys(serializedParam).length == 2 && typeof serializedParam.name != "undefined" && typeof serializedParam.contents != "undefined") { params.push(d.deserialize(serializedParam)); } else { params.push(serializedParam); } } return new this(...params); } //this method will return all descendant of json structure extractJSON(obj, descendant = []) { for (const i in obj) { if (Array.isArray(obj[i]) || typeof obj[i] === 'object') { if (obj[i].name != undefined) { descendant.push(obj[i]); } //this.extractJSON(obj[i], descendant); } } return descendant; } ////////////////////////// // d is a deserializer and j is a JSON structure // static deserialize(d, j) { // var instance = new this(); // //var getDescendants = this.constructor.extractJSON(j, descendant = []) // for (const descendant in getDescendants) { // //we can obtain j' with descendants[d] // d.deserialize(getDescendants[descendant]); // } // return instance // } // static deserialize(d, j) { // // var instance = new this(); // var descendant; // var getDescendants = extractJSON(j, descendant = [], true); // var instance = new this(getDescendants[0].contents[0], getDescendants[1].name, getDescendants[2].contents); // return instance; // } // //this method will return all descendant of json structure // extractJSON(obj, descendant = []) { // for (const i in obj) { // if (Array.isArray(obj[i]) || typeof obj[i] === 'object') { // if (obj[i].name != undefined) { // descendant.push(obj[i]) // } // descendant = extractJSON(obj[i], descendant); // } // } // return descendant; // } }
JavaScript
class ReturnValue extends _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Designator { constructor() { super(); } toString() { return "!"; } equals(o) { if (o == null || !(o instanceof ReturnValue)) { return false; } return true; } }
JavaScript
class ConstantFunction extends AbstractFunction { /** * Creates a new instance of constant function. * @param o The object to return */ constructor(o) { super(); this.value = _value_mjs__WEBPACK_IMPORTED_MODULE_1__.Value.lift(o); } evaluate() { return this.value; } getArity() { return 0; } set(variable, value) { return this; } }
JavaScript
class IsEqualTo extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { constructor() { super(2); } getValue() { var o1 = arguments[0]; var o2 = arguments[1]; if (o1 == null && o2 == null) { return true; } if (o1 == null && o2 != null || o1 != null && o2 == null) { return false; } if (typeof o1 === "number" && typeof o2 === "number") { return o1 === o2; } if (typeof o1 === "string" && typeof o2 === "string") { return o1 === o2; } return false; } }
JavaScript
class Addition extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { constructor(arity = 2) { super(arity); } getValue() { var sum = 0; for (var i = 0; i < this.arity; i++) { var o = arguments[i]; if (typeof o !== "number") { throw "Invalid argument type"; } sum += o; } return sum; } toString() { return "Addition"; } }
JavaScript
class Substraction extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { constructor(arity = 3) { super(arity); } getValue() { var sub = arguments[0]; for (var i = 1; i < arguments.length; i++) { var o = arguments[i]; if (typeof o !== "number") { throw "Invalid argument type"; } sub -= o; } return sub; } toString() { return "Substraction"; } }
JavaScript
class Multiplication extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { constructor(arity = 5) { super(arity); } compute() { if (arguments.length !== this.arity) { throw "Invalid number of arguments"; } var zero_values = []; var zero_positions = []; var result = 1; for (var i = 0; i < this.arity; i++) { var o = arguments[i].getValue(); if (typeof o !== "number") { throw "Invalid argument type"; } if (o === 0) { zero_values.push(arguments[i]); zero_positions.push(i); } else { result *= o; } } return this.getZeroValue(zero_values, zero_positions, result); } getZeroValue(zero_values = [], zero_positions = [], result = null) { if (zero_values.length === 0) { return result; } else { console.log(`Position of the returned Zero is ${zero_positions} in the array`); return parseFloat(zero_values); } } toString() { return "Multiplication"; } }
JavaScript
class Division extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { constructor(arity = 4) { super(arity); } getValue() { var div = arguments[0]; for (var i = 1; i < arguments.length; i++) { var o = arguments[i]; if (typeof o !== "number") { throw "Invalid argument type"; } div /= o; } return div; } toString() { return "Division"; } }
JavaScript
class GreaterThan extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { /** * Creates a new instance of the function. */ constructor() { super(2); } getValue() { var o1 = arguments[0]; var o2 = arguments[1]; if (typeof o1 !== "number" || typeof o2 !== "number") { throw new Error(`Invalid argument type. GreaterThan expects both arguments to be numbers, but the following were received instead: ${typeof o1} (${JSON.stringify(o1)}) and ${typeof o2} (${JSON.stringify(o2)}).`); } return o1 > o2; } toString() { return "&gt;"; } }
JavaScript
class LesserThan extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { /** * Creates a new instance of the function. */ constructor() { super(2); } getValue() { var o1 = arguments[0]; var o2 = arguments[1]; if (typeof o1 !== "number" || typeof o2 !== "number") { throw new Error(`Invalid argument type. LesserThan expects both arguments to be numbers, but the following were received instead: ${typeof o1} (${JSON.stringify(o1)}) and ${typeof o2} (${JSON.stringify(o2)}).`); } return o1 < o2; } toString() { return "&lt;"; } }
JavaScript
class GreaterOrEqual extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { /** * Creates a new instance of the function. */ constructor() { super(2); } getValue() { var o1 = arguments[0]; var o2 = arguments[1]; if (typeof o1 !== "number" || typeof o2 !== "number") { throw new Error(`Invalid argument type. GreaterOrEqual expects both arguments to be numbers, but the following were received instead: ${typeof o1} (${JSON.stringify(o1)}) and ${typeof o2} (${JSON.stringify(o2)}).`); } return o1 >= o2; } toString() { return "&ge;"; } }
JavaScript
class LesserOrEqual extends _atomic_function_mjs__WEBPACK_IMPORTED_MODULE_0__.AtomicFunction { /** * Creates a new instance of the function. */ constructor() { super(2); } getValue() { var o1 = arguments[0]; var o2 = arguments[1]; if (typeof o1 !== "number" || typeof o2 !== "number") { throw new Error(`Invalid argument type. LesserOrEqual expects both arguments to be numbers, but the following were received instead: ${typeof o1} (${JSON.stringify(o1)}) and ${typeof o2} (${JSON.stringify(o2)}).`); } return o1 <= o2; } toString() { return "&le;"; } }
JavaScript
class Quantifier extends _function_mjs__WEBPACK_IMPORTED_MODULE_0__.AbstractFunction { /** * Creates a new instance of quantifier. * @param index {integer|string} * @param domain {AbstractFunction} * @param phi {AbstractFunction} */ constructor(index, domain, phi) { super(); if (typeof index === "number") { this.index = index; } else { this.variable = index; } this.domain = domain; this.phi = phi; } getArity() { return 1; } evaluate() { if (arguments.length !== 1) { throw "Invalid number of arguments"; } var true_verdicts = []; var false_verdicts = []; var v_dom = this.domain.evaluate(...arguments); var o_dom = v_dom.getValue(); if (!Array.isArray(o_dom)) { throw "Domain expression does not return a list"; } var domain = o_dom; for (var i = 0; i < domain.length; i++) { var x = _value_mjs__WEBPACK_IMPORTED_MODULE_1__.Value.lift(domain[i]); var cf = this.phi.set(this.variable, x); var ret_val = cf.evaluate(...arguments); var o_b = ret_val.getValue(); if (typeof o_b !== "boolean") { throw "Invalid argument type"; } var b = o_b; if (b) { true_verdicts.push({ value: x, verdict: ret_val }); } else { false_verdicts.push({ value: x, verdict: ret_val }); } } return this.getQuantifierValue(false_verdicts, true_verdicts); } getQuantifierValue(false_verdicts, true_verdicts) { return null; // To be overridden by descendants } }
JavaScript
class QuantifierDisjunctiveVerdict extends QuantifierVerdict { query(q, d, root, factory) { var leaves = []; var n = factory.getOrNode(); for (var i = 0; i < this.verdicts.length; i++) { var vv = this.verdicts[i]; var v = vv.verdict; var sub_factory = factory.getSubTracer(this.referenceFunction); var sub_leaves = v.query(q, _function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, n, sub_factory); leaves.push(...sub_leaves); } var tn = factory.getObjectNode(_function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, this.referenceFunction); if (this.verdicts.length === 1) { tn.addChild(n.getChildren()[0]); } else { tn.addChild(n); } root.addChild(tn); return leaves; } }
JavaScript
class QuantifierConjunctiveVerdict extends QuantifierVerdict { query(q, d, root, factory) { var leaves = []; var n = factory.getAndNode(); for (var i = 0; i < this.verdicts.length; i++) { var vv = this.verdicts[i]; var v = vv.verdict; var sub_factory = factory.getSubTracer(v); var sub_leaves = v.query(q, _function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, n, sub_factory); leaves.push(...sub_leaves); } var tn = factory.getObjectNode(_function_mjs__WEBPACK_IMPORTED_MODULE_0__.ReturnValue.instance, this.referenceFunction); if (this.verdicts.length === 1) { tn.addChild(n.getChildren()[0]); } else { tn.addChild(n); } root.addChild(tn); return leaves; } }
JavaScript
class UniversalQuantifier extends Quantifier { getQuantifierValue(false_verdicts = [], true_verdicts = []) { if (false_verdicts.length === 0) { return new QuantifierConjunctiveVerdict(this, true, true_verdicts); } return new QuantifierDisjunctiveVerdict(this, false, false_verdicts); } toString() { return "ForAll"; } set(variable, value) { return new UniversalQuantifier(this.variable, this.domain.set(variable, value), this.phi.set(variable, value)); } // static deserialize(d, j) { // var instance = new this(); // return instance //var instance = new this(j.contents[0], j.contents[1].contents[0], j.contents[2]); // var descendant = [] // var getDescendants = instance.extractJSON(j, descendant) // for (const descendant in getDescendants) { // //we can obtain j' with descendants[d] // d.deserialize(getDescendants[descendant]); // } //return instance; //} }
JavaScript
class ExistentialQuantifier extends Quantifier { getQuantifierValue(false_verdicts = [], true_verdicts = []) { if (true_verdicts.length > 0) { return new QuantifierDisjunctiveVerdict(this, true, true_verdicts); } return new QuantifierConjunctiveVerdict(this, false, false_verdicts); } toString() { return "Exists"; } set(variable, value) { return new ExistentialQuantifier(this.variable, this.domain.set(variable, value), this.phi.set(variable, value)); } }
JavaScript
class Tracer { constructor() { /** * A map keeping trace of which designated objects already have nodes. */ this.nodes = new Map(); /** * The context in which the tracer operates (a stack). */ this.tracerContext = []; if (arguments.length > 0) { this.tracerContext = arguments; } /** * Whether to simplify the trees */ this.simplify = true; } /** * Sets whether the trees produced by the tracer should be simplified. * @param b {boolean} Set to true to simplify trees, false otherwise */ setSimplify(b) { this.simplify = b; } /** * Gets a new instance of an object node. * @param dob The designated object that will be contained inside the node * @return The object node. If an object node already exists for this * designated object, it is reused. Otherwise, a new object node is created. */ getObjectNode(d, o) { if (d instanceof DesignatedObject) { var dob = d; } else { var dob = new DesignatedObject(d, o); } if ((0,_util_mjs__WEBPACK_IMPORTED_MODULE_2__.map_contains)(this.nodes, dob)) { return (0,_util_mjs__WEBPACK_IMPORTED_MODULE_2__.map_get)(this.nodes, dob); } var on = new ObjectNode(dob); (0,_util_mjs__WEBPACK_IMPORTED_MODULE_2__.map_put)(this.nodes, dob, on); return on; } /** * Gets a new instance of an "and" node. * @return A new "and" node */ getAndNode() { return new AndNode(); } /** * Gets a new instance of an "or" node. * @return A new "or" node */ getOrNode() { return new OrNode(); } /** * Gets a new instance of an "unknown" node. * @return A new "unknown" node */ getUnknownNode() { return new UnknownNode(); } /** * Gets an instance of a sub-tracer from this tracer. * @param {Object} o An object to append at the end of the current * tracer's context */ getSubTracer(o) { var con = []; con.push(...this.tracerContext); con.push(o); return new Tracer(...con); } getTree(q, d, o) { var visited = []; var tn = this.getObjectNode(d, o); this.getChildren(q, tn, visited); return tn; } getChildren(q, root, visited) { if ((0,_util_mjs__WEBPACK_IMPORTED_MODULE_2__.set_contains)(visited, root)) { // This node has already been expanded return; } visited.push(root); if (!(root instanceof ObjectNode)) { // Nothing to expand return; } var dob = root.getDesignatedObject(); var o = dob.getObject(); var d = dob.getDesignator(); if (d instanceof _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.All || d instanceof _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Nothing || d instanceof _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Unknown) { // Trivial designator: nothing to expand return; } if (typeof o.query == "function") // Object is queryable { // Send the query and create nodes from its result var leaves = o.query(q, d, root, this); for (var i = 0; i < leaves.length; i++) { this.getChildren(q, leaves[i], visited); } } else {// Query is non-trivial, and object is not trackable: nothing to do //var n = this.getObjectNode(Unknown.instance, o); //root.addChild(n); } } }
JavaScript
class TraceabilityNode { /** * A counter for traceability node IDs. */ constructor() { /** * The node's unique ID */ this.id = TraceabilityNode.TN_ID_COUNTER++; /** * The node's children */ this.children = []; } /** * Gets the node'is unique ID. * @return The node's ID */ getId() { return this.id; } /** * Adds a child to the node. * @return The node to add */ addChild(n) { if (n == this) { return; } this.children.push(n); } /** * Gets the children of this node. * @return The list of children */ getChildren() { return this.children; } }
JavaScript
class OrNode extends TraceabilityNode { constructor() { super(); } toString() { var indent = ""; if (arguments.length == 1) { indent = arguments[0]; } var s = ""; s += indent + "v" + "\n"; for (var i = 0; i < this.children.length; i++) { s += indent + this.children[i].toString(indent + " "); } return s; } addChild(n) { if (n instanceof OrNode) { for (var i = 0; i < n.children.length; i++) { this.children.push(n.children[i]); } } else { this.children.push(n); } } }
JavaScript
class UnknownNode extends TraceabilityNode { constructor() { super(); } toString() { return "?"; } }
JavaScript
class ObjectNode extends TraceabilityNode { /** * Creates a new object node. * @param {Designator|DesignatedObject} d The designator * @param {Object} o The object that is designated */ constructor(d, o) { super(); if (d instanceof DesignatedObject) { this.designatedObject = d; } else { this.designatedObject = new DesignatedObject(d, o); } } /** * Gets the designated object contained inside this node. */ getDesignatedObject() { return this.designatedObject; } toString() { return this.designatedObject.toString(); } }
JavaScript
class DesignatedObject { /** * Creates a new designated object * @param designator The part of the object that is designated * @param object The object that is designated * @param context The object's context */ constructor(designator, object, context) { /** * The part of the object that is designated. */ this.designator = designator; /** * The object that is designated. */ this.object = object; /** * The object's context. */ if (arguments.length >= 3) { this.context = context; } else { this.context = []; } } /** * Retrieves the designator associated to an object. * @return The designator */ getDesignator() { return this.designator; } /** * Retrieves the object that is being designated. * @return The object */ getObject() { return this.object; } /** * Retrieves the object's context. * @return The context */ getContext() { return this.context; } equals(cdo) { if (cdo == null || !(cdo instanceof DesignatedObject)) { return false; } return (this.object == null && cdo.object == null || this.object != null && (0,_util_mjs__WEBPACK_IMPORTED_MODULE_2__.same_object)(this.object, cdo.object)) && this.designator.equals(cdo.designator) && this.sameContext(cdo); } /** * Checks if two designated objects have the same context. * @param cdo The other designated object * @return <tt>true</tt> if the two objects have the same context, * <tt>false</tt> otherwise */ sameContext(cdo) { if (this.context.length != cdo.context.length) { return false; } for (var i = 0; i < this.context.length; i++) { if (this.context[i] != cdo.context[i]) { return false; } } return true; } toString() { return this.designator.toString() + " of " + this.object.toString(); } }
JavaScript
class Explainer { constructor() {// Nothing to do } /** * Explains the result of a calculation produced by an * {@link AbstractFunction}. * @param v {Value} The value to explain * @param simplify Set to <tt>true</tt> to produce a simplified DAG * (default), <tt>false</tt> to get a full DAG */ static explain(v, simplify = true) { var tracer = new Tracer(); tracer.setSimplify(simplify); return tracer.getTree(null, _function_mjs__WEBPACK_IMPORTED_MODULE_1__.ReturnValue.instance, v); } }
JavaScript
class Value { /* constructor() { // Nothing to do } */ /** * Gets the concrete value carried by this Value object. * @return The value */ getValue() { // To be overridden by descendants return null; } /** * Queries the provenance of a value. * @param type The type of lineage relationship * @param d A designator representing the part of the object that is the * subject of the query * @param root The node to which the rsults of the query should be appended * as children * @param A factory to produce traceability nodes * @return The list of terminal traceability nodes produced by this query */ query(type, d, root, factory) {// To be overridden by descendants } /** * Converts an arbitrary object into a {@link Value}. * @param o The object to convert. If o is a {@link Value}, it is returned as * is. Otherwise, o is converted into a {@link ConstantValue} that returns o. * @return The converted value */ static lift(o) { if (o instanceof Value) { return o; } return new ConstantValue(o); } }
JavaScript
class NaryValue extends Value { /** * Creates a new instance of this value. * @param {Object} value The value to produce * @param {Array} values An array of {@link Value}s that are linked to * this value * @param {Array} positions An array of integers with the position of * each input value in the function's arguments */ constructor(value, values = [], positions = []) { super(); this.value = value; this.values = values; this.positions = positions; } getValue() { return this.value; } }
JavaScript
class ConstantValue extends Value { constructor(o) { super(); /** * The value represented by this constant */ this.value = o; } query(q, d, root, factory) { var leaves = []; var new_d = _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.CompoundDesignator.create(d, new ConstantDesignator()); var n = factory.getObjectNode(new_d, this.value); root.addChild(n); leaves.push(n); return leaves; } getValue() { return this.value; } toString() { return this.value.toString(); } equals(o) { if (o == null || !(o instanceof Value)) { return false; } return o.getValue() === this.value; } }
JavaScript
class ConstantDesignator extends _designator_mjs__WEBPACK_IMPORTED_MODULE_0__.Designator { /* constructor() { super(); } */ toString() { return "Value"; } }