text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Command } from "commander"; import { log } from "console"; import * as fs from "fs"; import { retry } from "../.."; import { EventManagementModels, MindSphereSdk } from "../../api/sdk"; import { isGuid } from "../../api/utils"; import { adjustColor, errorLog, getColor, getSdk, homeDirLog, proxyLog, serviceCredentialLog, verboseLog, } from "./command-utils"; import { createFilter } from "./download-events"; import path = require("path"); let color = getColor("magenta"); const red = getColor("red"); const yellow = getColor("yellow"); const blue = getColor("blue"); export default (program: Command) => { program .command("events") .alias("ev") .option( "-m, --mode [list|create|delete|template|filtertemplate|info]", "list | create | delete | template | filtertemplate | info", "list" ) .option("-f, --file <file>", ".mdsp.json file with event definition") .option("-i, --assetid <assetid>", "mindsphere asset id ") .option("-e, --eventid <eventid>", "event id ") .option( "-f, --filter [filter]", `JSON file with filter (see: ${color( "https://developer.mindsphere.io/apis/advanced-eventmanagement/api-eventmanagement-best-practices.html" )}) ` ) .option("-n, --eventtype <eventtype>", "the event type name") .option("-s, --size <size>", "max. number of events to list", "100") .option("-c, --includeshared", "include shared event types") .option("-g, --includeglobal", "include global event types") .option("-k, --passkey <passkey>", "passkey") .option("-y, --retry <number>", "retry attempts before giving up", "3") .option("-v, --verbose", "verbose output") .description(color("list, create or delete events *")) .action((options) => { (async () => { try { checkRequiredParamaters(options); const sdk = getSdk(options); color = adjustColor(color, options); homeDirLog(options.verbose, color); proxyLog(options.verbose, color); switch (options.mode) { case "list": await listEvents(sdk, options); break; case "template": await createEventTemplate(options, sdk); console.log("Edit the file before submitting it to MindSphere."); break; case "filtertemplate": createFilter(options); console.log("Edit the file before submitting it to MindSphere."); break; case "delete": await deleteEvent(options, sdk); break; case "create": await createEvent(options, sdk); break; case "info": await eventInfo(options, sdk); break; default: throw Error(`no such option: ${options.mode}`); } } catch (err) { errorLog(err, options.verbose); } })(); }) .on("--help", () => { log("\n Examples:\n"); log(` mc events --mode list \t\t\t\t list last <size> events (default:100)`); log(` mc events --mode list --eventtype PumpEvent\t\t list last <size> PumpEvents (default: 100)`); log(` mc events --mode info --eventid <eventid>\t\t get info about event with specified id`); log(` mc events --mode delete --eventid <eventid>\t\t delete event with specified id`); log(` mc events --mode filtertemplate \t\t\t create filter template for --mode list command`); log(` mc events --mode template --eventtype PumpEvent \t create a template file for event `); log(` mc events --mode create --file PumpEvent.eventtype.mdsp.json \t create event`); serviceCredentialLog(); }); }; async function createEvent(options: any, sdk: MindSphereSdk) { const includeShared = options.includeshared; const filePath = path.resolve(options.file); const file = fs.readFileSync(filePath); const event = JSON.parse(file.toString()); const result = await sdk.GetEventManagementClient().PostEvent(event, { includeShared: includeShared }); console.log(`creted event ${result.id}`); } async function createEventTemplate(options: any, sdk: MindSphereSdk) { const eventType = extractEventType(options, sdk.GetTenant()); const templateType = await sdk .GetEventManagementClient() .GetEventType(eventType, { includeShared: options.includeshared }); verboseLog(JSON.stringify(templateType, null, 2), options.verbose); writeEventToFile(options, templateType); } function extractEventType(options: any, tenant: string) { let eventType = options.eventtype || "com.siemens.mindsphere.eventmgmt.event.type.MindSphereStandardEvent"; eventType = isGuid(eventType) || (eventType! as string).includes(".") ? eventType : `${tenant}.${eventType}`; return eventType; } function writeEventToFile(options: any, templateType: EventManagementModels.EventTypeResponse) { const fileName = options.file || `${templateType.name}.event.mdsp.json`; const template: any = {}; template.entityId = options.assetid || "AssetID"; template.timestamp = new Date().toISOString(); template.typeId = templateType.id; templateType.fields.forEach((element) => { template[element.name] = `${element.type}${element.required ? " ,required" : ""}`; }); fs.writeFileSync(fileName, JSON.stringify(template, null, 2)); console.log( `The data was written into ${color( fileName )} run \n\n\tmc events --mode create --file ${fileName} \n\nto create the event.` ); } async function deleteEvent(options: any, sdk: MindSphereSdk) { const includeShared = options.includeshared; const id = options.eventid; const event = await retry(options.retry, () => sdk.GetEventManagementClient().GetEvent(id, { includeShared: includeShared }) ); const result = await retry(options.retry, () => sdk.GetEventManagementClient().PostDeleteEventsJob({ filter: { id: `${event.id}`, typeId: `${event.typeId}`, }, }) ); console.log(`Deletion job with id ${color(result.id)} is in state ${color(result.state)}.`); result.details && console.log(`Details: ${JSON.stringify(result.details)}.`); console.log(`Run\n\n\tmc events-bulk --mode check --jobid ${result.id}\n\nto check the state of the job.\n `); } async function listEvents(sdk: MindSphereSdk, options: any) { const assetNames: any = {}; const includeShared = options.includeshared; const eventMgmt = sdk.GetEventManagementClient(); let page = 0; let events; const filter = buildFilter(options, sdk.GetTenant()); // // verboseLog(JSON.stringify(filter, null, 2), options.verbose); // !options.idonly && console.log(`id etag aspects name owner scope sharing`); console.log(`eventid ${color("asset")} (assetid) severity type description`); let eventCount = 0; do { events = (await retry(options.retry, () => eventMgmt.GetEvents({ page: page, size: 100, filter: Object.keys(filter).length === 0 ? undefined : JSON.stringify(filter), sort: "timestamp,desc", includeShared: includeShared, }) )) as EventManagementModels.QueryEventsResponse; events._embedded = events._embedded || { events: [] }; events.page = events.page || { totalPages: 0 }; for (const event of events._embedded.events || []) { if (!assetNames[event.entityId]) { assetNames[event.entityId] = (await sdk.GetAssetManagementClient().GetAsset(event.entityId)).name; } eventCount++; !options.idonly && console.log( `${event.id} ${color(assetNames[event.entityId])} (${event.entityId}) ${toSeverityString( event.severity )} ${shortEvent(event.typeId)} ${event.timestamp} ${event.description || "<no description>"}` ); options.idonly && console.log(`${event.id}`); verboseLog(JSON.stringify(event, null, 2), options.verbose); } } while (page++ < (events.page.totalPages || 0) && eventCount < options.size); console.log(`${color(eventCount)} events listed.\n`); } function toSeverityString(severity: number | undefined) { let result: number | string | undefined = severity; result = severity === 20 ? red("Error") : result; result = severity === 30 ? yellow("Warning") : result; result = severity === 40 ? blue("Info") : result; return result || "<no severity>"; } function shortEvent(eventType: string) { const ev = eventType.split("."); const short = ev[ev.length - 1]; return short === "MindSphereStandardEvent" ? "MSE" : short; } function buildFilter(options: any, tenant: string) { const filter = (options.filter && JSON.parse(options.filter)) || {}; if (options.assetid) { filter.entityId = `${options.assetid}`; } if (options.eventtype) { const eventType = extractEventType(options, tenant); filter.typeId = `${eventType}`; } return filter; } async function eventInfo(options: any, sdk: MindSphereSdk) { const includeShared = options.includeshared; const id = options.eventid; const event = await sdk.GetEventManagementClient().GetEvent(id, { includeShared: includeShared }); console.log(JSON.stringify(event, null, 2)); } function checkRequiredParamaters(options: any) { options.mode === "create" && !options.file && errorLog( "you have to provide a file with event type to create an event type (see mc events --help for more details)", true ); options.mode === "delete" && !options.eventid && errorLog("you have to provide the eventid to delete (see mc events --help for more details)", true); options.mode === "info" && !options.eventid && errorLog("you have to provide the eventid (see mc events --help for more details)", true); }
the_stack
import { BitstreamMeasurer, BitstreamReader, BitstreamWriter } from "../bitstream"; import { BufferedWritable, Constructor } from "../common"; import { StructureSerializer } from "./structure-serializer"; import { ArraySerializer } from "./array-serializer"; import { BooleanSerializer } from "./boolean-serializer"; import { BufferSerializer } from "./buffer-serializer"; import { FieldDefinition } from "./field-definition"; import { NullSerializer } from "./null-serializer"; import { NumberSerializer } from "./number-serializer"; import { resolveLength } from "./resolve-length"; import { StringSerializer } from "./string-serializer"; import { VariantDefinition } from "./variant-definition"; /** * A reference to a field. Can be a string/symbol or a type-safe function * which exemplifies the field. */ export type FieldRef<T> = string | symbol | ((exemplar : { [P in keyof T]: any; }) => any); /** * Specify options when serializing a value */ export interface SerializeOptions { /** * Set of fields to skip while writing */ skip? : (string | symbol)[]; } export interface ReadOptions<T = BitstreamElement> extends SerializeOptions { parent? : BitstreamElement; field? : FieldDefinition; variator? : () => Promise<T>; } /** * BitstreamElement is a base class which can be extended to produce "structures" that can be * read from and written to a bitstream. It allows you to specify fields along with their type * and bitlength information declaratively, allowing BitstreamElement itself to handle the actual * serialization/deserialization in the context of a passed BitstreamReader/BitstreamWriter. */ export class BitstreamElement { private static _generatedReader : ( reader : BitstreamReader, instance : BitstreamElement, parent? : BitstreamElement, defn? : FieldDefinition, own? : boolean ) => Generator<number, BitstreamElement>; static get generatedReader() { this.generateReader(); return this._generatedReader; } /** * Retrieve the "syntax" of this element, which is the list of fields defined on the element * in order of appearance within the bitstream. */ static get syntax() : FieldDefinition[] { let parentSyntax = (<FieldDefinition[]>(Object.getPrototypeOf(this).syntax || [])); let syntax = parentSyntax.slice(); let ownSyntax = (<Object>this).hasOwnProperty('ownSyntax') ? this.ownSyntax : []; let insertIndex = syntax.findIndex(x => x.options.isVariantMarker); if (insertIndex >= 0) syntax.splice(insertIndex, 0, ...ownSyntax); else syntax.push(...ownSyntax); return syntax; } determineVariantType(parent? : BitstreamElement, variants? : (Function | VariantDefinition)[]) { let elementType : any = this.constructor; variants ??= elementType['variants'] || []; let variantDefns = variants.map((typeOrVariant : any) => typeof typeOrVariant === 'function' ? (<VariantDefinition>{ type: typeOrVariant, discriminant: typeOrVariant.variantDiscriminant }) : typeOrVariant ); variantDefns = variantDefns.sort((a, b) => { let aPriority = a.options.priority || 0; let bPriority = b.options.priority || 0; if (aPriority === 'first') aPriority = Number.MIN_SAFE_INTEGER; if (aPriority === 'last') aPriority = Number.MAX_SAFE_INTEGER; if (bPriority === 'first') bPriority = Number.MIN_SAFE_INTEGER; if (bPriority === 'last') bPriority = Number.MAX_SAFE_INTEGER; return aPriority - bPriority; }); return variantDefns.find(v => v.discriminant(this, parent))?.type; } /** * Create a copy of this element instance * @returns A new copy of this element */ clone(): this { let newInstance = new (<any>this.constructor)(); for (let field of this.syntax) newInstance[field.name] = this[field.name]; return newInstance; } /** * Retrieve the field definition of a field as specified by the given field reference * @param ref The field being referenced * @returns The field definition */ selectField(ref : FieldRef<this>) { if (typeof ref === 'string' || typeof ref === 'symbol') return this.syntax.find(x => x.name === ref); let selector : Record<string, symbol> = this.syntax.reduce((pv, cv) => (pv[cv.name] = cv.name, pv), {}); let selected : string = ref(<any>selector); return this.syntax.find(x => x.name === selected); } /** * Serialize all fields or a subset of fields into a buffer. * @param fromRef The first field that should be serialized. If not specified, serialization begins at the start of * the element * @param toRef The last field that should be serialized. If not specified, serialization continues until the end of * the element * @param autoPad When true and the bitsize of a field is not a multiple of 8, the final byte will * contain zeros up to the next byte. When false (default), serialize() will throw * if the size is not a multiple of 8. */ serialize(fromRef? : FieldRef<this>, toRef? : FieldRef<this>, autoPad = false) { if (!fromRef) fromRef = this.syntax[0].name; if (!toRef) { if (this.getFieldBeingComputed()) { let toIndex = this.syntax.findIndex(f => f.name === this.getFieldBeingComputed().name); if (!this.getFieldBeingComputedIntrospectable()) toIndex -= 1; if (toIndex < 0) return new Uint8Array(0); toRef = this.syntax[toIndex].name; } else if (this.isBeingRead) { let readFields = this.syntax.filter(x => this.readFields.includes(x.name)).map(x => x.name); toRef = readFields[readFields.length - 1]; } else { toRef = this.syntax[this.syntax.length - 1].name; } } let from = this.selectField(fromRef); let to = this.selectField(toRef); let fromIndex = this.syntax.findIndex(x => x === from); let toIndex = this.syntax.findIndex(x => x === to); let stream = new BufferedWritable(); let writer = new BitstreamWriter(stream); if (fromIndex > toIndex) { throw new Error(`Cannot measure from field ${fromIndex} (${String(from.name)}) to ${toIndex} (${String(to.name)}): First field comes after last field`); } let length = this.measure(fromRef, toRef); if (!autoPad && length % 8 !== 0) throw new Error(`Cannot serialize ${length} bits evenly into ${Math.ceil(length / 8)} bytes`); for (let i = fromIndex, max = toIndex; i <= max; ++i) { let field = this.syntax[i]; if (!this.isPresent(field, this)) continue; let writtenValue = this[field.name]; if (field.options.writtenValue) { if (typeof field.options.writtenValue === 'function') { writtenValue = field.options.writtenValue(this, field); } else { writtenValue = field.options.writtenValue; } } try { field.options.serializer.write(writer, field.type, this, field, writtenValue); } catch (e) { console.error(`Failed to write field ${field.type.name}#${String(field.name)} using ${field.options.serializer.constructor.name}: ${e.message}`); console.error(e); throw new Error(`Failed to write field ${String(field.name)} using ${field.options.serializer.constructor.name}: ${e.message}`); } } writer.end(); return stream.buffer; } /** * Measure the number of bits starting from the first field and continuing through the structure until the last * field. * @param fromRef The field to start measuring from (including the specified field). When not specified, measurement * starts from the first field * @param toRef The field to stop measuring at (including the specified field). When not specified, measurement * ends at the last field * @returns The number of bits occupied by the range of fields */ measure(fromRef? : FieldRef<this>, toRef? : FieldRef<this>) { if (!fromRef) fromRef = this.syntax[0].name; if (!toRef) { if (this.getFieldBeingComputed()) { let toIndex = this.syntax.findIndex(f => f.name === this.getFieldBeingComputed().name); if (!this.getFieldBeingComputedIntrospectable()) toIndex -= 1; if (toIndex < 0) return 0; toRef = this.syntax[toIndex].name; } else if (this.isBeingRead) { let readFields = this.syntax.filter(x => this.readFields.includes(x.name)).map(x => x.name); toRef = readFields[readFields.length - 1]; } else { toRef = this.syntax[this.syntax.length - 1].name; } } let from = this.selectField(fromRef); let to = this.selectField(toRef); let fieldBeingRead = this.syntax.find(x => !this.readFields.includes(x.name)); let fromIndex = this.syntax.findIndex(x => x === from); let toIndex = this.syntax.findIndex(x => x === to); let measurer = new BitstreamMeasurer(); if (fromIndex > toIndex) { throw new Error(`Cannot measure from field ${fromIndex} (${String(from.name)}) to ${toIndex} (${String(to.name)}): First field comes after last field`); } for (let i = fromIndex, max = toIndex; i <= max; ++i) { let field = this.syntax[i]; if (!this.isPresent(field, this)) continue; try { field.options.serializer.write(measurer, this.constructor, this, field, this[field.name]); } catch (e) { console.error(`Failed to measure field ${this.constructor.name}#${String(field.name)}:`); console.error(e); throw new Error(`${this.constructor.name}#${String(field.name)}: Cannot measure field: ${e.message}`); } } return measurer.bitLength; } /** * Measure from the beginning of the element to the given field * @param toRef The field to stop measuring at (including the specified field) * @returns The number of bits occupied by the set of fields */ measureTo(toRef? : FieldRef<this>) { return this.measure(undefined, toRef); } /** * Measure from the given field to the end of the element * @param fromRef The field to start measuing at (including the specified field) * @returns The number of bits occupied by the set of fields */ measureFrom(fromRef? : FieldRef<this>) { return this.measure(fromRef, undefined); } /** * Measure the size of a specific field * @param ref The field to measure * @returns The number of bits occupied by the field */ measureField(ref? : FieldRef<this>) { return this.measure(ref, ref); } /** * Check that this instance is one of a set of given subtypes. If it is, * this instance is returned with the more specific type. * If it is not, an error is thrown. * * @param typeChecks One or more subclasses to check * @returns This instance, but casted to the desired type */ as<T>(...typeChecks : Constructor<T>[]): T { if (!typeChecks.some(x => this instanceof x)) throw new Error(`Tried to cast to one of [${typeChecks.map(x => x.name).join(', ')}], but ${this.constructor.name} does not inherit from any of them`); return <any>this; } /** * Check that this instance is one of a set of given subtypes. * @param typeChecks * @returns */ is<T>(...typeChecks : Constructor<T>[]): this is T { return typeChecks.some(x => this instanceof x); } /** * Retrieve the set of defined variants for this element class */ static get variants() : VariantDefinition[] { return (<Object>this).hasOwnProperty('ownVariants') ? this.ownVariants : []; } /** * Retrieve the set of variants for this specific class, excluding those * of its superclasses */ static ownVariants : VariantDefinition[]; /** * Retrieve the syntax defined for this specific class, excluding the syntax * defined by its superclasses */ static ownSyntax : FieldDefinition[]; #parent : BitstreamElement; /** * Retrieve the element which contains this element, if any */ get parent() { return this.#parent; } /** * Set the parent element of this element */ set parent(value) { this.#parent = value; } #readFields : (string | symbol)[] = []; #isBeingRead : boolean; /** * True when this element is currently being read, false otherwise */ get isBeingRead() { return this.#isBeingRead; } /** * Set whether this element is currently being read */ set isBeingRead(value : boolean) { this.#isBeingRead = value; } /** * Retrieve the set of field names which has been read so far */ get readFields() { return this.#readFields; } #fieldBeingComputed : FieldDefinition; #fieldBeingComputedIntrospectable : boolean; /** * Determine if the field currently being computed is introspectable, * meaning that the bits it has read so far will be considered during measurement, * even though it possibly has not finished reading all bits it will read yet * @returns */ getFieldBeingComputedIntrospectable() { return this.#fieldBeingComputedIntrospectable; } /** * Get the definition of the field currently being computed, if any. * @returns */ getFieldBeingComputed() { return this.#fieldBeingComputed; } /** * Convert this element to a JSON-compatible representation which contains * only the fields defined on the element (aka its "syntax") */ toJSON() { return this.syntax .map(s => [s.name, this[s.name]]) .reduce((pv, [k, v]) => (pv[k] = v, pv), {}); } /** * Run the given callback while in a state where the given field is considered to be the one "being computed", * which is primarily used to enable the current size of arrays as they are read in cases where the count of * items in the array is dependent on the overall bitlength of the previous elements that have been read. See * the `hasMore` option of ArrayOptions * * @param field The field being computed * @param callback The function to run * @param introspectable When true, the computed field is marked as introspectable */ runWithFieldBeingComputed<T>(field : FieldDefinition, callback : () => T, introspectable? : boolean) { let before = this.getFieldBeingComputed(); let beforeIntrospectable = this.getFieldBeingComputedIntrospectable(); try { this.#fieldBeingComputed = field; this.#fieldBeingComputedIntrospectable = introspectable; return callback(); } finally { this.#fieldBeingComputed = before; this.#fieldBeingComputedIntrospectable = beforeIntrospectable; } } /** * Get the "syntax" of this element instance; this is the set of fields that compose the element, in order. */ get syntax() : FieldDefinition[] { return (this.constructor as any).syntax; } /** * Get the "syntax" of this element instance excluding syntax defined by its superclasses; this is the * set of fields that compose the elemnet, in order. */ get ownSyntax() : FieldDefinition[] { return (this.constructor as any).ownSyntax; } private leftPad(num : number | string, digits : number = 4) { let str = `${num}`; while (str.length < digits) str = ` ${str}`; return str; } private rightPad(num : number | string, digits : number = 4) { let str = `${num}`; while (str.length < digits) str = `${str} `; return str; } private zeroPad(num : number | string, digits : number = 4) { let str = `${num}`; while (str.length < digits) str = `0${str}`; return str; } private isPresent(element : FieldDefinition, instance : this) { if (element.options.presentWhen) { if (!instance.runWithFieldBeingComputed(element, () => element.options.presentWhen(instance))) { return false; } } if (element.options.excludedWhen) { if (instance.runWithFieldBeingComputed(element, () => element.options.excludedWhen(instance))) { return false; } } return true; } /** * Read a specific group of fields from the bitstream and serialize their values into this instance. This is called * by BitstreamElement for you, but can be used when overriding the default read behavior. * @param bitstream The bitstream reader to read from * @param name The name of the group to read. Some special values are accepted: '*' means all fields, '$*' means all * fields defined directly on this class (excluding its superclasses). Other group specifiers starting * with '$' match fields defined directly on this class which are part of the specified group (for * instance '$foo' matches directly defined fields in the 'foo' group). Otherwise, the string is * matched directly against the 'group' option of all fields. * @param variator A function which implements variation of this instance in the case where a `@VariantMarker` is * encountered. The function should determine an appropriate variant and return it; when it does so, * the group will continue to be read after the marker, but the results of reading the field will be * applied to the returned instance instead of this instance * @param options Serialization options that modify how the group is read. Most notably this allows you to skip * specific fields. * @returns The current instance, unless the instance was variated into a subclass, in which case it will be the * variated subclass instance. Because this process can occur, it is important to observe the result * of this function. */ protected *readGroup( bitstream : BitstreamReader, name : string, options? : ReadOptions<this> ) { let wasBeingRead = this.isBeingRead; let instance = this; instance.isBeingRead = true; try { let syntax : FieldDefinition[]; if (name === '*') { // all my fields syntax = this.syntax; } else if (name === '$*') { // all my own fields syntax = this.ownSyntax; } else if (name.startsWith('$')) { // my own fields in group $<group> // if (name !== '*' && element.options.group !== name) let group = name.slice(1); syntax = this.ownSyntax.filter(x => x.options.group === group); } else { // all my fields in group <group> syntax = this.ownSyntax.filter(x => x.options.group === name); } for (let element of syntax) { // Preconditions if (!this.isPresent(element, instance)) continue; if (options?.skip && options.skip.includes(element.name)) continue; if (element.options.isVariantMarker) { if (globalThis.BITSTREAM_TRACE) console.log(`Variating at marker...`); let g = this.variate(bitstream, options.parent, options.field); while (true) { let result = g.next(); if (result.done === false) { yield result.value; } else { instance = result.value; break; } } if (!instance) throw new Error(`Variator did not return a value!`); continue; } // Parsing let traceTimeout; if (globalThis.BITSTREAM_TRACE === true) { traceTimeout = setTimeout(() => { console.log(`[!!] ${element.containingType.name}#${String(element.name)}: Stuck reading!`); }, 5000); } try { let g = element.options.serializer.read(bitstream, element.type, instance, element); let readValue; while (true) { let result = g.next(); if (result.done === false) { yield result.value; } else { readValue = result.value; break; } } if (!element.options.isIgnored) instance[element.name] = readValue; instance.readFields.push(element.name); let displayedValue = `${readValue}`; if (typeof readValue === 'number') { displayedValue = `0x${readValue.toString(16)} [${readValue}]`; } if (globalThis.BITSTREAM_TRACE === true) { try { console.log( `[ + ${ this.leftPad(instance.measureField(element.name), 4) } bit(s) = ${ this.leftPad(Math.floor(instance.measureTo(element.name) / 8), 4) } byte(s), ${ this.leftPad( instance.measureTo(element.name) - Math.floor(instance.measureTo(element.name) / 8)*8 , 4) } bits = ${this.leftPad(instance.measureTo(element.name), 4)} bits total] ` + ` ${this.rightPad(`${element.containingType.name}#${String(element.name)}`, 50)} => ${displayedValue}` ); } catch (e) { console.log(`Error while tracing read operation for element ${String(element.name)}: ${e.message}`); console.error(e); } clearTimeout(traceTimeout); } } catch (thrown) { let e : Error = thrown; if (e.message.startsWith('underrun:')) { throw new Error( `Ran out of bits while deserializing field ${String(element.name)} ` + `in group '${name}' ` + `of element ${instance.constructor.name}` ); } else { throw e; } } } } finally { this.isBeingRead = wasBeingRead; } return instance; } /** * Write a group of fields to the given bitstream writer. This is used by BitstreamElement internally, but it can * be called directly when overriding the default write behavior in a subclass, if desired. * @param bitstream The bitstream writer to write the fields to * @param name The name of the group to write. * @param options Options that modify how the group is written. Most notably this allows you to skip specific * fields. */ protected writeGroup(bitstream : BitstreamWriter, name : string, options? : SerializeOptions) { let syntax = this.syntax; for (let element of syntax) { if (name !== '*' && element.options.group !== name) continue; if (options?.skip && options.skip.includes(element.name)) continue; // Preconditions if (!this.isPresent(element, this)) continue; let writtenValue = this[element.name]; if (element.options.writtenValue) { if (typeof element.options.writtenValue === 'function') { writtenValue = element.options.writtenValue(this, element); } else { writtenValue = element.options.writtenValue; } } try { element.options.serializer.write(bitstream, element.type, this, element, writtenValue); } catch (e) { console.error(`Failed to write field ${element.type.name}#${String(element.name)} using ${element.options.serializer.constructor.name}: ${e.message}`); console.error(e); throw new Error(`Failed to write field ${String(element.name)} using ${element.options.serializer.constructor.name}: ${e.message}`); } } } /** * Read this element from the given bitstream reader, applying the resulting values into this instance. * @param bitstream The reader to read from * @param variator A function which implements variation for this instance. The function should determine an * appropriate variant instance and return it; from there on out the rest of the fields read will * be applied to that instance instead of this instance. * @param options Options which modify how the element is read. Most notably this lets you skip specific fields * @returns The current instance, unless it was variated into a subclass instance, in which case it will be the * variated subclass instance. Thus it is important to observe the result of this method. */ *read(bitstream : BitstreamReader, options? : SerializeOptions) { let g = this.readGroup(bitstream, '*', options); while (true) { let result = g.next(); if (result.done === false) yield result.value; else return result.value; } } /** * Read just the fields that are part of this specific subclass, ignoring the fields that are defined on superclasses. * This is used by BitstreamElement during variation, and is equivalent to readGroup(bitstream, '$*', variator, options) * @param bitstream The reader to read from * @param variator A function which implements variation for this instance. The function should determine an * appropriate variant instance and return it; from there on out the rest of the fields read will * be applied to that instance instead of this instance. * @param options Options which modify how the element is read. Most notably this lets you skip specific fields * @returns The current instance, unless it was variated into a subclass instance, in which case it will be the * variated subclass instance. Thus it is important to observe the result of this method. */ *readOwn(bitstream : BitstreamReader, options? : SerializeOptions) { let g = this.readGroup(bitstream, '$*', options); while (true) { let result = g.next(); if (result.done === false) yield result.value; else return result.value; } } *variate(reader : BitstreamReader, parent? : BitstreamElement, defn? : FieldDefinition): Generator<number, this> { let variantType : typeof BitstreamElement = this.determineVariantType(parent, defn?.options.variants); if (variantType) { let g = variantType.read(reader, parent, defn, this); do { let result = g.next(); if (result.done === false) yield result.value; else return <this> result.value; } while (true); } return this; } /** * Create a new instance of this BitstreamElement subclass by reading the necessary fields from the given * BitstreamReader. * @param this * @param reader The reader to read from * @param parent Specify a parent instance which the new instance is found within * @returns */ static async readBlocking<T extends typeof BitstreamElement>( this : T, reader : BitstreamReader, parent? : BitstreamElement, defn? : FieldDefinition ) : Promise<InstanceType<T>> { let iterator = <Generator<number, InstanceType<T>>> this.read(reader, parent, defn); do { let result = iterator.next(); if (result.done === false) { await reader.assure(result.value); continue; } return result.value; } while (true); } /** * Deserialize an instance of this class from the given * data buffer. Will consider available variants, so the * result could be a subclass. * @param data * @returns */ static async deserialize<T extends typeof BitstreamElement>(this : T, data : Uint8Array): Promise<InstanceType<T>> { let reader = new BitstreamReader(); reader.addBuffer(data); let gen = this.read(reader); while (true) { let result = gen.next(); if (result.done === false) throw new Error(`Buffer exhausted when reading ${result.value} bits`); else return result.value; } } /** * Write this instance to the given writer * @param bitstream The writer to write to * @param options Options which modify how the element is written. Most notably this lets you skip specific fields */ write(bitstream : BitstreamWriter, options? : SerializeOptions) { this.writeGroup(bitstream, '*', options); } /** * Apply the given properties to this object and return ourself. * @param this * @param changes The changes to apply */ with<T>(this : T, changes : Partial<T>): T { Object.assign(this, changes); return this; } /** * Perform a synchronous read operation on the given reader with the given generator. If there are not enough bits available * to complete the operation, this method will throw an exception. * * @param reader * @param generator * @returns */ static readSync<T extends typeof BitstreamElement>(this : T, reader : BitstreamReader, parent? : BitstreamElement): InstanceType<T> { let iterator = <Generator<number, InstanceType<T>>> this.generatedReader(reader, parent); do { let result = iterator.next(); if (result.done === false) throw new Error(`Not enough bits: Reached end of buffer while trying to read ${result.value} bits!`); return result.value; } while (true); } /** * Try to read the bitstream using the given generator function synchronously, if there are not enough bits, abort * and return undefined. * @param reader The reader to read from * @param generator The generator that implements the read operation * @returns The result of the read operation if successful, or undefined if there was not enough bits to complete the operation. */ static tryRead<T extends typeof BitstreamElement>(this : T, reader : BitstreamReader, parent? : BitstreamElement): InstanceType<T> { let instance = new this(); let iterator = <Generator<number, InstanceType<T>>> this.generatedReader(reader, instance, parent); let previouslyRetaining = reader.retainBuffers; reader.retainBuffers = true; let startOffset = reader.offset; do { let result = iterator.next(); if (result.done === false) { // we need more bits, fail reader.offset = startOffset; reader.retainBuffers = previouslyRetaining; return undefined; } return result.value; } while (true); } /** * Try to read the bitstream using the given generator function synchronously, if there are not enough bits, abort * and return undefined. * @param reader The reader to read from * @param generator The generator that implements the read operation * @returns The result of the read operation if successful, or undefined if there was not enough bits to complete the operation. */ static *read<T extends typeof BitstreamElement>( this : T, reader : BitstreamReader, parent? : BitstreamElement, defn? : FieldDefinition, elementBeingVariated? : BitstreamElement ): Generator<number, InstanceType<T>> { let element = new this(); element.parent = parent; let parentStillReading = elementBeingVariated ? elementBeingVariated.isBeingRead : false; element.isBeingRead = true; if (elementBeingVariated) { element.syntax.forEach(f => { if (defn?.options?.skip && defn.options.skip.includes(f.name)) return; if (elementBeingVariated.syntax.some(x => x.name === f.name) && elementBeingVariated.readFields.includes(f.name)) { if (!f.options.isIgnored) element[f.name] = elementBeingVariated[f.name]; element.readFields.push(f.name); } }); let g = element.readOwn(reader, { skip: defn?.options?.skip }); while (true) { let result = g.next(); if (result.done === false) { yield result.value; } else { element = result.value; break; } } } else { let g = element.read(reader, { skip: defn?.options?.skip }); while (true) { let result = g.next(); if (result.done === false) { yield result.value; } else { element = result.value; break; } } } element.isBeingRead = parentStillReading; if (!element.ownSyntax.some(x => x.options.isVariantMarker)) { let g = element.variate(reader, parent, defn); while (true) { let result = g.next(); if (result.done === false) { yield result.value; } else { element = result.value; break; } } } return <InstanceType<T>> element; } private static generateReader() { if (this._generatedReader) return; let elementClass = this; let statements : string[] = []; let F = <FieldDefinition[]>elementClass.syntax; let RL = resolveLength; function rightPad(str : string, length : number) { while (str.length < length) str = `${str} `; return str; } function Rb(len : number, reader : BitstreamReader) { let buf = new Uint8Array(len); for (let i = 0; i < len; ++i) buf[i] = reader.readSync(8); return buf; } function Ex(reader : BitstreamReader, length : number) { return reader.available < length; } statements.push(`let I = instance, R = reader, P = parent, L = 0`, ``); for (let i = 0, max = F.length; i < max; ++i) { let field = F[i]; let name : string; if (typeof field.name === 'symbol') name = `F[${i}].name`; else name = JSON.stringify(field.name); let fieldRef = `I[${name}]`; let statement : string; let fieldAssign = `${fieldRef} = `; if (field.options.isVariantMarker) { // TODO } if (field.options.isIgnored) { fieldAssign = ''; } if (field.options.serializer instanceof ArraySerializer) { statement = `// [ARRAY] Not yet supported!`; } else if (field.options.serializer instanceof StructureSerializer) { (<any>field.type).generateReader(); if (field.type['__reader']) { statement = `${fieldAssign}F[${i}].type.__reader(reader, I)`; } } else if (field.options.serializer instanceof NullSerializer) { statement = `// [MARKER]`; } else if (field.options.serializer instanceof StringSerializer) { statement = `R.readString(L, F[${i}].options.string)`; } else if (field.options.serializer instanceof NumberSerializer) { statement = (`${fieldAssign}R.readSync(L)`); } else if (field.options.serializer instanceof BooleanSerializer) { statement = (`${fieldAssign}!!R.readSync(L)`); } else if (field.options.serializer instanceof BufferSerializer) { statement = `${fieldAssign}Rb(L, R)`; } else { if (field.options.serializer['readSync']) { statement = `${fieldAssign}F[${i}].options.serializer.readSync(R, P, F[${i}])`; } else if (field.options.serializer) { throw new Error(`Serializer ${field.options.serializer.constructor.name} is not compatible with BITSTREAM_READ_MODE=v2 as it does not implement readSync()`); } else { throw new Error(`Field ${String(field.name)} of type ${field.type} has no serializer and no built-in support!`); } } if (field.options?.presentWhen || field.options?.excludedWhen) { let conditions : string[] = []; if (field.options?.presentWhen) conditions.push(`F[${i}].options.presentWhen(I)`); if (field.options?.excludedWhen) conditions.push(`!F[${i}].options.presentWhen(I)`); statement = `if (${conditions.join(' && ')}) ${statement}`; } let length = `RL(F[${i}].length, P, F[${i}])`; statements.push(`/* ${rightPad(`[${field.type.name}] ${String(field.name)}`, 40)} */ ${rightPad(`L = ${length}; if (Ex(R, L)) yield L;`, 30)} ${statement}`); } statements.push(``, `return I`); // reader : BitstreamReader, // parent? : BitstreamElement, // defn? : FieldDefinition, // elementBeingVariated? : BitstreamElement let reader = eval(`(function *read(reader, instance, parent, defn, own) {\n ${statements.map(x => x && !x.includes(' // ') ? `${x};` : x).join("\n ")}\n})`); elementClass['__reader'] = reader; this._generatedReader = reader; } }
the_stack
import { Injectable } from '@angular/core'; // import * as translations from '../utils/translations'; import { TranslateService } from '@ngx-translate/core'; import { environment } from '../../environments/environment'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import { Globals } from '../utils/globals'; import { AppConfigService } from './app-config.service'; import { LoggerService } from '../../chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from '../../chat21-core/providers/logger/loggerInstance'; @Injectable() export class TranslatorService { private defaultLanguage = 'en'; // default language private language: string; // user language private logger: LoggerService = LoggerInstance.getInstance() // private translations: Object; translated_string: any; baseLocation: string; remoteTranslationsUrl: string; constructor( private _translate: TranslateService, public http: Http, public g: Globals, public appConfigService: AppConfigService ) { let windowContext = window; if (window.frameElement && window.frameElement.getAttribute('tiledesk_context') === 'parent') { windowContext = window.parent; } if (windowContext['tiledesk']) { this.baseLocation = windowContext['tiledesk'].getBaseLocation(); // console.log(`»»»» initI18n baseLocation`, this.baseLocation); } // this.initializeTransaltorService() } /** * * Return the browser language * used by humanWaitingTime in list-conversation * * @returns */ public getLanguage() { return this.language; // return this._translate.getBrowserLang(); } /** @unused method not used */ initializeTransaltorService() { this._translate.setDefaultLang('it'); const browserLang = this._translate.getBrowserLang(); this.logger.debug('[TRANSLATOR-SERV] initializeTransaltorService--> DEVICE LANG ', browserLang); if (browserLang) { if (browserLang === 'it') { this._translate.use('it'); this.http.get(this.baseLocation + `/assets/i18n/${browserLang}.json`).subscribe(data=> { console.log('ress lang', JSON.parse(data['_body'])) this._translate.setTranslation('it', JSON.parse(data['_body'])); this._translate.get('LABEL_PREVIEW').subscribe(res => { console.log('default translate --> ', res) }); }) // this._translate.setTranslation('it', './assets/i18n/en.json') } else { this._translate.use('en'); // this.http.get(this.baseLocation + `/assets/i18n/${browserLang}.json`).subscribe(data=> console.log('ress lang', data)) } } } getTranslationFileUrl(browserLang) { this.remoteTranslationsUrl = environment.remoteTranslationsUrl; // console.log(`»»»» initI18n remoteTranslationsUrl`, this.remoteTranslationsUrl); const remoteTranslationsUrl = this.appConfigService.getConfig().remoteTranslationsUrl; if (remoteTranslationsUrl) { this.remoteTranslationsUrl = remoteTranslationsUrl; } // console.log(`»»»» initI18n remoteTranslationsUrl2`, this.appConfigService.getConfig()); // console.log(`»»»» getTranslationFileUrl `, this.remoteTranslationsUrl); if (environment.loadRemoteTranslations) { return this.remoteTranslationsUrl + this.g.projectid + '/labels/' + browserLang.toUpperCase(); } else { return this.baseLocation + `/assets/i18n/${browserLang}.json`; } } // https://github.com/ngx-translate/core/issues/282 initI18n(): Promise<any> { this._translate.addLangs(['en', 'it']); this.logger.debug('[TRANSLATOR-SERV]»»»» initI18n getLangs ', this._translate.getLangs()); // Set the default language for translation strings. const defaultLanguage = 'en'; this.logger.debug('[TRANSLATOR-SERV] »»»» initI18n setDefaultLang '); this._translate.setDefaultLang(defaultLanguage); this.language = defaultLanguage; // Detect user language. let browserLang = this._translate.getBrowserLang(); if (this.g.lang && this.g.lang !== '') { browserLang = this.g.lang; this.language = this.g.lang } else { this.g.lang = browserLang; } // const languageUrl = this.getTranslationFileUrl(browserLang); // console.log(`»»»» browserLang `, browserLang, this.g.lang, this.getTranslationFileUrl(browserLang)); // Try to load the I18N JSON file for the detected language return new Promise((resolve, reject) => { const that = this; this.http.get(this.getTranslationFileUrl(browserLang)) .catch((error: any) => { // I18N File failed to load, fall back to default language // console.log(`»»»» initI18n !!! Problem with '${browserLang}' language initialization from URL `, error.url, ` - ERROR: `, error); this._translate.use(defaultLanguage); this.http.get(this.getTranslationFileUrl(defaultLanguage)).subscribe((data) => { this.translateWithBrowserLang(data['_body'], defaultLanguage); }, (er) => { // failed to load default language from remote - fall back to local default language this.logger.error('[TRANSLATOR-SERV] »»»» initI18n Get default language - ERROR ', er); this.logger.error('[TRANSLATOR-SERV] »»»» initI18n - »»» loadRemoteTranslations IN ERROR ?', environment.loadRemoteTranslations); }, () => { resolve(true); // console.log('»»»» initI18n Get default language * COMPLETE *'); }); return Observable.throw(error); }) .subscribe((data) => { // I18N File loaded successfully, we can proceed // console.log(`»»»» Successfully initialized '${browserLang}' language.'`, data); this.logger.debug(`[TRANSLATOR-SERV] »»»» initI18n Successfully initialized '${browserLang}' language from URL'`, data.url); if (!data._body || data._body === undefined || data._body === '') { browserLang = defaultLanguage; this.language = defaultLanguage; this.g.lang = defaultLanguage; this._translate.use(defaultLanguage); // console.log('»»»» translateWithBrowserLang ', this.getTranslationFileUrl(defaultLanguage)); this.http.get(this.getTranslationFileUrl(defaultLanguage)).subscribe((defaultdata) => { // console.log(`»»»» Successfully initialized '${browserLang}' language.'`, defaultdata); this.translateWithBrowserLang(defaultdata['_body'], browserLang); }); } else { // console.log(`»»»» translateWithBrowserLang '${browserLang}' language.'`); this.language = JSON.parse(data._body).lang.toLowerCase();; this.translateWithBrowserLang(data._body, this.language); } }, (error) => { this.logger.error(`[TRANSLATOR-SERV] »»»» initI18n Get '${browserLang}' language - ERROR `, error); }, () => { resolve(true); // console.log(`»»»» initI18n Get '${browserLang}' language - COMPLETE`); }); }); } private translateWithBrowserLang(body: any, lang: string) { this._translate.use(lang); this.logger.debug(`[TRANSLATOR-SERV] »»»» initI18n - »»» loadRemoteTranslations ?`, environment.loadRemoteTranslations); if (environment.loadRemoteTranslations) { const remote_translation_res = JSON.parse(body); // console.log(`»»»» initI18n - »»» remote translation response`, remote_translation_res); // console.log(`»»»» initI18n - »»» remote translation `, remote_translation_res.data); this._translate.setTranslation(lang, remote_translation_res.data, true); } else { this._translate.setTranslation(lang, JSON.parse(body), true); } } /** */ public translate(globals) { // set language // this.setLanguage(globals.windowContext, globals.lang); const labels: string[] = [ 'LABEL_TU', 'LABEL_PLACEHOLDER', 'LABEL_START_NW_CONV', 'LABEL_FIRST_MSG', 'LABEL_FIRST_MSG_NO_AGENTS', 'LABEL_SELECT_TOPIC', 'LABEL_COMPLETE_FORM', 'LABEL_FIELD_NAME', 'LABEL_ERROR_FIELD_NAME', 'LABEL_FIELD_EMAIL', 'LABEL_ERROR_FIELD_EMAIL', 'LABEL_ERROR_FIELD_REQUIRED', 'LABEL_WRITING', 'LABEL_SEND_NEW_MESSAGE', 'AGENT_NOT_AVAILABLE', 'AGENT_AVAILABLE', 'GUEST_LABEL', 'ALL_AGENTS_OFFLINE_LABEL', 'CALLOUT_TITLE_PLACEHOLDER', 'CALLOUT_MSG_PLACEHOLDER', 'ALERT_LEAVE_CHAT', 'YES', 'NO', 'BUTTON_CLOSE_TO_ICON', 'BUTTON_EDIT_PROFILE', 'DOWNLOAD_TRANSCRIPT', 'RATE_CHAT', 'WELLCOME_TITLE', 'WELLCOME_MSG', 'OPTIONS', 'SOUND_ON', 'SOUND_OFF', 'LOGOUT', 'CUSTOMER_SATISFACTION', 'YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE', 'YOUR_RATING', 'WRITE_YOUR_OPINION', 'SUBMIT', 'THANK_YOU_FOR_YOUR_EVALUATION', 'YOUR_RATING_HAS_BEEN_RECEIVED', 'CLOSE', 'PREV_CONVERSATIONS', 'YOU', 'SHOW_ALL_CONV', 'START_A_CONVERSATION', 'NO_CONVERSATION', 'SEE_PREVIOUS', 'WAITING_TIME_FOUND', 'WAITING_TIME_NOT_FOUND', 'CLOSED', 'LABEL_PREVIEW' ]; this._translate.get(labels).subscribe(res => { // console.log('»»»» initI18n »»»»»» »»»»»» GET TRANSLATED LABELS RES ', res); globals.LABEL_TU = res['LABEL_TU'] globals.LABEL_PLACEHOLDER = res['LABEL_PLACEHOLDER'] globals.LABEL_START_NW_CONV = res['LABEL_START_NW_CONV']; globals.LABEL_FIRST_MSG = res['LABEL_FIRST_MSG']; globals.LABEL_FIRST_MSG_NO_AGENTS = res['LABEL_FIRST_MSG_NO_AGENTS']; globals.LABEL_SELECT_TOPIC = res['LABEL_SELECT_TOPIC']; globals.LABEL_COMPLETE_FORM = res['LABEL_COMPLETE_FORM']; globals.LABEL_FIELD_NAME = res['LABEL_FIELD_NAME']; globals.LABEL_ERROR_FIELD_NAME = res['LABEL_ERROR_FIELD_NAME']; globals.LABEL_FIELD_EMAIL = res['LABEL_FIELD_EMAIL']; globals.LABEL_ERROR_FIELD_EMAIL = res['LABEL_ERROR_FIELD_EMAIL']; globals.LABEL_WRITING = res['LABEL_WRITING']; globals.LABEL_SEND_NEW_MESSAGE = res['LABEL_SEND_NEW_MESSAGE']; globals.AGENT_NOT_AVAILABLE = res['AGENT_NOT_AVAILABLE']; // is used ?? globals.AGENT_AVAILABLE = res['AGENT_AVAILABLE']; globals.GUEST_LABEL = res['GUEST_LABEL']; globals.ALL_AGENTS_OFFLINE_LABEL = res['ALL_AGENTS_OFFLINE_LABEL']; globals.CALLOUT_TITLE_PLACEHOLDER = res['CALLOUT_TITLE_PLACEHOLDER']; globals.CALLOUT_MSG_PLACEHOLDER = res['CALLOUT_MSG_PLACEHOLDER']; globals.ALERT_LEAVE_CHAT = res['ALERT_LEAVE_CHAT']; // is used ?? globals.YES = res['YES']; // is used ?? globals.NO = res['NO']; // is used ?? globals.BUTTON_CLOSE_TO_ICON = res['BUTTON_CLOSE_TO_ICON']; globals.BUTTON_EDIT_PROFILE = res['BUTTON_EDIT_PROFILE']; // is used ?? globals.DOWNLOAD_TRANSCRIPT = res['DOWNLOAD_TRANSCRIPT']; globals.RATE_CHAT = res['RATE_CHAT']; // is used ?? globals.WELLCOME_TITLE = res['WELLCOME_TITLE']; globals.WELLCOME_MSG = res['WELLCOME_MSG']; globals.OPTIONS = res['OPTIONS']; globals.SOUND_ON = res['SOUND_ON']; globals.SOUND_OFF = res['SOUND_OFF']; globals.LOGOUT = res['LOGOUT']; globals.CUSTOMER_SATISFACTION = res['CUSTOMER_SATISFACTION']; globals.YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE = res['YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE']; globals.YOUR_RATING = res['YOUR_RATING']; // is used ?? globals.WRITE_YOUR_OPINION = res['WRITE_YOUR_OPINION']; globals.SUBMIT = res['SUBMIT']; // se nn si carica la traduzione nn viene visualizzato il testo e si riname bloccati globals.THANK_YOU_FOR_YOUR_EVALUATION = res['THANK_YOU_FOR_YOUR_EVALUATION']; globals.YOUR_RATING_HAS_BEEN_RECEIVED = res['YOUR_RATING_HAS_BEEN_RECEIVED']; globals.CLOSE = res['CLOSE']; // se nn si carica la traduzione nn viene visualizzato il testo e si riname bloccati globals.PREV_CONVERSATIONS = res['PREV_CONVERSATIONS']; globals.YOU = res['YOU']; globals.SHOW_ALL_CONV = res['SHOW_ALL_CONV']; globals.START_A_CONVERSATION = res['START_A_CONVERSATION']; // is used ?? globals.NO_CONVERSATION = res['NO_CONVERSATION']; globals.SEE_PREVIOUS = res['SEE_PREVIOUS']; // is used ?? globals.WAITING_TIME_FOUND = res['WAITING_TIME_FOUND']; globals.WAITING_TIME_NOT_FOUND = res['WAITING_TIME_NOT_FOUND']; globals.CLOSED = res['CLOSED']; globals.LABEL_PREVIEW = res['LABEL_PREVIEW'] globals.LABEL_ERROR_FIELD_REQUIRED= res['LABEL_ERROR_FIELD_REQUIRED'] if (!globals.welcomeTitle) { globals.welcomeTitle = globals.WELLCOME_TITLE; /** Set the widget welcome message. Value type : string */ } if (!globals.welcomeMsg) { globals.welcomeMsg = globals.WELLCOME_MSG; /** Set the widget welcome message. Value type : string */ } }, (error) => { this.logger.error('[TRANSLATOR-SERV]»»»»»» »»»»»» GET TRANSLATED LABELS - ERROR ', error); }, () => { // console.log('»»»»»» »»»»»» GET TRANSLATED LABELS * COMPLETE *'); }); // globals.setParameter('lang', this.language); // translate // console.log('»»»»» globals', globals) // globals.LABEL_PLACEHOLDER = this.translateForKey('LABEL_PLACEHOLDER') // done // globals.LABEL_START_NW_CONV = this.translateForKey('LABEL_START_NW_CONV'); // done // globals.LABEL_FIRST_MSG = this.translateForKey('LABEL_FIRST_MSG'); // done // globals.LABEL_FIRST_MSG_NO_AGENTS = this.translateForKey('LABEL_FIRST_MSG_NO_AGENTS'); // done // globals.LABEL_SELECT_TOPIC = this.translateForKey('LABEL_SELECT_TOPIC'); // done // globals.LABEL_COMPLETE_FORM = this.translateForKey('LABEL_COMPLETE_FORM'); // done // globals.LABEL_FIELD_NAME = this.translateForKey('LABEL_FIELD_NAME'); // done // globals.LABEL_ERROR_FIELD_NAME = this.translateForKey('LABEL_ERROR_FIELD_NAME'); // done // globals.LABEL_FIELD_EMAIL = this.translateForKey('LABEL_FIELD_EMAIL'); // done // globals.LABEL_ERROR_FIELD_EMAIL = this.translateForKey('LABEL_ERROR_FIELD_EMAIL'); // done // globals.LABEL_WRITING = this.translateForKey('LABEL_WRITING'); // done // globals.AGENT_NOT_AVAILABLE = this.translateForKey('AGENT_NOT_AVAILABLE'); // done // globals.AGENT_AVAILABLE = this.translateForKey('AGENT_AVAILABLE'); // done // globals.GUEST_LABEL = this.translateForKey('GUEST_LABEL'); // done // globals.ALL_AGENTS_OFFLINE_LABEL = this.translateForKey('ALL_AGENTS_OFFLINE_LABEL'); // done // globals.CALLOUT_TITLE_PLACEHOLDER = this.translateForKey('CALLOUT_TITLE_PLACEHOLDER'); // done // globals.CALLOUT_MSG_PLACEHOLDER = this.translateForKey('CALLOUT_MSG_PLACEHOLDER'); // done // globals.ALERT_LEAVE_CHAT = this.translateForKey('ALERT_LEAVE_CHAT'); // done // globals.YES = this.translateForKey('YES'); // done // globals.NO = this.translateForKey('NO'); // done // globals.BUTTON_CLOSE_TO_ICON = this.translateForKey('BUTTON_CLOSE_TO_ICON'); // done // globals.BUTTON_EDIT_PROFILE = this.translateForKey('BUTTON_EDIT_PROFILE'); // done // globals.DOWNLOAD_TRANSCRIPT = this.translateForKey('DOWNLOAD_TRANSCRIPT'); // done // globals.RATE_CHAT = this.translateForKey('RATE_CHAT'); // done // globals.WELLCOME_TITLE = this.translateForKey('WELLCOME_TITLE'); // done // globals.WELLCOME_MSG = this.translateForKey('WELLCOME_MSG'); // done // globals.OPTIONS = this.translateForKey('OPTIONS'); // done // globals.SOUND_ON = this.translateForKey('SOUND_ON'); // done // globals.SOUND_OFF = this.translateForKey('SOUND_OFF'); // done // globals.LOGOUT = this.translateForKey('LOGOUT'); // done // globals.CUSTOMER_SATISFACTION = this.translateForKey('CUSTOMER_SATISFACTION'); // done // globals.YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE = this.translateForKey('YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE'); // done // globals.DOWNLOAD_TRANSCRIPT = this.translateForKey('DOWNLOAD_TRANSCRIPT'); // done // globals.YOUR_RATING = this.translateForKey('YOUR_RATING'); // done // globals.WRITE_YOUR_OPINION = this.translateForKey('WRITE_YOUR_OPINION'); // done // globals.SUBMIT = this.translateForKey('SUBMIT'); // done // globals.THANK_YOU_FOR_YOUR_EVALUATION = this.translateForKey('THANK_YOU_FOR_YOUR_EVALUATION'); // done // globals.YOUR_RATING_HAS_BEEN_RECEIVED = this.translateForKey('YOUR_RATING_HAS_BEEN_RECEIVED'); // done // globals.CLOSE = this.translateForKey('CLOSE'); // done // globals.PREV_CONVERSATIONS = this.translateForKey('PREV_CONVERSATIONS'); // done // globals.YOU = this.translateForKey('YOU'); // done // globals.SHOW_ALL_CONV = this.translateForKey('SHOW_ALL_CONV'); // done // globals.START_A_CONVERSATION = this.translateForKey('START_A_CONVERSATION'); // done // globals.NO_CONVERSATION = this.translateForKey('NO_CONVERSATION'); // done // globals.SEE_PREVIOUS = this.translateForKey('SEE_PREVIOUS'); // done // globals.WAITING_TIME_FOUND = this.translateForKey('WAITING_TIME_FOUND'); // done // globals.WAITING_TIME_NOT_FOUND = this.translateForKey('WAITING_TIME_NOT_FOUND'); // done // globals.CLOSED = this.translateForKey('CLOSED'); // if (!globals.wellcomeTitle) { // globals.wellcomeTitle = globals.WELLCOME_TITLE; /** Set the widget welcome message. Value type : string */ // } // if (!globals.wellcomeMsg) { // globals.wellcomeMsg = globals.WELLCOME_MSG; /** Set the widget welcome message. Value type : string */ // } } /** * Return the browser language if it is detected, an epty string otherwise * @returns the browser language */ // public getBrowserLanguage(windowContext) { // // console.log('windowContext', windowContext); // const browserLanguage = windowContext.navigator.language; // return !browserLanguage ? undefined : browserLanguage; // } /** * Set the language in which to translate. * If it is provided a not valid language it will use the default language (en) * @param language the language */ // public setLanguage(windowContext, language) { // // console.log('windowContext-language', windowContext, language); // // set the user languge if it is valid. // // if the user language is not valid, try to get the browser language. // // if the browser language is not valid, it use the default language (en) // if (!language) { // // user language not valid // if (this.getBrowserLanguage(windowContext) !== undefined) { // // browser language valid // this.language = this.getBrowserLanguage(windowContext); // } else { // // browser language not valid // this.language = this.defaultLanguage; // } // } else { // // user language valid // this.language = language; // } // this.language = this.language.substring(0, 2); // // retrieve the translation // // console.log('LINGUA IMPOSTATA: ', this.language); // this.getLanguageObject(this.language); // } // retrieve the language object // private getLanguageObject(language) { // if (language === 'en') { // this.translations = translations.en; // } else if (language === 'it') { // this.translations = translations.it; // } else { // // use the default language in any other case // this.translations = translations.en; // } // } /** * Translate a keyword to the language set with the method setLanguage(language) * @param keyword the keyword to translate * @returns the keyword translations */ // public translateForKey(keyword: string): string { // // console.log('this.translations -> keyword: ', this.translations[keyword]); // return !this.translations[keyword] ? '' : this.translations[keyword]; // } // public getDefaultLanguage() { // return this.defaultLanguage; // } }
the_stack
export function getMirrorConfig(stage: string) { if (stage === 'prod') { return [ { name: 'alpine', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.bfsu.edu.cn/alpine/' }, { name: 'apache', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/apache/' }, { name: 'archlinux', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/archlinux/' }, { name: 'archlinuxcn', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/archlinuxcn/' }, { name: 'archlinuxarm', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/archlinuxarm/' }, { name: 'elrepo', interval: 720, provider: 'rsync', upstream: 'rsync://ftp.yz.yamagata-u.ac.jp/pub/linux/RPMS/elrepo/' }, { name: 'epel', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/epel/' }, { name: 'centos', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/centos/' }, { name: 'centos-altarch', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/centos-altarch/' }, { name: 'debian', interval: 720, retry: 100, provider: 'rsync', upstream: 'rsync://mirrors.bfsu.edu.cn/debian/', rsync_options: ['"--no-H"'] }, { name: 'debian-security', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/debian-security/' }, { name: 'docker-ce', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/docker-ce/' }, { name: 'fedora', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/fedora/' }, { name: 'gitlab-ce', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/' }, { name: 'gitlab-runner', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/gitlab-runner/' }, { name: 'grafana', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/grafana/' }, { name: 'jenkins', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/jenkins/' }, { name: 'kubernetes', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/kubernetes/' }, { name: 'linuxmint', interval: 1440, provider: 'two-stage-rsync', stage1_profile: 'debian', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/linuxmint/', rsync_options: ['"--delete-excluded"'] }, { name: 'mariadb', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/mariadb/' }, { name: 'mongodb', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/mongodb/' }, { name: 'mysql', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/mysql/' }, { name: 'nodejs-release', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/nodejs-release/' }, { name: 'opensuse', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.bfsu.edu.cn/opensuse/' }, { name: 'pypi', /** * For unified cloudwatch agent to ingest multiple line logs, * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html#CloudWatch-Agent-Configuration-File-Logssection */ logStartPattern: '^\\\\\\\\d{4}-\\\\\\\\d{2}-\\\\\\\\d{2}\\\\\\\\s\\\\\\\\d{2}:\\\\\\\\d{2}:\\\\\\\\d{2},\\\\\\\\d{3}', timeFormat: '%Y-%m-%d %H:%M:%S', provider: 'command', upstream: 'https://pypi.python.org/', command: '$TUNASCRIPT_PATH/pypi.sh', interval: 5, envs: [ 'INIT = "0"', ] }, { name: 'raspbian', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/raspbian/' }, { name: 'raspberrypi', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/raspberrypi/' }, { name: 'rubygems', interval: 60, provider: 'command', upstream: 'https://mirrors.tuna.tsinghua.edu.cn/rubygems/', command: '$TUNASCRIPT_PATH/rubygems-s3.sh', docker_image: 'tunathu/rubygems-mirror-s3:release-v1.4.5', docker_volumes: ['"/tunasync-scripts/rubygems-s3.sh:/tunasync-scripts/rubygems-s3.sh:ro"'], envs: [ 'S3_BUCKET = "++TUNA_REPO_BUCKET++"', ], }, { name: 'ubuntu', interval: 720, provider: 'two-stage-rsync', stage1_profile: 'debian', upstream: 'rsync://archive.ubuntu.com/ubuntu/', rsync_options: ['"--delete-excluded"',] }, { name: 'ubuntu-cdimage', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.bfsu.edu.cn/ubuntu-cdimage/' }, { name: 'ubuntu-releases', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.bfsu.edu.cn/ubuntu-releases/' }, { name: 'bioconductor', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/bioconductor/' }, { name: 'CPAN', interval: 720, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/CPAN/' }, { name: 'CRAN', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/CRAN/' }, { name: 'CTAN', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/CTAN/' }, { name: 'ceph', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/ceph/' }, { name: 'chef', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/chef/' }, { name: 'clickhouse', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/clickhouse/' }, { name: 'clojars', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/clojars/' }, { name: 'dart-pub', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/dart-pub/' }, { name: 'elasticstack', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/elasticstack/' }, { name: 'erlang-solutions', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/erlang-solutions/' }, { name: 'flutter', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/flutter/' }, { name: 'hackage', interval: 120, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/hackage/' }, { name: 'influxdata', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/influxdata/' }, { name: 'julia', interval: 60, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/julia/' }, { name: 'julia-releases', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/julia-releases/' }, { name: 'libreoffice', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/libreoffice/' }, { name: 'openresty', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/openresty/' }, { name: 'rustup', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/rustup/' }, { name: 'sagemath', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/sagemath/' }, { name: 'saltstack', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/saltstack/' }, { name: 'zabbix', interval: 1440, provider: 'rsync', upstream: 'rsync://mirrors.tuna.tsinghua.edu.cn/zabbix/' }, ]; } else { return [ { name: 'elrepo', interval: 720, provider: 'rsync', retry: 10, upstream: 'rsync://ftp.yz.yamagata-u.ac.jp/pub/linux/RPMS/elrepo/' }, { name: 'pypi', /** * For unified cloudwatch agent to ingest multiple line logs, * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html#CloudWatch-Agent-Configuration-File-Logssection */ logStartPattern: '^\\\\\\\\d{4}-\\\\\\\\d{2}-\\\\\\\\d{2}\\\\\\\\s\\\\\\\\d{2}:\\\\\\\\d{2}:\\\\\\\\d{2},\\\\\\\\d{3}', timeFormat: '%Y-%m-%d %H:%M:%S', provider: 'command', upstream: 'https://pypi.python.org/', command: '$TUNASCRIPT_PATH/pypi.sh', interval: 5, envs: [ 'INIT = "0"', ] }]; } } export function getMirrorTestingConfig(stage: string, domainName: string) { if (stage === 'prod') { return [{ name: 'Ubuntu', repo: 'ubuntu', images: ['ubuntu:18.04', 'ubuntu:20.04'], commands: [ `sed -E -i "s/(archive.ubuntu.com|security.ubuntu.com)/${domainName}/" /etc/apt/sources.list`, 'apt update', ] }, { name: 'Debian', repo: 'debian', images: ['debian:stable', 'debian:testing'], commands: [ `sed -E -i "s/(deb.debian.org|security.debian.org)/${domainName}/" /etc/apt/sources.list`, 'apt update', ] }, { name: 'CentOS', repo: 'centos', images: ['centos:8', 'centos:7'], commands: [ `sed -i 's/mirrorlist/#mirrorlist/;s/#baseurl=http:\\/\\/mirror.centos.org/baseurl=https:\\/\\/${domainName}/' /etc/yum.repos.d/CentOS-*.repo`, 'yum makecache', ] }, { name: 'Fedora', repo: 'fedora', images: ['fedora:32', 'fedora:33'], commands: [ `sed -i 's/metalink/#metalink/;s/#baseurl=http:\\/\\/download.example\\/pub\\/fedora\\/linux/baseurl=https:\\/\\/${domainName}\\/fedora/' /etc/yum.repos.d/fedora{,-updates,-modular,-updates-modular}.repo`, 'yum makecache', ] }, { name: 'Alpine', repo: 'alpine', images: ['alpine:3.9', 'alpine:3.11', 'alpine:3.12'], commands: [ `sed -i 's/dl-cdn.alpinelinux.org/${domainName}/g' /etc/apk/repositories`, 'apk update', ] }, { name: 'ELRepo', repo: 'elrepo', images: ['centos:7'], commands: [ `sed -i 's/mirrorlist/#mirrorlist/;s/#baseurl=http:\\/\\/mirror.centos.org/baseurl=https:\\/\\/${domainName}/' /etc/yum.repos.d/CentOS-*.repo`, 'rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org', 'yum install -y https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm', `sed -i 's/mirrorlist/#mirrorlist/;s/elrepo.org\\/linux/${domainName}\\/elrepo/' /etc/yum.repos.d/elrepo.repo`, "yum makecache", ] }]; } else { return [{ name: 'ELRepo', repo: 'elrepo', images: ['centos:7'], commands: [ 'rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org', 'yum install -y https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm', `sed -i 's/mirrorlist/#mirrorlist/;s/elrepo.org\\/linux/${domainName}\\/elrepo/' /etc/yum.repos.d/elrepo.repo`, "yum makecache", ] }]; } }
the_stack
import { convertLatexToMarkup } from '../src/mathlive'; function markupAndError(formula: string): [string, string] { let errorCode = 'no-error'; const markup = convertLatexToMarkup(formula, { mathstyle: 'displaystyle', onError: (err) => { if (errorCode === 'no-error') { // Catch the first error only errorCode = err.code; } }, }); return [markup, errorCode]; } function error(expression: string) { return markupAndError(expression)[1]; } describe('MODE SHIFT', () => { test.each(['\\text{\\ensuremath{\\frac34}}'])( '%#/ %s renders correctly', (a) => { expect(markupAndError(a)).toMatchSnapshot(); } ); }); describe('FONTS', () => { test.each([ '\\alpha + x - 1 - \\Gamma', '\\alpha + x - 1 - \\Gamma', '\\alpha + x - 1 - \\Gamma', '\\alpha + x - 1 - \\Gamma', '\\mathfrak{\\sin}', ])('%#/ %s renders correctly', (a) => { expect(markupAndError(a)).toMatchSnapshot(); }); }); describe('BINARY OPERATORS', () => { test.each([ 'a+b', 'f(a)+f(b)', 'x^n+y^n', '+b', '(+b', '=+b', '\\sin+b', ', +b', '\\textcolor{red}{a}+b', '\\textcolor{red}{a=}+b', ])('%#/ %s renders corectly', (a) => { expect(markupAndError(a)).toMatchSnapshot(); }); }); describe('FRACTIONS', function () { test.each([ '\\frac57', '\\frac {5} {7}', '\\frac {\\frac57} {\\frac37}', '\\[ 1 + \\frac{q^2}{(1-q)}+\\frac{q^6}{(1-q)(1-q^2)}+\\cdots = \\prod_{j=0}^{\\infty}\\frac{1}{(1-q^{5j+2})(1-q^{5j+3})}, \\quad\\quad \\text{for $|q|<1$}. \\]', '\\binom{n}{k}', '\\dbinom{n}{k}', '\\tbinom{n}{k}', 'n \\choose k', '\\pdiff{f(x)}{x}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); describe('RULE AND DIMENSIONS', function () { test.each([ '\\rule{1em}{2em}', '\\rule[1em]{1em}{2em}', '\\rule{1em}', '\\rule{-1em}{+10em}', '\\rule{0}{4}', '\\rule{1245.5667em}{2902929,292929em}', '\\rule{5mm}{7mm}', '\\rule{5cm}{7cm}', '\\rule{5ex}{7ex}', '\\rule{5em}{7em}', '\\rule{5bp}{7bp}', '\\rule{5dd}{7dd}', '\\rule{5pc}{7pc}', '\\rule{5in}{7in}', '\\rule{5mu}{7mu}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); test.each([ ['\\rule{10}{10pt}', '\\rule{10pt}{10pt}'], ['\\rule{+10em}{+ 10 em}', '\\rule{10em}{10em}'], ["\\rule{'12em}{10em}", '\\rule{10em}{10em}'], ["\\rule{'12.9999em}{10em}", '\\rule{10pt}{10em}'], ['\\rule{"A em}{10em}', '\\rule{10em}{10em}'], ])('%#/ %s matches %s', (a, b) => { expect(convertLatexToMarkup(a)).toMatch(convertLatexToMarkup(b)); }); // However, TeX doesn't parse it either... Actually, TeX doesn't even parse "a2em // For TeX, hex digits have to be uppercase. Interestingly, TeX cannot parse // '\\rule{\"A EM}{10em}' (the AE confuses it) }); describe('BOX', () => { test.each([ '-\\bbox{\\sqrt{\\frac{2}{1+x}}}-', '-\\bbox[border:solid 1px red]{\\sqrt{\\frac{2}{1+x}}}-', '-\\bbox[yellow]{\\sqrt{\\frac{2}{1+x}}}-', '-\\bbox[yellow]{\\sqrt{\\frac{2}{1+x}}}-', '-\\bbox[ yellow , border: 1px solid red, 4 em ]{\\sqrt{\\frac{2}{1+x}}}-', // '-\\bbox[4em,border: 1px solid red,yellow]{\\sqrt{\\frac{\\frac{2}{\\frac{3}{\\frac{4}{\\frac{5}{\\frac{6}{\\frac{7}{\\frac{8}{\\frac{9}{\\frac{a}{\\frac{b}{\\frac{x}{\\frac{s}{d}}}}}}}}}}}}}{1+x}}}-', '\\rlap{x}o', '\\mathrlap{x}o', '\\llap{x}o', '\\mathllap{x}o', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); describe('OVER/UNDERLINE', () => { test.each([ 'a\\overline{x}b', '\\overline{xyz}\\overline{1+\\frac34}\\underline{abc}\\underline{\\frac57}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); describe('SPACING AND KERN', () => { test.each([ 'a\\hskip 3em b', 'a\\kern 3em b', 'a\\hspace{3em} b', 'a\\hskip 3em b', '+-a+b=c+-d=x^{2-\\frac{1}{2}}', '\\sqrt[\\placeholder{}]{x}\\scriptstyle \\sqrt[\\placeholder{}]{x}', 'x \\scriptstyle x', '\\vec{x} \\scriptstyle \\vec{x}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); function testLeftRightDelimiter(openDel, closeDel) { // Regular sized delimiters test('Delimiters ' + openDel + ' ' + closeDel, () => { expect( markupAndError('\\left' + openDel + ' x + 1' + '\\right' + closeDel) ).toMatchSnapshot(); // Delimiters with large expression expect( markupAndError( '\\left' + openDel + ' x \\frac{\\frac34}{\\frac57}' + '\\right' + closeDel ) ).toMatchSnapshot(); }); } describe('SUPERSCRIPT/SUBSCRIPT', () => { test('-1-\\frac56-1-x^{2-\\frac34}', () => { expect(markupAndError('-1-\\frac56-1-x^{2-\\frac34}')).toMatchSnapshot(); }); }); // //////////////////////////////////////////////////////////////////////////////// describe('LEFT/RIGHT', () => { [ ['(', ')'], ['{(}', '{)}'], ['.', '.'], ['\\lfloor', '\\rfloor'], ['\\ulcorner', '\\urcorner'], ['\\uparrow', '\\Downarrow'], ['\\downarrow', '\\vert'], ['\\langle', '\\rangle'], ['<', '>'], ['\\vert', '\\vert'], ['\\lvert', '\\rvert'], ['\\Vert', '\\Vert'], ['\\lVert', '\\rVert'], ['\\|', '|'], ['\\uparrow', '\\downarrow'], ['\\Downarrow', '\\Uparrow'], ['\\Updownarrow', '\\updownarrow'], ['\\lbrack', '\\rbrack'], ['\\lfloor', '\\rfloor'], ['\\lceil', '\\rceil'], ['(', ')'], ['\\{', '\\}'], ['\\lbrace', '\\rbrace'], ['\\lgroup', '\\rgroup'], ['\\lmoustache', '\\rmoustache'], ['\\surd', '\\surd'], ].forEach((x) => { const [openDelim, closeDelim] = x; testLeftRightDelimiter(openDelim, closeDelim); }); test('invalid delimiters', () => { expect(error('\\left a\\right)')).toMatch('unexpected-delimiter'); expect(error('\\left0\\right)')).toMatch('unexpected-delimiter'); }); test('middle delimiters', () => { expect(markupAndError('\\left(a\\middle|b\\right)')).toMatchSnapshot(); expect(markupAndError('\\left(a\\middle xb\\right)')).toMatchSnapshot(); }); }); describe('DELIMTIER SIZING COMMANDS', () => { test.each([ ['\\bigl', '\\bigr', '\\bigm', '\\big'], ['\\Bigl', '\\Bigr', '\\Bigm', '\\Big'], ['\\biggl', '\\biggr', '\\biggm', '\\bigg'], ['\\Biggl', '\\Biggr', '\\Biggm', '\\Bigg'], ])('%#/ sizing command %s, %s, %s, %s', (a, b, c, d) => { expect( markupAndError(`${a}(x${c}|y${b}) = x+${d}x${d}+`) ).toMatchSnapshot(); }); }); describe('SIZING COMMANDS', function () { test.each([ '\\text{a \\tiny x y}b', '\\mbox{a \\tiny x y}b', '\\binom12 \\sqrt[3]{x} \\Huge \\sqrt[3]{x} \\binom56 x \\text{text is huge}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); // //////////////////////////////////////////////////////////////////////////////// describe('ENVIRONMENTS', function () { test.each([ '\\begin{bmatrix}a & b & c\\end{bmatrix}', '\\begin{bmatrix}a & b & c\\\\ d & e & f\\end{bmatrix}', '\\begin{bmatrix}a & b & c\\\\ d \\end{bmatrix}', '\\begin{bmatrix}a & b & c\\\\ d \\\\ g & h & i & j\\end{bmatrix}', '\\begin{array}{ll}xyz & abc & 123 \\\\ cde & fgh \\end{array}', '\\begin{Bmatrix}a & b & c\\end{Bmatrix}', '\\begin{pmatrix}a & b & c\\end{pmatrix}', '\\begin{cases}\\sum_n^{100}+\\frac{x-y}{4}=\\frac{4-y}{8}\\\\-\\frac{y+3}{8}=\\frac{1-2x}{8}+\\sum_n^{100}\\end{cases}', '\\begin{dcases}\\sum_n^{100}+\\frac{x-y}{4}=\\frac{4-y}{8}\\\\-\\frac{y+3}{8}=\\frac{1-2x}{8}+\\sum_n^{100}\\end{dcases}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); test.each([ '\\begin', '\\begin{a}', '\\begin{a}\\end', '\\begin{a}\\end{x}', '\\begin{a}\\end{a}', '\\begin{array}{ll}\\end{a}', '\\begin{array}{ll}xyz\\end{a}', '\\begin{array}{ll}xyz', '\\begin{array}{ll}xyz', '\\begin{\\alpha}', '\\begin{.}\\end{.}', '\\begin{(}\\end{(}', ])('%#/ %s errors', (x) => { expect(error(x)).toMatchSnapshot(); }); }); // //////////////////////////////////////////////////////////////////////////////// describe('SURDS', function () { test.each([ '\\sqrt5', '\\sqrt{}', 'ax^2+bx+c = a \\left( x - \\frac{-b + \\sqrt {b^2-4ac}}{2a} \\right) \\left( x - \\frac{-b - \\sqrt {b^2-4ac}}{2a} \\right)', '\\sqrt[3]{5}', '\\sqrt[3]5', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); // //////////////////////////////////////////////////////////////////////////////// describe('ACCENTS', function () { test.each([ '\\vec', '\\acute', '\\grave', '\\dot', '\\ddot', '\\tilde', '\\bar', '\\breve', '\\check', '\\hat', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(`${x}{x}${x}{x + 1}${x}`)).toMatchSnapshot(); }); }); // The `\not`, `\ne` and `\neq` commands have special encoding to // handle the fact that the fonts don't have a ≠ glyph... describe('NOT', () => { test.each([ 'a \\ne b', 'a \\neq b', 'a\\not= b', 'a\\not< b', 'a\\not{c} b', 'a\\not{cd} b', 'a\\not{<} b', 'a\\not{<>} b', 'a\\not{} b', 'a\\not', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); // //////////////////////////////////////////////////////////////////////////////// // // describe('PHANTOM', function () {}); // //////////////////////////////////////////////////////////////////////////////// describe('COLORS', function () { test.each([ '\\sin x \\textcolor{#f00}{red} \\colorbox{yellow}{x + \\frac1{\\frac34}} \\textcolor{m1}{\\blacktriangle}\\textcolor{m2}{\\blacktriangle}\\textcolor{m3}{\\blacktriangle}\\textcolor{m4}{\\blacktriangle}\\textcolor{m5}{\\blacktriangle}\\textcolor{m6}{\\blacktriangle}\\textcolor{m7}{\\blacktriangle}\\textcolor{m8}{\\blacktriangle}\\textcolor{m9}{\\blacktriangle}', 'a+\\colorbox{#f00}{\\frac1{\\frac{a+1}{b+c}}}', 'a+\\colorbox{#f00}{\\frac{\\frac{\\frac{1}{2}}{c}}{\\frac{a+1}{b+c}}}', 'a+\\colorbox{#f00}{\\frac{\\frac{\\frac{1}{2}}{c}}{a}', 'a+\\colorbox{#f00}{\\frac1{\\frac{a+1}{b+c}}}', 'a+\\colorbox{#f00}{\\frac{\\frac{\\frac{1}{2}}{c}}{\\frac{a+1}{b+c}}}', 'a+\\colorbox{#f00}{\\frac{\\frac{\\frac{1}{2}}{c}}{a}', 'a{b\\color{#f00} c}d', 'a\\left(b\\color{#f00} c\\right)d', `{\\color{Apricot}\\blacksquare}{\\color{Aquamarine}\\blacksquare} {\\color{Bittersweet}\\blacksquare}{\\color{Black}\\blacksquare} {\\color{Blue}\\blacksquare}{\\color{BlueGreen}\\blacksquare} {\\color{BlueViolet}\\blacksquare}{\\color{BrickRed}\\blacksquare} {\\color{Brown}\\blacksquare}{\\color{BurntOrange}\\blacksquare} {\\color{CadetBlue}\\blacksquare}{\\color{CarnationPink}\\blacksquare} {\\color{Cerulean}\\blacksquare}{\\color{CornflowerBlue}\\blacksquare} {\\color{Cyan}\\blacksquare}{\\color{Dandelion}\\blacksquare} {\\color{DarkOrchid}\\blacksquare}{\\color{Emerald}\\blacksquare} {\\color{ForestGreen}\\blacksquare}{\\color{Fuchsia}\\blacksquare} {\\color{Goldenrod}\\blacksquare}{\\color{Gray}\\blacksquare} {\\color{Green}\\blacksquare}{\\color{GreenYellow}\\blacksquare} {\\color{JungleGreen}\\blacksquare}{\\color{Lavender}\\blacksquare} {\\color{LimeGreen}\\blacksquare}{\\color{Magenta}\\blacksquare} {\\color{Mahogany}\\blacksquare}{\\color{Maroon}\\blacksquare} {\\color{Melon}\\blacksquare}{\\color{MidnightBlue}\\blacksquare} {\\color{Mulberry}\\blacksquare}{\\color{NavyBlue}\\blacksquare} {\\color{OliveGreen}\\blacksquare}{\\color{Orange}\\blacksquare} {\\color{OrangeRed}\\blacksquare}{\\color{Orchid}\\blacksquare} {\\color{Peach}\\blacksquare}{\\color{Periwinkle}\\blacksquare} {\\color{PineGreen}\\blacksquare}{\\color{Plum}\\blacksquare} {\\color{ProcessBlue}\\blacksquare}{\\color{Purple}\\blacksquare} {\\color{RawSienna}\\blacksquare}{\\color{Red}\\blacksquare} {\\color{RedOrange}\\blacksquare}{\\color{RedViolet}\\blacksquare} {\\color{Rhodamine}\\blacksquare}{\\color{RoyalBlue}\\blacksquare} {\\color{RoyalPurple}\\blacksquare}{\\color{RubineRed}\\blacksquare} {\\color{Salmon}\\blacksquare}{\\color{SeaGreen}\\blacksquare} {\\color{Sepia}\\blacksquare}{\\color{SkyBlue}\\blacksquare} {\\color{SpringGreen}\\blacksquare}{\\color{Tan}\\blacksquare} {\\color{TealBlue}\\blacksquare}{\\color{Thistle}\\blacksquare} {\\color{Turquoise}\\blacksquare}{\\color{Violet}\\blacksquare} {\\color{VioletRed}\\blacksquare}{\\color{White}\\blacksquare} {\\color{WildStrawberry}\\blacksquare}{\\color{Yellow}\\blacksquare} {\\color{YellowGreen}\\blacksquare}{\\color{YellowOrange}\\blacksquare} `, ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); test.each([ 'aquamarine', // Not a valid color name (lowercase) 'rgb(240, 10, 200)', '#33d', '#3130da', 'white', 'Aquamarine', 'm5', '#fff', '#ffffff', '#fCFcfC', 'rgb(255, 255, 255)', 'rgb(255,255,255)', ' rgb ( 255 , 255 , 255 ) ', 'rgb(3.5, 0, 0)', 'rgb(3, 5, 7', 'rgb(125.5, 0.556, -12.5)', 'rgb(xxy)', 'rgb(3, 5)', 'rgb(3, 5, 7, 11)', '#111!50', '#111!50!#fff', '#111!50!#000', '-green!40!yellow', ])('%#/ color format "%s" renders correctly', (x) => { expect(markupAndError(`a\\textcolor{${x}}{x}b`)).toMatchSnapshot(); }); }); describe('EXTENSIONS', function () { test.each([ '\\htmlData{foo=green}{2+\\frac{1}{x}}', '\\htmlData{foo=green, bar}{2+\\frac{1}{x}}', '\\htmlData{foo=green, bar=blue}{2+\\frac{1}{x}}', '\\htmlData{foo bar=green, bar=blue}{2+\\frac{1}{x}}', '\\class{cssClassName}{2+\\frac{1}{x}}', '\\class{css class name}{2+\\frac{1}{x}}', '\\cssId{a-css-id-1234}{2+\\frac{1}{x}}', '\\cssId{a css id 1234}{2+\\frac{1}{x}}', ])('%#/ %s renders correctly', (x) => { expect(markupAndError(x)).toMatchSnapshot(); }); }); // // \cos(|x| + |y|) // // \cos (|\frac {x}{5}|+|\frac {y}{5}|) // // ----------------------------------------------------------- // // Resolved: // // \left(x^2+3y^2\right)e^{-x^2-y^2} // // \left(x^2+3y^2\right)\cdot e^{-x^2-y^2} // // \sin(\pi*x/5)-\tan(x*2) // // \sin \pi \cdot \frac {x}{5}-\tan 2x
the_stack
* @1900-2100区间内的公历、农历互转 * @charset UTF-8 * @Author Jea杨(JJonline@JJonline.Cn) * @Time 2014-7-21 * @Time 2016-8-13 Fixed 2033hex、Attribution Annals * @Time 2016-9-25 Fixed lunar LeapMonth Param Bug * @Version 1.0.2 * @公历转农历:calendar.solar2lunar(1987,11,01); //[you can ignore params of prefix 0] * @农历转公历:calendar.lunar2solar(1987,09,10); //[you can ignore params of prefix 0] */ var calendar = { /** * 农历1900-2100的润大小信息表 * @Array Of Property * @return Hex */ lunarInfo:[0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,//1900-1909 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,//1910-1919 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,//1920-1929 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,//1930-1939 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,//1940-1949 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0,//1950-1959 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,//1960-1969 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6,//1970-1979 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,//1980-1989 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0,//1990-1999 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,//2000-2009 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,//2010-2019 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,//2020-2029 0x05aa0,0x076a3,0x096d0,0x04afb,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,//2030-2039 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0,//2040-2049 /**Add By JJonline@JJonline.Cn**/ 0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50, 0x06b20,0x1a6c4,0x0aae0,//2050-2059 0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4,//2060-2069 0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0,//2070-2079 0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160,//2080-2089 0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252,//2090-2099 0x0d520],//2100 /** * 公历每个月份的天数普通表 * @Array Of Property * @return Number */ solarMonth:[31,28,31,30,31,30,31,31,30,31,30,31], /** * 农历节日 * @return String */ lunarHoliday: { '1-1': '春节', '1-15': '元宵节', '2-2': '龙头节', '5-5': '端午节', '7-7': '七夕节', '7-15': '中元节', '8-15': '中秋节', '9-9': '重阳节', '10-1': '寒衣节', '10-15': '下元节', '12-8': '腊八节', '12-23': '小年', }, /** * 阳历节日 * @return String */ gregorianHoliday: { '1-1': '元旦', '2-14': '情人节', '3-8': '妇女节', '3-12': '植树节', '5-1': '劳动节', '5-4': '青年节', '6-1': '儿童节', '7-1': '建党节', '8-1': '建军节', '9-10': '教师节', '10-1': '国庆节', '12-24': '平安夜', '12-25': '圣诞节', }, /** * 天干地支之天干速查表 * @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"] * @return Cn string */ Gan:["\u7532","\u4e59","\u4e19","\u4e01","\u620a","\u5df1","\u5e9a","\u8f9b","\u58ec","\u7678"], /** * 天干地支之地支速查表 * @Array Of Property * @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"] * @return Cn string */ Zhi:["\u5b50","\u4e11","\u5bc5","\u536f","\u8fb0","\u5df3","\u5348","\u672a","\u7533","\u9149","\u620c","\u4ea5"], /** * 天干地支之地支速查表<=>生肖 * @Array Of Property * @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"] * @return Cn string */ Animals:["\u9f20","\u725b","\u864e","\u5154","\u9f99","\u86c7","\u9a6c","\u7f8a","\u7334","\u9e21","\u72d7","\u732a"], /** * 24节气速查表 * @Array Of Property * @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"] * @return Cn string */ solarTerm:["\u5c0f\u5bd2","\u5927\u5bd2","\u7acb\u6625","\u96e8\u6c34","\u60ca\u86f0","\u6625\u5206","\u6e05\u660e","\u8c37\u96e8","\u7acb\u590f","\u5c0f\u6ee1","\u8292\u79cd","\u590f\u81f3","\u5c0f\u6691","\u5927\u6691","\u7acb\u79cb","\u5904\u6691","\u767d\u9732","\u79cb\u5206","\u5bd2\u9732","\u971c\u964d","\u7acb\u51ac","\u5c0f\u96ea","\u5927\u96ea","\u51ac\u81f3"], /** * 1900-2100各年的24节气日期速查表 * @Array Of Property * @return 0x string For splice */ sTermInfo:['9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf97c3598082c95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f','b027097bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f','97bd0b06bdb0722c965ce1cfcc920f','b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f','97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa','9778397bd19801ec9210c965cc920e','97b6b97bd19801ec95f8c965cc920f', '97bd09801d98082c95f8e1cfcc920f','97bd097bd097c36b0b6fc9210c8dc2','9778397bd197c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e','97bd09801d98082c95f8e1cfcc920f','97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec95f8c965cc920e','97bcf97c3598082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c3598082c95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f','97bd097bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9210c8dc2','9778397bd19801ec9210c9274c920e','97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f','97bd07f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec9210c965cc920e','97bd07f1487f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf7f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c9274c920e','97bcf7f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa','97b6b97bd197c36c9210c9274c920e','97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c920e', '97b6b7f0e47f531b0723b0b6fb0722','7f0e37f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b70c9274c91aa','97b6b7f0e47f531b0723b0b6fb0721','7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2','9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0787b0721','7f0e27f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa','97b6b7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9210c8dc2','977837f0e37f149b0723b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e37f5307f595b0b0bc920fb0722','7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0721','7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2','977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0723b06bd','7f07e7f0e37f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e37f1487f595b0b0bb0b6fb0722','7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0722','7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f531b0b0bb0b6fb0722','7f0e37f0e37f14898082b072297c35','7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f149b0723b0787b0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14998082b0723b06bd', '7f07e7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722','7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd','7f07e7f0e37f14998083b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14898082b0723b02d5','7f07e7f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e36665b66aa89801e9808297c35','665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0722','7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e36665b66a449801e9808297c35','665f67f0e37f14898082b072297c35','7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e26665b66a449801e9808297c35','665f67f0e37f1489801eb072297c35', '7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722'], /** * 数字转中文速查表 * @Array Of Property * @trans ['日','一','二','三','四','五','六','七','八','九','十'] * @return Cn string */ nStr1:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341"], /** * 日期转农历称呼速查表 * @Array Of Property * @trans ['初','十','廿','卅'] * @return Cn string */ nStr2:["\u521d","\u5341","\u5eff","\u5345"], /** * 月份转农历称呼速查表 * @Array Of Property * @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊'] * @return Cn string */ nStr3:["\u6b63","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u51ac","\u814a"], /** * 返回农历y年一整年的总天数 * @param lunar Year * @return Number * @eg:var count = calendar.lYearDays(1987) ;//count=387 */ lYearDays:function(y) { var i, sum = 348; for(i=0x8000; i>0x8; i>>=1) { sum += (calendar.lunarInfo[y-1900] & i)? 1: 0; } return(sum+calendar.leapDays(y)); }, /** * 返回农历y年闰月是哪个月;若y年没有闰月 则返回0 * @param lunar Year * @return Number (0-12) * @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6 */ leapMonth:function(y) { //闰字编码 \u95f0 return(calendar.lunarInfo[y-1900] & 0xf); }, /** * 返回农历y年闰月的天数 若该年没有闰月则返回0 * @param lunar Year * @return Number (0、29、30) * @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29 */ leapDays:function(y) { if(calendar.leapMonth(y)) { return((calendar.lunarInfo[y-1900] & 0x10000)? 30: 29); } return(0); }, /** * 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法 * @param lunar Year * @return Number (-1、29、30) * @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29 */ monthDays:function(y,m) { if(m>12 || m<1) {return -1}//月份参数从1至12,参数错误返回-1 return( (calendar.lunarInfo[y-1900] & (0x10000>>m))? 30: 29 ); }, /** * 返回公历(!)y年m月的天数 * @param solar Year * @return Number (-1、28、29、30、31) * @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30 */ solarDays:function(y,m) { if(m>12 || m<1) {return -1} //若参数错误 返回-1 var ms = m-1; if(ms==1) { //2月份的闰平规律测算后确认返回28或29 return(((y%4 == 0) && (y%100 != 0) || (y%400 == 0))? 29: 28); }else { return(calendar.solarMonth[ms]); } }, /** * 农历年份转换为干支纪年 * @param lYear 农历年的年份数 * @return Cn string */ toGanZhiYear:function(lYear) { var ganKey = (lYear - 3) % 10; var zhiKey = (lYear - 3) % 12; if(ganKey == 0) ganKey = 10;//如果余数为0则为最后一个天干 if(zhiKey == 0) zhiKey = 12;//如果余数为0则为最后一个地支 return calendar.Gan[ganKey-1] + calendar.Zhi[zhiKey-1]; }, /** * 公历月、日判断所属星座 * @param cMonth [description] * @param cDay [description] * @return Cn string */ toAstro:function(cMonth,cDay) { var s = "\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf"; var arr = [20,19,21,21,21,22,23,23,23,23,22,22]; return s.substr(cMonth*2 - (cDay < arr[cMonth-1] ? 2 : 0),2) + "\u5ea7";//座 }, /** * 传入offset偏移量返回干支 * @param offset 相对甲子的偏移量 * @return Cn string */ toGanZhi:function(offset) { return calendar.Gan[offset%10] + calendar.Zhi[offset%12]; }, /** * 传入公历(!)y年获得该年第n个节气的公历日期 * @param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起 * @return day Number * @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春 */ getTerm:function(y,n) { if(y<1900 || y>2100) {return -1;} if(n<1 || n>24) {return -1;} var _table = calendar.sTermInfo[y-1900]; var _info = [ parseInt('0x'+_table.substr(0,5)).toString() , parseInt('0x'+_table.substr(5,5)).toString(), parseInt('0x'+_table.substr(10,5)).toString(), parseInt('0x'+_table.substr(15,5)).toString(), parseInt('0x'+_table.substr(20,5)).toString(), parseInt('0x'+_table.substr(25,5)).toString() ]; var _calday = [ _info[0].substr(0,1), _info[0].substr(1,2), _info[0].substr(3,1), _info[0].substr(4,2), _info[1].substr(0,1), _info[1].substr(1,2), _info[1].substr(3,1), _info[1].substr(4,2), _info[2].substr(0,1), _info[2].substr(1,2), _info[2].substr(3,1), _info[2].substr(4,2), _info[3].substr(0,1), _info[3].substr(1,2), _info[3].substr(3,1), _info[3].substr(4,2), _info[4].substr(0,1), _info[4].substr(1,2), _info[4].substr(3,1), _info[4].substr(4,2), _info[5].substr(0,1), _info[5].substr(1,2), _info[5].substr(3,1), _info[5].substr(4,2), ]; return parseInt(_calday[n-1]); }, /** * 传入农历数字月份返回汉语通俗表示法 * @param lunar month * @return Cn string * @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月' */ toChinaMonth:function(m) { // 月 => \u6708 if(m>12 || m<1) {return -1} //若参数错误 返回-1 var s = calendar.nStr3[m-1]; s+= "\u6708";//加上月字 return s; }, /** * 传入农历日期数字返回汉字表示法 * @param lunar day * @return Cn string * @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一' */ toChinaDay:function(d){ //日 => \u65e5 var s; switch (d) { case 10: s = '\u521d\u5341'; break; case 20: s = '\u4e8c\u5341'; break; break; case 30: s = '\u4e09\u5341'; break; break; default : s = calendar.nStr2[Math.floor(d/10)]; s += calendar.nStr1[d%10]; } return(s); }, /** * 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春” * @param y year * @return Cn string * @eg:var animal = calendar.getAnimal(1987) ;//animal='兔' */ getAnimal: function(y) { return calendar.Animals[(y - 4) % 12] }, /** * 传入阳历年月日获得详细的公历、农历object信息 <=>JSON * @param y solar year * @param m solar month * @param d solar day * @return JSON object * @eg:console.log(calendar.solar2lunar(1987,11,01)); */ solar2lunar:function (y,m,d) { //参数区间1900.1.31~2100.12.31 if(y<1900 || y>2100) {return -1;}//年份限定、上限 if(y==1900&&m==1&&d<31) {return -1;}//下限 if(!y) { //未传参 获得当天 var objDate = new Date(); }else { var objDate = new Date(y,parseInt(m)-1,d) } var i, leap=0, temp=0; //修正ymd参数 var y = objDate.getFullYear(),m = objDate.getMonth()+1,d = objDate.getDate(); var offset = (Date.UTC(objDate.getFullYear(),objDate.getMonth(),objDate.getDate()) - Date.UTC(1900,0,31))/86400000; for(i=1900; i<2101 && offset>0; i++) { temp=calendar.lYearDays(i); offset-=temp; } if(offset<0) { offset+=temp; i--; } //是否今天 var isTodayObj = new Date(),isToday=false; if(isTodayObj.getFullYear()==y && isTodayObj.getMonth()+1==m && isTodayObj.getDate()==d) { isToday = true; } //星期几 var nWeek = objDate.getDay(),cWeek = calendar.nStr1[nWeek]; if(nWeek==0) {nWeek =7;}//数字表示周几顺应天朝周一开始的惯例 //农历年 var year = i; var leap = calendar.leapMonth(i); //闰哪个月 var isLeap = false; //效验闰月 for(i=1; i<13 && offset>0; i++) { //闰月 if(leap>0 && i==(leap+1) && isLeap==false){ --i; isLeap = true; temp = calendar.leapDays(year); //计算农历闰月天数 } else{ temp = calendar.monthDays(year, i);//计算农历普通月天数 } //解除闰月 if(isLeap==true && i==(leap+1)) { isLeap = false; } offset -= temp; } if(offset==0 && leap>0 && i==leap+1) if(isLeap){ isLeap = false; }else{ isLeap = true; --i; } if(offset<0){ offset += temp; --i; } //农历月 var month = i; //农历日 var day = offset + 1; //天干地支处理 var sm = m-1; var gzY = calendar.toGanZhiYear(year); //月柱 1900年1月小寒以前为 丙子月(60进制12) var firstNode = calendar.getTerm(year,(m*2-1));//返回当月「节」为几日开始 var secondNode = calendar.getTerm(year,(m*2));//返回当月「节」为几日开始 //依据12节气修正干支月 var gzM = calendar.toGanZhi((y-1900)*12+m+11); if(d>=firstNode) { gzM = calendar.toGanZhi((y-1900)*12+m+12); } //传入的日期的节气与否 var isTerm = false; var Term = null; if(firstNode==d) { isTerm = true; Term = calendar.solarTerm[m*2-2]; } if(secondNode==d) { isTerm = true; Term = calendar.solarTerm[m*2-1]; } //日柱 当月一日与 1900/1/1 相差天数 var dayCyclical = Date.UTC(y,sm,1,0,0,0,0)/86400000+25567+10; var gzD = calendar.toGanZhi(dayCyclical+d-1); //该日期所属的星座 var astro = calendar.toAstro(m,d); return {'lYear':year,'lMonth':month,'lDay':day,'Animal':calendar.getAnimal(year),'IMonthCn':(isLeap?"\u95f0":'')+calendar.toChinaMonth(month),'IDayCn':calendar.toChinaDay(day),'cYear':y,'cMonth':m,'cDay':d,'gzYear':gzY,'gzMonth':gzM,'gzDay':gzD,'isToday':isToday,'isLeap':isLeap,'nWeek':nWeek,'ncWeek':"\u661f\u671f"+cWeek,'isTerm':isTerm,'Term':Term,'astro':astro}; }, /** * 传入农历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON * @param y lunar year * @param m lunar month * @param d lunar day * @param isLeapMonth lunar month is leap or not.[如果是农历闰月第四个参数赋值true即可] * @return JSON object * @eg:console.log(calendar.lunar2solar(1987,9,10)); */ lunar2solar:function(y,m,d,isLeapMonth) { //参数区间1900.1.31~2100.12.1 var isLeapMonth = !!isLeapMonth; var leapOffset = 0; var leapMonth = calendar.leapMonth(y); var leapDay = calendar.leapDays(y); if(isLeapMonth&&(leapMonth!=m)) {return -1;}//传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 if(y==2100&&m==12&&d>1 || y==1900&&m==1&&d<31) {return -1;}//超出了最大极限值 var day = calendar.monthDays(y,m); var _day = day; //bugFix 2016-9-25 //if month is leap, _day use leapDays method if(isLeapMonth) { _day = calendar.leapDays(y,m); } if(y < 1900 || y > 2100 || d > _day) {return -1;}//参数合法性效验 //计算农历的时间差 var offset = 0; for(var i=1900;i<y;i++) { offset+=calendar.lYearDays(i); } var leap = 0,isAdd= false; for(var i=1;i<m;i++) { leap = calendar.leapMonth(y); if(!isAdd) {//处理闰月 if(leap<=i && leap>0) { offset+=calendar.leapDays(y);isAdd = true; } } offset+=calendar.monthDays(y,i); } //转换闰月农历 需补充该年闰月的前一个月的时差 if(isLeapMonth) {offset+=day;} //1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) var stmap = Date.UTC(1900,1,30,0,0,0); var calObj = new Date((offset+d-31)*86400000+stmap); var cY = calObj.getUTCFullYear(); var cM = calObj.getUTCMonth()+1; var cD = calObj.getUTCDate(); return calendar.solar2lunar(cY,cM,cD); } }; export default calendar;
the_stack
import { setImmediate } from "timers/promises"; import { RequestContext, RequestContextOptions, getRequestContext, } from "@miniflare/shared"; import { TestInputGate, noop, triggerPromise, useServer, waitsForOutputGate, } from "@miniflare/shared-test"; import { CloseEvent, MessageEvent, WebSocket, WebSocketPair, coupleWebSocket, } from "@miniflare/web-sockets"; import test, { ExecutionContext } from "ava"; import StandardWebSocket from "ws"; test("WebSocket: can accept multiple times", (t) => { const webSocket = new WebSocket(); webSocket.accept(); webSocket.accept(); t.pass(); }); test("WebSocket: cannot accept if already coupled", async (t) => { const server = await useServer(t, noop, (ws) => ws.send("test")); const ws = new StandardWebSocket(server.ws); const [webSocket1] = Object.values(new WebSocketPair()); await coupleWebSocket(ws, webSocket1); t.throws(() => webSocket1.accept(), { instanceOf: TypeError, message: "Can't accept() WebSocket that was already used in a response.", }); }); test("WebSocket: sends message to pair", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); const messages1: (string | ArrayBuffer)[] = []; const messages2: (string | ArrayBuffer)[] = []; webSocket1.addEventListener("message", (e) => messages1.push(e.data)); webSocket2.addEventListener("message", (e) => messages2.push(e.data)); webSocket1.send("from1"); await setImmediate(); t.deepEqual(messages1, []); t.deepEqual(messages2, ["from1"]); webSocket2.send("from2"); await setImmediate(); t.deepEqual(messages1, ["from2"]); t.deepEqual(messages2, ["from1"]); }); test("WebSocket: must accept before sending", (t) => { const [webSocket1] = Object.values(new WebSocketPair()); t.throws(() => webSocket1.send("test"), { instanceOf: TypeError, message: "You must call accept() on this WebSocket before sending messages.", }); }); test("WebSocket: queues messages if pair not accepted", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); const messages1: (string | ArrayBuffer)[] = []; const messages2: (string | ArrayBuffer)[] = []; webSocket1.addEventListener("message", (e) => messages1.push(e.data)); webSocket2.addEventListener("message", (e) => messages2.push(e.data)); webSocket1.accept(); webSocket1.send("from1_1"); await setImmediate(); t.deepEqual(messages1, []); t.deepEqual(messages2, []); webSocket2.accept(); webSocket2.send("from2_1"); await setImmediate(); t.deepEqual(messages1, ["from2_1"]); t.deepEqual(messages2, ["from1_1"]); webSocket1.send("from1_2"); webSocket2.send("from2_2"); await setImmediate(); t.deepEqual(messages1, ["from2_1", "from2_2"]); t.deepEqual(messages2, ["from1_1", "from1_2"]); }); test("WebSocket: fails to send message to pair if either side closed", (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); webSocket1.close(); t.throws(() => webSocket1.send("from1"), { instanceOf: Error, message: "Can't call WebSocket send() after close().", }); t.throws(() => webSocket2.send("from2"), { instanceOf: Error, message: "Can't call WebSocket send() after close().", }); }); test("WebSocket: closes both sides of pair", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); const closes: number[] = []; webSocket1.addEventListener("close", () => closes.push(1)); webSocket2.addEventListener("close", () => closes.push(2)); webSocket1.close(); await setImmediate(); // Check both event listeners called once t.deepEqual(closes, [1, 2]); }); test("WebSocket: waits for output gate to open before sending message", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); let event: MessageEvent | undefined; webSocket2.addEventListener("message", (e) => (event = e)); await waitsForOutputGate( t, () => webSocket1.send("test"), () => event ); }); test("WebSocket: waits for output gate to open before closing", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); let event: CloseEvent | undefined; webSocket2.addEventListener("close", (e) => (event = e)); await waitsForOutputGate( t, () => webSocket1.close(), () => event ); }); test("WebSocket: must accept before closing", (t) => { const [webSocket1] = Object.values(new WebSocketPair()); t.throws(() => webSocket1.close(), { instanceOf: TypeError, message: "You must call accept() on this WebSocket before sending messages.", }); }); test("WebSocket: can only call close once", (t) => { const [webSocket1] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket1.close(1000); t.throws(() => webSocket1.close(1000), { instanceOf: TypeError, message: "WebSocket already closed", }); }); test("WebSocket: validates close code", (t) => { const [webSocket1] = Object.values(new WebSocketPair()); webSocket1.accept(); // Try close with invalid code t.throws(() => webSocket1.close(1005 /*No Status Received*/), { instanceOf: TypeError, message: "Invalid WebSocket close code.", }); // Try close with reason without code t.throws(() => webSocket1.close(undefined, "Test Closure"), { instanceOf: TypeError, message: "If you specify a WebSocket close reason, you must also specify a code.", }); }); async function eventDispatchWaitsForInputGate( t: ExecutionContext, addEventListener: (listener: (event: unknown) => void) => void, dispatchEvent: () => void ): Promise<void> { const inputGate = new TestInputGate(); const [openTrigger, openPromise] = triggerPromise<void>(); const events: number[] = []; const promise = inputGate.runWith(() => { // Close input gate (inside runWith as runWith waits for gate to be open // before running closure, so would deadlock if already closed) // noinspection ES6MissingAwait void inputGate.runWithClosed(() => openPromise); return new Promise((resolve) => { addEventListener(resolve); }).then(() => events.push(1)); }); await setImmediate(); // Give enough time for addEventListener to be called dispatchEvent(); await inputGate.waitedPromise; events.push(2); openTrigger(); await promise; t.deepEqual(events, [2, 1]); } test("WebSocket: waits for input gate to open before receiving message", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); await eventDispatchWaitsForInputGate( t, (listener) => webSocket2.addEventListener("message", listener), () => webSocket1.send("test") ); }); test("WebSocket: waits for input gate to open before receiving close event", async (t) => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); await eventDispatchWaitsForInputGate( t, (listener) => webSocket2.addEventListener("close", listener), () => webSocket1.close() ); }); test("WebSocketPair: requires 'new' operator to construct", (t) => { // @ts-expect-error this shouldn't type check t.throws(() => WebSocketPair(), { instanceOf: TypeError, message: /^Failed to construct 'WebSocketPair'/, }); }); // Test WebSocketPair types // eslint-disable-next-line @typescript-eslint/no-unused-vars function testWebSocketPairTypes() { const pair = new WebSocketPair(); let [webSocket1, webSocket2] = Object.values(pair); // @ts-expect-error // eslint-disable-next-line @typescript-eslint/no-unused-vars [webSocket1, webSocket2] = pair; // eslint-disable-next-line @typescript-eslint/no-unused-vars webSocket1 = pair[0]; // @ts-expect-error // eslint-disable-next-line @typescript-eslint/no-unused-vars webSocket2 = pair[2]; } // Test request context subrequest limits function useSubrequest() { getRequestContext()?.incrementSubrequests(); } const ctxOpts: RequestContextOptions = { requestDepth: 5, pipelineDepth: 10 }; function assertSubrequests(t: ExecutionContext, expected: number) { const ctx = getRequestContext(); t.is(ctx?.subrequests, expected); // Also check depths copied across t.is(ctx?.requestDepth, ctxOpts.requestDepth); t.is(ctx?.pipelineDepth, ctxOpts.pipelineDepth); } test("WebSocket: shares subrequest limit for WebSockets in regular worker handler", async (t) => { // Check WebSocket with both ends terminated in same worker handler await new RequestContext(ctxOpts).runWith(async () => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); useSubrequest(); const [trigger, promise] = triggerPromise<void>(); webSocket1.addEventListener("message", () => { assertSubrequests(t, 1); trigger(); }); webSocket2.send("test"); await promise; }); // Check WebSocket with one end terminated in worker and one in client const [trigger, promise] = triggerPromise<void>(); const webSocket2 = await new RequestContext(ctxOpts).runWith(async () => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); useSubrequest(); webSocket1.addEventListener("message", () => { assertSubrequests(t, 1); trigger(); }); return webSocket2; }); webSocket2.accept(); webSocket2.send("test"); await promise; }); test("WebSocket: resets subrequest limit for WebSockets in Durable Object", async (t) => { // Check WebSocket with both ends terminated in same Durable Object const durableOpts: RequestContextOptions = { ...ctxOpts, durableObject: true, }; await new RequestContext(durableOpts).runWith(async () => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); webSocket2.accept(); useSubrequest(); const [trigger, promise] = triggerPromise<void>(); webSocket1.addEventListener("message", () => { assertSubrequests(t, 0); trigger(); }); webSocket2.send("test"); await promise; }); // Check WebSocket with one end terminated in Durable Object and one in fetch handler let [trigger, promise] = triggerPromise<void>(); let webSocket2 = await new RequestContext(durableOpts).runWith(async () => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); useSubrequest(); webSocket1.addEventListener("message", () => { assertSubrequests(t, 0); trigger(); }); return webSocket2; }); new RequestContext(ctxOpts).runWith(() => { webSocket2.accept(); webSocket2.send("test"); }); await promise; // Check WebSocket with one end terminated in Durable Object and one in client [trigger, promise] = triggerPromise<void>(); webSocket2 = await new RequestContext(durableOpts).runWith(async () => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); useSubrequest(); webSocket1.addEventListener("message", () => { assertSubrequests(t, 0); trigger(); }); return webSocket2; }); webSocket2.accept(); webSocket2.send("test"); await promise; }); test("WebSocket: resets subrequest limit for WebSockets outside worker", async (t) => { // Check WebSocket with one end terminate in fetch handler and one in test const webSocket2 = new RequestContext(ctxOpts).runWith(() => { const [webSocket1, webSocket2] = Object.values(new WebSocketPair()); webSocket1.accept(); useSubrequest(); webSocket1.send("test"); return webSocket2; }); const [trigger, promise] = triggerPromise<void>(); webSocket2.accept(); webSocket2.addEventListener("message", () => { const ctx = getRequestContext(); t.is(ctx?.subrequests, 0); // Depths should have default values in this case t.is(ctx?.requestDepth, 1); t.is(ctx?.pipelineDepth, 1); trigger(); }); await promise; });
the_stack
import * as fs from "fs"; import * as path from "path"; import * as chalk from "chalk"; const fsextra = require("fs-extra"); import { help, loadUserSrc, tryLoadPackage, extractEntryPoint, extractConfig, extractOutput, extractEntryPointsAll } from "./args_load"; import { ConfigBuild, Package } from "./package_load"; import { PackageConfig, SymbolicActionMode } from "../compiler/mir_assembly"; import { workflowEmitICPPFile } from "../tooling/icpp/transpiler/iccp_workflows"; import { generateStandardVOpts, workflowEmitToFile } from "../tooling/checker/smt_workflows"; import { execSync } from "child_process"; import { transpile } from "../tooling/morphir/converter/walker"; function processBuildActionBytecode(args: string[]) { let workingdir = process.cwd(); let pckg: Package | undefined = undefined; if (path.extname(args[1]) === ".json") { workingdir = path.dirname(path.resolve(args[1])); pckg = tryLoadPackage(path.resolve(args[1])); } else { const implicitpckg = path.resolve(workingdir, "package.json"); if (fs.existsSync(implicitpckg)) { pckg = tryLoadPackage(implicitpckg); } } if (pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("build"); process.exit(1); } const cfg = extractConfig<ConfigBuild>(args, pckg, workingdir, "build"); if (cfg === undefined) { process.stderr.write(chalk.red("Could not parse 'config' option\n")); help("build"); process.exit(1); } const entrypoints = extractEntryPointsAll(workingdir, pckg.src.entrypoints); if (entrypoints === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("build"); process.exit(1); } const output = extractOutput(workingdir, args); if (output === undefined) { process.stderr.write(chalk.red("Could not parse 'output' option\n")); help("build"); process.exit(1); } const srcfiles = loadUserSrc(workingdir, [...pckg.src.entrypoints, ...pckg.src.bsqsource]); if (srcfiles === undefined) { process.stderr.write(chalk.red("Failed when loading source files\n")); process.exit(1); } const usersrcinfo = srcfiles.map((sf) => { return { srcpath: sf, filename: path.basename(sf), contents: fs.readFileSync(sf).toString() }; }); const userpackage = new PackageConfig([...cfg.macros, ...cfg.globalmacros], usersrcinfo); try { fsextra.ensureDirSync(output.path); } catch (ex) { process.stderr.write(chalk.red("Could not create 'output' directory\n")); help("build"); process.exit(1); } //bosque build bytecode [package_path.json] [--config cname] [--output out] workflowEmitICPPFile(path.join(output.path, cfg.name + ".json"), userpackage, true, cfg.buildlevel, false, {}, entrypoints); } function processBuildActionSymbolic(args: string[]) { const timeout = 10000; const noerr = { file: "[No Error Trgt]", line: -1, pos: -1 }; let smtonly = args.includes("--smtlib"); let vopts = generateStandardVOpts(SymbolicActionMode.ChkTestSymbolic); if (args[1] === "chk") { vopts = generateStandardVOpts(SymbolicActionMode.ChkTestSymbolic); } else if (args[1] === "eval") { vopts = generateStandardVOpts(SymbolicActionMode.EvaluateSymbolic); } else { process.stderr.write(chalk.red("Could not parse symbolic build mode\n")); help("build"); process.exit(1); } let workingdir = process.cwd(); let pckg: Package | undefined = undefined; if (path.extname(args[smtonly ? 3 : 2]) === ".json") { workingdir = path.dirname(path.resolve(args[smtonly ? 3 : 2])); pckg = tryLoadPackage(path.resolve(args[smtonly ? 3 : 2])); } else { const implicitpckg = path.resolve(workingdir, "package.json"); if (fs.existsSync(implicitpckg)) { pckg = tryLoadPackage(implicitpckg); } } if (pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("build"); process.exit(1); } const cfg = extractConfig<ConfigBuild>(args, pckg, workingdir, "build"); if (cfg === undefined) { process.stderr.write(chalk.red("Could not parse 'config' option\n")); help("build"); process.exit(1); } const entrypoint = extractEntryPoint(args, workingdir, pckg.src.entrypoints); if (entrypoint === undefined) { process.stderr.write(chalk.red("Could not parse 'entrypoint' option\n")); help("build"); process.exit(1); } const output = extractOutput(workingdir, args); if (output === undefined) { process.stderr.write(chalk.red("Could not parse 'output' option\n")); help("build"); process.exit(1); } const srcfiles = loadUserSrc(workingdir, [...pckg.src.entrypoints, ...pckg.src.bsqsource]); if (srcfiles === undefined) { process.stderr.write(chalk.red("Failed when loading source files\n")); process.exit(1); } const usersrcinfo = srcfiles.map((sf) => { return { srcpath: sf, filename: path.basename(sf), contents: fs.readFileSync(sf).toString() }; }); const userpackage = new PackageConfig([...cfg.macros, ...cfg.globalmacros], usersrcinfo); try { fsextra.ensureDirSync(output.path); } catch (ex) { process.stderr.write(chalk.red("Could not create 'output' directory\n")); help("build"); process.exit(1); } //bosque build smt [err|chk|eval] [package_path.json] [--config cname] [--output out] if (smtonly) { workflowEmitToFile(path.join(output.path, cfg.name + ".smt2"), userpackage, cfg.buildlevel, false, timeout, vopts, entrypoint, noerr, true); } else { workflowEmitToFile(path.join(output.path, cfg.name + ".json"), userpackage, cfg.buildlevel, false, timeout, vopts, entrypoint, noerr, false); } } function processBuildActionNode(args: string[]) { let workingdir = process.cwd(); let pckg: Package | undefined = undefined; if (path.extname(args[1]) === ".json") { workingdir = path.dirname(path.resolve(args[1])); pckg = tryLoadPackage(path.resolve(args[1])); } else { const implicitpckg = path.resolve(workingdir, "package.json"); if (fs.existsSync(implicitpckg)) { pckg = tryLoadPackage(implicitpckg); } } if (pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("build"); process.exit(1); } const cfg = extractConfig<ConfigBuild>(args, pckg, workingdir, "build"); if (cfg === undefined) { process.stderr.write(chalk.red("Could not parse 'config' option\n")); help("build"); process.exit(1); } const output = extractOutput(workingdir, args); if (output === undefined) { process.stderr.write(chalk.red("Could not parse 'output' option\n")); help("build"); process.exit(1); } //bosque build node [package_path.json] [--config cname] [--output out] process.stderr.write(chalk.red("Transpile to NPM module not implemented yet.\n")); process.exit(1); } function processBuildActionMorphir(args: string[]) { let workingdir = process.cwd(); let pckg: string | undefined = undefined; if (path.extname(args[1]) === ".json") { workingdir = path.dirname(path.resolve(args[1])); pckg = path.resolve(args[1]); } else { pckg = path.resolve(workingdir, "morphir.json"); } if (pckg === undefined) { process.stderr.write(chalk.red("Could not parse 'package' option\n")); help("build"); process.exit(1); } if(!fs.existsSync(pckg)) { process.stderr.write(chalk.red(`Directory "${workingdir}" does not contain a morphir package\n`)); process.exit(1); } const output = extractOutput(workingdir, args); if (output === undefined) { process.stderr.write(chalk.red("Could not parse 'output' option\n")); help("build"); process.exit(1); } try { fsextra.ensureDirSync(output.path); } catch (ex) { process.stderr.write(chalk.red("Could not create 'output' directory\n")); help("build"); process.exit(1); } const morphir_cmd = path.join(__dirname, "../../", "node_modules/.bin/morphir-elm"); try { const mv = execSync(`${morphir_cmd} -v`).toString().trim(); if(mv !== "2.49.0") { process.stderr.write(`Unsupported version of "morphir-elm" compiler -- please install with "npm install -g morphir-elm@2.49.0"\n`); process.exit(1); } } catch(ex) { process.stderr.write(`Missing "morphir-elm" compiler -- please install with "npm install -g morphir-elm@2.49.0"\n`); process.exit(1); } try { process.stdout.write(`Converting Elm source in ${workingdir}...\n`); execSync(`${morphir_cmd} make`, { cwd: workingdir }); } catch(ex) { process.stderr.write(`Failed to convert elm source to MorphirIR -- ${ex}\n`); process.exit(1); } const srcfile = path.join(workingdir, "morphir-ir.json"); const dstdir = path.join(path.parse(srcfile).dir, "bsqproj"); const dstsrc = path.join(dstdir, "app.bsqapi"); const dstpckg = path.join(dstdir, "package.json"); process.stdout.write(`Transpiling MorphirIR in ${srcfile}...\n`); try { const source_ir = fs.readFileSync(srcfile).toString(); const bsqcode = transpile(JSON.parse(source_ir)); process.stdout.write(`Writing Bosque source to ${dstdir}...\n`); if(!fs.existsSync(dstdir)) { fs.mkdirSync(dstdir); } fs.writeFileSync(dstsrc, bsqcode); fs.writeFileSync(dstpckg, JSON.stringify( { "name": `transpiled-${path.basename(srcfile, ".json")}`, "version": "0.0.0.0", "description": "Transpiled code for testing/analysis", "license": "MIT", "src": { "bsqsource": [ ], "entrypoints": [ `./app.bsqapi` ], "testfiles": [ ] } }, undefined, 2 )); } catch (ex) { process.stderr.write(`Failed to transpile --- ${ex}`); } } function processBuildAction(args: string[]) { if(args.length === 1) { if(args[0] === "morphir") { args.push("./morphir.json"); } else { args.push("./package.json"); } } if(args[0] === "node") { processBuildActionNode(args); } else if(args[0] === "bytecode") { processBuildActionBytecode(args); } else if(args[0] === "sym") { processBuildActionSymbolic(args); } else if(args[0] === "morphir") { processBuildActionMorphir(args); } else { process.stderr.write(chalk.red(`Unknown build target '${args[0]}'\n`)); help("build"); process.exit(1); } } export { processBuildAction, processBuildActionMorphir };
the_stack
import { App, Modal, Notice, PluginSettingTab, Setting, Platform, requireApiVersion, } from "obsidian"; import type { TextComponent } from "obsidian"; import { createElement, Eye, EyeOff } from "lucide"; import { API_VER_REQURL, DEFAULT_DEBUG_FOLDER, SUPPORTED_SERVICES_TYPE, SUPPORTED_SERVICES_TYPE_WITH_REMOTE_BASE_DIR, VALID_REQURL, WebdavAuthType, WebdavDepthType, } from "./baseTypes"; import { exportVaultSyncPlansToFiles, exportVaultLoggerOutputToFiles, } from "./debugMode"; import { exportQrCodeUri } from "./importExport"; import { clearAllSyncMetaMapping, clearAllSyncPlanRecords, destroyDBs, clearAllLoggerOutputRecords, insertLoggerOutputByVault, clearExpiredLoggerOutputRecords, } from "./localdb"; import type RemotelySavePlugin from "./main"; // unavoidable import { RemoteClient } from "./remote"; import { DEFAULT_DROPBOX_CONFIG, getAuthUrlAndVerifier as getAuthUrlAndVerifierDropbox, sendAuthReq as sendAuthReqDropbox, setConfigBySuccessfullAuthInplace, } from "./remoteForDropbox"; import { DEFAULT_ONEDRIVE_CONFIG, getAuthUrlAndVerifier as getAuthUrlAndVerifierOnedrive, } from "./remoteForOnedrive"; import { messyConfigToNormal } from "./configPersist"; import type { TransItemType } from "./i18n"; import { checkHasSpecialCharForDir } from "./misc"; import { applyWebdavPresetRulesInplace } from "./presetRules"; import { applyLogWriterInplace, log, restoreLogWritterInplace, } from "./moreOnLog"; class PasswordModal extends Modal { plugin: RemotelySavePlugin; newPassword: string; constructor(app: App, plugin: RemotelySavePlugin, newPassword: string) { super(app); this.plugin = plugin; this.newPassword = newPassword; } onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; // contentEl.setText("Add Or change password."); contentEl.createEl("h2", { text: t("modal_password_title") }); t("modal_password_shortdesc") .split("\n") .forEach((val, idx) => { contentEl.createEl("p", { text: val, }); }); [ t("modal_password_attn1"), t("modal_password_attn2"), t("modal_password_attn3"), t("modal_password_attn4"), t("modal_password_attn5"), ].forEach((val, idx) => { if (idx < 3) { contentEl.createEl("p", { text: val, cls: "password-disclaimer", }); } else { contentEl.createEl("p", { text: val, }); } }); new Setting(contentEl) .addButton((button) => { button.setButtonText(t("modal_password_secondconfirm")); button.onClick(async () => { this.plugin.settings.password = this.newPassword; await this.plugin.saveSettings(); new Notice(t("modal_password_notice")); this.close(); }); button.setClass("password-second-confirm"); }) .addButton((button) => { button.setButtonText(t("goback")); button.onClick(() => { this.close(); }); }); } onClose() { let { contentEl } = this; contentEl.empty(); } } class ChangeRemoteBaseDirModal extends Modal { readonly plugin: RemotelySavePlugin; readonly newRemoteBaseDir: string; readonly service: SUPPORTED_SERVICES_TYPE_WITH_REMOTE_BASE_DIR; constructor( app: App, plugin: RemotelySavePlugin, newRemoteBaseDir: string, service: SUPPORTED_SERVICES_TYPE_WITH_REMOTE_BASE_DIR ) { super(app); this.plugin = plugin; this.newRemoteBaseDir = newRemoteBaseDir; this.service = service; } onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; contentEl.createEl("h2", { text: t("modal_remotebasedir_title") }); t("modal_remotebasedir_shortdesc") .split("\n") .forEach((val, idx) => { contentEl.createEl("p", { text: val, }); }); if ( this.newRemoteBaseDir === "" || this.newRemoteBaseDir === this.app.vault.getName() ) { new Setting(contentEl) .addButton((button) => { button.setButtonText( t("modal_remotebasedir_secondconfirm_vaultname") ); button.onClick(async () => { // in the settings, the value is reset to the special case "" this.plugin.settings[this.service].remoteBaseDir = ""; await this.plugin.saveSettings(); new Notice(t("modal_remotebasedir_notice")); this.close(); }); button.setClass("remotebasedir-second-confirm"); }) .addButton((button) => { button.setButtonText(t("goback")); button.onClick(() => { this.close(); }); }); } else if (checkHasSpecialCharForDir(this.newRemoteBaseDir)) { contentEl.createEl("p", { text: t("modal_remotebasedir_invaliddirhint"), }); new Setting(contentEl).addButton((button) => { button.setButtonText(t("goback")); button.onClick(() => { this.close(); }); }); } else { new Setting(contentEl) .addButton((button) => { button.setButtonText(t("modal_remotebasedir_secondconfirm_change")); button.onClick(async () => { this.plugin.settings[this.service].remoteBaseDir = this.newRemoteBaseDir; await this.plugin.saveSettings(); new Notice(t("modal_remotebasedir_notice")); this.close(); }); button.setClass("remotebasedir-second-confirm"); }) .addButton((button) => { button.setButtonText(t("goback")); button.onClick(() => { this.close(); }); }); } } onClose() { let { contentEl } = this; contentEl.empty(); } } class DropboxAuthModal extends Modal { readonly plugin: RemotelySavePlugin; readonly authDiv: HTMLDivElement; readonly revokeAuthDiv: HTMLDivElement; readonly revokeAuthSetting: Setting; constructor( app: App, plugin: RemotelySavePlugin, authDiv: HTMLDivElement, revokeAuthDiv: HTMLDivElement, revokeAuthSetting: Setting ) { super(app); this.plugin = plugin; this.authDiv = authDiv; this.revokeAuthDiv = revokeAuthDiv; this.revokeAuthSetting = revokeAuthSetting; } async onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; let needManualPatse = false; const userAgent = window.navigator.userAgent.toLocaleLowerCase() || ""; // some users report that, // the Linux would open another instance Obsidian if jumping back, // so fallback to manual paste on Linux if ( Platform.isDesktopApp && !Platform.isMacOS && (/linux/.test(userAgent) || /ubuntu/.test(userAgent) || /debian/.test(userAgent) || /fedora/.test(userAgent) || /centos/.test(userAgent)) ) { needManualPatse = true; } const { authUrl, verifier } = await getAuthUrlAndVerifierDropbox( this.plugin.settings.dropbox.clientID, needManualPatse ); if (needManualPatse) { t("modal_dropboxauth_manualsteps") .split("\n") .forEach((val) => { contentEl.createEl("p", { text: val, }); }); } else { this.plugin.oauth2Info.verifier = verifier; t("modal_dropboxauth_autosteps") .split("\n") .forEach((val) => { contentEl.createEl("p", { text: val, }); }); } const div2 = contentEl.createDiv(); div2.createEl( "button", { text: t("modal_dropboxauth_copybutton"), }, (el) => { el.onclick = async () => { await navigator.clipboard.writeText(authUrl); new Notice(t("modal_dropboxauth_copynotice")); }; } ); contentEl.createEl("p").createEl("a", { href: authUrl, text: authUrl, }); if (needManualPatse) { let authCode = ""; new Setting(contentEl) .setName(t("modal_dropboxauth_maualinput")) .setDesc(t("modal_dropboxauth_maualinput_desc")) .addText((text) => text .setPlaceholder("") .setValue("") .onChange((val) => { authCode = val.trim(); }) ) .addButton(async (button) => { button.setButtonText(t("submit")); button.onClick(async () => { new Notice(t("modal_dropboxauth_maualinput_notice")); try { const authRes = await sendAuthReqDropbox( this.plugin.settings.dropbox.clientID, verifier, authCode ); const self = this; setConfigBySuccessfullAuthInplace( this.plugin.settings.dropbox, authRes, () => self.plugin.saveSettings() ); const client = new RemoteClient( "dropbox", undefined, undefined, this.plugin.settings.dropbox, undefined, this.app.vault.getName(), () => self.plugin.saveSettings() ); const username = await client.getUser(); this.plugin.settings.dropbox.username = username; await this.plugin.saveSettings(); new Notice( t("modal_dropboxauth_maualinput_conn_succ", { username: username, }) ); this.authDiv.toggleClass( "dropbox-auth-button-hide", this.plugin.settings.dropbox.username !== "" ); this.revokeAuthDiv.toggleClass( "dropbox-revoke-auth-button-hide", this.plugin.settings.dropbox.username === "" ); this.revokeAuthSetting.setDesc( t("modal_dropboxauth_maualinput_conn_succ_revoke", { username: this.plugin.settings.dropbox.username, }) ); this.close(); } catch (err) { console.error(err); new Notice(t("modal_dropboxauth_maualinput_conn_fail")); } }); }); } } onClose() { let { contentEl } = this; contentEl.empty(); } } export class OnedriveAuthModal extends Modal { readonly plugin: RemotelySavePlugin; readonly authDiv: HTMLDivElement; readonly revokeAuthDiv: HTMLDivElement; readonly revokeAuthSetting: Setting; constructor( app: App, plugin: RemotelySavePlugin, authDiv: HTMLDivElement, revokeAuthDiv: HTMLDivElement, revokeAuthSetting: Setting ) { super(app); this.plugin = plugin; this.authDiv = authDiv; this.revokeAuthDiv = revokeAuthDiv; this.revokeAuthSetting = revokeAuthSetting; } async onOpen() { let { contentEl } = this; const { authUrl, verifier } = await getAuthUrlAndVerifierOnedrive( this.plugin.settings.onedrive.clientID, this.plugin.settings.onedrive.authority ); this.plugin.oauth2Info.verifier = verifier; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; t("modal_onedriveauth_shortdesc") .split("\n") .forEach((val) => { contentEl.createEl("p", { text: val, }); }); const div2 = contentEl.createDiv(); div2.createEl( "button", { text: t("modal_onedriveauth_copybutton"), }, (el) => { el.onclick = async () => { await navigator.clipboard.writeText(authUrl); new Notice(t("modal_onedriveauth_copynotice")); }; } ); contentEl.createEl("p").createEl("a", { href: authUrl, text: authUrl, }); } onClose() { let { contentEl } = this; contentEl.empty(); } } export class OnedriveRevokeAuthModal extends Modal { readonly plugin: RemotelySavePlugin; readonly authDiv: HTMLDivElement; readonly revokeAuthDiv: HTMLDivElement; constructor( app: App, plugin: RemotelySavePlugin, authDiv: HTMLDivElement, revokeAuthDiv: HTMLDivElement ) { super(app); this.plugin = plugin; this.authDiv = authDiv; this.revokeAuthDiv = revokeAuthDiv; } async onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; contentEl.createEl("p", { text: t("modal_onedriverevokeauth_step1"), }); const consentUrl = "https://microsoft.com/consent"; contentEl.createEl("p").createEl("a", { href: consentUrl, text: consentUrl, }); contentEl.createEl("p", { text: t("modal_onedriverevokeauth_step2"), }); new Setting(contentEl) .setName(t("modal_onedriverevokeauth_clean")) .setDesc(t("modal_onedriverevokeauth_clean_desc")) .addButton(async (button) => { button.setButtonText(t("modal_onedriverevokeauth_clean_button")); button.onClick(async () => { try { this.plugin.settings.onedrive = JSON.parse( JSON.stringify(DEFAULT_ONEDRIVE_CONFIG) ); await this.plugin.saveSettings(); this.authDiv.toggleClass( "onedrive-auth-button-hide", this.plugin.settings.onedrive.username !== "" ); this.revokeAuthDiv.toggleClass( "onedrive-revoke-auth-button-hide", this.plugin.settings.onedrive.username === "" ); new Notice(t("modal_onedriverevokeauth_clean_notice")); this.close(); } catch (err) { console.error(err); new Notice(t("modal_onedriverevokeauth_clean_fail")); } }); }); } onClose() { let { contentEl } = this; contentEl.empty(); } } class SyncConfigDirModal extends Modal { plugin: RemotelySavePlugin; saveDropdownFunc: () => void; constructor( app: App, plugin: RemotelySavePlugin, saveDropdownFunc: () => void ) { super(app); this.plugin = plugin; this.saveDropdownFunc = saveDropdownFunc; } async onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; t("modal_syncconfig_attn") .split("\n") .forEach((val) => { contentEl.createEl("p", { text: val, }); }); new Setting(contentEl) .addButton((button) => { button.setButtonText(t("modal_syncconfig_secondconfirm")); button.onClick(async () => { this.plugin.settings.syncConfigDir = true; await this.plugin.saveSettings(); this.saveDropdownFunc(); new Notice(t("modal_syncconfig_notice")); this.close(); }); }) .addButton((button) => { button.setButtonText(t("goback")); button.onClick(() => { this.close(); }); }); } onClose() { let { contentEl } = this; contentEl.empty(); } } class ExportSettingsQrCodeModal extends Modal { plugin: RemotelySavePlugin; constructor(app: App, plugin: RemotelySavePlugin) { super(app); this.plugin = plugin; } async onOpen() { let { contentEl } = this; const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; const { rawUri, imgUri } = await exportQrCodeUri( this.plugin.settings, this.app.vault.getName(), this.plugin.manifest.version ); const div1 = contentEl.createDiv(); t("modal_qr_shortdesc") .split("\n") .forEach((val) => { div1.createEl("p", { text: val, }); }); const div2 = contentEl.createDiv(); div2.createEl( "button", { text: t("modal_qr_button"), }, (el) => { el.onclick = async () => { await navigator.clipboard.writeText(rawUri); new Notice(t("modal_qr_button_notice")); }; } ); const div3 = contentEl.createDiv(); div3.createEl( "img", { cls: "qrcode-img", }, async (el) => { el.src = imgUri; } ); } onClose() { let { contentEl } = this; contentEl.empty(); } } const getEyesElements = () => { const eyeEl = createElement(Eye); const eyeOffEl = createElement(EyeOff); return { eye: eyeEl.outerHTML, eyeOff: eyeOffEl.outerHTML, }; }; const wrapTextWithPasswordHide = (text: TextComponent) => { const { eye, eyeOff } = getEyesElements(); const hider = text.inputEl.insertAdjacentElement("afterend", createSpan()); // the init type of hider is "hidden" === eyeOff === password hider.innerHTML = eyeOff; hider.addEventListener("click", (e) => { const isText = text.inputEl.getAttribute("type") === "text"; hider.innerHTML = isText ? eyeOff : eye; text.inputEl.setAttribute("type", isText ? "password" : "text"); text.inputEl.focus(); }); // the init type of text el is password text.inputEl.setAttribute("type", "password"); return text; }; export class RemotelySaveSettingTab extends PluginSettingTab { readonly plugin: RemotelySavePlugin; constructor(app: App, plugin: RemotelySavePlugin) { super(app, plugin); this.plugin = plugin; } display(): void { let { containerEl } = this; containerEl.empty(); const t = (x: TransItemType, vars?: any) => { return this.plugin.i18n.t(x, vars); }; containerEl.createEl("h1", { text: "Remotely Save" }); ////////////////////////////////////////////////// // below for service chooser (part 1/2) ////////////////////////////////////////////////// // we need to create the div in advance of any other service divs const serviceChooserDiv = containerEl.createDiv(); serviceChooserDiv.createEl("h2", { text: t("settings_chooseservice") }); ////////////////////////////////////////////////// // below for s3 ////////////////////////////////////////////////// const s3Div = containerEl.createEl("div", { cls: "s3-hide" }); s3Div.toggleClass("s3-hide", this.plugin.settings.serviceType !== "s3"); s3Div.createEl("h2", { text: t("settings_s3") }); const s3LongDescDiv = s3Div.createEl("div", { cls: "settings-long-desc" }); for (const c of [ t("settings_s3_disclaimer1"), t("settings_s3_disclaimer2"), ]) { s3LongDescDiv.createEl("p", { text: c, cls: "s3-disclaimer", }); } if (!VALID_REQURL) { s3LongDescDiv.createEl("p", { text: t("settings_s3_cors"), }); } s3LongDescDiv.createEl("p", { text: t("settings_s3_prod"), }); const s3LinksUl = s3LongDescDiv.createEl("ul"); s3LinksUl.createEl("li").createEl("a", { href: "https://docs.aws.amazon.com/general/latest/gr/s3.html", text: t("settings_s3_prod1"), }); s3LinksUl.createEl("li").createEl("a", { href: "https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-your-credentials.html", text: t("settings_s3_prod2"), }); if (!VALID_REQURL) { s3LinksUl.createEl("li").createEl("a", { href: "https://docs.aws.amazon.com/AmazonS3/latest/userguide/enabling-cors-examples.html", text: t("settings_s3_prod3"), }); } new Setting(s3Div) .setName(t("settings_s3_endpoint")) .setDesc(t("settings_s3_endpoint")) .addText((text) => text .setPlaceholder("") .setValue(this.plugin.settings.s3.s3Endpoint) .onChange(async (value) => { this.plugin.settings.s3.s3Endpoint = value.trim(); await this.plugin.saveSettings(); }) ); new Setting(s3Div) .setName(t("settings_s3_region")) .setDesc(t("settings_s3_region_desc")) .addText((text) => text .setPlaceholder("") .setValue(`${this.plugin.settings.s3.s3Region}`) .onChange(async (value) => { this.plugin.settings.s3.s3Region = value.trim(); await this.plugin.saveSettings(); }) ); new Setting(s3Div) .setName(t("settings_s3_accesskeyid")) .setDesc(t("settings_s3_accesskeyid_desc")) .addText((text) => { wrapTextWithPasswordHide(text); text .setPlaceholder("") .setValue(`${this.plugin.settings.s3.s3AccessKeyID}`) .onChange(async (value) => { this.plugin.settings.s3.s3AccessKeyID = value.trim(); await this.plugin.saveSettings(); }); }); new Setting(s3Div) .setName(t("settings_s3_secretaccesskey")) .setDesc(t("settings_s3_secretaccesskey_desc")) .addText((text) => { wrapTextWithPasswordHide(text); text .setPlaceholder("") .setValue(`${this.plugin.settings.s3.s3SecretAccessKey}`) .onChange(async (value) => { this.plugin.settings.s3.s3SecretAccessKey = value.trim(); await this.plugin.saveSettings(); }); }); new Setting(s3Div) .setName(t("settings_s3_bucketname")) .setDesc(t("settings_s3_bucketname")) .addText((text) => text .setPlaceholder("") .setValue(`${this.plugin.settings.s3.s3BucketName}`) .onChange(async (value) => { this.plugin.settings.s3.s3BucketName = value.trim(); await this.plugin.saveSettings(); }) ); new Setting(s3Div) .setName(t("settings_s3_urlstyle")) .setDesc(t("settings_s3_urlstyle_desc")) .addDropdown((dropdown) => { dropdown.addOption( "virtualHostedStyle", "Virtual Hosted-Style (default)" ); dropdown.addOption("pathStyle", "Path-Style"); dropdown .setValue( this.plugin.settings.s3.forcePathStyle ? "pathStyle" : "virtualHostedStyle" ) .onChange(async (val: string) => { this.plugin.settings.s3.forcePathStyle = val === "pathStyle"; await this.plugin.saveSettings(); }); }); if (VALID_REQURL) { new Setting(s3Div) .setName(t("settings_s3_bypasscorslocally")) .setDesc(t("settings_s3_bypasscorslocally_desc")) .addDropdown((dropdown) => { dropdown .addOption("disable", t("disable")) .addOption("enable", t("enable")); dropdown .setValue( `${ this.plugin.settings.s3.bypassCorsLocally ? "enable" : "disable" }` ) .onChange(async (value) => { if (value === "enable") { this.plugin.settings.s3.bypassCorsLocally = true; } else { this.plugin.settings.s3.bypassCorsLocally = false; } await this.plugin.saveSettings(); }); }); } new Setting(s3Div) .setName(t("settings_s3_parts")) .setDesc(t("settings_s3_parts_desc")) .addDropdown((dropdown) => { dropdown.addOption("1", "1"); dropdown.addOption("2", "2"); dropdown.addOption("3", "3"); dropdown.addOption("5", "5"); dropdown.addOption("10", "10"); dropdown.addOption("15", "15"); dropdown.addOption("20", "20 (default)"); dropdown .setValue(`${this.plugin.settings.s3.partsConcurrency}`) .onChange(async (val) => { const realVal = parseInt(val); this.plugin.settings.s3.partsConcurrency = realVal; await this.plugin.saveSettings(); }); }); new Setting(s3Div) .setName(t("settings_checkonnectivity")) .setDesc(t("settings_checkonnectivity_desc")) .addButton(async (button) => { button.setButtonText(t("settings_checkonnectivity_button")); button.onClick(async () => { new Notice(t("settings_checkonnectivity_checking")); const client = new RemoteClient("s3", this.plugin.settings.s3); const errors = { msg: "" }; const res = await client.checkConnectivity((err: any) => { errors.msg = err; }); if (res) { new Notice(t("settings_s3_connect_succ")); } else { new Notice(t("settings_s3_connect_fail")); new Notice(errors.msg); } }); }); ////////////////////////////////////////////////// // below for dropbpx ////////////////////////////////////////////////// const dropboxDiv = containerEl.createEl("div", { cls: "dropbox-hide" }); dropboxDiv.toggleClass( "dropbox-hide", this.plugin.settings.serviceType !== "dropbox" ); dropboxDiv.createEl("h2", { text: t("settings_dropbox") }); const dropboxLongDescDiv = dropboxDiv.createEl("div", { cls: "settings-long-desc", }); for (const c of [ t("settings_dropbox_disclaimer1"), t("settings_dropbox_disclaimer2"), ]) { dropboxLongDescDiv.createEl("p", { text: c, cls: "dropbox-disclaimer", }); } dropboxLongDescDiv.createEl("p", { text: t("settings_dropbox_folder", { pluginID: this.plugin.manifest.id, remoteBaseDir: this.plugin.settings.dropbox.remoteBaseDir || this.app.vault.getName(), }), }); const dropboxSelectAuthDiv = dropboxDiv.createDiv(); const dropboxAuthDiv = dropboxSelectAuthDiv.createDiv({ cls: "dropbox-auth-button-hide settings-auth-related", }); const dropboxRevokeAuthDiv = dropboxSelectAuthDiv.createDiv({ cls: "dropbox-revoke-auth-button-hide settings-auth-related", }); const dropboxRevokeAuthSetting = new Setting(dropboxRevokeAuthDiv) .setName(t("settings_dropbox_revoke")) .setDesc( t("settings_dropbox_revoke_desc", { username: this.plugin.settings.dropbox.username, }) ) .addButton(async (button) => { button.setButtonText(t("settings_dropbox_revoke_button")); button.onClick(async () => { try { const self = this; const client = new RemoteClient( "dropbox", undefined, undefined, this.plugin.settings.dropbox, undefined, this.app.vault.getName(), () => self.plugin.saveSettings() ); await client.revokeAuth(); this.plugin.settings.dropbox = JSON.parse( JSON.stringify(DEFAULT_DROPBOX_CONFIG) ); await this.plugin.saveSettings(); dropboxAuthDiv.toggleClass( "dropbox-auth-button-hide", this.plugin.settings.dropbox.username !== "" ); dropboxRevokeAuthDiv.toggleClass( "dropbox-revoke-auth-button-hide", this.plugin.settings.dropbox.username === "" ); new Notice(t("settings_dropbox_revoke_notice")); } catch (err) { console.error(err); new Notice(t("settings_dropbox_revoke_noticeerr")); } }); }); new Setting(dropboxRevokeAuthDiv) .setName(t("settings_dropbox_clearlocal")) .setDesc(t("settings_dropbox_clearlocal_desc")) .addButton(async (button) => { button.setButtonText(t("settings_dropbox_clearlocal_button")); button.onClick(async () => { this.plugin.settings.dropbox = JSON.parse( JSON.stringify(DEFAULT_DROPBOX_CONFIG) ); await this.plugin.saveSettings(); dropboxAuthDiv.toggleClass( "dropbox-auth-button-hide", this.plugin.settings.dropbox.username !== "" ); dropboxRevokeAuthDiv.toggleClass( "dropbox-revoke-auth-button-hide", this.plugin.settings.dropbox.username === "" ); new Notice(t("settings_dropbox_clearlocal_notice")); }); }); new Setting(dropboxAuthDiv) .setName(t("settings_dropbox_auth")) .setDesc(t("settings_dropbox_auth_desc")) .addButton(async (button) => { button.setButtonText(t("settings_dropbox_auth_button")); button.onClick(async () => { const modal = new DropboxAuthModal( this.app, this.plugin, dropboxAuthDiv, dropboxRevokeAuthDiv, dropboxRevokeAuthSetting ); this.plugin.oauth2Info.helperModal = modal; this.plugin.oauth2Info.authDiv = dropboxAuthDiv; this.plugin.oauth2Info.revokeDiv = dropboxRevokeAuthDiv; this.plugin.oauth2Info.revokeAuthSetting = dropboxRevokeAuthSetting; modal.open(); }); }); dropboxAuthDiv.toggleClass( "dropbox-auth-button-hide", this.plugin.settings.dropbox.username !== "" ); dropboxRevokeAuthDiv.toggleClass( "dropbox-revoke-auth-button-hide", this.plugin.settings.dropbox.username === "" ); let newDropboxRemoteBaseDir = this.plugin.settings.dropbox.remoteBaseDir || ""; new Setting(dropboxDiv) .setName(t("settings_remotebasedir")) .setDesc(t("settings_remotebasedir_desc")) .addText((text) => text .setPlaceholder(this.app.vault.getName()) .setValue(newDropboxRemoteBaseDir) .onChange((value) => { newDropboxRemoteBaseDir = value.trim(); }) ) .addButton((button) => { button.setButtonText(t("confirm")); button.onClick(() => { new ChangeRemoteBaseDirModal( this.app, this.plugin, newDropboxRemoteBaseDir, "dropbox" ).open(); }); }); new Setting(dropboxDiv) .setName(t("settings_checkonnectivity")) .setDesc(t("settings_checkonnectivity_desc")) .addButton(async (button) => { button.setButtonText(t("settings_checkonnectivity_button")); button.onClick(async () => { new Notice(t("settings_checkonnectivity_checking")); const self = this; const client = new RemoteClient( "dropbox", undefined, undefined, this.plugin.settings.dropbox, undefined, this.app.vault.getName(), () => self.plugin.saveSettings() ); const errors = { msg: "" }; const res = await client.checkConnectivity((err: any) => { errors.msg = `${err}`; }); if (res) { new Notice(t("settings_dropbox_connect_succ")); } else { new Notice(t("settings_dropbox_connect_fail")); new Notice(errors.msg); } }); }); ////////////////////////////////////////////////// // below for onedrive ////////////////////////////////////////////////// const onedriveDiv = containerEl.createEl("div", { cls: "onedrive-hide" }); onedriveDiv.toggleClass( "onedrive-hide", this.plugin.settings.serviceType !== "onedrive" ); onedriveDiv.createEl("h2", { text: t("settings_onedrive") }); const onedriveLongDescDiv = onedriveDiv.createEl("div", { cls: "settings-long-desc", }); for (const c of [ t("settings_onedrive_disclaimer1"), t("settings_onedrive_disclaimer2"), ]) { onedriveLongDescDiv.createEl("p", { text: c, cls: "onedrive-disclaimer", }); } onedriveLongDescDiv.createEl("p", { text: t("settings_onedrive_folder", { pluginID: this.plugin.manifest.id, remoteBaseDir: this.plugin.settings.onedrive.remoteBaseDir || this.app.vault.getName(), }), }); onedriveLongDescDiv.createEl("p", { text: t("settings_onedrive_nobiz"), }); const onedriveSelectAuthDiv = onedriveDiv.createDiv(); const onedriveAuthDiv = onedriveSelectAuthDiv.createDiv({ cls: "onedrive-auth-button-hide settings-auth-related", }); const onedriveRevokeAuthDiv = onedriveSelectAuthDiv.createDiv({ cls: "onedrive-revoke-auth-button-hide settings-auth-related", }); const onedriveRevokeAuthSetting = new Setting(onedriveRevokeAuthDiv) .setName(t("settings_onedrive_revoke")) .setDesc( t("settings_onedrive_revoke_desc", { username: this.plugin.settings.onedrive.username, }) ) .addButton(async (button) => { button.setButtonText(t("settings_onedrive_revoke_button")); button.onClick(async () => { new OnedriveRevokeAuthModal( this.app, this.plugin, onedriveAuthDiv, onedriveRevokeAuthDiv ).open(); }); }); new Setting(onedriveAuthDiv) .setName(t("settings_onedrive_auth")) .setDesc(t("settings_onedrive_auth_desc")) .addButton(async (button) => { button.setButtonText(t("settings_onedrive_auth_button")); button.onClick(async () => { const modal = new OnedriveAuthModal( this.app, this.plugin, onedriveAuthDiv, onedriveRevokeAuthDiv, onedriveRevokeAuthSetting ); this.plugin.oauth2Info.helperModal = modal; this.plugin.oauth2Info.authDiv = onedriveAuthDiv; this.plugin.oauth2Info.revokeDiv = onedriveRevokeAuthDiv; this.plugin.oauth2Info.revokeAuthSetting = onedriveRevokeAuthSetting; modal.open(); }); }); onedriveAuthDiv.toggleClass( "onedrive-auth-button-hide", this.plugin.settings.onedrive.username !== "" ); onedriveRevokeAuthDiv.toggleClass( "onedrive-revoke-auth-button-hide", this.plugin.settings.onedrive.username === "" ); let newOnedriveRemoteBaseDir = this.plugin.settings.onedrive.remoteBaseDir || ""; new Setting(onedriveDiv) .setName(t("settings_remotebasedir")) .setDesc(t("settings_remotebasedir_desc")) .addText((text) => text .setPlaceholder(this.app.vault.getName()) .setValue(newOnedriveRemoteBaseDir) .onChange((value) => { newOnedriveRemoteBaseDir = value.trim(); }) ) .addButton((button) => { button.setButtonText(t("confirm")); button.onClick(() => { new ChangeRemoteBaseDirModal( this.app, this.plugin, newOnedriveRemoteBaseDir, "onedrive" ).open(); }); }); new Setting(onedriveDiv) .setName(t("settings_checkonnectivity")) .setDesc(t("settings_checkonnectivity_desc")) .addButton(async (button) => { button.setButtonText(t("settings_checkonnectivity_button")); button.onClick(async () => { new Notice(t("settings_checkonnectivity_checking")); const self = this; const client = new RemoteClient( "onedrive", undefined, undefined, undefined, this.plugin.settings.onedrive, this.app.vault.getName(), () => self.plugin.saveSettings() ); const errors = { msg: "" }; const res = await client.checkConnectivity((err: any) => { errors.msg = `${err}`; }); if (res) { new Notice(t("settings_onedrive_connect_succ")); } else { new Notice(t("settings_onedrive_connect_fail")); new Notice(errors.msg); } }); }); ////////////////////////////////////////////////// // below for webdav ////////////////////////////////////////////////// const webdavDiv = containerEl.createEl("div", { cls: "webdav-hide" }); webdavDiv.toggleClass( "webdav-hide", this.plugin.settings.serviceType !== "webdav" ); webdavDiv.createEl("h2", { text: t("settings_webdav") }); const webdavLongDescDiv = webdavDiv.createEl("div", { cls: "settings-long-desc", }); webdavLongDescDiv.createEl("p", { text: t("settings_webdav_disclaimer1"), cls: "webdav-disclaimer", }); if (!VALID_REQURL) { webdavLongDescDiv.createEl("p", { text: t("settings_webdav_cors_os"), }); webdavLongDescDiv.createEl("p", { text: t("settings_webdav_cors"), }); } webdavLongDescDiv.createEl("p", { text: t("settings_webdav_folder", { remoteBaseDir: this.plugin.settings.webdav.remoteBaseDir || this.app.vault.getName(), }), }); new Setting(webdavDiv) .setName(t("settings_webdav_addr")) .setDesc(t("settings_webdav_addr_desc")) .addText((text) => text .setPlaceholder("") .setValue(this.plugin.settings.webdav.address) .onChange(async (value) => { this.plugin.settings.webdav.address = value.trim(); if ( this.plugin.settings.webdav.depth === "auto_1" || this.plugin.settings.webdav.depth === "auto_infinity" ) { this.plugin.settings.webdav.depth = "auto_unknown"; } // TODO: any more elegant way? applyWebdavPresetRulesInplace(this.plugin.settings.webdav); // normally saved await this.plugin.saveSettings(); }) ); new Setting(webdavDiv) .setName(t("settings_webdav_user")) .setDesc(t("settings_webdav_user_desc")) .addText((text) => { wrapTextWithPasswordHide(text); text .setPlaceholder("") .setValue(this.plugin.settings.webdav.username) .onChange(async (value) => { this.plugin.settings.webdav.username = value.trim(); if ( this.plugin.settings.webdav.depth === "auto_1" || this.plugin.settings.webdav.depth === "auto_infinity" ) { this.plugin.settings.webdav.depth = "auto_unknown"; } await this.plugin.saveSettings(); }); }); new Setting(webdavDiv) .setName(t("settings_webdav_password")) .setDesc(t("settings_webdav_password_desc")) .addText((text) => { wrapTextWithPasswordHide(text); text .setPlaceholder("") .setValue(this.plugin.settings.webdav.password) .onChange(async (value) => { this.plugin.settings.webdav.password = value.trim(); if ( this.plugin.settings.webdav.depth === "auto_1" || this.plugin.settings.webdav.depth === "auto_infinity" ) { this.plugin.settings.webdav.depth = "auto_unknown"; } await this.plugin.saveSettings(); }); }); new Setting(webdavDiv) .setName(t("settings_webdav_auth")) .setDesc(t("settings_webdav_auth_desc")) .addDropdown(async (dropdown) => { dropdown.addOption("basic", "basic"); if (VALID_REQURL) { dropdown.addOption("digest", "digest"); } // new version config, copied to old version, we need to reset it if (!VALID_REQURL && this.plugin.settings.webdav.authType !== "basic") { this.plugin.settings.webdav.authType = "basic"; await this.plugin.saveSettings(); } dropdown .setValue(this.plugin.settings.webdav.authType) .onChange(async (val: WebdavAuthType) => { this.plugin.settings.webdav.authType = val; await this.plugin.saveSettings(); }); }); new Setting(webdavDiv) .setName(t("settings_webdav_depth")) .setDesc(t("settings_webdav_depth_desc")) .addDropdown((dropdown) => { dropdown.addOption("auto", t("settings_webdav_depth_auto")); dropdown.addOption("manual_1", t("settings_webdav_depth_1")); dropdown.addOption("manual_infinity", t("settings_webdav_depth_inf")); let initVal = "auto"; const autoOptions: Set<WebdavDepthType> = new Set([ "auto_unknown", "auto_1", "auto_infinity", ]); if (autoOptions.has(this.plugin.settings.webdav.depth)) { initVal = "auto"; } else { initVal = this.plugin.settings.webdav.depth || "auto"; } type DepthOption = "auto" | "manual_1" | "manual_infinity"; dropdown.setValue(initVal).onChange(async (val: DepthOption) => { if (val === "auto") { this.plugin.settings.webdav.depth = "auto_unknown"; this.plugin.settings.webdav.manualRecursive = false; } else if (val === "manual_1") { this.plugin.settings.webdav.depth = "manual_1"; this.plugin.settings.webdav.manualRecursive = true; } else if (val === "manual_infinity") { this.plugin.settings.webdav.depth = "manual_infinity"; this.plugin.settings.webdav.manualRecursive = false; } // TODO: any more elegant way? applyWebdavPresetRulesInplace(this.plugin.settings.webdav); // normally save await this.plugin.saveSettings(); }); }); let newWebdavRemoteBaseDir = this.plugin.settings.webdav.remoteBaseDir || ""; new Setting(webdavDiv) .setName(t("settings_remotebasedir")) .setDesc(t("settings_remotebasedir_desc")) .addText((text) => text .setPlaceholder(this.app.vault.getName()) .setValue(newWebdavRemoteBaseDir) .onChange((value) => { newWebdavRemoteBaseDir = value.trim(); }) ) .addButton((button) => { button.setButtonText(t("confirm")); button.onClick(() => { new ChangeRemoteBaseDirModal( this.app, this.plugin, newWebdavRemoteBaseDir, "webdav" ).open(); }); }); new Setting(webdavDiv) .setName(t("settings_checkonnectivity")) .setDesc(t("settings_checkonnectivity_desc")) .addButton(async (button) => { button.setButtonText(t("settings_checkonnectivity_button")); button.onClick(async () => { new Notice(t("settings_checkonnectivity_checking")); const self = this; const client = new RemoteClient( "webdav", undefined, this.plugin.settings.webdav, undefined, undefined, this.app.vault.getName(), () => self.plugin.saveSettings() ); const errors = { msg: "" }; const res = await client.checkConnectivity((err: any) => { errors.msg = `${err}`; }); if (res) { new Notice(t("settings_webdav_connect_succ")); } else { if (VALID_REQURL) { new Notice(t("settings_webdav_connect_fail")); } else { new Notice(t("settings_webdav_connect_fail_withcors")); } new Notice(errors.msg); } }); }); ////////////////////////////////////////////////// // below for general chooser (part 2/2) ////////////////////////////////////////////////// // we need to create chooser // after all service-div-s being created new Setting(serviceChooserDiv) .setName(t("settings_chooseservice")) .setDesc(t("settings_chooseservice_desc")) .addDropdown(async (dropdown) => { dropdown.addOption("s3", t("settings_chooseservice_s3")); dropdown.addOption("dropbox", t("settings_chooseservice_dropbox")); dropdown.addOption("webdav", t("settings_chooseservice_webdav")); dropdown.addOption("onedrive", t("settings_chooseservice_onedrive")); dropdown .setValue(this.plugin.settings.serviceType) .onChange(async (val: SUPPORTED_SERVICES_TYPE) => { this.plugin.settings.serviceType = val; s3Div.toggleClass( "s3-hide", this.plugin.settings.serviceType !== "s3" ); dropboxDiv.toggleClass( "dropbox-hide", this.plugin.settings.serviceType !== "dropbox" ); onedriveDiv.toggleClass( "onedrive-hide", this.plugin.settings.serviceType !== "onedrive" ); webdavDiv.toggleClass( "webdav-hide", this.plugin.settings.serviceType !== "webdav" ); await this.plugin.saveSettings(); }); }); ////////////////////////////////////////////////// // below for basic settings ////////////////////////////////////////////////// const basicDiv = containerEl.createEl("div"); basicDiv.createEl("h2", { text: t("settings_basic") }); let newPassword = `${this.plugin.settings.password}`; new Setting(basicDiv) .setName(t("settings_password")) .setDesc(t("settings_password_desc")) .addText((text) => { wrapTextWithPasswordHide(text); text .setPlaceholder("") .setValue(`${this.plugin.settings.password}`) .onChange(async (value) => { newPassword = value.trim(); }); }) .addButton(async (button) => { button.setButtonText(t("confirm")); button.onClick(async () => { new PasswordModal(this.app, this.plugin, newPassword).open(); }); }); new Setting(basicDiv) .setName(t("settings_autorun")) .setDesc(t("settings_autorun_desc")) .addDropdown((dropdown) => { dropdown.addOption("-1", t("settings_autorun_notset")); dropdown.addOption(`${1000 * 60 * 1}`, t("settings_autorun_1min")); dropdown.addOption(`${1000 * 60 * 5}`, t("settings_autorun_5min")); dropdown.addOption(`${1000 * 60 * 10}`, t("settings_autorun_10min")); dropdown.addOption(`${1000 * 60 * 30}`, t("settings_autorun_30min")); dropdown .setValue(`${this.plugin.settings.autoRunEveryMilliseconds}`) .onChange(async (val: string) => { const realVal = parseInt(val); this.plugin.settings.autoRunEveryMilliseconds = realVal; await this.plugin.saveSettings(); if ( (realVal === undefined || realVal === null || realVal <= 0) && this.plugin.autoRunIntervalID !== undefined ) { // clear window.clearInterval(this.plugin.autoRunIntervalID); this.plugin.autoRunIntervalID = undefined; } else if ( realVal !== undefined && realVal !== null && realVal > 0 ) { const intervalID = window.setInterval(() => { this.plugin.syncRun("auto"); }, realVal); this.plugin.autoRunIntervalID = intervalID; this.plugin.registerInterval(intervalID); } }); }); new Setting(basicDiv) .setName(t("settings_runoncestartup")) .setDesc(t("settings_runoncestartup_desc")) .addDropdown((dropdown) => { dropdown.addOption("-1", t("settings_runoncestartup_notset")); dropdown.addOption( `${1000 * 1 * 1}`, t("settings_runoncestartup_1sec") ); dropdown.addOption( `${1000 * 10 * 1}`, t("settings_runoncestartup_10sec") ); dropdown.addOption( `${1000 * 30 * 1}`, t("settings_runoncestartup_30sec") ); dropdown .setValue(`${this.plugin.settings.initRunAfterMilliseconds}`) .onChange(async (val: string) => { const realVal = parseInt(val); this.plugin.settings.initRunAfterMilliseconds = realVal; await this.plugin.saveSettings(); }); }); new Setting(basicDiv) .setName(t("settings_skiplargefiles")) .setDesc(t("settings_skiplargefiles_desc")) .addDropdown((dropdown) => { dropdown.addOption("-1", t("settings_skiplargefiles_notset")); const mbs = [1, 5, 10, 50, 100, 500, 1000]; for (const mb of mbs) { dropdown.addOption(`${mb * 1000 * 1000}`, `${mb} MB`); } dropdown .setValue(`${this.plugin.settings.skipSizeLargerThan}`) .onChange(async (val) => { this.plugin.settings.skipSizeLargerThan = parseInt(val); await this.plugin.saveSettings(); }); }); ////////////////////////////////////////////////// // below for advanced settings ////////////////////////////////////////////////// const advDiv = containerEl.createEl("div"); advDiv.createEl("h2", { text: t("settings_adv"), }); new Setting(advDiv) .setName(t("settings_concurrency")) .setDesc(t("settings_concurrency_desc")) .addDropdown((dropdown) => { dropdown.addOption("1", "1"); dropdown.addOption("2", "2"); dropdown.addOption("3", "3"); dropdown.addOption("5", "5 (default)"); dropdown.addOption("10", "10"); dropdown.addOption("15", "15"); dropdown.addOption("20", "20"); dropdown .setValue(`${this.plugin.settings.concurrency}`) .onChange(async (val) => { const realVal = parseInt(val); this.plugin.settings.concurrency = realVal; await this.plugin.saveSettings(); }); }); new Setting(advDiv) .setName(t("settings_syncunderscore")) .setDesc(t("settings_syncunderscore_desc")) .addDropdown((dropdown) => { dropdown.addOption("disable", t("disable")); dropdown.addOption("enable", t("enable")); dropdown .setValue( `${this.plugin.settings.syncUnderscoreItems ? "enable" : "disable"}` ) .onChange(async (val) => { this.plugin.settings.syncUnderscoreItems = val === "enable"; await this.plugin.saveSettings(); }); }); new Setting(advDiv) .setName(t("settings_configdir")) .setDesc( t("settings_configdir_desc", { configDir: this.app.vault.configDir, }) ) .addDropdown((dropdown) => { dropdown.addOption("disable", t("disable")); dropdown.addOption("enable", t("enable")); const bridge = { secondConfirm: false, }; dropdown .setValue( `${this.plugin.settings.syncConfigDir ? "enable" : "disable"}` ) .onChange(async (val) => { if (val === "enable" && !bridge.secondConfirm) { dropdown.setValue("disable"); new SyncConfigDirModal(this.app, this.plugin, () => { bridge.secondConfirm = true; dropdown.setValue("enable"); }).open(); } else { bridge.secondConfirm = false; this.plugin.settings.syncConfigDir = false; await this.plugin.saveSettings(); } }); }); ////////////////////////////////////////////////// // below for import and export functions ////////////////////////////////////////////////// // import and export const importExportDiv = containerEl.createEl("div"); importExportDiv.createEl("h2", { text: t("settings_importexport"), }); new Setting(importExportDiv) .setName(t("settings_export")) .setDesc(t("settings_export_desc")) .addButton(async (button) => { button.setButtonText(t("settings_export_desc_button")); button.onClick(async () => { new ExportSettingsQrCodeModal(this.app, this.plugin).open(); }); }); new Setting(importExportDiv) .setName(t("settings_import")) .setDesc(t("settings_import_desc")); ////////////////////////////////////////////////// // below for debug ////////////////////////////////////////////////// const debugDiv = containerEl.createEl("div"); debugDiv.createEl("h2", { text: t("settings_debug") }); new Setting(debugDiv) .setName(t("settings_debuglevel")) .setDesc(t("settings_debuglevel_desc")) .addDropdown(async (dropdown) => { dropdown.addOption("info", "info"); dropdown.addOption("debug", "debug"); dropdown .setValue(this.plugin.settings.currLogLevel) .onChange(async (val: string) => { this.plugin.settings.currLogLevel = val; log.setLevel(val as any); await this.plugin.saveSettings(); log.info(`the log level is changed to ${val}`); }); }); new Setting(debugDiv) .setName(t("settings_outputsettingsconsole")) .setDesc(t("settings_outputsettingsconsole_desc")) .addButton(async (button) => { button.setButtonText(t("settings_outputsettingsconsole_button")); button.onClick(async () => { const c = messyConfigToNormal(await this.plugin.loadData()); log.info(c); new Notice(t("settings_outputsettingsconsole_notice")); }); }); new Setting(debugDiv) .setName(t("settings_syncplans")) .setDesc(t("settings_syncplans_desc")) .addButton(async (button) => { button.setButtonText(t("settings_syncplans_button_json")); button.onClick(async () => { await exportVaultSyncPlansToFiles( this.plugin.db, this.app.vault, this.plugin.vaultRandomID, "json" ); new Notice(t("settings_syncplans_notice")); }); }) .addButton(async (button) => { button.setButtonText(t("settings_syncplans_button_table")); button.onClick(async () => { await exportVaultSyncPlansToFiles( this.plugin.db, this.app.vault, this.plugin.vaultRandomID, "table" ); new Notice(t("settings_syncplans_notice")); }); }); new Setting(debugDiv) .setName(t("settings_delsyncplans")) .setDesc(t("settings_delsyncplans_desc")) .addButton(async (button) => { button.setButtonText(t("settings_delsyncplans_button")); button.onClick(async () => { await clearAllSyncPlanRecords(this.plugin.db); new Notice(t("settings_delsyncplans_notice")); }); }); new Setting(debugDiv) .setName(t("settings_logtodb")) .setDesc(t("settings_logtodb_desc")) .addDropdown(async (dropdown) => { dropdown.addOption("enable", t("enable")); dropdown.addOption("disable", t("disable")); dropdown .setValue(this.plugin.settings.logToDB ? "enable" : "disable") .onChange(async (val: string) => { const logToDB = val === "enable"; if (logToDB) { applyLogWriterInplace((...msg: any[]) => { insertLoggerOutputByVault( this.plugin.db, this.plugin.vaultRandomID, ...msg ); }); } else { restoreLogWritterInplace(); } clearExpiredLoggerOutputRecords(this.plugin.db); this.plugin.settings.logToDB = logToDB; await this.plugin.saveSettings(); }); }); new Setting(debugDiv) .setName(t("settings_logtodbexport")) .setDesc( t("settings_logtodbexport_desc", { debugFolder: DEFAULT_DEBUG_FOLDER, }) ) .addButton(async (button) => { button.setButtonText(t("settings_logtodbexport_button")); button.onClick(async () => { await exportVaultLoggerOutputToFiles( this.plugin.db, this.app.vault, this.plugin.vaultRandomID ); new Notice(t("settings_logtodbexport_notice")); }); }); new Setting(debugDiv) .setName(t("settings_logtodbclear")) .setDesc(t("settings_logtodbclear_desc")) .addButton(async (button) => { button.setButtonText(t("settings_logtodbclear_button")); button.onClick(async () => { await clearAllLoggerOutputRecords(this.plugin.db); new Notice(t("settings_logtodbclear_notice")); }); }); new Setting(debugDiv) .setName(t("settings_delsyncmap")) .setDesc(t("settings_delsyncmap_desc")) .addButton(async (button) => { button.setButtonText(t("settings_delsyncmap_button")); button.onClick(async () => { await clearAllSyncMetaMapping(this.plugin.db); new Notice(t("settings_delsyncmap_notice")); }); }); new Setting(debugDiv) .setName(t("settings_outputbasepathvaultid")) .setDesc(t("settings_outputbasepathvaultid_desc")) .addButton(async (button) => { button.setButtonText(t("settings_outputbasepathvaultid_button")); button.onClick(async () => { new Notice(this.plugin.getVaultBasePath()); new Notice(this.plugin.vaultRandomID); }); }); new Setting(debugDiv) .setName(t("settings_resetcache")) .setDesc(t("settings_resetcache_desc")) .addButton(async (button) => { button.setButtonText(t("settings_resetcache_button")); button.onClick(async () => { await destroyDBs(); new Notice(t("settings_resetcache_notice")); }); }); } hide() { let { containerEl } = this; containerEl.empty(); super.hide(); } }
the_stack
namespace BeaconService { /** * The Beacon structure sent back to inspectIT. * Corresponds to rocks.inspectit.shared.all.communication.data.eum.Beacon. */ interface IBeacon { tabID: IdNumber; sessionID: IdNumber; activeAgentModules: string; data?: DTO<BeaconElement>[]; } /** * The cookie used for holding the inspectit session ID. */ const SESSION_COOKIE_NAME = "inspectIT_session"; /** * The URL to which the service will try to send the beacons. */ const BEACON_URL = SETTINGS.eumManagementServer; /** * The list of active modules in this agent. * It is stored as it is also sent back to the server. */ const ACTIVE_MODULES = SETTINGS.activeAgentModules; /** * Constant holding whether navigator.sendBeacon is supported. */ const BEACON_API_SUPPORTED = (typeof navigator.sendBeacon !== "undefined"); /** * The special value for sessionID and tabID to be sent in beacons for requesting a new ID. */ const REQUEST_NEW_ID_MARKER = "-1"; /** * After this amount of time of inactivity (no new data added to send), the beacon will be sent. */ const TIME_WINDOW: number = 2500; /** * A element is guaranteed to be no longer buffered than this duration. This means if elements are added regularly to the queue, a * beacon will be sent at this frequency. */ const MAX_TIME_WINDOW = 15000; // Failure handling /** * The inital backoff in case the beacon could not be sent in milliseconds. */ const INITIAL_BACKOFF = 5 * 1000; /** * The maximum backoff after repeated failures in milliseconds. */ const MAX_BACKOFF = 60 * 1000; /** * Defines how often we retry in case of errors until we give up. */ const MAX_FAILURES_IN_A_ROW = 8; // == about five minutes let dataToSend: DTO<BeaconElement>[] = []; let firstDataInQueueTimestamp: number | null = null; let lastDataInQueueTimestamp: number | null = null; // counts the number of consecutive sends which failed let failuresInARow = 0; // do not send until this timestamp is reached // used to prevent spamming in case of long-time network failures let backoffTimestamp = 0; /** * Flag whether beaconing has been disabled due to a failure. */ let isDisabled = false; /** * Variables holding the sessionID and teh tabID assigned by the Java Agent. */ let sessionID: IdNumber = REQUEST_NEW_ID_MARKER; let tabID: IdNumber = REQUEST_NEW_ID_MARKER; /** * This flag makes sure that only one beacon is sent at a time. It is true if we still are awaiting the response of a previously * sent beacon. */ let awaitingResponse: boolean = false; /** * Regular timer for checking the queue and possibly sending a beacon. */ let sendTimer: number | null = null; export function init() { Instrumentation.runWithout(() => { sendTimer = setInterval(sendConditionChecker, 1000); }); const sessionCookie: IdNumber | null = Util.getCookie(SESSION_COOKIE_NAME); if (sessionCookie === null) { // send an empty beacon immediately to request a new session ID // - it seems like this page has been cached or the JS agent has been injected manually forceBeaconSend(false); } else { // session cookie available- read it sessionID = sessionCookie; // reset the PRNG based on the sessionID (guaranteed source of randomness) Util.PRNG.setSeed(sessionID + Util.timestampMS()); } } /** * Disables the service in case of some kind of failure. * This makes the service just ignore queued data. */ function disableBeaconService() { isDisabled = true; if (sendTimer) { clearInterval(sendTimer); sendTimer = null; } dataToSend = []; } /** * A timer executed every second to check the conditions for sending a new beacon. If the conditions are met, a beacon is sent. */ function sendConditionChecker() { if (!awaitingResponse && dataToSend.length > 0) { const time = Util.timestampMS(); if (time >= backoffTimestamp && ((time - firstDataInQueueTimestamp!) >= MAX_TIME_WINDOW || (time - lastDataInQueueTimestamp!) >= TIME_WINDOW)) { forceBeaconSend(false); } } } /** * Adds an element to the send queue and updates the timing Binformation for the sending policy. * * @param element * the element to send */ export function send<T extends BeaconElement>(element: DTO<T>) { if (isDisabled) { return; } dataToSend.push(element as any); const time = Util.timestampMS(); lastDataInQueueTimestamp = time; // are we the first element in the queue? if (dataToSend.length === 1) { firstDataInQueueTimestamp = time; } } /** * Sends a beacon, ignoring whether the conditions are met. * * @param useBeaconAPI true, if the beacon API should be used. This means that no feedback regarding success / failure is given! */ function forceBeaconSend(useBeaconAPI: boolean) { // disable instrumentation as we interact with APIs Instrumentation.runWithout(function () { const beaconObj: IBeacon = { tabID, sessionID, activeAgentModules: ACTIVE_MODULES }; if (sessionID === REQUEST_NEW_ID_MARKER) { // we have to request a new session ID, as this page was probably cached. // we therefore will send an empty beacon instead due to a possible race condition // across multiple tabs within the same session beaconObj.data = []; } else { beaconObj.data = dataToSend; dataToSend = []; lastDataInQueueTimestamp = null; firstDataInQueueTimestamp = null; } // use the beacon API if we do not care about the response and network failures let beaconApiSuccess = false; if (useBeaconAPI && BEACON_API_SUPPORTED && sessionID !== REQUEST_NEW_ID_MARKER && tabID !== REQUEST_NEW_ID_MARKER) { beaconApiSuccess = navigator.sendBeacon(BEACON_URL, JSON.stringify(beaconObj)); } if (!beaconApiSuccess) { const xhrPost = new XMLHttpRequest(); xhrPost.open("POST", BEACON_URL, true); xhrPost.setRequestHeader("Content-Type", "application/json"); let responseHandled = false; const responseHandler = Instrumentation.disableFor(function () { // assert that only one of the three listeners is run if (!responseHandled) { responseHandled = true; if (xhrPost.status === 200) { failuresInARow = 0; const responseObj = JSON.parse(xhrPost.responseText); if (tabID === REQUEST_NEW_ID_MARKER) { tabID = responseObj.tabID; // reset the PRNG based on the tabID, the best source of randomness Util.PRNG.setSeed(tabID + Util.timestampMS()); } if (sessionID === REQUEST_NEW_ID_MARKER) { const sessionCookie = Util.getCookie(SESSION_COOKIE_NAME); if (sessionCookie !== null) { // ignore the received id and instead use the stored one sessionID = sessionCookie; awaitingResponse = false; } else { // possible race condition between multiple tabs here // we just wait a moment and then take the winner of this race condition document.cookie = SESSION_COOKIE_NAME + "=" + responseObj.sessionID + "; path=/"; setTimeout(function () { Instrumentation.runWithout(function () { sessionID = Util.getCookie(SESSION_COOKIE_NAME)!; awaitingResponse = false; }); awaitingResponse = false; }, 200); } } else { awaitingResponse = false; } } else { failuresInARow++; if (failuresInARow >= MAX_FAILURES_IN_A_ROW) { disableBeaconService(); // give up ;( } else { // retry after backoff backoffTimestamp = Util.timestampMS() + Math.min(MAX_BACKOFF, Math.pow(2, failuresInARow - 1) * INITIAL_BACKOFF); if (beaconObj.data) { for (const element of beaconObj.data) { send(element); } } } awaitingResponse = false; } } }); xhrPost.addEventListener("load", responseHandler); xhrPost.addEventListener("error", responseHandler); xhrPost.addEventListener("abort", responseHandler); xhrPost.send(JSON.stringify(beaconObj)); awaitingResponse = true; } }); } /** * Try a final send before leaving the page. */ export function beforeUnload() { // cancel timer Instrumentation.runWithout(function () { if (sendTimer) { clearInterval(sendTimer); } }); if (dataToSend.length > 0) { forceBeaconSend(true); } } }
the_stack
// @filename: external.ts export class Reflect {} export interface Foo {} export declare namespace Bar { type _ = unknown; } export const enum Baz {} export default class {}; // @filename: locals.ts export {}; declare class B { static w(): number; } class C extends B { static _ = [ (() => { var Reflect; // collision (es2015-es2021 only) super.w(); })(), (() => { var { Reflect } = { Reflect: null }; // collision (es2015-es2021 only) super.w(); })(), (() => { var [Reflect] = [null]; // collision (es2015-es2021 only) super.w(); })(), (() => { class Reflect {} // collision (es2015-es2021 only) super.w(); })(), (() => { function Reflect() {} // collision (es2015-es2021 only) super.w(); })(), (() => { enum Reflect {} // collision (es2015-es2021 only) super.w(); })(), (() => { const enum Reflect {} // collision (es2015-es2021 only) super.w(); })(), (() => { type Reflect = unknown; // no collision super.w(); })(), (() => { interface Reflect {}; // no collision super.w(); })(), (() => { (class Reflect {}); // no collision super.w(); })(), (() => { (function Reflect() {}); // no collision super.w(); })(), ]; static { var { Reflect } = { Reflect: null }; // collision (es2015-es2021 only) super.w(); } static { var [Reflect] = [null]; // collision (es2015-es2021 only) super.w(); } static { var Reflect; // collision (es2015-es2021 only) super.w(); } static { class Reflect {} // collision (es2015-es2021 only) super.w(); } static { function Reflect() {} // collision (es2015-es2021 only) super.w(); } static { enum Reflect {} // collision (es2015-es2021 only) super.w(); } static { const enum Reflect {} // collision (es2015-es2021 only) super.w(); } static { type Reflect = unknown; // no collision super.w(); } static { interface Reflect {} // no collision super.w(); } static { (class Reflect {}) // no collision super.w(); } static { (function Reflect() {}) // no collision super.w(); } } // @filename: varInContainingScopeStaticField1.ts export {}; declare class B { static w(): number; } var Reflect = null; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: varInContainingScopeStaticField2.ts export {}; declare class B { static w(): number; } var { Reflect } = { Reflect: null }; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: varInContainingScopeStaticField3.ts export {}; declare class B { static w(): number; } var [Reflect] = [null]; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: varInContainingScopeStaticBlock1.ts export {}; declare class B { static w(): number; } var Reflect = null; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: varInContainingScopeStaticBlock2.ts export {}; declare class B { static w(): number; } var { Reflect } = { Reflect: null }; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: varInContainingScopeStaticBlock3.ts export {}; declare class B { static w(): number; } var [Reflect] = [null]; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: classDeclInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } class Reflect {} // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: classDeclInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } class Reflect {} // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: funcDeclInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } function Reflect() {} // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: funcDeclInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } function Reflect() {} // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: valueNamespaceInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } namespace Reflect {} // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: valueNamespaceInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } namespace Reflect {} // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: enumInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } enum Reflect {} // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: enumInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } enum Reflect {} // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: constEnumInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } const enum Reflect {} // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: constEnumInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } const enum Reflect {} // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: namespaceImportInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import * as Reflect from "./external"; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: namespaceImportInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import * as Reflect from "./external"; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: namedImportInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import { Reflect } from "./external"; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: namedImportInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import { Reflect } from "./external"; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: namedImportOfInterfaceInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import { Foo as Reflect } from "./external"; // collision (es2015-es2021 only, not a type-only import) class C extends B { static _ = super.w(); } // @filename: namedImportOfInterfaceInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import { Foo as Reflect } from "./external"; // collision (es2015-es2021 only, not a type-only import) class C extends B { static { super.w(); } } // @filename: namedImportOfUninstantiatedNamespaceInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import { Bar as Reflect } from "./external"; // collision (es2015-es2021 only, not a type-only import) class C extends B { static _ = super.w(); } // @filename: namedImportOfUninstantiatedNamespaceInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import { Bar as Reflect } from "./external"; // collision (es2015-es2021 only, not a type-only import) class C extends B { static { super.w(); } } // @filename: namedImportOfConstEnumInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import { Baz as Reflect } from "./external"; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: namedImportOfConstEnumInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import { Baz as Reflect } from "./external"; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: typeOnlyNamedImportInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import type { Reflect } from "./external"; // no collision class C extends B { static _ = super.w(); } // @filename: typeOnlyNamedImportInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import type { Reflect } from "./external"; // no collision class C extends B { static { super.w(); } } // @filename: defaultImportInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import Reflect from "./external"; // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } // @filename: defaultImportInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import Reflect from "./external"; // collision (es2015-es2021 only) class C extends B { static { super.w(); } } // @filename: typeOnlyDefaultImportInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } import type Reflect from "./external"; // no collision class C extends B { static _ = super.w(); } // @filename: typeOnlyDefaultImportInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } import type Reflect from "./external"; // no collision class C extends B { static { super.w(); } } // @filename: typeInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } type Reflect = unknown; // no collision class C extends B { static _ = super.w(); } // @filename: typeInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } type Reflect = unknown; // no collision class C extends B { static { super.w(); } } // @filename: interfaceInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } interface Reflect {}; // no collision class C extends B { static _ = super.w(); } // @filename: interfaceInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } interface Reflect {}; // no collision class C extends B { static { super.w(); } } // @filename: uninstantiatedNamespaceInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } declare namespace Reflect { type _ = unknown; }; // no collision class C extends B { static _ = super.w(); } // @filename: uninstantiatedNamespaceInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } declare namespace Reflect { type _ = unknown; }; // no collision class C extends B { static { super.w(); } } // @filename: classExprInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } (class Reflect {}); // no collision class C extends B { static _ = super.w(); } // @filename: classExprInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } (class Reflect {}); // no collision class C extends B { static { super.w(); } } // @filename: inContainingClassExprStaticField.ts export {}; declare class B { static w(): number; } (class Reflect { // collision (es2015-es2021 only) static { class C extends B { static _ = super.w(); } } }); // @filename: inContainingClassExprStaticBlock.ts export {}; declare class B { static w(): number; } (class Reflect { // collision (es2015-es2021 only) static { class C extends B { static { super.w(); } } } }); // @filename: funcExprInContainingScopeStaticField.ts export {}; declare class B { static w(): number; } (function Reflect() {}); // no collision class C extends B { static _ = super.w(); } // @filename: funcExprInContainingScopeStaticBlock.ts export {}; declare class B { static w(): number; } (function Reflect() {}); // no collision class C extends B { static { super.w(); } } // @filename: inContainingFuncExprStaticField.ts export {}; declare class B { static w(): number; } (function Reflect() { // collision (es2015-es2021 only) class C extends B { static _ = super.w(); } }); // @filename: inContainingFuncExprStaticBlock.ts export {}; declare class B { static w(): number; } (function Reflect() { // collision (es2015-es2021 only) class C extends B { static { super.w(); } } });
the_stack
import { getPeriodName } from "../../../common"; import { g, helpers } from "../../util"; import type { PlayType, TeamNum } from "./types"; // Convert clock in minutes to min:sec, like 1.5 -> 1:30 const formatClock = (clock: number) => { const secNum = Math.ceil((clock % 1) * 60); let sec; if (secNum >= 60) { sec = "59"; } else if (secNum < 10) { sec = `0${secNum}`; } else { sec = `${secNum}`; } return `${Math.floor(clock)}:${sec}`; }; const descriptionYdsTD = ( yds: number, td: boolean, touchdownText: string, showYdsOnTD: boolean, ) => { if (td && showYdsOnTD) { return `${yds} yards${td ? ` and ${touchdownText}!` : ""}`; } if (td) { return `${touchdownText}!`; } return `${yds} yards`; }; class PlayByPlayLogger { active: boolean; playByPlay: any[]; twoPointConversionTeam: number | undefined; quarter: string; constructor(active: boolean) { this.active = active; this.playByPlay = []; this.quarter = "Q1"; } logEvent( type: PlayType, { automaticFirstDown, clock, count, decision, injuredPID, lost, made, names, offense, offsetStatus, penaltyName, quarter, overtimes, safety, success, t, tackOn, td, touchback, yds, spotFoul, halfDistanceToGoal, placeOnOne, }: { automaticFirstDown?: boolean; clock: number; count?: number; decision?: "accept" | "decline"; injuredPID?: number; lost?: boolean; made?: boolean; names?: string[]; offense?: boolean; offsetStatus?: "offset" | "overrule"; penaltyName?: string; quarter?: number; overtimes?: number; safety?: boolean; success?: boolean; t?: TeamNum; tackOn?: boolean; td?: boolean; touchback?: boolean; yds?: number; spotFoul?: boolean; halfDistanceToGoal?: boolean; placeOnOne?: boolean; }, ) { // Handle touchdowns, 2 point conversions, and 2 point conversion returns by the defense let touchdownText = "a touchdown"; let showYdsOnTD = true; if (this.twoPointConversionTeam !== undefined) { if (this.twoPointConversionTeam === t) { touchdownText = "a two point conversion"; showYdsOnTD = false; } else { touchdownText = "two points"; } } let text; if (this.playByPlay !== undefined) { if (type === "injury") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} was injured!`; } else if (type === "quarter") { if (quarter === undefined) { throw new Error("Missing quarter"); } text = `Start of ${helpers.ordinal(quarter)} ${getPeriodName( g.get("numPeriods"), )}`; this.quarter = `Q${quarter}`; } else if (type === "overtime") { if (overtimes === undefined) { throw new Error("Missing overtimes"); } this.quarter = `OT${overtimes}`; text = `Start of ${ overtimes === 1 ? "" : `${helpers.ordinal(overtimes)} ` } overtime`; } else if (type === "gameOver") { text = "End of game"; } else if (type === "kickoff") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} kicked off${ touchback ? " for a touchback" : yds < 0 ? " into the end zone" : ` to the ${yds} yard line` }`; } else if (type === "kickoffReturn") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} returned the kickoff ${yds} yards${ td ? " for a touchdown!" : "" }`; } else if (type === "onsideKick") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} gets ready to attempt an onside kick`; } else if (type === "onsideKickRecovery") { if (success === undefined) { throw new Error("Missing success"); } if (td === undefined) { throw new Error("Missing td"); } text = `The onside kick was recovered by ${ success ? "the kicking team!" : `the receiving team${td ? " and returned for a touchdown!" : ""}` }`; } else if (type === "punt") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} punted ${yds} yards${ touchback ? " for a touchback" : yds < 0 ? " into the end zone" : "" }`; } else if (type === "puntReturn") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} returned the punt ${yds} yards${ td ? " for a touchdown!" : "" }`; } else if (type === "extraPoint") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} ${made ? "made" : "missed"} the extra point`; } else if (type === "fieldGoal") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} ${ made ? "made" : "missed" } a ${yds} yard field goal`; } else if (type === "fumble") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} fumbled the ball!`; } else if (type === "fumbleRecovery") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } if (safety || touchback) { text = `${ names[0] } recovered the fumble in the endzone, resulting in a ${ safety ? "safety!" : "touchback" }`; } else if (lost) { text = `${names[0]} recovered the fumble for the defense ${ td && yds < 1 ? `in the endzone for ${touchdownText}!` : `and returned it ${yds} yards${ td ? ` for ${touchdownText}!` : "" }` }`; } else { text = `${names[0]} recovered the fumble for the offense${ td ? ` and carried it into the endzone for ${touchdownText}!` : "" }`; } } else if (type === "interception") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} intercepted the pass `; if (touchback) { text += "in the endzone"; } else { text += `and returned it ${yds} yards${ td ? ` for ${touchdownText}!` : "" }`; } } else if (type === "sack") { if (names === undefined) { throw new Error("Missing names"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `${names[0]} was sacked by ${names[1]} for a ${ safety ? "safety!" : `${Math.abs(yds)} yard loss` }`; } else if (type === "dropback") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} drops back to pass`; } else if (type === "passComplete") { if (names === undefined) { throw new Error("Missing names"); } if (td === undefined) { throw new Error("Missing td"); } if (yds === undefined) { throw new Error("Missing yds"); } if (safety) { text = `${names[0]} completed a pass to ${names[1]} but he was tackled in the endzone for a safety!`; } else { const result = descriptionYdsTD(yds, td, touchdownText, showYdsOnTD); text = `${names[0]} completed a pass to ${names[1]} for ${result}`; } } else if (type === "passIncomplete") { if (names === undefined) { throw new Error("Missing names"); } text = `Incomplete pass to ${names[1]}`; } else if (type === "handoff") { if (names === undefined) { throw new Error("Missing names"); } if (names.length > 1) { // If names.length is 1, its a QB keeper, no need to log the handoff text = `${names[0]} hands the ball off to ${names[1]}`; } } else if (type === "run") { if (names === undefined) { throw new Error("Missing names"); } if (td === undefined) { throw new Error("Missing td"); } if (yds === undefined) { throw new Error("Missing yds"); } if (safety) { text = `${names[0]} was tackled in the endzone for a safety!`; } else { const result = descriptionYdsTD(yds, td, touchdownText, showYdsOnTD); text = `${names[0]} rushed for ${result}`; } } else if (type === "penaltyCount") { if (count === undefined) { throw new Error("Missing count"); } text = `There are ${count} ${ offsetStatus === "offset" ? "offsetting " : "" }fouls on the play${ offsetStatus === "offset" ? ", the previous down will be replayed" : "" }`; } else if (type === "penalty") { if (decision === undefined) { throw new Error("Missing decision"); } if (automaticFirstDown === undefined) { throw new Error("Missing automaticFirstDown"); } if (names === undefined) { throw new Error("Missing names"); } if (penaltyName === undefined) { throw new Error("Missing penaltyName"); } if (yds === undefined) { throw new Error("Missing yds"); } text = `Penalty, ABBREV${t} - ${penaltyName.toLowerCase()}${ names.length > 0 ? ` on ${names[0]}` : "" }`; if (offsetStatus !== "offset") { const spotFoulText = tackOn ? " from the end of the play" : spotFoul ? " from the spot of the foul" : ""; const automaticFirstDownText = automaticFirstDown ? " and an automatic first down" : ""; if (halfDistanceToGoal) { text += `, half the distance to the goal${spotFoulText}`; } else if (placeOnOne) { text += `, the ball will be placed at the 1 yard line${automaticFirstDownText}`; } else { text += `, ${yds} yards${spotFoulText}${automaticFirstDownText}`; } let decisionText; if (offsetStatus === "overrule") { decisionText = decision === "accept" ? "enforced" : "overruled"; } else { decisionText = decision === "accept" ? "accepted" : "declined"; } text += ` - ${decisionText}`; } } else if (type === "timeout") { text = `Time out, ${offense ? "offense" : "defense"}`; } else if (type === "twoMinuteWarning") { text = "Two minute warning"; } else if (type === "kneel") { if (names === undefined) { throw new Error("Missing names"); } text = `${names[0]} kneels`; } else if (type === "flag") { text = "Flag on the play"; } else if (type === "extraPointAttempt") { text = "Extra point attempt"; } else if (type === "twoPointConversion") { text = "Two point conversion attempt"; } else if (type === "twoPointConversionFailed") { text = "Two point conversion failed"; } else if (type === "turnoverOnDowns") { text = "Turnover on downs"; } else { throw new Error(`No text for "${type}"`); } if (text) { const event: any = { type: "text", text, t, time: formatClock(clock), quarter: this.quarter, }; if (injuredPID !== undefined) { event.injuredPID = injuredPID; } if ( safety || td || type === "extraPoint" || type === "twoPointConversionFailed" || (made && type === "fieldGoal") ) { event.scoringSummary = true; } this.playByPlay.push(event); } } } logStat( qtr: number, t: number, pid: number | undefined | null, s: string, amt: number, ) { if (!this.active) { return; } this.playByPlay.push({ type: "stat", quarter: this.quarter, t, pid, s, amt, }); } logClock({ awaitingKickoff, clock, down, scrimmage, t, toGo, }: { awaitingKickoff: TeamNum | undefined; clock: number; down: number; scrimmage: number; t: TeamNum; toGo: number; }) { if (!this.active) { return; } this.playByPlay.push({ type: "clock", awaitingKickoff, down, scrimmage, t, time: formatClock(clock), toGo, }); } getPlayByPlay(boxScore: any) { if (!this.active) { return; } return [ { type: "init", boxScore, }, ...this.playByPlay, ]; } removeLastScore() { this.playByPlay.push({ type: "removeLastScore", }); } } export default PlayByPlayLogger;
the_stack
import { FsApi, File, Credentials, Fs, filetype } from '../Fs'; import * as ftp from 'ftp'; import * as path from 'path'; import * as fs from 'fs'; import { Transform } from 'stream'; import { throttle } from '../../utils/throttle'; import { Logger, JSObject } from '../../components/Log'; import { EventEmitter } from 'events'; import { isWin, DOWNLOADS_DIR } from '../../utils/platform'; import * as nodePath from 'path'; import { LocalizedError } from '../../locale/error'; const invalidChars = /^[\.]+$/gi; function join(path1: string, path2: string): string { let prefix = ''; if (path1.match(/^ftp:\/\//)) { prefix = 'ftp://'; path1 = path1.replace('ftp://', ''); } // since under Windows path.join will use '\' as separator // we replace it with '/' if (isWin) { return prefix + path.join(path1, path2).replace(/\\/g, '/'); } else { return prefix + path.join(path1, path2); } } class Client { // eslint-disable-next-line @typescript-eslint/no-explicit-any private client: any; public connected: boolean; public host: string; public status: 'busy' | 'ready' | 'offline' = 'offline'; public api: FtpAPI = null; public options: Credentials; // eslint-disable-next-line @typescript-eslint/no-explicit-any private readyResolve: () => any; // eslint-disable-next-line @typescript-eslint/no-explicit-any private readyReject: (err: any) => any; private readyPromise: Promise<void>; private previousError: LocalizedError = null; static clients: Array<Client> = []; // eslint-disable-next-line @typescript-eslint/no-explicit-any static addClient(hostname: string, options: any = {}): Client { const client = new Client(hostname, options); Client.clients.push(client); return client; } private instanceId = 0; static id = 0; // TODO: return promise if client is not connected ?? static getFreeClient(hostname: string): Client { let client = Client.clients.find( (client) => client.host === hostname && !client.api && client.status === 'ready', ); if (!client) { client = Client.addClient(hostname, {}); } else { console.log('using existing client'); } return client; } // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(host: string, options: any = {}) { console.log('creating ftp client'); this.instanceId = Client.id++; this.host = host; this.connected = false; this.client = new ftp(); this.bindEvents(); } getLoggerArgs(params: (string | number | boolean | JSObject)[]): (string | number | boolean | JSObject)[] { // append host and client instance return [`[${this.host}:${this.instanceId}]`, ...params]; } success(...params: (string | number | boolean | JSObject)[]): void { Logger.success(...this.getLoggerArgs(params)); } log(...params: (string | number | boolean | JSObject)[]): void { Logger.log(...this.getLoggerArgs(params)); } warn(...params: (string | number | boolean | JSObject)[]): void { Logger.warn(...this.getLoggerArgs(params)); } error(...params: (string | number | boolean | JSObject)[]): void { Logger.error(...this.getLoggerArgs(params)); } public login(options: Credentials): Promise<void> { if (!this.connected) { this.log( 'connecting to', this.host, 'with options', Object.assign({ host: this.host, ...options }, { password: '****' }), ); this.options = options; this.readyPromise = new Promise((resolve, reject) => { this.readyResolve = resolve; this.readyReject = reject; this.client.connect({ host: this.host, ...options, debug: window.console.log }); }); } return this.readyPromise; } private bindEvents(): void { this.client.on('ready', this.onReady.bind(this)); this.client.on('error', this.onError.bind(this)); this.client.on('close', this.onClose.bind(this)); this.client.on('greeting', this.onGreeting.bind(this)); } private onReady(): void { this.success('ready, setting transfer mode to binary'); this.client.binary((err: Error) => { if (err) { this.warn('could not set transfer mode to binary'); } this.readyResolve(); this.status = 'ready'; this.connected = true; }); } private onClose(): void { this.warn('close'); this.connected = false; this.status = 'offline'; if (this.api) { this.api.onClose(); } } private goOffline(error: LocalizedError): void { this.status = 'offline'; if (this.readyReject) { this.readyReject(error); } } private onError(error: LocalizedError): void { this.log(typeof error.code); this.error('onError', `${error.code}: ${error.message}`); switch (error.code) { // 500 series: command not accepted // user not logged in (user limit may be reached too) case 530: case 'ENOTFOUND': case 'ECONNREFUSED': this.goOffline(error); break; case 550: // is also returned when attempting to get the size of a directory console.error('Requested action not taken. File unavailable, not found, not accessible'); break; case 421: // service not available: control connection closed console.error('Service not available, closing connection'); this.client.close(); this.goOffline(error); break; case 'ETIMEDOUT': debugger; break; default: // sometimes error.code is undefined or is a string (!!) this.warn('unhandled error code:', error.code); if (error && (error as string).match(/Timeout/)) { this.warn('Connection timeout ?'); } break; } this.previousError = error; } private onGreeting(greeting: string): void { for (const line of greeting.split('\n')) { this.log(line); } } public list(path: string): Promise<File[]> { this.status = 'busy'; this.log('list', path); return new Promise((resolve, reject) => { const newpath = this.pathpart(path); // Note: since node-ftp only supports the LIST cmd and // some servers do not implement "LIST path" when path // contains a space we send an empty path so list uses // the CWD (and "CWD path") has no problems with a path // containing a space // // We could also use MLSD instead but unfortunately it's // not implemented in node-ftp // see: https://github.com/warpdesign/react-ftp/wiki/FTP-LIST-command // eslint-disable-next-line @typescript-eslint/no-explicit-any this.client.list('', (err: Error, list: any[]) => { this.status = 'ready'; if (err) { this.error('error calling list for', newpath); reject(err); } else { const files: File[] = list .filter((ftpFile) => !ftpFile.name.match(/^[\.]{1,2}$/)) .map((ftpFile) => { const format = nodePath.parse(ftpFile.name); const ext = format.ext.toLowerCase(); const mDate = new Date(ftpFile.date); const file: File = { dir: path, name: ftpFile.name, fullname: ftpFile.name, isDir: ftpFile.type === 'd', length: parseInt(ftpFile.size, 10), cDate: mDate, mDate: mDate, bDate: mDate, extension: '', mode: 0, readonly: false, type: (ftpFile.type !== 'd' && filetype(0, 0, 0, ext)) || '', isSym: false, target: null, id: { ino: mDate.getTime(), dev: new Date().getTime(), }, }; return file; }); resolve(files); } }); }); } public cd(path: string): Promise<string> { this.log('cd', path); return new Promise((resolve, reject) => { const oldPath = path; const newpath = this.pathpart(path); // eslint-disable-next-line @typescript-eslint/no-explicit-any this.client.cwd(newpath, (err: any, dir: string) => { if (!err) { // some ftp servers return windows-like paths // when ran in windows if (dir) { dir = dir.replace(/\\/g, '/'); } // const joint = join(this.host, (dir || newpath)); const joint = newpath === '/' ? join(oldPath, dir || newpath) : oldPath; resolve(joint); } else { reject(err); } }); }); } public pathpart(path: string): string { // we have to encode any % character other they may be // lost when calling decodeURIComponent try { const info = new URL(path.replace(/%/g, '%25')); return decodeURIComponent(info.pathname); } catch (err) { console.error('error getting pathpart for', path); return ''; } // const pathPart = path.replace(ServerPart, ''); // return pathPart; } public get(path: string, dest: string): Promise<string> { return new Promise((resolve, reject) => { const newpath = this.pathpart(path); this.log('downloading file', newpath, dest); this.client.get(newpath, (err: Error, readStream: fs.ReadStream) => { if (err) { reject(err); } else { console.log('creating stream'); const writeStream = fs.createWriteStream(dest); readStream.once('close', function (): void { resolve(dest); }); readStream.pipe(writeStream); readStream.on('data', (chunk) => console.log('data', chunk.length)); } }); }); } public getStream(path: string): Promise<fs.ReadStream> { this.status = 'busy'; console.log('getting stream', path); return new Promise((resolve, reject) => { const newpath = this.pathpart(path); this.client.get(newpath, (err: Error, readStream: fs.ReadStream) => { this.status = 'ready'; if (err) { reject(err); } else { resolve(readStream); } }); }); } public putStream(readStream: fs.ReadStream, path: string, progress: (pourcent: number) => void): Promise<void> { this.status = 'busy'; let bytesRead = 0; const throttledProgress = throttle((): void => { progress(bytesRead); }, 800); readStream.once('close', function () { console.log('get ended!'); }); const reportProgress = new Transform({ transform(chunk, encoding, callback) { bytesRead += chunk.length; throttledProgress(); console.log('data', bytesRead / 1024, 'Ko'); callback(null, chunk); }, highWaterMark: 16384 * 31, }); return new Promise((resolve, reject) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const newpath = this.pathpart(path); this.client.put(readStream.pipe(reportProgress), newpath, (err: Error): void => { this.status = 'ready'; if (err) { reject(err); } else { // readStream.once('close', () => resolve()); resolve(); } }); }); } public rename(serverPath: string, oldName: string, newName: string): Promise<string> { const path = this.pathpart(serverPath); const oldPath = join(path, oldName); const newPath = join(path, newName); this.log('rename', oldPath, newPath); return new Promise((resolve, reject) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any return this.client.rename(oldPath, newPath, (err: any) => { if (!err) { resolve(newName); } else { reject({ oldName: oldName, newName: newName, code: err.code, message: err.message, }); } }); }); } public mkdir(parent: string, name: string): Promise<string> { const path = this.pathpart(parent); const newPath = join(path, name); this.log('mkdir', path, newPath); return new Promise((resolve, reject) => { this.client.mkdir(newPath, true, (err: Error): void => { if (err) { reject(err); } else { resolve(join(parent, name)); } }); }); } public delete(ftpPath: string, isDir: boolean): Promise<void> { debugger; const path = this.pathpart(ftpPath); return new Promise((resolve, reject) => { if (isDir) { return this.client.rmdir(path, false, (err: Error) => { if (err) { debugger; reject(err); } else { debugger; resolve(); } }); } else { this.client.delete(path, (err: Error) => { if (err) { debugger; reject(err); } else { debugger; resolve(); } }); } }); } // TODO: implement it using stat public stat(ftpPath: string): Promise<boolean> { return new Promise((resolve, reject) => { try { this.list(ftpPath); debugger; resolve(true); } catch (err) { debugger; reject(err); } }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public size(ftpPath: string): Promise<number> { const path = this.pathpart(ftpPath); return new Promise((resolve, reject) => { this.client.size(path, (err: Error, bytes: number): void => { if (err) { reject(err); } else { resolve(bytes); } }); }); } } class FtpAPI implements FsApi { type = 1; hostname = ''; connected = false; // main client: the one which will issue list/cd commands *only* master: Client = null; loginOptions: Credentials = null; eventList = new Array<string>(); emitter: EventEmitter; constructor(serverUrl: string) { this.emitter = new EventEmitter(); this.updateServer(serverUrl); } updateServer(url: string): void { this.hostname = this.getHostname(url); this.master = Client.getFreeClient(this.hostname); this.master.api = this; this.connected = this.master.connected; // retrieve options that were used to connect the client if (this.master.options) { this.loginOptions = this.master.options; } } isDirectoryNameValid(dirName: string): boolean { console.log('FTP.isDirectoryNameValid'); return !invalidChars.test(dirName); } resolve(newPath: string): string { return newPath.replace(/\/\.\.$/, ''); } join(path: string, path2: string): string { return join(path, path2); } // eslint-disable-next-line @typescript-eslint/no-unused-vars size(source: string, files: string[]): Promise<number> { console.warn('FTP.size not implemented'); return Promise.resolve(0); } // copy(source: string, files: string[], dest: string): Promise<any> & cp.ProgressEmitter { // console.log('TODO: FsFtp.copy'); // const prom: Promise<void> & cp.ProgressEmitter = new Promise((resolve, reject) => { // resolve(); // }) as Promise<void> & cp.ProgressEmitter; // prom.on = (name, handler): Promise<void> => { // return prom; // } // return prom; // }; makedir(parent: string, name: string): Promise<string> { console.log('FsFtp.makedir'); return this.master.mkdir(parent, name); } delete(source: string, files: File[]): Promise<number> { debugger; return new Promise(async (resolve, reject) => { const fileList = files.filter((file) => !file.isDir); const dirList = files.filter((file) => file.isDir); debugger; for (const file of fileList) { try { debugger; const fullPath = this.join(source, file.fullname); await this.master.delete(fullPath, false); } catch (err) { debugger; reject(err); } } for (const dir of dirList) { try { debugger; const fullPath = this.join(dir.dir, dir.fullname); await this.master.cd(fullPath); debugger; const files = await this.master.list(fullPath); debugger; // first delete files found inside the folder await this.delete(fullPath, files); // then delete the folder itself await this.master.delete(fullPath, true); } catch (err) { debugger; // list // delete() reject(err); } } debugger; resolve(fileList.length + dirList.length); }); } rename(source: string, file: File, newName: string): Promise<string> { console.log('FsFtp.rename'); return this.master.rename(source, file.fullname, newName); } // eslint-disable-next-line @typescript-eslint/no-unused-vars isDir(path: string): Promise<boolean> { console.warn('FsFtp.isDir not implemented: always returns true'); return Promise.resolve(true); } exists(path: string): Promise<boolean> { console.warn('FsFtp.exists not implemented: always returns true'); return this.master.stat(path); // return Promise.resolve(false); } list(dir: string): Promise<File[]> { console.log('FsFtp.readDirectory', dir); return this.master.list(dir); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async makeSymlink(targetPath: string, path: string, transferId?: number): Promise<boolean> { console.log('FsFtp.makeSymlink'); return true; } // eslint-disable-next-line @typescript-eslint/no-unused-vars async stat(fullPath: string): Promise<File> { console.warn('FsFtp.stat: TODO'); return Promise.resolve({ dir: '', fullname: '', name: '', extension: '', cDate: new Date(), mDate: new Date(), length: 0, mode: 777, isDir: false, readonly: false, type: '', } as File); } cd(path: string): Promise<string> { console.log('FsFtp.cd', path); const resolved = this.resolve(path); console.log('FsFtp.cd resolved', resolved); return this.master.cd(resolved); } get(file_path: string, file: string): Promise<string> { const dest = path.join(DOWNLOADS_DIR, file); console.log('need to get file', this.join(file_path, file), 'to', dest); return this.master.get(this.join(file_path, file), dest); } login(server?: string, credentials?: Credentials): Promise<void> { if (server) { this.updateServer(server); // user: string, password: string, port: number this.loginOptions = { ...credentials }; this.loginOptions.user = this.loginOptions.user || 'anonymous'; // user: credentials.user || 'anonymous', // password: credentials.password, // port // }; } else { console.log('FsFtp: attempt to relogin: connection closed ?'); } if (!this.master) { return Promise.reject('calling login but no master client set'); } else if (this.connected) { console.warn('login: already connected'); return Promise.resolve(); } else { return this.master.login(this.loginOptions).then(() => { this.connected = true; }); } } isConnected(): boolean { return this.connected; } isRoot(path: string): boolean { try { const parsed = new URL(path); return parsed.pathname === '/'; } catch (err) { return path === '/'; } } off(): void { console.log('*** free'); // free client this.master.api = null; // remove all listeners for (const event of this.eventList) { this.emitter.removeAllListeners(event); } // close any connections ? // this.master.close(); } async getStream(path: string, file: string): Promise<fs.ReadStream> { console.log('FsFtp.getStream'); try { console.log('*** connecting', this.hostname, Object.assign({ ...this.loginOptions }, { password: '***' })); // 1. get ready client // 2. if not, add one (or wait ?) => use limit connection console.log('getting client'); const client = Client.getFreeClient(this.hostname); console.log('connecting new client'); await client.login(this.loginOptions); console.log('client logged in, creating read stream'); const stream = client.getStream(this.join(path, file)); return Promise.resolve(stream); } catch (err) { console.log('FsLocal.getStream error', err); return Promise.reject(err); } } async putStream(readStream: fs.ReadStream, dstPath: string, progress: (bytesRead: number) => void): Promise<void> { console.log('FsFtp.putStream'); try { // 1. get ready client // 2. if not, add one (or wait ?) => use limit connection console.log('getting client'); const client = Client.getFreeClient(this.hostname); console.log('connecting new client'); await client.login(this.loginOptions); console.log('client logged in, creating read stream'); return client.putStream(readStream, dstPath, progress); } catch (err) { console.log('FsFtp.putStream error', err); return Promise.reject(err); } } getHostname(str: string): string { const info = new URL(str); return info.hostname.toLowerCase(); } getParentTree(dir: string): Array<{ dir: string; fullname: string }> { console.error('TODO: implement me'); const numParts = dir.replace(/^\//, '').split('/').length; for (let i = 0; i < numParts; ++i) {} return []; } sanityze(path: string): string { // first remove credentials from here const info = new URL(path); if (info.username) { let str = info.username; if (info.password) { str += `:${info.password}`; } path = path.replace(`${str}@`, ''); } return path; } // eslint-disable-next-line @typescript-eslint/no-explicit-any on(event: string, cb: (data: any) => void): void { if (this.eventList.indexOf(event) < 0) { this.eventList.push(event); } this.emitter.on(event, cb); } onClose(): void { this.connected = false; this.emitter.emit('close'); } } export const FsFtp: Fs = { icon: 'globe-network', name: 'ftp', description: 'Fs that just implements fs over ftp', options: { needsRefresh: true, }, canread(str: string): boolean { const info = new URL(str); console.log('FsFtp.canread', str, info.protocol, info.protocol === 'ftp:'); return info.protocol === 'ftp:'; }, // eslint-disable-next-line @typescript-eslint/no-unused-vars serverpart(str: string, lowerCase = true): string { const info = new URL(str); return `${info.protocol}//${info.hostname}`; }, credentials(str: string): Credentials { const info = new URL(str); return { port: parseInt(info.port, 10) || 21, password: info.password, user: info.username, }; }, displaypath(str: string) { const info = new URL(str); const split = info.pathname.split('/'); return { fullPath: str, shortPath: split.slice(-1)[0] || '/', }; }, API: FtpAPI, };
the_stack
import { IDataSet, IAxisSet, ICalculatedFields } from '../../src/base/engine'; import { pivot_dataset } from '../base/datasource.spec'; import { PivotView } from '../../src/pivotview/base/pivotview'; import { createElement, remove, EventHandler, getInstance } from '@syncfusion/ej2-base'; import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar'; import { FieldList } from '../../src/common/actions/field-list'; import { CalculatedField } from '../../src/common/calculatedfield/calculated-field'; import { MenuEventArgs } from '@syncfusion/ej2-navigations'; import { MaskedTextBox } from '@syncfusion/ej2-inputs'; import * as util from '../utils.spec'; import { profile, inMB, getMemoryProfile } from '../common.spec'; import { CalculatedFieldCreateEventArgs } from '../../src/common/base/interface'; describe('Calculated Field', () => { let originalTimeout: number; let pivotGridObj: PivotView; let cf: any; let mouseEvent: any; let tapEvent: any; let mouseEventArgs: any = { preventDefault: function () { }, target: null }; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:600px; width:100%' }); PivotView.Inject(CalculatedField, GroupingBar, FieldList); beforeAll(() => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); pivotGridObj = new PivotView( { dataSourceSettings: { dataSource: pivot_dataset as IDataSet[], expandAll: false, enableSorting: true, sortSettings: [{ name: 'state', order: 'Descending' }], formatSettings: [{ name: 'balance', format: 'C' }], calculatedFieldSettings: [{ name: 'price', formula: '"Sum(balance)"+"Count(quantity)"' }], filterSettings: [ { name: 'state', type: 'Include', items: ['Delhi', 'Tamilnadu', 'New Jercy'] } ], rows: [{ name: 'state' }, { name: 'product' }], columns: [{ name: 'eyeColor' }], values: [{ name: 'balance' }, { name: 'quantity' }, { name: 'price', type: 'CalculatedField' }] }, allowCalculatedField: true, showGroupingBar: true, showFieldList: true, calculatedFieldCreate: (args: CalculatedFieldCreateEventArgs)=>{ expect(args.calculatedField).toBeTruthy; expect(args.cancel).toBe(false); console.log('CreateCalcaltedFieldName: ' + args.calculatedField.name); } }); pivotGridObj.appendTo('#PivotGrid'); }); it('Create Dialog', (done: Function) => { cf = new CalculatedField(pivotGridObj); cf.createCalculatedFieldDialog(pivotGridObj); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('nodeExpanding event is triggered', () => { mouseEvent = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false }; tapEvent = { originalEvent: mouseEvent, tapCount: 1 }; let li: Element[] = <Element[] & NodeListOf<Element>>cf.treeObj.element.querySelectorAll('li'); mouseEvent.target = li[2].querySelector('.e-icons'); cf.treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); it('drag and drop node to drop field', () => { let treeObj: any = cf.treeObj; let filterAxiscontent: HTMLElement = document.getElementById(cf.parentID + 'droppable'); let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); let mousedown: any = util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[15].querySelector('.e-drag'), 15, 10); EventHandler.trigger(treeObj.element, 'mousedown', mousedown); let mousemove: any = util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[15].querySelector('.e-drag'), 15, 70); EventHandler.trigger(<any>(document), 'mousemove', mousemove); mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent; mousemove = util.setMouseCordinates(mousemove, 150, 400); EventHandler.trigger(<any>(document), 'mousemove', mousemove); let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent); mouseup.type = 'mouseup'; EventHandler.trigger(<any>(document), 'mouseup', mouseup); expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value !== null).toBeTruthy; (document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value = ''; }); it('drag and drop node to drop field', () => { let treeObj: any = cf.treeObj; let filterAxiscontent: HTMLElement = document.getElementById(cf.parentID + 'droppable'); let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); let mousedown: any = util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[0].querySelector('.e-drag'), 15, 10); EventHandler.trigger(treeObj.element, 'mousedown', mousedown); let mousemove: any = util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[0].querySelector('.e-drag'), 15, 70); EventHandler.trigger(<any>(document), 'mousemove', mousemove); mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent; mousemove = util.setMouseCordinates(mousemove, 150, 400); EventHandler.trigger(<any>(document), 'mousemove', mousemove); let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent); mouseup.type = 'mouseup'; EventHandler.trigger(<any>(document), 'mouseup', mouseup); expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value !== null).toBeTruthy; }); it('drag and drop node to drop field', () => { let treeObj: any = cf.treeObj; let filterAxiscontent: HTMLElement = document.getElementById(cf.parentID + 'droppable'); let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); let mousedown: any = util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[15].querySelector('.e-drag'), 15, 10); EventHandler.trigger(treeObj.element, 'mousedown', mousedown); let mousemove: any = util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[15].querySelector('.e-drag'), 15, 70); EventHandler.trigger(<any>(document), 'mousemove', mousemove); mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent; mousemove = util.setMouseCordinates(mousemove, 150, 400); EventHandler.trigger(<any>(document), 'mousemove', mousemove); let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent); mouseup.type = 'mouseup'; EventHandler.trigger(<any>(document), 'mouseup', mouseup); expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value !== null).toBeTruthy; }); it('drag and drop node to drop field', () => { let treeObj: any = cf.treeObj; let filterAxiscontent: HTMLElement = document.getElementById(cf.parentID + 'droppable'); let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); let mousedown: any = util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[1].querySelector('.e-drag'), 15, 10); EventHandler.trigger(treeObj.element, 'mousedown', mousedown); let mousemove: any = util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[1].querySelector('.e-drag'), 15, 70); EventHandler.trigger(<any>(document), 'mousemove', mousemove); mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent; mousemove = util.setMouseCordinates(mousemove, 150, 400); EventHandler.trigger(<any>(document), 'mousemove', mousemove); let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent); mouseup.type = 'mouseup'; EventHandler.trigger(<any>(document), 'mouseup', mouseup); expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value !== null).toBeTruthy; }); it('drag and drop node to drop field', () => { let treeObj: any = cf.treeObj; let filterAxiscontent: HTMLElement = document.querySelector('.e-pivot-treeview-outer'); let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); let mousedown: any = util.getEventObject('MouseEvents', 'mousedown', treeObj.element, li[2].querySelector('.e-drag'), 15, 10); EventHandler.trigger(treeObj.element, 'mousedown', mousedown); let mousemove: any = util.getEventObject('MouseEvents', 'mousemove', treeObj.element, li[2].querySelector('.e-drag'), 15, 70); EventHandler.trigger(<any>(document), 'mousemove', mousemove); mousemove.srcElement = mousemove.target = mousemove.toElement = filterAxiscontent; mousemove = util.setMouseCordinates(mousemove, 150, 400); EventHandler.trigger(<any>(document), 'mousemove', mousemove); let mouseup: any = util.getEventObject('MouseEvents', 'mouseup', treeObj.element, filterAxiscontent); mouseup.type = 'mouseup'; EventHandler.trigger(<any>(document), 'mouseup', mouseup); expect((document.querySelector('.e-pivot-formula') as HTMLTextAreaElement).value === null).toBeTruthy; }); it('nodeCollapsing event is triggered', (done: Function) => { let li: Element[] = <Element[] & NodeListOf<Element>>cf.treeObj.element.querySelectorAll('li'); mouseEventArgs.target = li[0].querySelector('.e-icons'); tapEvent.originalEvent = mouseEventArgs; cf.treeObj.touchClickObj.tap(tapEvent); setTimeout(function () { cf.treeObj.touchClickObj.tap(tapEvent); expect(true).toEqual(true); done(); }, 1000); }); it('OK Button Click', () => { cf.inputObj.value = 'New'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'New'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '10'; let formatString: MaskedTextBox = getInstance(document.querySelector('#' + pivotGridObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; formatString.setProperties({ value: 'C0' }); formatString.refresh(); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); cf.dialog.buttons[0].click(); }); it('Open Dialog', (done: Function) => { setTimeout(() => { expect((pivotGridObj.pivotValues[2][4] as IAxisSet).formattedText).toBe('$10'); cf.createCalculatedFieldDialog(pivotGridObj); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('treeview click', () => { // (document.querySelectorAll('.e-pivot-treeview-outer .e-fullrow')[1] as HTMLElement).click(); let treeObj: any = cf.treeObj; // let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); // let e: any = { // target: li[1].querySelector('.e-fullrow') // }; // cf.fieldClickHandler(e as MouseEvent); let li: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('li'); mouseEvent.target = li[1].querySelector('.e-format'); tapEvent.originalEvent = mouseEvent; treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); // it('treeview click', () => { // let treeObj: any = cf.treeObj; // let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>treeObj.element.querySelectorAll('li'); // let e: any = { // target: li[0].querySelector('.e-fullrow') // }; // cf.fieldClickHandler(e as MouseEvent); // // (document.querySelector('.e-pivot-treeview-outer .e-fullrow') as HTMLElement).click(); // expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); // }); it('Context menu click', () => { // let contextmenu: any = util.getEventObject('MouseEvents', 'contextmenu'); // EventHandler.trigger(document.querySelector('#' + cf.parentID + 'contextmenu'), 'contextmenu', contextmenu); // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(() => { // mouseEventArgs.target = document.querySelector('#' + cf.parentID + 'contextmenu li'); // mouseEventArgs.type = 'click'; // cf.menuObj.clickHandler(mouseEventArgs); // done(); // }, 1000); let menuObj: any = cf.menuObj; let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>menuObj.element.querySelectorAll('li'); let menu: any = { element: li[0] }; menuObj.element.style.display = 'none'; cf.selectContextMenu(menu as MenuEventArgs); expect(true).toBeTruthy(); }); it('check context menu click', () => { expect(document.querySelector('#' + cf.parentID + 'contextmenu')).toBeTruthy; // expect((document.querySelector('#' + cf.parentID + 'contextmenu') as HTMLElement).style.display).toBe('none'); }); it('treeview click', function () { var treeObj = cf.treeObj; // var li = treeObj.element.querySelectorAll('li'); // var e = { // target: li[13].querySelector('.e-edit') // }; // cf.fieldClickHandler(e); let li: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('li'); mouseEvent.target = li[13].querySelector('.e-edit'); tapEvent.originalEvent = mouseEvent; treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); it('Edit Click', function () { var treeObj = cf.treeObj; let li: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('li'); mouseEvent.target = li[13].querySelector('.e-edited'); tapEvent.originalEvent = mouseEvent; treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); it('Clear Click', function () { var treeObj = cf.treeObj; let li: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('li'); mouseEvent.target = li[13].querySelector('.e-edit'); tapEvent.originalEvent = mouseEvent; treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); it('Edit Formula', function (done) { cf.inputObj.value = 'Price'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'Price'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '100/100'; let formatString: MaskedTextBox = getInstance(document.querySelector('#' + pivotGridObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; expect(formatString.value).toBe('C0'); formatString.setProperties({ value: 'P1' }); formatString.refresh(); setTimeout(function () { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); cf.dialog.buttons[0].click(); done(); }, 1000); }); it('Open Dialog', function (done) { setTimeout(function () { expect((pivotGridObj.pivotValues[2][4] as IAxisSet).formattedText).toBe('100.0%'); cf.createCalculatedFieldDialog(pivotGridObj); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('Open Dialog', (done: Function) => { cf.inputObj.value = 'price'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'price'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '10'; let formatString: MaskedTextBox = getInstance(document.querySelector('#' + pivotGridObj.element.id + 'Custom_Format_Element') as HTMLElement, MaskedTextBox) as MaskedTextBox; expect(formatString).toBeTruthy; formatString.setProperties({ value: 'C2' }); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); cf.dialog.buttons[0].click(); done(); }, 1000); }); it('OK Button Click', (done: Function) => { setTimeout(() => { (document.querySelector('.e-ok-btn') as HTMLElement).click(); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('Open Dialog', (done: Function) => { expect((pivotGridObj.pivotValues[2][3] as IAxisSet).formattedText).toBe('$10.00'); cf.createCalculatedFieldDialog(pivotGridObj); setTimeout(() => { cf.inputObj.value = 'price1'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'price1'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '10'; expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('OK Button Click', (done: Function) => { // cf.dialog.buttons[0].click(); let calcInfo: ICalculatedFields = { name: 'price1', formula: '10', formatString: '' }; cf.replaceFormula(calcInfo); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('Open Dialog', (done: Function) => { cf.createCalculatedFieldDialog(pivotGridObj); setTimeout(() => { cf.inputObj.value = 'price1'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'price1'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = '100/*-78'; done(); }, 1000); }); it('OK Button Click', (done: Function) => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); cf.dialog.buttons[0].click(); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('Open Dialog', (done: Function) => { (document.querySelector('.e-control.e-btn.e-ok-btn') as any).click(); // document.querySelector('.e-pivot-error-dialog').remove(); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); cf.dialog.buttons[1].click(); done(); }, 1000); }); it('Cancel Button Click', (done: Function) => { setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); (document.querySelector('.e-toggle-field-list') as HTMLElement).click(); done(); }, 1000); }); it('check field list icon', (done: Function) => { (document.querySelector('.e-calculated-field') as HTMLElement).click(); setTimeout(() => { (pivotGridObj.pivotFieldListModule.calculatedFieldModule as any).inputObj.value = 'Pric'; (document.querySelector('.e-pivot-calc-input') as HTMLInputElement).value = 'Pric'; (document.querySelector('.e-pivot-formula') as HTMLInputElement).value = 'balance*100'; (pivotGridObj.pivotFieldListModule.calculatedFieldModule as any).dialog.buttons[0].click(); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('check calculated field button for edit option', (done: Function) => { let rightAxisPanel: HTMLElement = pivotGridObj.pivotFieldListModule.axisTableModule.axisTable.querySelector('.e-right-axis-fields'); let pivotButtons: HTMLElement[] = [].slice.call(rightAxisPanel.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(6); expect(pivotButtons[4].id).toBe('New'); (pivotButtons[4].querySelector('.e-edit') as HTMLElement).click(); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('Price'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('100/100'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe('P1'); (pivotGridObj.pivotFieldListModule.calculatedFieldModule as any).inputObj.value = 'New-1'; done(); }, 1000); }); it('Update and close calculated field dialog', (done: Function) => { (pivotGridObj.pivotFieldListModule.calculatedFieldModule as any).dialog.buttons[0].click(); setTimeout(() => { let rightAxisPanel: HTMLElement = pivotGridObj.pivotFieldListModule.axisTableModule.axisTable.querySelector('.e-right-axis-fields'); let pivotButtons: HTMLElement[] = [].slice.call(rightAxisPanel.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(6); expect(pivotButtons[4].id).toBe('New'); expect(pivotButtons[4].textContent).toBe('New-1'); done(); }, 1000); }); it('close field list popup', (done: Function) => { expect(document.getElementsByClassName('e-dialog').length === 1).toBeTruthy(); (document.getElementsByClassName('e-cancel-btn')[0] as any).click(); setTimeout(() => { expect((document.getElementsByClassName('e-dialog')[0] as any).classList.contains('e-popup-open')).toBe(false); done(); }, 1000); }); it('check calculated field button for edit option in grouping bar', (done: Function) => { let leftAxisPanel: HTMLElement = pivotGridObj.element.querySelector('.e-left-axis-fields'); let pivotButtons: HTMLElement[] = [].slice.call(leftAxisPanel.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(5); expect(pivotButtons[4].id).toBe('Pric'); (pivotButtons[4].querySelector('.e-edit') as HTMLElement).click(); setTimeout(() => { expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); expect((document.querySelector('.e-pivot-calc-input') as any).value).toBe('Pric'); expect((document.querySelector('.e-pivot-formula') as any).value).toBe('balance*100'); expect((document.querySelector('.e-custom-format-input') as any).value).toBe(''); cf.inputObj.value = 'Price-1'; done(); }, 1000); }); it('Update and close calculated field dialog', (done: Function) => { cf.dialog.buttons[0].click(); setTimeout(() => { let leftAxisPanel: HTMLElement = pivotGridObj.element.querySelector('.e-left-axis-fields'); let pivotButtons: HTMLElement[] = [].slice.call(leftAxisPanel.querySelectorAll('.e-pivot-button')); expect(pivotButtons.length).toEqual(5); expect(pivotButtons[4].id).toBe('Pric'); expect(pivotButtons[4].textContent).toBe('Price-1'); done(); }, 1000); }); it('Open Dialog', (done: Function) => { setTimeout(() => { pivotGridObj.setProperties({ enableRtl: true }, true); pivotGridObj.enableRtl = true; cf.createCalculatedFieldDialog(pivotGridObj); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); done(); }, 1000); }); it('treeview click', () => { let treeObj: any = cf.treeObj; let li: Element[] = <Element[] & NodeListOf<Element>>treeObj.element.querySelectorAll('li'); mouseEvent.target = li[1].querySelector('.e-format'); tapEvent.originalEvent = mouseEvent; treeObj.touchClickObj.tap(tapEvent); expect(document.getElementsByClassName('e-dialog').length > 0).toBeTruthy(); }); it('Context menu click', () => { let menuObj: any = cf.menuObj; let li: Element[] = <Element[] & NodeListOf<HTMLLIElement>>menuObj.element.querySelectorAll('li'); let menu: any = { element: li[0] }; menuObj.element.style.display = 'none'; cf.selectContextMenu(menu as MenuEventArgs); expect(true).toBeTruthy(); }); it('check context menu click', () => { expect(document.querySelector('#' + cf.parentID + 'contextmenu')).toBeTruthy; cf.dialog.buttons[1].click(); // remove(document.querySelector('.e-dialog')); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB //expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); });
the_stack
/// <reference types="jquery" /> type CallBack = () => void; /** * bootstrap */ interface ModalOptions { backdrop?: boolean | string; keyboard?: boolean; show?: boolean; remote?: string; } interface ModalOptionsBackdropString { backdrop?: string; // for "static" keyboard?: boolean; show?: boolean; remote?: string; } interface ScrollSpyOptions { offset?: number; target?: string; } interface TooltipOptions { animation?: boolean; html?: boolean; placement?: string | CallBack; selector?: string; title?: string | CallBack; trigger?: string; template?: string; delay?: number | object; container?: string | boolean; viewport?: string | CallBack | object; } interface PopoverOptions { animation?: boolean; html?: boolean; placement?: string | CallBack; selector?: string; trigger?: string; title?: string | CallBack; template?: string; content?: any; delay?: number | object; container?: string | boolean; viewport?: string | CallBack | object; } interface CollapseOptions { parent?: any; toggle?: boolean; } interface CarouselOptions { interval?: number; pause?: string; wrap?: boolean; keyboard?: boolean; } interface TypeaheadOptions { source?: any; items?: number; minLength?: number; matcher?(item: any): boolean; sorter?(items: any[]): any[]; updater?(item: any): any; highlighter?(item: any): string; } interface AffixOptions { offset?: number | CallBack | object; target?: any; } interface TransitionEventNames { end: string; } interface JQuery { modal(options?: ModalOptions | ModalOptionsBackdropString): JQuery; modal(command: string): JQuery; dropdown(command?: string): JQuery; scrollspy(options?: ScrollSpyOptions | string): JQuery; tab(command?: string): JQuery; tooltip(options?: TooltipOptions): JQuery; tooltip(command: string, params?: string): JQuery; popover(options?: PopoverOptions | string): JQuery; alert(command?: string): JQuery; button(command?: string): JQuery; collapse(options?: CollapseOptions | string): JQuery; carousel(options?: CarouselOptions | string): JQuery; typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; emulateTransitionEnd(duration: number): JQuery; } interface JQuerySupport { transition: boolean | TransitionEventNames; } /** * datetime picker */ interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { oldDate: any; } interface DatetimepickerEventObject extends JQueryEventObject { date: any; } interface DatetimepickerIcons { time?: string; date?: string; up?: string; down?: string; } interface DatetimepickerOptions { weekStart?: number; todayBtn?: number | boolean; autoclose?: number | boolean; todayHighlight?: number | boolean; startView?: number; forceParse?: number | boolean; showMeridian?: boolean | number; minView?: number; maxView?: number; pickDate?: boolean; pickTime?: boolean; useMinutes?: boolean; useSeconds?: boolean; useCurrent?: boolean; minuteStepping?: number; minDate?: Date | string | any; maxDate?: Date | string | any; showToday?: boolean; collapse?: boolean; language?: string; defaultDate?: Date | string | any; disabledDates?: Array<Date | string | object>; enabledDates?: Array<Date | string | object>; icons?: DatetimepickerIcons; useStrict?: boolean; direction?: string; sideBySide?: boolean; daysOfWeekDisabled?: number[]; calendarWeeks?: boolean; format?: string | boolean; locale?: string; showTodayButton?: boolean; viewMode?: string; inline?: boolean; toolbarPlacement?: string; showClear?: boolean; ignoreReadonly?: boolean; } interface Datetimepicker { date(date: Date | string | object): void; date(): object; minDate(date: Date | string | object): void; minDate(): boolean | object; maxDate(date: Date | string | object): void; maxDate(): boolean | object; show(): void; disable(): void; enable(): void; destroy(): void; toggle(): void; } interface JQuery { datetimepicker(options?: DatetimepickerOptions): JQuery; // off(events: "dp.change", selector?: string, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; // off(events: "dp.change", handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; // on(events: "dp.change", selector: string, data: any, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; // on(events: "dp.change", selector: string, handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; // on(events: 'dp.change', handler: (eventObject: DatetimepickerChangeEventObject) => any): JQuery; // off(events: "dp.show", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // off(events: "dp.show", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.show", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.show", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: 'dp.show', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; // off(events: "dp.hide", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // off(events: "dp.hide", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.hide", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: 'dp.hide', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; // off(events: "dp.error", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // off(events: "dp.error", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.error", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: "dp.error", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; // on(events: 'dp.error', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; data(key: 'DateTimePicker'): Datetimepicker; } /** * store */ interface StoreStatic { enable: boolean; storage: any; length(): number; remove(key: string): any; get<T>(key: string): T; set<T>(key: string, value?: T): any; key(index: number): string; forEach<T>(cb: (key: string, value: T) => any): any; serialize(value: any): string; deserialize<T>(value: string): T; getAll<T>(): T; removeItem(key: string): any; getItem(key: string): string; setItem(key: string, value: any): any; clear(): void; page: any; pageGet(key: string): any; pageSet(key: string, value: any): any; pageRemove(key: string): any; pageSave(): any; pageClear(): any; } /** * messager */ declare enum MessagerTypeEnum { 'default', 'primary', 'success', 'info', 'warning', 'danger', 'important', 'special' } interface Action { name?: string; icon?: string; text?: string; html?: string; action?: ActionFunc; } type ActionFunc = () => boolean; type OnActionFunc = (name: string, action: string, messager: Messager) => any; interface MessagerOption { type?: MessagerTypeEnum | string; placement?: string; time?: number; message?: string; parent?: string; icon?: string; close?: boolean; fade?: boolean; scale?: boolean; actions?: Action[]; onAction?: OnActionFunc; cssClass?: string; contentClass?: string; show?: boolean; } interface Messager { show(cb?: CallBack): any; show(message: string, cb?: CallBack): any; hide(cb?: CallBack): any; } interface MessagerStatic { new(option?: MessagerOption): Messager; new(message: string, option?: MessagerOption): Messager; } interface ZuiStatic { // $.zui.messager messager: Messager; Messager: MessagerStatic; store: StoreStatic; } /** * modal trigger */ interface ModalTriggerOption { name?: string; className?: string; type?: string; url?: string; remote?: string; iframe?: string; size?: string; width?: string; height?: string; showHeader?: boolean; title?: string; icon?: string; fade?: boolean; postion?: string; backdrop?: boolean; keyboard?: boolean; moveable?: boolean; rememberPos?: boolean; waittime?: number; loadingIcon?: string; show?(): any; onShow?(): any; onHide?(): any; hidden?(): any; loaded?(): any; broken?(): any; } interface ModalTrigger { show(option?: ModalTriggerOption): any; close(): any; toggle(option?: ModalTriggerOption): any; adjustPostion(option?: ModalTriggerOption): any; } interface ModalTriggerStatic { new(option?: ModalTriggerOption): ModalTrigger; } interface JQuery { modalTrigger(option?: ModalTriggerOption): JQuery; // $('#modal').modalTrigger() data(value: string): JQuery; } interface ZuiStatic { ModalTrigger: ModalTriggerStatic; modalTrigger: ModalTrigger; } interface JQueryStatic { zui: ZuiStatic; } /** * color */ interface Color { rgb(rgbaColor?: string): object; hue(hue: string): string; darken(percent: number): string; lighten(percent: number): string; clone(): Color; fade(percent: number): any; toHsl(): object; luma(): string; saturate(): string; contrast(dark: string, light: string, threshold: number): string; hexStr(): string; toCssStr(): string; } interface ColorStatic { new(r: number, g: number, b: number, a?: number): Color; new(hexStrOrrgbColorOrRgbaColorOrName?: string): Color; isColor(str: string): boolean; names: string[]; } interface ColorSet { get(name: string): Color; } interface ZuiStatic { Color: ColorStatic; colorset: ColorSet; } /** * draggable */ interface Postion { left: number; top: number; width: number; height: number; } interface DraggableEvent { event?: object; element?: JQuery | object; target?: JQuery | object; pos?: Postion; offset?: object; smallOffset?: object; startOffset?: object; } interface DraggableOption { container?: string; move?: boolean; selector?: string; handle?: string; mouseButton?: string; stopPropagation?: boolean; before?(e?: DraggableEvent): boolean; drag?(e: DraggableEvent): void; finish?(e: DraggableEvent): void; } interface JQuery { draggable(option: DraggableOption | string): JQuery; } /** * droppable */ interface Postion { left: number; top: number; width: number; height: number; } interface DroppableEvent { event?: object; element?: JQuery; target?: JQuery; pos?: Postion; offset?: object; smallOffset?: object; startOffset?: object; } interface DroppableOption { container?: string; selector?: string; handle?: string; target: JQuery | string; flex?: boolean; deviation?: number; sensorOffsetX?: number; sensorOffsetY?: number; before?(e?: DroppableEvent): boolean; start?(e?: DroppableEvent): void; drag?(e: DroppableEvent): void; beforeDrop?(e: DroppableEvent): boolean; drop?(e: DroppableEvent): void; finish?(e: DroppableEvent): void; always?(e: DroppableEvent): void; } interface JQuery { droppable(option: DroppableOption | string): JQuery; } /** * sortable */ interface SortEvent extends Event { list: Array<JQuery | object>; element: JQuery | object; } interface SortableOption { selector?: string; trigger?: string; reverse?: boolean; dragCssClass?: string; sortingClass?: string; mouseButton?: string; start?(e?: SortEvent): void; order?(e?: SortEvent): void; finish?(e?: SortEvent): void; } interface JQuery { sortable(option?: SortableOption | string): JQuery; } /** * selectable */ interface SelectableEvent extends Event { selections: Map<number, boolean>; selected: number[]; } interface SelectableOption { selector?: string; trigger?: string; rangeStyle?: string | object; clickBehavior?: string; mouseButton?: string; ignoreVal?: number; start?(e?: SelectableEvent): boolean; finish?(e?: SelectableEvent): void; select?(e?: SelectableEvent): void; unselect?(e?: SelectableEvent): void; } interface Selectable { toggle(elementOrId?: string | object | JQuery): any; select(elementOrId?: string | object | JQuery): any; unselect(elementOrId?: string | object | JQuery): any; } interface JQuery { selectable(option?: SelectableOption): JQuery; } /** * image cutter */ interface ImageCutterOption { coverColor?: string; coverOpacity?: number; defaultWidth?: number; defaultHeight?: number; fixedRatio?: boolean; minWidth?: number; minHeight?: number; post?: string; get?: string; } interface ImageData { originWidth: number; originHeight: number; scaled: boolean; scaleHeight: number; scaleWidth: number; // width: number; // height: number; left: number; right: number; top: number; bottom: number; } interface ImageCutter { resetImage(img: string): any; getData(): ImageData; } interface JQuery { imgCutter(option: ImageCutterOption): JQuery; data(cmd: string): ImageCutter; } /** * treeview */ interface TreeNode { title?: string; url?: string; html?: string; children?: TreeNode[]; open?: boolean; id?: string; } interface TreeMenuOption { animate?: boolean; initialState?: string; data?: TreeNode[]; itemCreator?(li: JQuery | object, item: TreeNode): any; itemWrapper?: boolean; } interface TreeMenu { expand(params?: JQuery, disableAnimate?: boolean): void; collapse(params?: JQuery, disableAnimate?: boolean): void; toggle(params?: JQuery, disableAnimate?: boolean): void; show(params?: JQuery, disableAnimate?: boolean): void; add(element: JQuery, items: TreeNode[], expand?: boolean, disabledAnimate?: boolean): void; toData($ul?: JQuery, filter?: string): object; reload(data: TreeNode[]): void; remove(): void; empty(): void; } interface JQuery { tree(option?: TreeMenuOption): JQuery; } interface Column { width?: number; text?: string; type?: string; flex?: boolean; colClass?: string; sort?: string; ignore?: boolean; } interface Row { id?: string; checked?: boolean; cssClass?: string; css?: string; data?: [number, string, string]; } interface DataTableData { rows: Row[]; cols: Column[]; } interface AfterLoadEvent extends Event { data: DataTableData; } interface SortEvent extends Event { sorter: { index: number; sortUp: boolean; }; } interface SizeChangeEvent extends Event { changes: { change: string; oldWidth: number; newWidth: number; colIndex: number; }; } interface ChecksChangeEvent extends Event { checks: { checkedAll: boolean; checks: number[]; }; } interface DataTableOption { checkable?: boolean; checkByClickRow?: boolean; checkedClass?: string; storage?: boolean; sortable?: boolean; fixedHeader?: boolean; fixedHeaderOffset?: number; fixedLeftWidth?: string; fixedRightWidth?: string; flexHeadDrag?: boolean; scrollPos?: string; rowHover?: boolean; colHover?: boolean; fixCellHeight?: boolean; minColWidth?: number; minFixedLeftWidth?: number; minFixedRightWidth?: number; minFlexAreaWidth?: number; selectable?: boolean | object; afterLoad?(event: AfterLoadEvent): void; ready?(): void; sort?(event: SortEvent): void; sizeChanged?(event: SizeChangeEvent): void; checksChanged?(event: ChecksChangeEvent): void; } interface DataTable { checks: { checkedAll: boolean, checks: number[] }; } interface JQuery { datatable(option?: DataTableOption): JQuery; datatable(command: string, optionOrData: DataTableOption | DataTableData): JQuery; } /** * uploader */ interface UploaderOption { drop_element?: string; browse_button?: string; url: string; qiniu?: object; filters?: { mime_type: Array<{ title?: string; extensions?: string; }>, max_file_size?: string; prevent_duplicates?: string; }; fileList?: string; fileTemplate?: string; fileFormater?($file: JQuery, file: FileObj, status: STATUS): void; fileIconCreator?(fileType: string, file: FileObj, uploader: Uploader): void; staticFiles?: Array<{ id?: string; name?: string; type?: string; size?: string; origSize?: string; lastModifiedDate?: Date; }>; rename?: boolean; renameExtension?: boolean; renameByClick?: boolean; autoUpload?: boolean; browseByClickList?: boolean; dropPlaceholder?: boolean; previewImageIcon?: boolean; sendFileName?: boolean; sendFileId?: boolean; responseHandler?: boolean | CallBack; limitFilesCount?: boolean | number; deleteConfirm?: boolean | string; removeUploaded?: boolean; statusCreator?(total: UploadProgress, state: STATUS, uploader: Uploader): void; previewImageSize?: { width: number, height: number }; uploadedMessage?: boolean; deleteActionOnDone?: boolean; renameActionOnDone?: boolean; headers?: object; multipart?: boolean; multipart_params?: object | CallBack; max_retries?: number; chunk_size?: string; resize?: { width?: number; height?: number; crop?: boolean; quuality?: number; preserve_headers?: boolean; }; multi_selection?: boolean; unique_names?: boolean; runtimes?: string; file_data_name?: string; flash_swf_url?: string; silverlight_xap_url?: string; lang?: string; onInit?(): void; onFilesAdded?(fiels: FileObj[]): void; onUploadProgress?(file: FileObj): void; onFileUploaded?(file: FileObj, responseObject: ResponseObject): void; onUploadComplete?(files: FileObj[]): void; onFilesRemoved?(files: FileObj[]): void; onChunkUploaded?(file: FileObj, responseObject: ResponseObject): void; onUploadFile?(file: FileObj): void; onBeforeUpload?(file: FileObj): void; onStateChanged?(status: STATUS): void; onQueueChanged?(): void; onError?(error: { error: ERRORS, message: string, file: FileObj }): void; } interface ResponseObject { response?: string; responseHeaders?: object; status?: number; offset?: number; total?: number; } declare enum STATUS { STOPPED = 1, STARTED = 2, QUEUED = 1, UPLOADING = 2, FAILED = 3, DONE = 4 } interface FileObj { id?: string; name?: string; type?: string; ext?: string; isImage?: boolean; previewImage?: string; size?: number; origSize?: number; loaded?: number; percent?: number; status?: STATUS; lastModifiedDate?: Date; getNative(): File; destroy(): void; } interface UploadProgress { size?: number; loaded?: number; uploaded?: number; failed?: number; queued?: number; percent?: number; bytesPerSec?: number; } declare enum ERRORS { GENERIC_ERROR = -100, HTTP_ERROR = -200, IO_ERROR = -300, SECURITY_ERROR = -400, INIT_ERROR = -500, FILE_SIZE_ERROR = -600, FILE_EXTENSION_ERROR = -601, FILE_DUPLICATE_ERROR = -602, IMAGE_FORMAT_ERROR = -700, IMAGE_MEMORY_ERROR = -701, IMAGE_DIMENSIONS_ERROR = -702 } interface Uploader { showMessage(message: string, type: string, time?: number): void; hideMessage(): void; start(): void; stop(): void; getState(): STATUS; isStarted(): boolean; isStopped(): boolean; getFiles(): FileObj[]; getTotal(): UploadProgress; disableBrowse(disable: boolean): void; getFile(id: string): FileObj; showFile(file: FileObj | FileObj[]): void; removeFile(file: FileObj): void; destroy(): void; showStatus(): void; } interface JQuery { uploader(option: UploaderOption): JQuery; }
the_stack
import { app, BrowserWindow, Menu, Tray, globalShortcut, powerMonitor, ipcMain, Notification, } from 'electron'; import getLogger from './Logger'; import path from 'path'; import is_dev from 'electron-is-dev'; import { buildEmitters, killEmitters, loopsAreRunning, runLoop, } from './IPCEvents/IPCEmitters'; import { HID } from 'node-hid'; import { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer'; import url from 'url'; import { buildPath, loadConfig, writeConfig } from './IPCEvents/ConfigLoader'; import { setUpNewG14ControlKey } from './IPCEvents/HID/HIDDevice'; import { buildIpcConnection } from './IPCEvents/IPCListeners'; import { FnF5mapperBuilder, ROGmapperBuilder, } from './IPCEvents/RogKeyRemapperListener'; import { buildTrayIcon } from './TrayIcon'; import installExtension from 'electron-devtools-installer'; import forceFocus from 'forcefocus'; import AutoUpdater from './AppUpdater'; import { isUndefined } from 'lodash'; import { buildTaskbarMenu } from './Taskbar'; import { NotificationConstructorOptions } from 'electron/main'; import { initSwitch, initF5Switch } from './AutoPowerSwitching'; import { initStartupPlan } from './StartupPlan'; import updateConfigOnUpdate from './UpdateConfig'; const LOGGER = getLogger('Main'); const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { LOGGER.info('Another process had the lock, quitting!'); app.exit(); } export let g14Config: G14Config; export const setG14Config = (g14conf: G14Config) => { g14Config = g14conf; }; const ICONPATH = is_dev ? path.join(__dirname, '../', 'src', 'assets', 'icon.ico') : path.join( app.getPath('exe'), '../', 'resources', 'extraResources', 'icon.ico' ); export let powerDelivery: 'battery' | 'ac' = 'ac'; export const getPowerDelivery = () => powerDelivery; export const setPowerDelivery = (val: 'battery' | 'ac') => (powerDelivery = val); export let powerPlan: 'battery' | 'ac' = 'ac'; export const getPowerPlan = () => powerPlan; const setPowerPlan = (val: 'battery' | 'ac') => (powerPlan = val); export let browserWindow: BrowserWindow; export let showIconEnabled = false; export let tray: Tray; export let trayContext: Menu; export let hid: HID; export let updateNote: AutoUpdater<{}>; if (is_dev) { LOGGER.info('Running in development'); } else { LOGGER.info('Running in production'); } export const getConfig = () => g14Config; export const minMaxFunc = () => { if (browserWindow.isVisible() && browserWindow.isFocused()) { let conf = getConfig(); conf.current.minToTray ? browserWindow.hide() : browserWindow.minimize(); } else { LOGGER.info('Attempting to force focus to the browserWindow'); if (browserWindow) { browserWindow.show(); forceFocus.focusWindow(browserWindow); browserWindow.show(); } else { LOGGER.info("browserWindow didn't exist."); } } }; export const togglePlan = () => { LOGGER.info('FN+F5 pressed'); initF5Switch(); }; export const getROGHID = () => hid; export const setHidMain = (hiddevice: HID) => { LOGGER.info('Updating state of rogKey hid device.'); hid = hiddevice; }; export const updateMenuVisible = (_minimized?: boolean) => { if (browserWindow.isMinimized() || !browserWindow.isVisible()) { trayContext.getMenuItemById('showapp').enabled = true; trayContext.getMenuItemById('hideapp').enabled = false; } else { trayContext.getMenuItemById('showapp').enabled = false; trayContext.getMenuItemById('hideapp').enabled = true; } }; const args = process.argv; export const showNotification = (title: string, body: string) => { const notification: NotificationConstructorOptions = { icon: ICONPATH, title: title, body: body, silent: false, timeoutType: 'default', }; new Notification(notification).show(); }; export const buildBrowserListeners = (browserWindow: BrowserWindow) => { // set up renderer process events. browserWindow.on('hide', async () => { if (loopsAreRunning()) { await killEmitters(); } updateMenuVisible(); }); browserWindow.on('show', () => { if (!loopsAreRunning()) { runLoop(browserWindow); } updateMenuVisible(); }); browserWindow.on('minimize', async () => { if (loopsAreRunning()) { await killEmitters(); } updateMenuVisible(); }); browserWindow.on('restore', () => { if (!loopsAreRunning()) { runLoop(browserWindow); } updateMenuVisible(); }); browserWindow.on('unresponsive', () => { LOGGER.info('Window is unresponsive...'); browserWindow.webContents.reload(); }); }; export async function createWindow( gotTheLock: any, g14Config: G14Config, browserWindow: BrowserWindow, tray: Tray, trayContext: any, ICONPATH: string, _hid: HID ) { // Create the browser window. if (!gotTheLock) { app.quit(); } await buildPath(); // load the config try { g14Config = JSON.parse((await loadConfig()).toString()) as G14Config; } catch (err) { LOGGER.error('Error loading config at startup'); } await updateConfigOnUpdate(g14Config); // Set appid so notifications don't show entire app id. app.setAppUserModelId('G14ControlV2'); // logic for start on boot minimized let startWithFocus = true; if (args.length > 1 && args[1] === 'hide') { LOGGER.info('Starting with hidden browser Window'); if (isUndefined(g14Config.startup.startMinimized)) { g14Config.startup['startMinimized'] = true; writeConfig(g14Config); } if (g14Config.startup.startMinimized) { startWithFocus = false; } } browserWindow = new BrowserWindow({ width: 960, height: 600, resizable: true, maxWidth: is_dev ? 1920 : 1300, minWidth: 960, titleBarStyle: 'hidden', autoHideMenuBar: true, frame: false, icon: ICONPATH, show: startWithFocus, webPreferences: { allowRunningInsecureContent: false, worldSafeExecuteJavaScript: true, accessibleTitle: 'G14ControlV2', preload: __dirname + '/Preload.js', enableRemoteModule: true, }, darkTheme: true, }); // install dev tools if (is_dev) { installExtension(REACT_DEVELOPER_TOOLS) .then((name: any) => console.log(`Added Extension: ${name}`)) .catch((err: any) => console.log('An error occurred adding devtools: ', err) ); } // create ipc and modify listeners const ipc = ipcMain; ipc.setMaxListeners(35); browserWindow.setMaxListeners(35); app.setMaxListeners(35); buildIpcConnection(ipc, browserWindow); buildEmitters(ipc, browserWindow); // and load the index.html of the app. let loadurl = 'http://localhost:3000/'; if (!is_dev) { browserWindow.loadURL( url.format({ pathname: path.join(__dirname, './index.html'), protocol: 'file:', slashes: true, }) ); } else { browserWindow.loadURL(loadurl); } // build tray icon menu let results = await buildTrayIcon(tray, trayContext, browserWindow); tray = results.tray; trayContext = results.trayContext; browserWindow = results.browserWindow; buildBrowserListeners(browserWindow); ipcMain.handle('getVersion', () => { return app.getVersion(); }); ipcMain.once('isLoaded', () => { LOGGER.info('Renderer process built and updater being initialized...'); updateNote = new AutoUpdater<{}>(browserWindow, ipcMain); updateNote.checkForUpdate(); }); let { shortcuts, rogKey } = g14Config.current; // Register global shortcut ctrl + space if (shortcuts.minmax.enabled) { let registered = globalShortcut.register( shortcuts.minmax.accelerator, () => { if (browserWindow.isFocused()) { browserWindow.minimize(); } else { browserWindow.show(); } } ); if (registered) { LOGGER.info('Show app shortcut registered.'); } else { LOGGER.info('Error registering shortcut.'); } } if (rogKey.enabled) { let hdd = setUpNewG14ControlKey(ROGmapperBuilder); if (hdd) { setHidMain(hdd); LOGGER.info('ROG key HID built and listening.'); } else { LOGGER.info('There was an issue setting up ROG HID'); } } if ( g14Config.f5Switch && g14Config.f5Switch.enabled && g14Config.f5Switch.f5Plans.length > 1 ) { const hdd2 = setUpNewG14ControlKey(FnF5mapperBuilder); if (hdd2) { setHidMain(hdd2); LOGGER.info('FN+F5 HID built and listening.'); } else { LOGGER.info('There was an issue setting up FN+F5 HID'); } } browserWindow.setMenu(null); if (g14Config.autoSwitch && g14Config.autoSwitch.applyOnBoot) { setTimeout(() => { initStartupPlan(getConfig()); }, 3000); } return { tray, browserWindow, g14Config, trayContext }; } export const setupElectronReload = (config: G14Config) => { let { shortcuts, rogKey } = config.current; // Register global shortcut (example: ctrl + space) if (shortcuts.minmax.enabled) { globalShortcut.unregisterAll(); let registered = globalShortcut.register( shortcuts.minmax.accelerator, minMaxFunc ); if (registered) { LOGGER.info('Show app shortcut registered.'); } else { LOGGER.info('Error registering shortcut.'); } } if (rogKey.enabled && !hid) { let hdd = setUpNewG14ControlKey(ROGmapperBuilder); if (hdd) { setHidMain(hdd); LOGGER.info('ROG key HID built and listening.'); } else { LOGGER.info('There was an issue setting up ROG HID'); } } if ( g14Config.autoSwitch && g14Config.autoSwitch.enabled && g14Config.autoSwitch.dcPlan && g14Config.autoSwitch.acPlan ) { const hdd2 = setUpNewG14ControlKey(FnF5mapperBuilder); if (hdd2) { setHidMain(hdd2); LOGGER.info('FN+F5 HID built and listening.'); } else { LOGGER.info('There was an issue setting up FN+F5 HID'); } } }; powerMonitor.on('shutdown', () => { LOGGER.info('Windows is shutting down (sent from powermonitor)'); globalShortcut.unregisterAll(); if (hid) { hid.close(); } if (!tray.isDestroyed()) { tray.destroy(); } if (!browserWindow.isDestroyed()) { browserWindow.destroy(); } if (loopsAreRunning()) { killEmitters().then(() => { app.quit(); }); } else { app.quit(); } }); powerMonitor.on('resume', () => { LOGGER.info('Resume: initializing startup plan.'); if (g14Config.autoSwitch && g14Config.autoSwitch.applyOnBoot) { setTimeout(() => { initStartupPlan(getConfig()); }, 3000); } }); powerMonitor.on('suspend', () => { LOGGER.info('Windows is suspending (sent from powermonitor)'); browserWindow.hide(); }); powerMonitor.on('on-ac', () => { if ( g14Config.autoSwitch && g14Config.autoSwitch.enabled && g14Config.autoSwitch.acPlan ) { initSwitch('ac').then(() => setPowerPlan('battery')); } }); powerMonitor.on('on-battery', () => { if ( g14Config.autoSwitch && g14Config.autoSwitch.enabled && g14Config.autoSwitch.dcPlan ) { initSwitch('battery').then(() => setPowerPlan('ac')); } }); app.on('window-all-closed', async () => { await killEmitters(); showIconEnabled = true; updateMenuVisible(); LOGGER.info('window closed'); }); app.on('before-quit', async () => { if (gotTheLock) { globalShortcut.unregisterAll(); if (hid) { hid.close(); } LOGGER.info('Keyboard shortcuts unregistered.'); LOGGER.info('Preparing to quit.'); killEmitters(); } app.exit(); }); app.on('quit', async (evt, e) => { LOGGER.info(`Quitting with exit code. ${e}`); }); app.on('ready', async () => { if (!gotTheLock) { app.quit(); } else { let results = await createWindow( gotTheLock, g14Config, browserWindow, tray, trayContext, ICONPATH, hid ); g14Config = results.g14Config; tray = results.tray; browserWindow = results.browserWindow; trayContext = results.trayContext; browserWindow = await buildTaskbarMenu(browserWindow); browserWindow.on('close', (ev) => { ev.preventDefault(); browserWindow.hide(); }); } }); app.on('renderer-process-crashed', (event, webcontents, killed) => { LOGGER.info( `Renderer process crashed: ${JSON.stringify( event, null, 2 )}\nWas killed? ${killed} ... ${killed ? 'RIP' : ''}` ); app.quit(); }); app.on('render-process-gone', (event, contents, details) => { LOGGER.info(`Renderer Process is Gone:\n${details.reason}`); app.quit(); }); app.on('second-instance', () => { if (browserWindow) { if (browserWindow.isMinimized()) browserWindow.restore(); browserWindow.focus(); } if (!gotTheLock) { app.exit(); } else { LOGGER.info('Another process interupted my thoughts, how dare he!'); new Notification({ title: 'G14ControlV2', body: 'Only one process allowed at a time!', timeoutType: 'default', hasReply: false, }).show(); } });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/labsMappers"; import * as Parameters from "../models/parameters"; import { ManagedLabsClientContext } from "../managedLabsClientContext"; /** Class representing a Labs. */ export class Labs { private readonly client: ManagedLabsClientContext; /** * Create a Labs. * @param {ManagedLabsClientContext} client Reference to the service client. */ constructor(client: ManagedLabsClientContext) { this.client = client; } /** * List labs in a given lab account. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param [options] The optional parameters * @returns Promise<Models.LabsListResponse> */ list(resourceGroupName: string, labAccountName: string, options?: Models.LabsListOptionalParams): Promise<Models.LabsListResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, options: Models.LabsListOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): void; list(resourceGroupName: string, labAccountName: string, options?: Models.LabsListOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationLab>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): Promise<Models.LabsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, options }, listOperationSpec, callback) as Promise<Models.LabsListResponse>; } /** * Get lab * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param [options] The optional parameters * @returns Promise<Models.LabsGetResponse> */ get(resourceGroupName: string, labAccountName: string, labName: string, options?: Models.LabsGetOptionalParams): Promise<Models.LabsGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, labName: string, callback: msRest.ServiceCallback<Models.Lab>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, labName: string, options: Models.LabsGetOptionalParams, callback: msRest.ServiceCallback<Models.Lab>): void; get(resourceGroupName: string, labAccountName: string, labName: string, options?: Models.LabsGetOptionalParams | msRest.ServiceCallback<Models.Lab>, callback?: msRest.ServiceCallback<Models.Lab>): Promise<Models.LabsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, options }, getOperationSpec, callback) as Promise<Models.LabsGetResponse>; } /** * Create or replace an existing Lab. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param [options] The optional parameters * @returns Promise<Models.LabsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.Lab, options?: msRest.RequestOptionsBase): Promise<Models.LabsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.Lab, callback: msRest.ServiceCallback<Models.Lab>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.Lab, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Lab>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.Lab, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Lab>, callback?: msRest.ServiceCallback<Models.Lab>): Promise<Models.LabsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, lab, options }, createOrUpdateOperationSpec, callback) as Promise<Models.LabsCreateOrUpdateResponse>; } /** * Delete lab. This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,labAccountName,labName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Modify properties of labs. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param [options] The optional parameters * @returns Promise<Models.LabsUpdateResponse> */ update(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.LabFragment, options?: msRest.RequestOptionsBase): Promise<Models.LabsUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.LabFragment, callback: msRest.ServiceCallback<Models.Lab>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param lab Represents a lab. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.LabFragment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Lab>): void; update(resourceGroupName: string, labAccountName: string, labName: string, lab: Models.LabFragment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Lab>, callback?: msRest.ServiceCallback<Models.Lab>): Promise<Models.LabsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, lab, options }, updateOperationSpec, callback) as Promise<Models.LabsUpdateResponse>; } /** * Add users to a lab * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param addUsersPayload Payload for Add Users operation on a Lab. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: Models.AddUsersPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param addUsersPayload Payload for Add Users operation on a Lab. * @param callback The callback */ addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: Models.AddUsersPayload, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param addUsersPayload Payload for Add Users operation on a Lab. * @param options The optional parameters * @param callback The callback */ addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: Models.AddUsersPayload, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; addUsers(resourceGroupName: string, labAccountName: string, labName: string, addUsersPayload: Models.AddUsersPayload, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, addUsersPayload, options }, addUsersOperationSpec, callback); } /** * Register to managed lab. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ register(resourceGroupName: string, labAccountName: string, labName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param callback The callback */ register(resourceGroupName: string, labAccountName: string, labName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param options The optional parameters * @param callback The callback */ register(resourceGroupName: string, labAccountName: string, labName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; register(resourceGroupName: string, labAccountName: string, labName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, options }, registerOperationSpec, callback); } /** * Delete lab. This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, labAccountName, labName, options }, beginDeleteMethodOperationSpec, options); } /** * List labs in a given lab account. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.LabsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.LabsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationLab>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationLab>): Promise<Models.LabsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.LabsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName ], queryParameters: [ Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationLab }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.expand, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Lab }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "lab", mapper: { ...Mappers.Lab, required: true } }, responses: { 200: { bodyMapper: Mappers.Lab }, 201: { bodyMapper: Mappers.Lab }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "lab", mapper: { ...Mappers.LabFragment, required: true } }, responses: { 200: { bodyMapper: Mappers.Lab }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const addUsersOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/addUsers", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "addUsersPayload", mapper: { ...Mappers.AddUsersPayload, required: true } }, responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const registerOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/register", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationLab }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as net from '../lib/net/net.types'; import * as uproxy_core_api from './uproxy_core_api'; export interface UserPath { network :SocialNetworkInfo; userId :string; // ID for a friend } export interface SocialNetworkInfo { name :string; userId ?:string; // ID for current user } export interface InstancePath extends UserPath { instanceId :string; } // export interface BaseUser { userId :string; name :string; } export interface StopProxyInfo { instanceId :string; error :boolean; } export interface PermissionTokenInfo { isRequesting :boolean; isOffering :boolean; createdAt :number; acceptedByUserIds :string[]; } export interface LocalInstanceState { instanceId :string; userId :string; userName :string; imageData :string; invitePermissionTokens :{ [token :string] :PermissionTokenInfo }; exchangeInviteToken : (token :string, userId :string) => PermissionTokenInfo; } export interface NetworkMessage { name :string; online :boolean; userId :string; userName :string; imageData :string } export interface UserProfileMessage { status?: UserStatus; imageData ?:string; // Image URI (e.g. data:image/png;base64,adkwe329...) name ?:string; url ?:string; userId :string; } // The profile of a user on a social network. export interface UserProfile { userId :string; status ?:number; name ?:string; url ?:string; // Image URI (e.g. data:image/png;base64,adkwe329...) imageData ?:string; timestamp ?:number; } export interface ConsentState { ignoringRemoteUserOffer :boolean; ignoringRemoteUserRequest :boolean; localGrantsAccessToRemote :boolean; localRequestsAccessFromRemote :boolean; remoteRequestsAccessFromLocal :boolean; } export enum VerifyState { VERIFY_NONE = 0, VERIFY_BEGIN = 1, VERIFY_COMPLETE = 2, VERIFY_FAILED = 3 } export interface InstanceData { bytesReceived :number; bytesSent :number; description :string; instanceId :string; isOnline :boolean; verifyState :VerifyState; verifySAS :string; localGettingFromRemote :GettingState; localSharingWithRemote :SharingState; activeEndpoint :net.Endpoint; proxyingId ?:string; } export interface UserData { allInstanceIds ?:string[]; consent :ConsentState; isOnline :boolean; network :string; offeringInstances ?:InstanceData[]; instancesSharingWithLocal :string[]; user :UserProfileMessage; } export interface NetworkState { name :string; profile :UserProfileMessage; roster :{[userId :string] :UserData }; } export interface NetworkOptions { isFirebase :boolean; enableMonitoring :boolean; areAllContactsUproxy :boolean; supportsReconnect :boolean; displayName ?:string; // Network name to be displayed in the UI. metricsName ?:string; // Name to use for metrics isEncrypted ?:boolean; rosterFunction ?:(rosterNames:string[])=>number; } /** * Messages are sent from Core to a remote Core - they are peer communications * between uProxy users. This enum describes the possible Message types. */ // TODO: move into generic_core. // TODO: rename to PeerMessageType & PeerMessage. // TODO: consider every message having every field, and that MessageType is // no longer needed. This would use fewer larger messages. export enum PeerMessageType { INSTANCE = 3000, // Instance messages notify the user about instances. // These are for the signalling-channel. The payloads are arbitrary, and // could be specified from uProxy, or could also be SDP headers forwarded // from socks-rtc's RTCPeerConnection. SIGNAL_FROM_CLIENT_PEER, SIGNAL_FROM_SERVER_PEER, // Request that an instance message be sent back from a peer. INSTANCE_REQUEST, // Key Verification KEY_VERIFY_MESSAGE, PERMISSION_TOKEN } export interface PeerMessage { type :PeerMessageType; // TODO: Add a comment to explain the types that data can take and their // relationship to MessageType. data: Object; } // Actual type sent over the wire; version is added immediately before // JSON-ification. export interface VersionedPeerMessage extends PeerMessage { // Client version of the peer, viz. MESSAGE_VERSION. version: number; } // The different states that uProxy consent can be in w.r.t. a peer. These // are the values that get sent or received on the wire. export interface ConsentWireState { isRequesting :boolean; isOffering :boolean; } /** * Instance Handshakes are sent between uProxy installations to notify each * other about existence. */ export interface InstanceHandshake { instanceId :string; consent :ConsentWireState; description ?:string; // publicKey is not set for networks which include the public key in their // clientId (Quiver). publicKey ?:string; } // This is only used for sending the received permission token back to the // user who generated the token. export interface PermissionTokenMessage { token :string; }; // Describing whether or not a remote instance is currently accessing or not, // assuming consent is GRANTED for that particular pathway. export enum GettingState { NONE = 100, TRYING_TO_GET_ACCESS, // Initial connection is in progress GETTING_ACCESS, FAILED, // Connection has failed, but user hasn't cancelled. Might retry. RETRYING } export enum SharingState { NONE = 200, TRYING_TO_SHARE_ACCESS, SHARING_ACCESS } // We use this to map Freedom's untyped social network structures into a real // type-script enum & interface. // Status of a client; used for both this client (in which case it will be // either ONLINE or OFFLINE) export enum ClientStatus { OFFLINE, // This client runs the same freedom.js app as you and is online ONLINE, // This client is online, but not with the same application/agent type // (i.e. can be useful to invite others to your freedom.js app) ONLINE_WITH_OTHER_APP, } export enum UserStatus { FRIEND = 0, LOCAL_INVITED_BY_REMOTE = 1, REMOTE_INVITED_BY_LOCAL = 2, CLOUD_INSTANCE_CREATED_BY_LOCAL = 3, CLOUD_INSTANCE_SHARED_WITH_LOCAL = 4 } // Status of a client connected to a social network. export interface ClientState { userId :string; clientId :string; status :ClientStatus; timestamp :number; } export interface UserState { name :string; imageData :string; url :string; // Only save and load the instanceIDs. The actual RemoteInstances will // be saved and loaded separately. instanceIds :string[]; consent :ConsentState; status :UserStatus; } export interface RemoteUserInstance { start() :Promise<net.Endpoint>; stop() :Promise<void>; } // Payload for SIGNAL_FROM_CLIENT_PEER and SIGNAL_FROM_SERVER_PEER messages. // Other payload types exist, e.g. bridging peerconnection signals. export interface SignallingMetadata { // Random ID associated with this proxying attempt. // Used for logging purposes and implicitly delimits proxying attempts. proxyingId ?:string; } export interface InviteTokenPermissions { token :string; isRequesting :boolean; isOffering :boolean; } export interface InviteTokenData { v :number; // version networkName :string; // TODO: make this optional, it's not used by cloud social provider (and maybe others) userName :string; networkData :string|Object; permission ?:InviteTokenPermissions; userId ?:string; // Only included if permissions also set instanceId ?:string; // Only included if permissions also set } /** * */ export interface RemoteUser { modifyConsent(action:uproxy_core_api.ConsentUserAction) : Promise<void>; getInstance(instanceId:string) :RemoteUserInstance; } /** * The |Network| class represents a single network and the local uProxy client's * interaction as a user on the network. * * NOTE: All JSON stringify / parse happens automatically through the * network's communication methods. The rest of the code should deal purely * with the data objects. * * Furthermore, at the Social.Network level, all communications deal directly * with the clientIds. This is because instanceIds occur at the User level, as * the User manages the instance <--> client mappings (see 'user.ts'). */ export interface Network { name :string; // TODO: Review visibility of these attributes and the interface. roster :{[userId:string]:RemoteUser}; // TODO: Make this private. Have other objects use getLocalInstance // instead. myInstance :LocalInstanceState; /** * Logs in to the network. Updates the local client information, as * appropriate, and sends an update to the UI upon success. Does nothing if * already logged in. */ login :(loginType :uproxy_core_api.LoginType, userName ?:string) => Promise<void>; getStorePath :() => string; /** * Does nothing if already logged out. */ logout :() => Promise<void>; /** * Returns true iff a login is pending (e.g. waiting on user's password). */ getLocalInstanceId :() => string; /** * Returns the User corresponding to |userId|. */ getUser :(userId :string) => RemoteUser; /** * Accept an invite to use uProxy with a friend */ acceptInvitation: (token ?:InviteTokenData, userId ?:string) => Promise<void>; /** * Send an invite to a GitHub friend to use uProxy */ inviteGitHubUser: (data :uproxy_core_api.CreateInviteArgs) => Promise<void>; /** * Generates an invite token */ getInviteUrl: (data :uproxy_core_api.CreateInviteArgs) => Promise<string>; /** * Generates an invite token */ sendEmail: (to :string, subject :string, body :string) => void; /** * Resends the instance handeshake to all uProxy instances. */ resendInstanceHandshakes :() => void; /** * Sends a message to a remote client. * * Assumes that |clientId| is valid. Implementations of Social.Network do * not manually manage lists of clients or instances. (That is handled in * user.ts, which calls Network.send after doing the validation checks * itself.) * * Still, it is expected that if there is a problem, such as the clientId * being invalid / offline, the promise returned from the social provider * will reject. */ send :(user :BaseUser, clientId:string, msg:PeerMessage) => Promise<void>; getNetworkState : () => NetworkState; areAllContactsUproxy : () => boolean; isEncrypted : () => boolean; getKeyFromClientId : (clientId :string) => string; /** * Removes user from the network's roster and storage */ removeUserFromStorage : (userId :string) => Promise<void>; }
the_stack
import React, { useState, useCallback, useRef } from "react"; import styled from "styled-components"; import { OptionTypeBase } from "react-select/src/types"; import classNames from "classnames"; import { useWindowWidth } from "src/shared/hooks/useWindowWidth"; import { useOnClickOutside } from "src/shared/hooks/useOnClickOutside"; import { SearchType } from "src/shared/constants/search"; import { Size } from "src/theme"; import { useMobileMenuContext } from "src/contexts"; import Button, { UnstyledButton } from "src/components/Button"; import Card from "src/components/Card"; import Text from "src/components/Text"; import TextInput from "src/components/TextInput"; import Tooltip from "src/components/Tooltip"; import Select from "src/components/Select"; import Checkbox from "src/components/Checkbox"; import StarRating from "src/components/StarRating"; import { HEADER_HEIGHT, MOBILE_MENU_HEIGHT } from "src/components/PageHeader"; import { baseLinkStyles } from "src/components/Link"; import Icon, { IconName } from "src/components/Icon"; /******************************************************************* * **Types** * *******************************************************************/ export interface ISearchOptionsMenuProps extends React.ComponentPropsWithoutRef<"div"> { sortOption?: { options: OptionTypeBase[]; value?: OptionTypeBase; onChange: (value?: OptionTypeBase) => void; }; typeOption?: { value?: SearchType; onChange: (value?: SearchType) => void; }; ratingOption?: { value: (number | undefined)[]; onChange: (value: (number | undefined)[]) => void; }; salaryOption?: { value: (number | undefined)[]; onChange: (value: (number | undefined)[]) => void; }; onOptionChange?: () => void; } /******************************************************************* * **Utility functions/constants** * *******************************************************************/ const MENU_WIDTH = 400; const MENU_WIDTH_MOBILE = 320; const MIN_WIDTH_TO_DISABLE_COLLAPSE = 1800; /******************************************************************* * **Styles** * *******************************************************************/ const Container = styled(Card)<{ menuOpen: boolean }>` position: fixed; top: ${HEADER_HEIGHT + 80}px; right: 0; width: ${MENU_WIDTH}px; padding: 30px 45px; cursor: ${({ menuOpen }) => (menuOpen ? "initial" : "pointer")}; box-shadow: ${({ theme }) => theme.boxShadow.hover}; z-index: ${({ theme }) => theme.zIndex.header - 1}; transition: transform 150ms; transform: ${({ menuOpen }) => menuOpen ? "translateX(0)" : `translateX(${MENU_WIDTH - 65}px)`}; &.mobile-menu-open { top: ${HEADER_HEIGHT + MOBILE_MENU_HEIGHT + 20}px; } & > * { margin-top: 15px; &:first-child { margin-top: 0; margin-bottom: 15px; } & > * { opacity: ${({ menuOpen }) => (menuOpen ? 1 : 0)}; } } & .heading { opacity: 1; transform: ${({ menuOpen }) => (menuOpen ? "" : "rotate(-90deg)")}; position: relative; top: ${({ menuOpen }) => (menuOpen ? "unset" : "25px")}; left: ${({ menuOpen }) => (menuOpen ? "unset" : "-60px")}; } & .tooltip { margin-left: 5px; } @media (min-width: 2000px) { transform: translateX(-150px); } @media (min-width: ${MIN_WIDTH_TO_DISABLE_COLLAPSE}px) { top: ${HEADER_HEIGHT + 150}px; transform: translateX(-60px); & .close-indicator { display: none; } } ${({ theme }) => theme.mediaQueries.tablet` padding-top: 30px; `} ${({ theme, menuOpen }) => theme.mediaQueries.largeMobile` width: ${MENU_WIDTH_MOBILE}px; padding: 20px 30px; transform: ${ menuOpen ? "translateX(0)" : `translateX(${MENU_WIDTH_MOBILE - 45}px)` }; & > * { margin-bottom: 5px; } & .heading { opacity: 1; font-size: ${theme.fontSize[Size.MEDIUM]}px; left: ${menuOpen ? "unset" : "-43px"}; } `} `; const CenterContainer = styled.div` display: flex; justify-content: space-between; align-items: center; `; const TopContainer = styled.div` display: flex; justify-content: space-between; align-items: flex-start; `; const SortOptionSelect = styled(Select)` width: 70%; & > div { padding: 10px; } `; const VerticalAlignContainer = styled.div` width: 70%; margin-left: auto; display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start; `; const CloseIndicator = styled(UnstyledButton)` transition: transform 150ms; transform: scale(0.9); cursor: pointer; &:hover, &:focus { transform: scale(1); } & > svg { transform: rotate(-90deg); } `; const TypeCheckbox = styled(Checkbox)` margin-bottom: 7px; `; const SalaryInput = styled(TextInput)` margin-top: 7px; `; const ActionContainer = styled.div` display: flex; flex-direction: column; align-items: center; & > * { margin-top: 5px; } & .reset-options-button { color: ${({ theme }) => theme.color.textSecondary}; ${baseLinkStyles} } `; /******************************************************************* * **Component** * *******************************************************************/ const SearchOptionsMenu: React.FC<ISearchOptionsMenuProps> = ({ className, sortOption, typeOption, ratingOption, salaryOption, onOptionChange, }) => { const { isMobileMenuOpen } = useMobileMenuContext(); const { windowWidth } = useWindowWidth(); /** * Tracks if the options menu is open. */ const [menuOpen, setMenuOpen] = useState( windowWidth >= MIN_WIDTH_TO_DISABLE_COLLAPSE ); const closeMenu = useCallback( () => setMenuOpen(windowWidth >= MIN_WIDTH_TO_DISABLE_COLLAPSE), [windowWidth] ); const onCloseIndicatorClick = useCallback( (e: React.MouseEvent<HTMLButtonElement>) => { e.stopPropagation(); closeMenu(); }, [closeMenu] ); /** * Automatically close the side menu when clicking outside, * since it obstructs visibility of search results. */ const menuRef = useRef<HTMLDivElement | null>(null); useOnClickOutside(menuRef, closeMenu); /** * Store the current value of options internally. Changed * options are not applied instantly for performance; * we don't want new searches to be performed every time a user * changes or types an option, especially for input fields * like salary/location. */ const [internalSortOptionVal, setInternalSortOptionVal] = useState( sortOption && sortOption.value ); const [internalTypeOptionVal, setInternalTypeOptionVal] = useState( typeOption && typeOption.value ); const [internalRatingFilterOptionVal, setInternalRatingFilterOptionVal] = useState((ratingOption && ratingOption.value) || []); const [internalSalaryFilterOptionVal, setInternalSalaryFilterOptionVal] = useState((salaryOption && salaryOption.value) || []); /** * Callback to reset all options to their empty state. */ const resetOptions = () => { setInternalSortOptionVal(undefined); setInternalTypeOptionVal(undefined); setInternalRatingFilterOptionVal([]); setInternalSalaryFilterOptionVal([]); }; /** * Callback to apply options selected in the menu. It will * execute the provided callback for an option only if the value * of that option has changed. * (the settimeout call is due to a bug in use-query-params where * multiple calls to update query params will override each other * if called synchronously) */ const applyOptions = () => { let optionsChanged = false; if (sortOption && internalSortOptionVal !== sortOption.value) { optionsChanged = true; setTimeout(() => sortOption.onChange(internalSortOptionVal), 0); } if (typeOption && internalTypeOptionVal !== typeOption.value) { optionsChanged = true; setTimeout(() => typeOption.onChange(internalTypeOptionVal), 0); } if ( ratingOption && (internalRatingFilterOptionVal[0] !== ratingOption.value[0] || internalRatingFilterOptionVal[1] !== ratingOption.value[1]) ) { optionsChanged = true; setTimeout(() => ratingOption.onChange(internalRatingFilterOptionVal), 0); } if ( salaryOption && (internalSalaryFilterOptionVal[0] !== salaryOption.value[0] || internalSalaryFilterOptionVal[1] !== salaryOption.value[1]) ) { optionsChanged = true; setTimeout(() => salaryOption.onChange(internalSalaryFilterOptionVal), 0); } if (optionsChanged && onOptionChange) onOptionChange(); }; return ( <Container className={classNames("options-menu", className, { "mobile-menu-open": isMobileMenuOpen, })} backgroundColor="backgroundSecondary" menuOpen={menuOpen} onFocus={() => setMenuOpen(true)} onClick={() => setMenuOpen(true)} onMouseEnter={() => setMenuOpen(true)} ref={menuRef} > <CenterContainer> <Text variant="heading2" as="h2" className="heading"> Options </Text> <CloseIndicator className="close-indicator" onClick={onCloseIndicatorClick} tabIndex={menuOpen ? 0 : -1} > <Icon name={IconName.CHEVRON} size={16} /> </CloseIndicator> </CenterContainer> {typeOption && ( <TopContainer aria-hidden={menuOpen ? "false" : "true"}> <Text variant="heading4">Type</Text> <VerticalAlignContainer> <TypeCheckbox className="type checkbox companies" color="backgroundPrimary" checked={internalTypeOptionVal === SearchType.COMPANIES} onChange={(e) => setInternalTypeOptionVal( e.target.checked ? SearchType.COMPANIES : undefined ) } tabIndex={menuOpen ? 0 : -1} > <Text variant="subheading" color="textSecondary"> companies only </Text> </TypeCheckbox> <TypeCheckbox className="type checkbox jobs" color="backgroundPrimary" checked={internalTypeOptionVal === SearchType.JOBS} onChange={(e) => setInternalTypeOptionVal( e.target.checked ? SearchType.JOBS : undefined ) } tabIndex={menuOpen ? 0 : -1} > <Text variant="subheading" color="textSecondary"> positions only </Text> </TypeCheckbox> <TypeCheckbox className="type checkbox reviews" color="backgroundPrimary" checked={internalTypeOptionVal === SearchType.REVIEWS} onChange={(e) => setInternalTypeOptionVal( e.target.checked ? SearchType.REVIEWS : undefined ) } tabIndex={menuOpen ? 0 : -1} > <Text variant="subheading" color="textSecondary"> reviews only </Text> </TypeCheckbox> </VerticalAlignContainer> </TopContainer> )} {salaryOption && ( <div> <CenterContainer aria-hidden={menuOpen ? "false" : "true"}> <CenterContainer> <Text variant="heading4">Salary</Text> <Tooltip color="textTertiary"> <Text variant="body"> The minimum and maximum hourly salary to search for. </Text> </Tooltip> </CenterContainer> <VerticalAlignContainer> <TextInput type="number" min={0} value={internalSalaryFilterOptionVal[0] || ""} onChange={(e) => { const val = e.target.value ? parseInt(e.target.value) : undefined; if (val === undefined || !isNaN(val)) { setInternalSalaryFilterOptionVal((prevVal) => [ val, prevVal[1], ]); } }} color="backgroundPrimary" placeholder="min" className="salary min" /> </VerticalAlignContainer> </CenterContainer> <VerticalAlignContainer> <SalaryInput type="number" min={0} value={internalSalaryFilterOptionVal[1] || ""} onChange={(e) => { const val = e.target.value ? parseInt(e.target.value) : undefined; if (val === undefined || !isNaN(val)) { setInternalSalaryFilterOptionVal((prevVal) => [ prevVal[0], val, ]); } }} color="backgroundPrimary" placeholder="max" className="salary max" /> </VerticalAlignContainer> </div> )} {ratingOption && ( <TopContainer aria-hidden={menuOpen ? "false" : "true"}> <Text variant="heading4">Rating</Text> <VerticalAlignContainer> <StarRating className="rating min" maxStars={5} value={internalRatingFilterOptionVal[0] || 0} onChange={(stars) => setInternalRatingFilterOptionVal((prevVal) => [ stars, prevVal[1], ]) } > <Text variant="subheading" color="textSecondary"> min </Text> </StarRating> <StarRating className="rating max" maxStars={5} value={internalRatingFilterOptionVal[1] || 0} onChange={(stars) => setInternalRatingFilterOptionVal((prevVal) => [ prevVal[0], stars, ]) } > <Text variant="subheading" color="textSecondary"> max </Text> </StarRating> </VerticalAlignContainer> </TopContainer> )} {sortOption && ( <CenterContainer aria-hidden={menuOpen ? "false" : "true"}> <CenterContainer> <Text variant="heading4">Sort</Text> <Tooltip color="textTertiary"> <Text variant="body" as="div"> When sorting by salary: companies are sorted by their median, whereas jobs are sorted by their average review salary. </Text> <br /> <Text variant="body" as="div"> By default, reviews are sorted chronologically. </Text> </Tooltip> </CenterContainer> <SortOptionSelect className="sort select" color="backgroundPrimary" placeholder="by..." options={sortOption.options} value={internalSortOptionVal || ""} onChange={setInternalSortOptionVal} tabIndex={menuOpen ? 0 : -1} /> </CenterContainer> )} <ActionContainer> <Button onClick={applyOptions} color="greenSecondary" className="apply-button" > <Text variant="subheading" color="textPrimary"> Apply </Text> </Button> <UnstyledButton onClick={resetOptions} className="reset-options-button"> <Text variant="subheading" color="textSecondary"> reset all </Text> </UnstyledButton> </ActionContainer> </Container> ); }; export default SearchOptionsMenu;
the_stack
import {evaluation, Global} from 'rcre-runtime'; function loopCases(cases: any[], context: Object = {}) { for (let i = 0; i < cases.length; i++) { let title = cases[i][0]; let result = cases[i][1]; it(title, () => { let ret = evaluation(title, context); expect(ret).toBe(result); }); } } describe('Compiler test', () => { describe('Error Report', () => { expect(() => evaluation('aaaa', {})).toThrow(); }); describe('BinaryExpression Test', () => { const cases: [string, number | string | boolean][] = [ ['1 + 1 * 2', 3], ['1 * 4', 4], ['8 % 3', 2], ['8 / 2', 4], ['2 ** 3', 8], ['2 in [1,2,3,4]', true], ['10 >>> 1', 5], ['10 >= 10', true], ['12 > 10', true], ['10 <= 10', true], ['12 < 14', true], ['true == 1', true], ['1 + "2"', '12'], ['null + null', 0], ['111 + 222', 333], ['1 + 1 > 0', true], ['-1 + 1', 0] ]; loopCases(cases); }); describe('Literal and Identifier Test', () => { let context: Object; beforeEach(() => { context = { x: 4 }; }); it('x + 1', () => { let ret = evaluation('x + 1', context); expect(ret).toBe(5); }); it('x + x', () => { let ret = evaluation('x + x', context); expect(ret).toBe(8); }); it('$data.username', () => { context = { $data: { username: '$data' } }; let code = '$data.username + 1'; expect(evaluation(code, context)).toBe('$data1'); }); }); describe('memberExpression Test', () => { let context = { obj: { age: 10, inner: { deep: 2 }, innerArr: [5, 6, 7, 8, 9, 10] }, arr: [1, 2, 3, 4, 5], str: '0' }; it('obj.age === 10', () => { let ret = evaluation('obj.age', context); expect(ret).toBe(10); }); it('obj.age + obj.age === 20', () => { let ret = evaluation('obj.age + obj.age', context); expect(ret).toBe(20); }); it('obj.inner.deep === 2', () => { let ret = evaluation('obj.inner.deep', context); expect(ret).toBe(2); }); it('obj.arr[0] === 1', () => { let ret = evaluation('arr[0]', context); expect(ret).toBe(1); }); it('obj.innerArr[0]', () => { expect(evaluation('obj.innerArr[0]', context)).toBe(5); }); it('$data', () => { let result = evaluation('$data', { $data: { name: 1 } }); expect(result).toEqual({name: 1}); }); it('str', () => { let result = evaluation('obj.str', { obj: { str: '0' } }); expect(result).toBe('0'); }); it('a', () => { let result = evaluation('a', { a: 10 }); expect(result).toBe(10); }); // it('$data.dynamicSelect + "value"', () => { // let result = evaluation('$data.dynamicSelect + "value"', { // '$data': { // 'dynamicSelect': '$parent', // 'username': '$thisvalue' // } // }); // // console.log(result); // }); }); describe('ObjectExpression', () => { it('{name: 1, age: 2}', () => { let origin = { name: 1, age: 2 }; expect(typeof evaluation('({name: 1, age: 2})', {})).toBe('object'); expect(JSON.stringify(evaluation('({name: 1, age: 2})', {}))).toBe(JSON.stringify(origin)); }); it('{name: x, age: y}', () => { let context = { x: 1, y: 2 }; let ret = { name: 1, age: 2 }; expect(JSON.stringify(evaluation('({name: x, age: y})', context))).toBe(JSON.stringify(ret)); }); it('$data.str.split()', () => { let context = { $data: { str: 'a,b,c,d,e' } }; Object.assign(context, Global); expect( evaluation('String.prototype.split.call($data.str, ",")', context)) .toEqual(['a', 'b', 'c', 'd', 'e']); }); it('$args.value.length === 0', () => { let ret = evaluation('$args.value.length === 0', { $args: { value: '' } }); expect(ret).toBe(true); }); it('Object.prototype.toString.call', () => { let result = evaluation('Object.prototype.toString({name: 1})', Global); expect(result).toBe('[object Object]'); }); it('[].slice', () => { let result = evaluation('[1,2,3,4,5,6].slice(3)', Global); expect(result).toEqual([4, 5, 6]); }); it('Array.prototype.slice.call', () => { let result = evaluation('Array.prototype.slice.call([1,2,3,4,5,6], 2)', Global); expect(result).toEqual([3, 4, 5, 6]); }); it('Array.prototype.slice.apply', () => { let result = evaluation('Array.prototype.slice.apply([1,2,3,4,5,6], [2])', Global); expect(result).toEqual([3, 4, 5, 6]); }); it('JSON.stringify({name: 1, age: 2})', () => { let result = evaluation('JSON.stringify({name: 1, age: 2})', Global); expect(result).toBe(JSON.stringify({name: 1, age: 2})); }); }); describe('ConditionExpression', () => { it('1 + 1 > 0 ? true : false', () => { expect(evaluation('1 + 1 > 0 ? true : false', {})).toBe(true); }); it('1 + 1 < 0 ? true : false', () => { expect(evaluation('1 + 1 < 0 ? true : false', {})).toBe(false); }); it('({name: true}).name ? true : false', () => { expect(evaluation('({name: true}).name ? true : false', {})).toBe(true); }); it('1 > 0 ? sumAll(prev, next) : sumAll(-prev, -next)', () => { const sumAll = (...args: number[]) => args.reduce((total, next) => total + next, 0); let context = { prev: 1, next: 2, sumAll: sumAll }; let result = evaluation('1 > 0 ? sumAll(prev, next) : sumAll(-prev, -next)', context); expect(result).toBe(3); }); it('1 < 0 ? sumAll(prev, next) : sumAll(-prev, -next)', () => { let sumAll = (a: number, b: number) => { return a + b; }; let context = { prev: 1, next: 2, sumAll: sumAll }; let result = evaluation('1 < 0 ? sumAll(prev, next) : sumAll(-prev, -next)', context); expect(result).toBe(-3); }); it('str length', () => { let context = { $data: { str: 'helloworld' }, $nest: { $data: [{str: 'helloworld'}] } }; let result = evaluation('$data.str.length', context); expect(evaluation('$nest.$data[0].str.length', context)).toBe(10); expect(evaluation('$nest.$notFound', context)).toBe(undefined); expect(result).toBe(10); }); it('call Number.prototype property', () => { let context = { $data: { number: 10 } }; expect(evaluation('$data.number.toFixed(2)', context)).toBe('10.00'); }); it('call String.prototype property', () => { let context = { $data: { str: 'helloworld' } }; expect(evaluation('$data.str.toUpperCase()', context)).toBe('HELLOWORLD'); }); }); describe('ArrayExpression', () => { it('[1,2,3,4]', () => { let result = evaluation('[1,2,3,4]', {}); expect(result.length).toBe(4); expect(Array.isArray(result)).toBe(true); expect(result[0]).toBe(1); expect([1, 2, 3, 4]).toEqual([1, 2, 3, 4]); }); it('[1,2,3, ..."hello"]', () => { let result = evaluation('[1,2,3, ..."hello"]', {}); expect(result.length).toBe(8); expect(result).toEqual([1, 2, 3, 'h', 'e', 'l', 'l', 'o']); }); it('[a, b, c, d, e, f, g]', () => { let context = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7 }; let result = evaluation('[a, b, c, d, e, f, g]', context); expect(result).toEqual([1, 2, 3, 4, 5, 6, 7]); }); it('[[],[],[[[]]]]', () => { let context = { arr: [] }; let result = evaluation('[arr, arr, [arr], [[arr]]]', context); expect(result).toEqual([[], [], [[]], [[[]]]]); }); }); // describe('UpdateExpression', () => { // it('a++', () => { // let context = { // a: 1 // }; // let result = evaluation('a++', context); // expect(result).toBe(1); // expect(context.a).toBe(2); // }); // // it('++a', () => { // let context = { // a: 1 // }; // let result = evaluation('++a', context); // expect(result).toBe(2); // expect(context.a).toBe(2); // }); // // it('[a, ++a, ++a, ++a, ++a]', () => { // let context = { // a: 1 // }; // let result = evaluation('[a, ++a, ++a, ++a, ++a]', context); // expect(result).toEqual([1, 2, 3, 4, 5]); // }); // }); describe('complex example', () => { let context = { $data: { dateDiff: '1', dataKind: 1 } }; it('#ES{$data.dateDiff === "1" && $data.dataKind === 1}', () => { expect(evaluation('$data.dateDiff === "1" && $data.dataKind === 1', context)).toBe(true); }); it('#ES{!($data.dateDiff === "1" && $data.dataKind === 1)}', () => { expect(evaluation('!($data.dateDiff === "1" && $data.dataKind === 1)', context)).toBe(false); }); }); describe('UnaryExpression', () => { it('!a', () => { let context = { a: true }; let result = evaluation('!a', context); expect(result).toBe(false); }); it('-a', () => { let context = { a: 1 }; let result = evaluation('-a', context); expect(result).toBe(-1); }); }); describe('LogicExpression', () => { it('true || 0', () => { let result = evaluation('true || 0', {}); expect(result).toBe(true); }); it('1 + 1 > 0 || false', () => { let result = evaluation('1 + 1 > 0 || false', {}); expect(result).toBe(true); }); it('1 + 1 < 0 || -1', () => { let result = evaluation('1 + 1 < 0 || - 1', {}); expect(result).toBe(-1); }); it('1 + 1 > 0 && 1', () => { let result = evaluation('1 + 1 > 0 && 1', {}); expect(result).toBe(1); }); }); describe('FunctionExpression', () => { it('sum(1, 1)', () => { let context = { sum: (a: number, b: number) => a + b }; let result = evaluation('sum(1, 1)', context); expect(result).toBe(2); }); it('sum(sum(sum(sum(1, 2), sum(3, 4)), sum(5, 6)), sum(7, 8)))', () => { let context = { sum: (a: number, b: number) => a + b }; let result = evaluation('sum(sum(sum(sum(1, 2), sum(3, 4)), sum(5, 6)), sum(7, 8))', context); expect(result).toBe(36); }); it('$data.sum', () => { let context = { $data: { sum: (a: number, b: number) => a + b } }; let result = evaluation('$data.sum(1, 1)', context); expect(result).toBe(2); }); }); describe('NewExpression', () => { it('new F(1,2,3,4)', () => { class F { private a: number; private b: number; private c: number; private d: number; constructor(a: number, b: number, c: number, d: number) { this.a = a; this.b = b; this.c = c; this.d = d; } public getValue() { return { a: this.a, b: this.b, c: this.c, d: this.d }; } } let ret = evaluation('new F(1, 2, 3, 4)', {F: F}); expect(ret).toEqual({a: 1, b: 2, c: 3, d: 4}); }); }); describe('Regexp', () => { it('/\\d+/.test(1)', () => { let ret = evaluation('/1462853203791|1462853496485|1462854074707|1462854136999/.test("1462853496485")', {}); expect(ret).toEqual(true); }); }); describe('Literal as argument', () => { it('function key in context', () => { let context = { concat: (a: string, b: string) => a + b, sum: (a: number, b: number) => a + b }; let ret = evaluation('concat("1", "sum")', context); expect(ret).toEqual('1sum'); }); it('string key in context', () => { let context = { concat: (a: string, b: string) => a + b, name: '1' }; let ret = evaluation('concat("1", "name")', context); expect(ret).toEqual('1name'); }); it('key not in context', () => { let context = { concat: (a: string, b: string) => a + b }; let ret = evaluation('concat("1", "sum")', context); expect(ret).toEqual('1sum'); }); }); });
the_stack
import Mesh from "./mesh"; import { MaterialLibrary, TextureMapData } from "./material"; function downloadMtlTextures(mtl: MaterialLibrary, root: string) { const mapAttributes = [ "mapDiffuse", "mapAmbient", "mapSpecular", "mapDissolve", "mapBump", "mapDisplacement", "mapDecal", "mapEmissive", ]; if (!root.endsWith("/")) { root += "/"; } const textures = []; for (const materialName in mtl.materials) { if (!mtl.materials.hasOwnProperty(materialName)) { continue; } const material = mtl.materials[materialName]; for (const attr of mapAttributes) { const mapData = (material as any)[attr] as TextureMapData; if (!mapData || !mapData.filename) { continue; } const url = root + mapData.filename; textures.push( fetch(url) .then(response => { if (!response.ok) { throw new Error(); } return response.blob(); }) .then(function(data) { const image = new Image(); image.src = URL.createObjectURL(data); mapData.texture = image; return new Promise(resolve => (image.onload = resolve)); }) .catch(() => { console.error(`Unable to download texture: ${url}`); }), ); } } return Promise.all(textures); } function getMtl(modelOptions: DownloadModelsOptions): string { if (!(typeof modelOptions.mtl === "string")) { return modelOptions.obj.replace(/\.obj$/, ".mtl"); } return modelOptions.mtl; } export interface DownloadModelsOptions { obj: string; mtl?: boolean | string; downloadMtlTextures?: boolean; mtlTextureRoot?: string; name?: string; indicesPerMaterial?: boolean; calcTangentsAndBitangents?: boolean; } type ModelPromises = [Promise<string>, Promise<Mesh>, undefined | Promise<MaterialLibrary>]; export type MeshMap = { [name: string]: Mesh }; /** * Accepts a list of model request objects and returns a Promise that * resolves when all models have been downloaded and parsed. * * The list of model objects follow this interface: * { * obj: 'path/to/model.obj', * mtl: true | 'path/to/model.mtl', * downloadMtlTextures: true | false * mtlTextureRoot: '/models/suzanne/maps' * name: 'suzanne' * } * * The `obj` attribute is required and should be the path to the * model's .obj file relative to the current repo (absolute URLs are * suggested). * * The `mtl` attribute is optional and can either be a boolean or * a path to the model's .mtl file relative to the current URL. If * the value is `true`, then the path and basename given for the `obj` * attribute is used replacing the .obj suffix for .mtl * E.g.: {obj: 'models/foo.obj', mtl: true} would search for 'models/foo.mtl' * * The `name` attribute is optional and is a human friendly name to be * included with the parsed OBJ and MTL files. If not given, the base .obj * filename will be used. * * The `downloadMtlTextures` attribute is a flag for automatically downloading * any images found in the MTL file and attaching them to each Material * created from that file. For example, if material.mapDiffuse is set (there * was data in the MTL file), then material.mapDiffuse.texture will contain * the downloaded image. This option defaults to `true`. By default, the MTL's * URL will be used to determine the location of the images. * * The `mtlTextureRoot` attribute is optional and should point to the location * on the server that this MTL's texture files are located. The default is to * use the MTL file's location. * * @returns {Promise} the result of downloading the given list of models. The * promise will resolve with an object whose keys are the names of the models * and the value is its Mesh object. Each Mesh object will automatically * have its addMaterialLibrary() method called to set the given MTL data (if given). */ export function downloadModels(models: DownloadModelsOptions[]): Promise<MeshMap> { const finished = []; for (const model of models) { if (!model.obj) { throw new Error( '"obj" attribute of model object not set. The .obj file is required to be set ' + "in order to use downloadModels()", ); } const options = { indicesPerMaterial: !!model.indicesPerMaterial, calcTangentsAndBitangents: !!model.calcTangentsAndBitangents, }; // if the name is not provided, dervive it from the given OBJ let name = model.name; if (!name) { const parts = model.obj.split("/"); name = parts[parts.length - 1].replace(".obj", ""); } const namePromise = Promise.resolve(name); const meshPromise = fetch(model.obj) .then(response => response.text()) .then(data => { return new Mesh(data, options); }); let mtlPromise; // Download MaterialLibrary file? if (model.mtl) { const mtl = getMtl(model); mtlPromise = fetch(mtl) .then(response => response.text()) .then( (data: string): Promise<[MaterialLibrary, any]> => { const material = new MaterialLibrary(data); if (model.downloadMtlTextures !== false) { let root = model.mtlTextureRoot; if (!root) { // get the directory of the MTL file as default root = mtl.substr(0, mtl.lastIndexOf("/")); } // downloadMtlTextures returns a Promise that // is resolved once all of the images it // contains are downloaded. These are then // attached to the map data objects return Promise.all([Promise.resolve(material), downloadMtlTextures(material, root)]); } return Promise.all([Promise.resolve(material), undefined]); }, ) .then((value: [MaterialLibrary, any]) => { return value[0]; }); } const parsed: ModelPromises = [namePromise, meshPromise, mtlPromise]; finished.push(Promise.all<string, Mesh, MaterialLibrary | undefined>(parsed)); } return Promise.all(finished).then(ms => { // the "finished" promise is a list of name, Mesh instance, // and MaterialLibary instance. This unpacks and returns an // object mapping name to Mesh (Mesh points to MTL). const models: MeshMap = {}; for (const model of ms) { const [name, mesh, mtl] = model; mesh.name = name; if (mtl) { mesh.addMaterialLibrary(mtl); } models[name] = mesh; } return models; }); } export interface NameAndUrls { [meshName: string]: string; } /** * Takes in an object of `mesh_name`, `'/url/to/OBJ/file'` pairs and a callback * function. Each OBJ file will be ajaxed in and automatically converted to * an OBJ.Mesh. When all files have successfully downloaded the callback * function provided will be called and passed in an object containing * the newly created meshes. * * **Note:** In order to use this function as a way to download meshes, a * webserver of some sort must be used. * * @param {Object} nameAndAttrs an object where the key is the name of the mesh and the value is the url to that mesh's OBJ file * * @param {Function} completionCallback should contain a function that will take one parameter: an object array where the keys will be the unique object name and the value will be a Mesh object * * @param {Object} meshes In case other meshes are loaded separately or if a previously declared variable is desired to be used, pass in a (possibly empty) json object of the pattern: { '<mesh_name>': OBJ.Mesh } * */ export function downloadMeshes( nameAndURLs: NameAndUrls, completionCallback: (meshes: MeshMap) => void, meshes: MeshMap, ) { if (meshes === undefined) { meshes = {}; } const completed: Promise<[string, Mesh]>[] = []; for (const mesh_name in nameAndURLs) { if (!nameAndURLs.hasOwnProperty(mesh_name)) { continue; } const url = nameAndURLs[mesh_name]; completed.push( fetch(url) .then(response => response.text()) .then(data => { return [mesh_name, new Mesh(data)] as [string, Mesh]; }), ); } Promise.all(completed).then(ms => { for (const [name, mesh] of ms) { meshes[name] = mesh; } return completionCallback(meshes); }); } export interface ExtendedGLBuffer extends WebGLBuffer { itemSize: number; numItems: number; } function _buildBuffer(gl: WebGLRenderingContext, type: GLenum, data: number[], itemSize: number): ExtendedGLBuffer { const buffer = gl.createBuffer() as ExtendedGLBuffer; const arrayView = type === gl.ARRAY_BUFFER ? Float32Array : Uint16Array; gl.bindBuffer(type, buffer); gl.bufferData(type, new arrayView(data), gl.STATIC_DRAW); buffer.itemSize = itemSize; buffer.numItems = data.length / itemSize; return buffer; } export interface MeshWithBuffers extends Mesh { normalBuffer: ExtendedGLBuffer; textureBuffer: ExtendedGLBuffer; vertexBuffer: ExtendedGLBuffer; indexBuffer: ExtendedGLBuffer; } /** * Takes in the WebGL context and a Mesh, then creates and appends the buffers * to the mesh object as attributes. * * @param {WebGLRenderingContext} gl the `canvas.getContext('webgl')` context instance * @param {Mesh} mesh a single `OBJ.Mesh` instance * * The newly created mesh attributes are: * * Attrbute | Description * :--- | --- * **normalBuffer** |contains the model&#39;s Vertex Normals * normalBuffer.itemSize |set to 3 items * normalBuffer.numItems |the total number of vertex normals * | * **textureBuffer** |contains the model&#39;s Texture Coordinates * textureBuffer.itemSize |set to 2 items * textureBuffer.numItems |the number of texture coordinates * | * **vertexBuffer** |contains the model&#39;s Vertex Position Coordinates (does not include w) * vertexBuffer.itemSize |set to 3 items * vertexBuffer.numItems |the total number of vertices * | * **indexBuffer** |contains the indices of the faces * indexBuffer.itemSize |is set to 1 * indexBuffer.numItems |the total number of indices * * A simple example (a lot of steps are missing, so don't copy and paste): * * const gl = canvas.getContext('webgl'), * mesh = OBJ.Mesh(obj_file_data); * // compile the shaders and create a shader program * const shaderProgram = gl.createProgram(); * // compilation stuff here * ... * // make sure you have vertex, vertex normal, and texture coordinate * // attributes located in your shaders and attach them to the shader program * shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); * gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); * * shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal"); * gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute); * * shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); * gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute); * * // create and initialize the vertex, vertex normal, and texture coordinate buffers * // and save on to the mesh object * OBJ.initMeshBuffers(gl, mesh); * * // now to render the mesh * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vertexBuffer); * gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, mesh.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0); * // it's possible that the mesh doesn't contain * // any texture coordinates (e.g. suzanne.obj in the development branch). * // in this case, the texture vertexAttribArray will need to be disabled * // before the call to drawElements * if(!mesh.textures.length){ * gl.disableVertexAttribArray(shaderProgram.textureCoordAttribute); * } * else{ * // if the texture vertexAttribArray has been previously * // disabled, then it needs to be re-enabled * gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute); * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.textureBuffer); * gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, mesh.textureBuffer.itemSize, gl.FLOAT, false, 0, 0); * } * * gl.bindBuffer(gl.ARRAY_BUFFER, mesh.normalBuffer); * gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, mesh.normalBuffer.itemSize, gl.FLOAT, false, 0, 0); * * gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.mesh.indexBuffer); * gl.drawElements(gl.TRIANGLES, model.mesh.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0); */ export function initMeshBuffers(gl: WebGLRenderingContext, mesh: Mesh): MeshWithBuffers { (mesh as MeshWithBuffers).normalBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.vertexNormals, 3); (mesh as MeshWithBuffers).textureBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.textures, mesh.textureStride); (mesh as MeshWithBuffers).vertexBuffer = _buildBuffer(gl, gl.ARRAY_BUFFER, mesh.vertices, 3); (mesh as MeshWithBuffers).indexBuffer = _buildBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, mesh.indices, 1); return mesh as MeshWithBuffers; } export function deleteMeshBuffers(gl: WebGLRenderingContext, mesh: MeshWithBuffers) { gl.deleteBuffer(mesh.normalBuffer); gl.deleteBuffer(mesh.textureBuffer); gl.deleteBuffer(mesh.vertexBuffer); gl.deleteBuffer(mesh.indexBuffer); }
the_stack
import * as Consul from "consul"; import {createHttpClient, Driver, genAssert, genLogger, genMemCache, http, IDriverAdaptor, turtle} from "../../"; import Service = Consul.Agent.Service; import * as fs from "fs-extra"; import * as Path from "path"; import {BigNumber} from "bignumber.js"; import {promisify} from "util"; interface IHealth { api?: string; script?: string; interval?: string; ttl?: string; notes?: string; status?: string; } export interface IConsulConf { optional?: boolean; // default false options?: { host?: string; // (String, default: 127.0.0.1): agent address port?: number; // (Integer, default: 8500): agent HTTP(S) port secure?: boolean; // (Boolean, default: false): enable HTTPS ca?: string[]; }; health: IHealth | IHealth[]; dc?: string; tags?: string[]; did?: { head_refresh?: "process" | "stable" | "dynamic" }; request_fallback: { [key: string]: { http?: string, https?: string, tcp?: string, udp?: string } }; } export interface IServiceNode { id: string; address: string; port: number; healthy: boolean; } enum NodeStatus { NOTEXIST, UNHEALTHY_ME, UNHEALTHY_OTHER, HEALTHY, } class DIDGenerator { private _idSeq = { time: 0, seq: 0 }; private pow2_40Str = new BigNumber(1099511627776); private pow2_12Str = new BigNumber(4096); update(header: number, base: number = 10): string { const timestamp = Math.floor((Date.now() - 1560096000000) / 1000); if (this._idSeq.time !== timestamp) { this._idSeq.time = timestamp; this._idSeq.seq = 0; } const seq = ++this._idSeq.seq; if (seq >= 4096) { throw new Error("overflow"); } const did = (this.pow2_40Str.multipliedBy(header)).plus(this.pow2_12Str.multipliedBy(timestamp)).plus(seq); return did.toString(base); } } @Driver("discover/consul") export class DiscoverConsulDriver implements IDriverAdaptor<IConsulConf, any> { public static inst: DiscoverConsulDriver; public consul: Consul.Consul; public didHead: number; protected conf: IConsulConf; protected log = genLogger(); public assert = genAssert(); protected servicesCache = genMemCache(); protected httpClientCache = genMemCache(); private didGenerator = new DIDGenerator(); static assertConsulExist(driver: DiscoverConsulDriver, methodName: string) { driver.assert.ok(driver.consul, () => `call ${methodName} failed, cannot reach the consul agent`); } static FieldExist(object: DiscoverConsulDriver, methodName: string, descriptor: TypedPropertyDescriptor<Function>) { const originMethod = descriptor.value; descriptor.value = function (...args: any[]) { DiscoverConsulDriver.assertConsulExist(this, methodName); return originMethod.apply(this, args); }; } constructor() { DiscoverConsulDriver.inst = this; } protected async loadConsul() { if (!require) { throw new Error("Cannot load consul. Try to install all required dependencies."); } if (!this.consul) { let check; this.log.silly(`try connect to consul agent ${JSON.stringify(this.conf)}`); const options = this.conf.options || {}; const url = `${options.secure ? "https" : "http"}://${options.host || "127.0.0.1"}:${options.port || "8500"}/v1/agent/self`; try { check = await http().get(url); } catch (e) { check = false; this.log.warn(`touch consul error: ${e.message}`); } if (check) { try { this.consul = require("consul")(this.conf.options); } catch (e) { throw new Error("consul package was not found installed. Try to install it: npm install consul --save"); } } else { if (!this.conf.optional) { throw new Error(`cannot reach the consul agent, and the optional tag is off ${this.conf.optional}`); } else { this.log.warn(`cannot reach the consul agent, and the optional tag is open`); } } } return this.consul; } async init(conf: IConsulConf): Promise<any> { this.conf = conf; return await this.loadConsul(); } async onApiStart() { if (!this.consul) { if (this.conf.optional) { this.log.warn(`onApiStart is skipped, optional consul is unreachable.`); return; } else { throw new Error(`onApiStart: cannot reach the consul agent`); } } const status = await this.getStatusSelf(); if (status === NodeStatus.HEALTHY || status === NodeStatus.UNHEALTHY_OTHER) { throw new Error(`consul driver startup failed: the service ${turtle.serviceId} is already exist(${status})`); } else if (status === NodeStatus.UNHEALTHY_ME) { this.log.warn(`unhealthy me ${turtle.serviceId}(${status}) detected: override`); } else { this.log.info(`me ${turtle.serviceId}(${status}) are not exist: start to register`); } let check, checks; function healthConfToCheck(conf: IHealth) { return { http: `http://localhost:${turtle.runtime.port}/${conf.api}`, interval: conf.interval || "5s", notes: conf.notes, status: conf.status }; } if (this.conf.health instanceof Array) { checks = this.conf.health.map(h => healthConfToCheck(h)); } else { check = healthConfToCheck(this.conf.health); } const runtime = turtle.runtime; const regResult = await this.register({ id: `${turtle.conf.name}:${turtle.conf.id}`, name: turtle.conf.name, tags: this.conf.tags, address: runtime.ip, port: runtime.port, check, checks }); // console.log("regResult", regResult); } async onApiClose() { if (!this.consul) { if (this.conf.optional) { this.log.warn(`onApiClose is skipped, optional consul is unreachable.`); return; } else { throw new Error(`onApiClose: cannot reach the consul agent`); } } await this.deregister(turtle.serviceId); } @DiscoverConsulDriver.FieldExist async createServiceDIDHeader(): Promise<number> { const key = "service_did"; const headRefreshRule = this.conf && this.conf.did && this.conf.did.head_refresh ? this.conf.did.head_refresh : "process"; const didFilePath = Path.resolve(process.cwd(), `.${turtle.conf.name}-${turtle.conf.id}.turtle.did`); if (headRefreshRule !== "dynamic") { if (this.didHead) { return this.didHead; } if (headRefreshRule === "stable" && fs.existsSync(didFilePath)) { const didStr = fs.readJsonSync(didFilePath); if (didStr) { return this.didHead = parseInt(didStr.head); } } } let result = false; this.didHead = this.didHead || 0; while (!result) { const ExistedKey = await this.get(key); const Value = ExistedKey ? parseInt(ExistedKey.Value) : 0; const ModifyIndex = ExistedKey ? ExistedKey.ModifyIndex : 0; this.didHead = Value + 1; const ret = await this.cas(key, `${this.didHead}`, `${ModifyIndex}`); result = ret; } if (headRefreshRule !== "dynamic" && this.didHead !== 0) { // this.didHead === 0 means error fs.writeJSONSync(didFilePath, {head: this.didHead}); } return this.didHead; } @DiscoverConsulDriver.FieldExist async createServiceDID(base: number = 10) { return this.didGenerator.update(await this.createServiceDIDHeader(), base); } @DiscoverConsulDriver.FieldExist async get(key: string): Promise<{ LockIndex: number, Key: string, Flags: number, Value: string, CreateIndex: number, ModifyIndex: number }> { const val: any = await new Promise((resolve, reject) => this.consul.kv.get(key, (err, result) => { if (err) { reject(err); } resolve(result); })); return val; } @DiscoverConsulDriver.FieldExist async set(key: string, val: string) { const ret = await new Promise((resolve, reject) => this.consul.kv.set(key, val, (err, result) => { if (err) { reject(err); } resolve(result); })); return ret; } @DiscoverConsulDriver.FieldExist async cas(key: string, value: string, modifyIndex: string): Promise<any> { const opt = { key, value, cas: modifyIndex }; return await new Promise((resolve, reject) => this.consul.kv.set(opt, (err, result) => { if (err) { this.log.warn(`cas operation failed : ${opt} ${err}`); resolve(false); } resolve(result); })); } @DiscoverConsulDriver.FieldExist async register(opts: Service.RegisterOptions) { const service = this.consul.agent.service; return await promisify(service.register.bind(service))(opts).catch((ex: Error) => { this.log.error(`register driver discover/consul failed : ${ex}, ${ex.stack}`); if (!this.conf.optional) { throw ex; } }); } async deregister(serviceId: string) { if (!this.consul && this.conf.optional) { return; } DiscoverConsulDriver.assertConsulExist(this, "deregister"); const service = this.consul.agent.service; return await promisify(service.deregister.bind(service))(serviceId).catch((ex: Error) => { // this.log.error(`deregister driver discover/consul failed : ${ex}`); if (!this.conf.optional) { throw ex; } }); } // @DiscoverConsulDriver.FieldExist async httpClient(serviceName: string) { return await this.httpClientCache.getLoosingCache( // todo: can you do this ? how dose the copy? serviceName, async (name) => { let ret; if (this.consul) { const services = await this.serviceNodes(name, true); if (services.length > 0) { const service = services[Math.floor(services.length * Math.random())]; ret = createHttpClient(`http://${service.address}:${service.port}`); } } if (!ret) { let fallBackUrl = this.conf.request_fallback[serviceName] && this.conf.request_fallback[serviceName].http; if (fallBackUrl) { this.log.warn(`discover/consul: httpClient of service ${serviceName} fallback to ${fallBackUrl}`); ret = createHttpClient(fallBackUrl); } } return ret; }, 5); } @DiscoverConsulDriver.FieldExist async serviceNodes(serviceName: string, onlyHealthy: boolean = false): Promise<IServiceNode[]> { let result: IServiceNode[] = await this.servicesCache.getLoosingCache( serviceName, async (name): Promise<IServiceNode[]> => { const health = this.consul.health; // this.consul.health.service const healthNodes: any = await promisify(health.service.bind(health))(name); return healthNodes.map((h: any) => { const {ID, Address, Port} = h.Service; return { id: ID, address: Address, port: Port, healthy: (h.Checks as any[]).findIndex((c: any) => c.Status !== "passing") < 0 }; }).filter((c: any) => c); }, 2); // refresh cache every second, racing may happen, delay can be up to 2 + ttl // console.log("serviceNodes", result); return onlyHealthy ? result.filter(n => n.healthy) : result; } @DiscoverConsulDriver.FieldExist async getServiceNames() { const cat = this.consul.catalog; const services = await promisify(cat.services.bind(cat))(); return Object.keys(services); } @DiscoverConsulDriver.FieldExist async getServices(): Promise<{ [serviceName: string]: IServiceNode[] }> { const serviceNames = await this.getServiceNames(); const ret: { [serviceName: string]: IServiceNode[] } = {}; await Promise.all( serviceNames.map((sn) => (async () => { ret[sn] = await this.serviceNodes(sn, false); })() ) ); return ret; } @DiscoverConsulDriver.FieldExist async getSelf(): Promise<IServiceNode | undefined> { const services = await this.serviceNodes(turtle.conf.name, false); return services.find(t => t.id === turtle.serviceId); } @DiscoverConsulDriver.FieldExist async getStatusSelf(): Promise<NodeStatus> { const service = await this.getSelf(); if (!service) { return NodeStatus.NOTEXIST; } else if (service.healthy) { return NodeStatus.HEALTHY; } else { const runtime = turtle.runtime; if (service.address === runtime.ip && service.port === runtime.port) { return NodeStatus.UNHEALTHY_ME; } else { return NodeStatus.UNHEALTHY_OTHER; } } } }
the_stack
import React, { useState, useRef, Fragment, ChangeEvent } from 'react'; import Form, {IChangeEvent, ISubmitEvent} from '@rjsf/core'; import metaSchemaDraft04 from 'ajv/lib/refs/json-schema-draft-04.json' import JSON_RESUME_SCHEMA from '../../../../schemes/json-resume-schema_0.0.0.json' import { VALID_INVOKE_CHANNELS, INotification, IThemeEntry } from '../../../definitions' import styles from './App.css' import { useThemeList } from '../../hooks/useThemeList'; // read https://github.com/async-library/react-async export default function App() { /** * State - Hooks */ const [schema , setSchema] = useState(JSON_RESUME_SCHEMA as Record<string, any>); const [cvData, setCvData] = useState({}); const [notifications, setNotifications] = useState<Array<INotification>>([]); const [themeListFetchingError, themeList, setThemeList] = useThemeList(); // Add the error when theme-list fetching failed to the notifications if (themeListFetchingError) { setNotifications([...notifications, themeListFetchingError]) } const [selectedFormatsForExport, setSelectedFormatsForExport] = useState({ pdf: true, png: false, html: false, docx: false, } as Record<string, any>); const [fetchingThemeInProgress, setFetchingThemeInProgress] = useState(false); const [processingThemeInProgress, setProcessingThemeInProgress] = useState(false); const [exportCvAfterProcessing, setExportCvAfterProcessing] = useState(false); const [saveCvDataInProgress, setSaveCvDataInProgress] = useState(false); // The ref to the Form component const cvForm = useRef<Form<{}>>(null); const themeSelector = useRef<HTMLSelectElement>(null); // Logging helper const log = (type: any) => console.log.bind(console, type); /** * Handler for loading CV data. Uses the defined API invoke call on the open-cv chanel. Returns JSON data which is * then manually validated against the current schema of the Form. */ const handleOpenCvButtonClick = () => { window.api.invoke(VALID_INVOKE_CHANNELS['open-cv']).then((result: null | Record<string, any>) => { if (result) { const { errorSchema, errors } = cvForm.current.validate(result, schema, [metaSchemaDraft04]); if (errors && errors.length) { setNotifications([...notifications, {type: 'warning', text: `${errors.length} validations errors found in the loaded data.`}]) } setCvData(result); } }).catch((err: PromiseRejectionEvent) => { // display a warning ...TBD setNotifications([...notifications, {type: 'danger', text: `Opening of CV data failed: ${err}`}]) }) }; /** * Form-data-change handler making react-jsonschema-form controlled component. * @param changeEvent {IChangeEvent} The rjsf-form change event */ const handleFormDataChange = (changeEvent: IChangeEvent) => { setCvData(changeEvent.formData); }; /** * Click-handler for the Process-cv-button which triggers the form-submit function programmatically. */ const handleProcessCvButtonClick = () => { cvForm.current.submit(); }; /** * Checkbox change-handler updating the state of the selected output formats * @param evt {HTMLInputElement} The change event of the checkbox */ const handleFormatsForExportChange = (evt: ChangeEvent<HTMLInputElement>) => { // ignore the setter in case of undefined or other monkey business if (typeof selectedFormatsForExport[evt.target.name] === "boolean") { const newSelectedFormatsForExportState = { ...selectedFormatsForExport, [evt.target.name]: evt.target.checked }; // Do not allow unselecting all formats if (Object.keys(newSelectedFormatsForExportState).every((k) => !newSelectedFormatsForExportState[k])) { setNotifications([...notifications, {type: 'warning', text: 'At least one format must be selected for export!'}]) return; } setSelectedFormatsForExport({...selectedFormatsForExport, [evt.target.name]: evt.target.checked}) } }; /** * Click-handler for the Export-cv-button which triggers the CV export. */ const handleExportCvButtonClick = () => { // set the export-after-processing flag to true setExportCvAfterProcessing(true); cvForm.current.submit(); }; /** * Click-handler for the Save-cv-data-button which triggers the cv data save invocation. */ const handleSaveCvDataClick = () => { setSaveCvDataInProgress(true); window.api.invoke(VALID_INVOKE_CHANNELS['save-cv'], cvData).then(() => { // TODO: notification }) .catch((err: PromiseRejectionEvent) => { // display a warning ...TBD setNotifications([...notifications, {type: 'danger', text: `Saving of CV data failed: ${err}`}]) }).finally(() => { // set the state of fetching-state-in-progress to false setSaveCvDataInProgress(false); }); }; /** * Theme-list-change handler */ const handleSelectThemeChange = (evt: ChangeEvent<HTMLSelectElement>) => { if (fetchingThemeInProgress) { return } const selectedThemeIndex = parseInt(evt.target.value); const selectedTheme = themeList[selectedThemeIndex]; // download the theme if not present yet if (!selectedTheme.present) { // set the state of fetching-state-in-progress to true setFetchingThemeInProgress(true); window.api.invoke(VALID_INVOKE_CHANNELS['fetch-theme'], selectedTheme) .then(() => { themeList[selectedThemeIndex]['present'] = true; // update the theme list setThemeList([...themeList]); }).catch((err: PromiseRejectionEvent) => { // display a warning notification setNotifications([...notifications, {type: 'danger', text: `Fetching of theme ${selectedTheme.name} failed: ${err}`}]) }).finally(() => { // set the state of fetching-state-in-progress to false setFetchingThemeInProgress(false); }); } }; /** * The submit-event handler. */ const handleFormSubmit = (submitEvent: ISubmitEvent<any>) => { const selectedTheme = themeList[parseInt(themeSelector.current.value)]; // set the state of processing-state-in-progress to true setProcessingThemeInProgress(true); window.api.invoke(VALID_INVOKE_CHANNELS['process-cv'], submitEvent.formData, selectedTheme, selectedFormatsForExport, exportCvAfterProcessing ) .then((markup: string) => { // TODO: success notification }).catch((err: PromiseRejectionEvent) => { // display a warning notification setNotifications([...notifications, {type: 'danger', text: `Processing of CV data failed: ${err}`}]) }).finally(() => { // set the state of fetching-state-in-progress to false setProcessingThemeInProgress(false); // set the export-after-processing flag to false setExportCvAfterProcessing(false); }); }; return <div className="container-fluid "> <div className="row"> <div className="col-md-8 col-md-push-4 xs-pb-15"> <span className="glyphicon glyphicon-info-sign float-left xs-pr-5 xs-pt-5" /> <div className={styles['notification-area']}> { notifications.map((notification: INotification, index: number) => <div className={`alert alert-slim alert-${notification.type}`} role="alert" key={index}>{notification.text}</div> ) } </div> </div> <div className="col-md-4 col-md-pull-8 xs-pb-15"> <div className="btn-toolbar xs-pb-15" role="toolbar" aria-label="Upper toolbar with buttons"> <button className='btn btn-primary' onClick={handleOpenCvButtonClick}> Open CV </button> <button className='btn btn-primary' onClick={handleProcessCvButtonClick} disabled={fetchingThemeInProgress || processingThemeInProgress}> Process CV </button> <button className='btn btn-success pull-right' onClick={handleExportCvButtonClick} disabled={fetchingThemeInProgress || processingThemeInProgress}> Export CV </button> <div className="btn-group pull-right" role="group"> <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select output formats <span className="caret"></span> </button> <ul className="dropdown-menu"> <li> <div className="checkbox"> <label> <input type="checkbox" name="pdf" onChange={handleFormatsForExportChange} checked={selectedFormatsForExport['pdf']}/> Document PDF </label> </div> </li> <li> <div className="checkbox"> <label> <input type="checkbox" name="png" onChange={handleFormatsForExportChange} checked={selectedFormatsForExport['png']}/> Image PNG </label> </div> </li><li> <div className="checkbox"> <label> <input type="checkbox" name="html" onChange={handleFormatsForExportChange} checked={selectedFormatsForExport['html']}/> Website HTML </label> </div> </li><li> <div className="checkbox"> <label> <input type="checkbox" name="docx" onChange={handleFormatsForExportChange} checked={selectedFormatsForExport['docx']}/> Word DOCX </label> </div> </li> </ul> </div> <button className='btn pull-right' onClick={handleSaveCvDataClick} disabled={saveCvDataInProgress}> Save CV data </button> </div> <select className="form-control" defaultValue={'DEFAULT'} disabled={fetchingThemeInProgress} onChange={handleSelectThemeChange} ref={themeSelector}> <option key='0' value="DEFAULT" disabled>Select theme, default: jsonresume-theme-flat - A theme for JSON Resume</option> { themeList.map((theme: IThemeEntry, index: number) => // Note the explicit unicode white-space characters after the emoji characters <option key={index+1} value={index}>{theme.present ? '✅ ' : '📥 '} {theme.name} {theme.description ? '- ' : '' }{theme.description}</option> ) } </select> </div> </div> <Form schema={schema} formData={cvData} additionalMetaSchemas={[metaSchemaDraft04]} onChange={handleFormDataChange} onSubmit={handleFormSubmit} onError={log("errors")} ref={cvForm}> {/*workaround to hide the submit button, see https://github.com/rjsf-team/react-jsonschema-form/issues/705*/} <Fragment /> </Form> </div> }
the_stack
import { FieldsSelection } from '@genql/runtime/src/client/typeSelection' import { NoExtraProperties } from '@genql/runtime' // types requirements /* - no arguments, only request objects - response type picks from request type - at first level - at nested level - response type has all fields if __scalar is present - response type does not have __scalar field - at first level - at nested levels - response type is union of the on_ fields values (after their selection) - response type does not have on_ fields - works with NoExtraProperties */ type SRC = { literalsUnion: 'a' | 'b' nullableField: null | { x: boolean; optional?: string } list: { x: number a: string optional?: string }[] nested?: { list?: { edges?: { x?: number }[] }[] } category: { a: Date b: Date c: Date nested1: { a: string b: string c: string } nested2: { a: string b: string } optionalFieldsNested?: { a?: string b?: number } } optionalFields: { a?: string b?: number } order: { customer: { address: { city: 1 a: 1 b: 1 } } } union: | { a: string; __isUnion?: true } | { a: string; b: string; __isUnion?: true } nesting: { nestedUnion: | { a: string; __isUnion?: true } | { a: string; b: string; __isUnion?: true } } xxx: { xxx: boolean } yyy: { yyy: boolean } argumentSyntax: { a: string optional?: string nesting: { x: number y: number } union: | { a: string; __isUnion?: true } | { a: string; b: string; __isUnion?: true } list: { x: number a: string optional?: string }[] } } describe('pick', () => { const req = { category: { a: 1, b: 1, nested1: { a: 1, }, }, argumentSyntax: [ { x: 3 }, { a: 1, nesting: { __scalar: 1, }, }, ] as const, } const z: FieldsSelection<SRC, NoExtraProperties<typeof req>> = {} as any test( 'response type picks from request type', dontExecute(() => { z.category z.category.a z.category.b // @ts-expect-error z.category.c z.category.nested1.a }), ) test( 'response type does not have additional properties', dontExecute(() => { // TODO i can access keys with value type equal never // @ts-expect-error z.order // @ts-expect-error z.category.nested1.b // @ts-expect-error z.category.nested1.b // @ts-expect-error z.category.nested1.c // @ts-expect-error z.category.nested2 }), ) test( 'argument syntax', dontExecute(() => { z.argumentSyntax.a.toLocaleLowerCase }), ) }) describe('__scalar', () => { const req = { __name: 'name', category: { __scalar: 1, nested1: { a: 1, }, }, argumentSyntax: [ { a: 7 }, { __scalar: 1, }, ] as const, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'response type picks from request type', dontExecute(() => { z.category z.category.a z.category.b z.category.c z.category.nested1.a z.category.a.getDate z.category.b.getDate }), ) test( 'response type does not have additional properties', dontExecute(() => { // TODO i can access keys with value type equal never // @ts-expect-error z.order // @ts-expect-error z.category.nested1.b // @ts-expect-error z.category.nested1.c // @ts-expect-error z.category.nested2 }), ) test( '__scalar is not present', dontExecute(() => { // @ts-expect-error z.category.__scalar }), ) test( '__name is not present', dontExecute(() => { // @ts-expect-error __name z.__name }), ) test( 'argument syntax', dontExecute(() => { z.argumentSyntax.a.toLocaleLowerCase z.argumentSyntax.optional?.big // @ts-expect-error z.argumentSyntax.nesting.x }), ) }) describe('optional fields', () => { const req = { optionalFields: { a: 1, b: 1, }, category: { optionalFieldsNested: { __scalar: 1, }, }, argumentSyntax: [ {}, { optional: 1, }, ] as const, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'optional fields are preserved', dontExecute(() => { // @ts-expect-error z.optionalFields.a.toLocaleLowerCase z.optionalFields.a?.toLocaleLowerCase // @ts-expect-error z.optionalFields.b.toLocaleLowerCase z.optionalFields.b?.toFixed // @ts-expect-error z.category.optionalFieldsNested.a // @ts-expect-error z.category?.optionalFieldsNested.a }), ) test( 'optional fields are preserved in __scalar', dontExecute(() => { // @ts-expect-error z.optionalFields.a.toLocaleLowerCase z.optionalFields.a?.toLocaleLowerCase // @ts-expect-error z.optionalFields.b.toLocaleLowerCase z.optionalFields.b?.toFixed // @ts-expect-error z.category.optionalFieldsNested.a z.category.optionalFieldsNested?.a?.toLocaleLowerCase }), ) test( 'argument syntax', dontExecute(() => { // @ts-expect-error optional z.argumentSyntax.optional.toLocaleLowerCase z.argumentSyntax.optional?.toLocaleLowerCase }), ) }) describe('unions', () => { const req = { union: { onX: { a: 1, __scalar: 1, }, }, nesting: { nestedUnion: { onX: { a: 1, }, onY: { b: 1, }, }, }, argumentSyntax: { union: { a: 1, onX: { b: 1, }, }, }, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'pick union fields', dontExecute(() => { z.union.a.toLocaleLowerCase z.union.a.toLocaleLowerCase z.nesting.nestedUnion.a.toLocaleLowerCase }), ) test( 'does not have __isUnion', dontExecute(() => { // @ts-expect-error z.union.__isUnion // @ts-expect-error z.nesting.nestedUnion.__isUnion }), ) test( 'argument syntax', dontExecute(() => { z.argumentSyntax.union.a.charAt // @ts-expect-error z.argumentSyntax.a }), ) }) describe('hide fields in request', () => { const SKIP: false = false const req = { category: { a: 1, b: SKIP, c: false as const, }, } const z: FieldsSelection<SRC, typeof req> = {} as any // test( // 'cannot access falsy fields', // dontExecute(() => { // z.category.a // // @ts-expect-error inaccessible // z.category.b // // @ts-expect-error inaccessible // z.category.c // }), // ) }) describe('arrays', () => { const req = { list: { a: 1, x: 1, optional: 1, }, nested: [ { x: 1 }, { __scalar: 1, list: { edges: { x: 1, }, }, }, ] as const, argumentSyntax: { list: { x: 1, optional: 1, }, }, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'list', dontExecute(() => { z.list[0].a.charCodeAt z.list[0].x.toFixed }), ) test( 'nested', dontExecute(() => { z.nested?.list?.[0]?.edges?.[0].x?.toFixed }), ) test( 'maintain optionals', dontExecute(() => { // @ts-expect-error optional z.list[0].optional.bold z.list[0].optional?.bold }), ) test( 'args syntax', dontExecute(() => { z.argumentSyntax.list[0].x z.argumentSyntax.list[0].optional?.blink // @ts-expect-error optional z.argumentSyntax.list[0].optional.blink }), ) }) describe('literals unions', () => { const req = { literalsUnion: 1, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'literals', dontExecute(() => { z.literalsUnion.blink z.literalsUnion === 'a' z.literalsUnion === 'b' // @ts-expect-error z.literalsUnion === 'x' }), ) }) describe('literals unions', () => { const req = { nullableField: { x: 1, optional: 1, }, } const z: FieldsSelection<SRC, typeof req> = {} as any test( 'accessible', dontExecute(() => { z.nullableField.x z.nullableField.optional?.big // @ts-expect-error optional z.nullableField.optional.big }), ) }) test( 'complex optional type with array', dontExecute(() => { interface ForkConnection { edges?: (ForkEdge | undefined)[] __typename?: 'ForkConnection' } interface ForkEdge { cursor?: string node?: { x: string; y: string } nodes?: { x?: string; y?: string }[] __typename?: 'ForkEdge' } // issue type X = FieldsSelection< ForkConnection | undefined, { edges?: { node: { x: 1 } nodes: { __scalar: 1 } } } > const x: X = {} as any x?.edges?.[0]?.node?.x?.toLocaleLowerCase // @ts-expect-error not present x?.edges?.[0]?.node?.y?.toLocaleLowerCase x?.edges?.[0]?.nodes?.[0].x?.toLocaleLowerCase x?.edges?.[0]?.nodes?.[0].y?.toLocaleLowerCase }), ) ///////////////////////////////////// unions // { // // only one union // type One = { one: string; __typename: string } // type Two = { two: string; __typename: string } // type SRC = { // union?: { // __union: One | Two // __resolve: { // on_One: One // on_Two: Two // } // __typename: 'One' | 'Two' // } // } // type DST = { // union?: { // on_One: { // one: true // } // // on_Two: { // // two: 1 // // } // } // } // const z: FieldsSelection<SRC, DST> = {} as any // z.union?.one // } // { // // 2 unions together // type One = { one: string; __typename: string } // type Two = { two: string; __typename: string } // type SRC = { // union?: { // __union: One | Two // __resolve: { // on_One: One // on_Two: Two // } // __typename: 'One' | 'Two' // } // } // type DST = { // union?: { // on_One?: { // one?: true // } // on_Two?: { // two?: true // } // } // } // const z: FieldsSelection<SRC, DST> = {} as any // z.union // this is a union type, it cannot be directly be accessed without a guard // } // { // // without top level object // type One = { one?: string; __typename?: string } // type Two = { two?: string; __typename?: string } // type SRC = { // __union: One | Two // __resolve: { // on_One?: One // on_Two?: Two // } // __typename?: 'One' | 'Two' // } // type DST = { // on_One?: { // one?: true // } // __typename?: 1 // // on_Two: { // // two: 1 // // } // } // const z: FieldsSelection<SRC, DST> = {} as any // z.one // } // { // type One = { one: string; __typename: string } // const x: ObjectFieldsSelection<One, { one?: true }> = {} as any // x.one // } function dontExecute(f: any) { return () => {} }
the_stack
import test from 'ava'; import {JsonGetter} from '../src/decorators/JsonGetter'; import {JsonSetter, JsonSetterNulls} from '../src/decorators/JsonSetter'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonProperty} from '../src/decorators/JsonProperty'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {JacksonError} from '../src/core/JacksonError'; test('@JsonGetter and @JsonSetter', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonGetter() @JsonClassType({type: () => [String]}) getFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonSetter() setFullname(fullname: string) { this.fullname = fullname.split(' '); } } const user = new User(1, 'John', 'Alfa'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"firstname":"John","lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.fullname instanceof Array); t.deepEqual(userParsed.fullname, ['John', 'Alfa']); }); test('@JsonGetter and @JsonSetter with value', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) fullname: string[]; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonGetter({value: 'fullname'}) @JsonClassType({type: () => [String]}) getMyFullname(): string { return this.firstname + ' ' + this.lastname; } @JsonSetter({value: 'fullname'}) setMyFullname(fullname: string) { this.fullname = fullname.split(' '); } } const user = new User(1, 'John', 'Alfa'); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"firstname":"John","lastname":"Alfa","fullname":"John Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.fullname instanceof Array); t.deepEqual(userParsed.fullname, ['John', 'Alfa']); }); test('@JsonSetter with nulls and contentNulls options set to JsonSetterNulls.FAIL', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) otherInfoArray: string[] = []; @JsonProperty() @JsonClassType({type: () => [Map, [String, String]]}) otherInfoMap: Map<string, string> = new Map(); @JsonProperty() @JsonClassType({type: () => [Object, [String, String]]}) otherInfoObjLiteral = {}; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonSetter({nulls: JsonSetterNulls.FAIL, contentNulls: JsonSetterNulls.FAIL}) setOtherInfoArray(@JsonClassType({type: () => [Array]}) otherInfoArray: string[]) { this.otherInfoArray = otherInfoArray; } @JsonSetter({nulls: JsonSetterNulls.FAIL, contentNulls: JsonSetterNulls.FAIL}) setOtherInfoMap(@JsonClassType({type: () => [Map]}) otherInfoMap: Map<string, string>) { this.otherInfoMap = otherInfoMap; } @JsonSetter({nulls: JsonSetterNulls.FAIL, contentNulls: JsonSetterNulls.FAIL}) setOtherInfoObjLiteral(otherInfoObjLiteral: any) { this.otherInfoObjLiteral = otherInfoObjLiteral; } } const objectMapper = new ObjectMapper(); let err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":null,"otherInfoMap":{},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":["info 1", null, "info 3"],"otherInfoMap":{},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":null,"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{"mapKey1": "mapValue1","mapKey2":null,"mapKey3":"mapValue3"},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{},"otherInfoObjLiteral":null}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); err = t.throws<JacksonError>(() => { // eslint-disable-next-line max-len objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{},"otherInfoObjLiteral":{"objLiteralKey1": "objLiteralValue1","objLiteralKey2":null,"objLiteralKey3":"objLiteralValue3"}}', {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); }); test('@JsonSetter with nulls and contentNulls options set to JsonSetterNulls.SKIP', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [String]]}) otherInfoArray: string[] = []; @JsonProperty() @JsonClassType({type: () => [Map, [String, String]]}) otherInfoMap: Map<string, string> = new Map(); @JsonProperty() @JsonClassType({type: () => [Object, [String, String]]}) otherInfoObjLiteral = {}; constructor(id: number, firstname: string, lastname: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; } @JsonSetter({nulls: JsonSetterNulls.SKIP, contentNulls: JsonSetterNulls.SKIP}) setOtherInfoArray(@JsonClassType({type: () => [Array]}) otherInfoArray: string[]) { this.otherInfoArray = otherInfoArray; } @JsonSetter({nulls: JsonSetterNulls.SKIP, contentNulls: JsonSetterNulls.SKIP}) setOtherInfoMap(@JsonClassType({type: () => [Map]}) otherInfoMap: Map<string, string>) { this.otherInfoMap = otherInfoMap; } @JsonSetter({nulls: JsonSetterNulls.SKIP, contentNulls: JsonSetterNulls.SKIP}) setOtherInfoObjLiteral(otherInfoObjLiteral: any) { this.otherInfoObjLiteral = otherInfoObjLiteral; } } const objectMapper = new ObjectMapper(); // eslint-disable-next-line max-len let userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":null,"otherInfoMap":{},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, []); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map()); // eslint-disable-next-line max-len userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":["info 1", null, "info 3"],"otherInfoMap":{},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, ['info 1', 'info 3']); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map()); t.assert(userParsed.otherInfoObjLiteral instanceof Object); t.deepEqual(userParsed.otherInfoObjLiteral, {}); // eslint-disable-next-line max-len userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":null,"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, []); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map()); t.assert(userParsed.otherInfoObjLiteral instanceof Object); t.deepEqual(userParsed.otherInfoObjLiteral, {}); // eslint-disable-next-line max-len userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{"mapKey1": "mapValue1","mapKey2":null,"mapKey3":"mapValue3"},"otherInfoObjLiteral":{}}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, []); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map([['mapKey1', 'mapValue1'], ['mapKey3', 'mapValue3']])); t.assert(userParsed.otherInfoObjLiteral instanceof Object); t.deepEqual(userParsed.otherInfoObjLiteral, {}); // eslint-disable-next-line max-len userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{},"otherInfoObjLiteral":null}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, []); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map()); t.assert(userParsed.otherInfoObjLiteral instanceof Object); t.deepEqual(userParsed.otherInfoObjLiteral, {}); // eslint-disable-next-line max-len userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","otherInfoArray":[],"otherInfoMap":{},"otherInfoObjLiteral":{"objLiteralKey1": "objLiteralValue1","objLiteralKey2":null,"objLiteralKey3":"objLiteralValue3"}}', {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.is(userParsed.id, 1); t.is(userParsed.firstname, 'John'); t.is(userParsed.lastname, 'Alfa'); t.assert(userParsed.otherInfoArray instanceof Array); t.deepEqual(userParsed.otherInfoArray, []); t.assert(userParsed.otherInfoMap instanceof Map); t.deepEqual(userParsed.otherInfoMap, new Map()); t.assert(userParsed.otherInfoObjLiteral instanceof Object); t.deepEqual(userParsed.otherInfoObjLiteral, {objLiteralKey1: 'objLiteralValue1', objLiteralKey3: 'objLiteralValue3'}); });
the_stack
import { HighlightedStatus, Notification, EventNoticer, GUIEvent, GUIHighlightedEvent, GUIKeyEvent, GUIClickEvent, GUITouchEvent, GUIMouseEvent, GUIActionEvent, } from './event'; import * as value from './value'; import ViewController from './ctr'; import { StyleSheet } from './css'; import { Action, ActionIn, KeyframeOptions } from './_action'; const _ftr = __require__('_ftr'); export interface DOM { id: string; readonly __meta__: View; readonly owner: ViewController | null; remove(): void; appendTo(parentView: View): View; afterTo(prevView: View): View; style: StyleSheet; }; /** * @class View */ export declare class View extends Notification<GUIEvent> implements DOM { readonly onKeyDown: EventNoticer<GUIKeyEvent>; readonly onKeyPress: EventNoticer<GUIKeyEvent>; readonly onKeyUp: EventNoticer<GUIKeyEvent>; readonly onKeyEnter: EventNoticer<GUIKeyEvent>; readonly onBack: EventNoticer<GUIClickEvent>; readonly onClick: EventNoticer<GUIClickEvent>; readonly onTouchStart: EventNoticer<GUITouchEvent>; readonly onTouchMove: EventNoticer<GUITouchEvent>; readonly onTouchEnd: EventNoticer<GUITouchEvent>; readonly onTouchCancel: EventNoticer<GUITouchEvent>; readonly onMouseOver: EventNoticer<GUIMouseEvent>; readonly onMouseOut: EventNoticer<GUIMouseEvent>; readonly onMouseLeave: EventNoticer<GUIMouseEvent>; readonly onMouseEnter: EventNoticer<GUIMouseEvent>; readonly onMouseMove: EventNoticer<GUIMouseEvent>; readonly onMouseDown: EventNoticer<GUIMouseEvent>; readonly onMouseUp: EventNoticer<GUIMouseEvent>; readonly onMouseWheel: EventNoticer<GUIMouseEvent>; readonly onFocus: EventNoticer<GUIEvent>; readonly onBlur: EventNoticer<GUIEvent>; readonly onHighlighted: EventNoticer<GUIHighlightedEvent>; readonly onActionKeyframe: EventNoticer<GUIActionEvent>; readonly onActionLoop: EventNoticer<GUIActionEvent>; prepend(view: View): void; append(view: View): void; appendText(str: string): void; before(view: View): void; after(view: View): void; remove(): void; removeAllChild(): void; focus(): boolean; blur(): boolean; layoutOffset(): value.Vec2; layoutOffsetFrom(parents: View): value.Vec2; getAction(): Action | null; private _setAction(action: Action | null): void; screenRect(): value.Rect; finalMatrix(): value.Mat; finalOpacity(): number; position(): value.Vec2; overlapTest(): boolean; addClass(cls: string): void; removeClass(): void; toggleClass(): void; firstButton(): Button | null; hasChild(child: View): boolean; readonly innerText: string; readonly parent: View | null; readonly prev: View | null; readonly next: View | null; readonly first: View | null; readonly last: View | null; x: number; y: number; scaleX: number; scaleY: number; rotateZ: number; skewX: number; skewY: number; opacity: number; visible: boolean; readonly finalVisible: boolean; readonly drawVisible: boolean; translate: value.Vec2; scale: value.Vec2; skew: value.Vec2; originX: number; originY: number; origin: value.Vec2; readonly matrix: value.Mat; readonly level: number; needDraw: boolean; receive: boolean; isFocus: boolean; readonly viewType: number; class: string; id: string; // ext readonly __meta__: View; readonly owner: ViewController | null; ownerAs<T extends ViewController = ViewController>(): T; action: Action | null; actionAs<T extends Action = Action>(): T; style: StyleSheet; setAction(action: ActionIn | null): void; hashCode(): number; appendTo(parentView: View): this; afterTo(prevView: View): this; transition(style: KeyframeOptions, cb?: (e: GUIActionEvent)=>void): Action; transition(style: KeyframeOptions, delay?: number, cb?: (e: GUIActionEvent)=>void): Action; show(): void; hide(): void; static readonly isViewController: boolean; } type Texture = any; export declare class Sprite extends View { src: string; texture: Texture | null; startX: number; startY: number; width: number; height: number; start: number; ratioX: number; ratioY: number; ratio: value.Vec2; repeat: value.Repeat; } export interface TextFont { simpleLayoutWidth(str: string): number; textBackgroundColor: value.TextColor; textColor: value.TextColor; textSize: value.TextSize; textStyle: value.TextStyle; textFamily: value.TextFamily; textShadow: value.TextShadow; textLineHeight: value.TextLineHeight; textDecoration: value.TextDecoration; } export interface TextLayout extends TextFont { textOverflow: value.TextOverflow; textWhiteSpace: value.TextWhiteSpace; } export declare abstract class Layout extends View { readonly clientWidth: number; readonly clientHeight: number; } export declare abstract class Box extends Layout { width: value.Value; height: value.Value; margin: value.Value[]; // marginLeft: value.Value; marginTop: value.Value; marginRight: value.Value; marginBottom: value.Value; border: value.Border[]; // borderLeft: value.Border; borderTop: value.Border; borderRight: value.Border; borderBottom: value.Border; borderWidth: number[]; // borderLeftWidth: number; borderTopWidth: number; borderRightWidth: number; borderBottomWidth: number; borderColor: value.Color[]; borderLeftColor: value.Color; borderTopColor: value.Color; borderRightColor: value.Color; borderBottomColor: value.Color; borderRadius: number[]; // borderRadiusLeftTop: number; borderRadiusRightTop: number; borderRadiusRightBottom: number; borderRadiusLeftBottom: number; backgroundColor: value.Color; background: value.Background | null; newline: boolean; clip: boolean; readonly finalWidth: number; readonly finalHeight: number; readonly finalMarginLeft: number; readonly finalMarginTop: number; readonly finalMarginRight: number; readonly finalMarginBottom: number; } export declare class Span extends Layout implements TextLayout { simpleLayoutWidth(str: string): number; textBackgroundColor: value.TextColor; textColor: value.TextColor; textSize: value.TextSize; textStyle: value.TextStyle; textFamily: value.TextFamily; textShadow: value.TextShadow; textLineHeight: value.TextLineHeight; textDecoration: value.TextDecoration; textOverflow: value.TextOverflow; textWhiteSpace: value.TextWhiteSpace; } export declare class TextNode extends Span { readonly length: number; value: string; readonly textHoriBearing: number; readonly textHeight: number; } export declare class Div extends Box { contentAlign: value.ContentAlign; } export declare class Image extends Div { readonly onLoad: EventNoticer<GUIEvent>; readonly onError: EventNoticer<GUIEvent<Error>>; src: string; readonly sourceWidth: number; readonly sourceHeight: number; } export declare class Panel extends Div { readonly onFocusMove: EventNoticer<GUIEvent>; allowLeave: boolean; allowEntry: boolean; intervalTime: number; enableSelect: boolean; readonly isActivity: boolean; readonly parentPanel: Panel; } export interface IScroll { readonly onScroll: EventNoticer<GUIEvent>; scrollTo(value: value.Vec2, duration?: number, curve?: value.Curve): void; terminate(): void; scroll: value.Vec2; scrollX: number; scrollY: number; readonly scrollWidth: number; readonly scrollHeight: number; scrollbar: boolean; resistance: number; bounce: boolean; bounceLock: boolean; momentum: boolean; lockDirection: boolean; catchPositionX: number; catchPositionY: number; scrollbarColor: value.Color; readonly hScrollbar: boolean; readonly vScrollbar: boolean; scrollbarWidth: number; scrollbarMargin: number; defaultScrollDuration: number; defaultScrollCurve: value.Curve; } export declare class Scroll extends Panel implements IScroll { focusMarginLeft: number; focusMarginRight: number; focusMarginTop: number; focusMarginBottom: number; focusAlignX: value.Align; focusAlignY: value.Align; enableFocusAlign: boolean; readonly isFixedScrollSize: boolean; setFixedScrollSize(size: value.Vec2): void; // implements IScroll readonly onScroll: EventNoticer<GUIEvent>; scrollTo(value: value.Vec2, duration?: number, curve?: value.Curve): void; terminate(): void; scroll: value.Vec2; scrollX: number; scrollY: number; readonly scrollWidth: number; readonly scrollHeight: number; scrollbar: boolean; resistance: number; bounce: boolean; bounceLock: boolean; momentum: boolean; lockDirection: boolean; catchPositionX: number; catchPositionY: number; scrollbarColor: value.Color; readonly hScrollbar: boolean; readonly vScrollbar: boolean; scrollbarWidth: number; scrollbarMargin: number; defaultScrollDuration: number; defaultScrollCurve: value.Curve; } export declare class Indep extends Div { alignX: value.Align; alignY: value.Align; align: value.Vec2[]; } export interface ILimit { minWidth: value.Value; minHeight: value.Value; maxWidth: value.Value; maxHeight: value.Value; } export declare class Limit extends Div implements ILimit { // implements ILimit minWidth: value.Value; minHeight: value.Value; maxWidth: value.Value; maxHeight: value.Value; } export declare class LimitIndep extends Indep implements ILimit { // implements ILimit minWidth: value.Value; minHeight: value.Value; maxWidth: value.Value; maxHeight: value.Value; } export declare class Hybrid extends Box implements TextLayout { textAlign: value.TextAlign; // implements TextLayout simpleLayoutWidth(str: string): number; textBackgroundColor: value.TextColor; textColor: value.TextColor; textSize: value.TextSize; textStyle: value.TextStyle; textFamily: value.TextFamily; textShadow: value.TextShadow; textLineHeight: value.TextLineHeight; textDecoration: value.TextDecoration; textOverflow: value.TextOverflow; textWhiteSpace: value.TextWhiteSpace; } export declare class Label extends View implements TextFont { readonly length: number; value: string; readonly textHoriBearing: number; readonly textHeight: number; textAlign: value.TextAlign; // implements TextFont simpleLayoutWidth(str: string): number; textBackgroundColor: value.TextColor; textColor: value.TextColor; textSize: value.TextSize; textStyle: value.TextStyle; textFamily: value.TextFamily; textShadow: value.TextShadow; textLineHeight: value.TextLineHeight; textDecoration: value.TextDecoration; } export declare class Text extends Hybrid { readonly length: number; value: string; readonly textHoriBearing: number; readonly textHeight: number; } export declare class Input extends Text { readonly onChange: EventNoticer<GUIEvent>; type: value.KeyboardType; returnType: value.KeyboardReturnType; placeholder: string; placeholderColor: value.Color; security: boolean; textMargin: number; } export declare class Textarea extends Input implements IScroll { // implements IScroll readonly onScroll: EventNoticer<GUIEvent>; scrollTo(value: value.Vec2, duration?: number, curve?: value.Curve): void; terminate(): void; scroll: value.Vec2; scrollX: number; scrollY: number; readonly scrollWidth: number; readonly scrollHeight: number; scrollbar: boolean; resistance: number; bounce: boolean; bounceLock: boolean; momentum: boolean; lockDirection: boolean; catchPositionX: number; catchPositionY: number; scrollbarColor: value.Color; readonly hScrollbar: boolean; readonly vScrollbar: boolean; scrollbarWidth: number; scrollbarMargin: number; defaultScrollDuration: number; defaultScrollCurve: value.Curve; } export declare class Button extends Hybrid { findNextButton(): Button | null; panel(): Panel | null; defaultStyle: boolean; setHighlighted(status: HighlightedStatus): void; triggerHighlighted(evt: GUIHighlightedEvent): number; } export declare class Root extends Panel {} export class Clip extends (_ftr.Div as typeof Div) { constructor() { super(); this.clip = true; } } Object.assign(exports, { View: _ftr.View, Sprite: _ftr.Sprite, Label: _ftr.Label, Span: _ftr.Span, TextNode: _ftr.TextNode, Div: _ftr.Div, Image: _ftr.Image, Textarea: _ftr.Textarea, Panel: _ftr.Panel, Scroll: _ftr.Scroll, Indep: _ftr.Indep, Limit: _ftr.Limit, LimitIndep: _ftr.LimitIndep, Hybrid: _ftr.Hybrid, Text: _ftr.Text, Input: _ftr.Input, Button: _ftr.Button, Root: _ftr.Root, });
the_stack
export let icons = [ { label: "", code: "F0C8", value: "success" }, { label: "", code: "F0A2", value: "plus" }, { label: "", code: "F042", value: "cross" }, { label: "", code: "F056", value: "fail" }, { label: "", code: "F009", value: "arrow-up" }, { label: "", code: "F007", value: "arrow-down" }, { label: "", code: "F008", value: "arrow-left" }, { label: "", code: "F00A", value: "arrow" }, { label: "", code: "F07C", value: "location-o" }, { label: "", code: "F079", value: "like-o" }, { label: "", code: "F0C4", value: "star" }, { label: "", code: "F0C3", value: "star-o" }, { label: "", code: "F09A", value: "phone-o" }, { label: "", code: "F0B4", value: "setting-o" }, { label: "", code: "F059", value: "fire-o" }, { label: "", code: "F03F", value: "coupon-o" }, { label: "", code: "F026", value: "cart-o" }, { label: "", code: "F0BB", value: "shopping-cart-o" }, { label: "", code: "F024", value: "cart-circle-o" }, { label: "", code: "F05E", value: "friends-o" }, { label: "", code: "F03B", value: "comment-o" }, { label: "", code: "F060", value: "gem-o" }, { label: "", code: "F064", value: "gift-o" }, { label: "", code: "F0A3", value: "point-gift-o" }, { label: "", code: "F0B0", value: "send-gift-o" }, { label: "", code: "F0B2", value: "service-o" }, { label: "", code: "F00F", value: "bag-o" }, { label: "", code: "F0CB", value: "todo-list-o" }, { label: "", code: "F011", value: "balance-list-o" }, { label: "", code: "F034", value: "close" }, { label: "", code: "F032", value: "clock-o" }, { label: "", code: "F0A9", value: "question-o" }, { label: "", code: "F092", value: "passed" }, { label: "", code: "F000", value: "add-o" }, { label: "", code: "F066", value: "gold-coin-o" }, { label: "", code: "F074", value: "info-o" }, { label: "", code: "F09F", value: "play-circle-o" }, { label: "", code: "F093", value: "pause-circle-o" }, { label: "", code: "F0C5", value: "stop-circle-o" }, { label: "", code: "F0DF", value: "warning-o" }, { label: "", code: "F098", value: "phone-circle-o" }, { label: "", code: "F087", value: "music-o" }, { label: "", code: "F0C1", value: "smile-o" }, { label: "", code: "F0C9", value: "thumb-circle-o" }, { label: "", code: "F039", value: "comment-circle-o" }, { label: "", code: "F01D", value: "browsing-history-o" }, { label: "", code: "F0D0", value: "underway-o" }, { label: "", code: "F085", value: "more-o" }, { label: "", code: "F0D5", value: "video-o" }, { label: "", code: "F0B9", value: "shop-o" }, { label: "", code: "F0B7", value: "shop-collect-o" }, { label: "", code: "F02D", value: "chat-o" }, { label: "", code: "F0BF", value: "smile-comment-o" }, { label: "", code: "F0D7", value: "vip-card-o" }, { label: "", code: "F00D", value: "award-o" }, { label: "", code: "F048", value: "diamond-o" }, { label: "", code: "F0D9", value: "volume-o" }, { label: "", code: "F036", value: "cluster-o" }, { label: "", code: "F0DB", value: "wap-home-o" }, { label: "", code: "F09C", value: "photo-o" }, { label: "", code: "F062", value: "gift-card-o" }, { label: "", code: "F052", value: "expand-o" }, { label: "", code: "F083", value: "medel-o" }, { label: "", code: "F068", value: "good-job-o" }, { label: "", code: "F080", value: "manager-o" }, { label: "", code: "F077", value: "label-o" }, { label: "", code: "F01B", value: "bookmark-o" }, { label: "", code: "F018", value: "bill-o" }, { label: "", code: "F06E", value: "hot-o" }, { label: "", code: "F06F", value: "hot-sale-o" }, { label: "", code: "F08B", value: "new-o" }, { label: "", code: "F089", value: "new-arrival-o" }, { label: "", code: "F06A", value: "goods-collect-o" }, { label: "", code: "F054", value: "eye-o" }, { label: "", code: "F013", value: "balance-o" }, { label: "", code: "F0AC", value: "refund-o" }, { label: "", code: "F01A", value: "birthday-cake-o" }, { label: "", code: "F0D4", value: "user-o" }, { label: "", code: "F08F", value: "orders-o" }, { label: "", code: "F0CE", value: "tv-o" }, { label: "", code: "F050", value: "envelop-o" }, { label: "", code: "F05B", value: "flag-o" }, { label: "", code: "F05C", value: "flower-o" }, { label: "", code: "F058", value: "filter-o" }, { label: "", code: "F015", value: "bar-chart-o" }, { label: "", code: "F02C", value: "chart-trending-o" }, { label: "", code: "F01F", value: "brush-o" }, { label: "", code: "F021", value: "bullhorn-o" }, { label: "", code: "F072", value: "hotel-o" }, { label: "", code: "F02A", value: "cashier-o" }, { label: "", code: "F08D", value: "newspaper-o" }, { label: "", code: "F0DE", value: "warn-o" }, { label: "", code: "F08E", value: "notes-o" }, { label: "", code: "F022", value: "calender-o" }, { label: "", code: "F020", value: "bulb-o" }, { label: "", code: "F0D3", value: "user-circle-o" }, { label: "", code: "F047", value: "desktop-o" }, { label: "", code: "F006", value: "apps-o" }, { label: "", code: "F06D", value: "home-o" }, { label: "", code: "F0B6", value: "share" }, { label: "", code: "F0AF", value: "search" }, { label: "", code: "F0A5", value: "points" }, { label: "", code: "F04D", value: "edit" }, { label: "", code: "F044", value: "delete" }, { label: "", code: "F0A8", value: "qr" }, { label: "", code: "F0A7", value: "qr-invalid" }, { label: "", code: "F035", value: "closed-eye" }, { label: "", code: "F04B", value: "down" }, { label: "", code: "F0AE", value: "scan" }, { label: "", code: "F05D", value: "free-postage" }, { label: "", code: "F02B", value: "certificate" }, { label: "", code: "F07F", value: "logistics" }, { label: "", code: "F03E", value: "contact" }, { label: "", code: "F028", value: "cash-back-record" }, { label: "", code: "F003", value: "after-sale" }, { label: "", code: "F051", value: "exchange" }, { label: "", code: "F0D2", value: "upgrade" }, { label: "", code: "F04E", value: "ellipsis" }, { label: "", code: "F030", value: "circle" }, { label: "", code: "F046", value: "description" }, { label: "", code: "F0AB", value: "records" }, { label: "", code: "F0BE", value: "sign" }, { label: "", code: "F03D", value: "completed" }, { label: "", code: "F057", value: "failure" }, { label: "", code: "F04C", value: "ecard-pay" }, { label: "", code: "F096", value: "peer-pay" }, { label: "", code: "F014", value: "balance-pay" }, { label: "", code: "F041", value: "credit-pay" }, { label: "", code: "F043", value: "debit-pay" }, { label: "", code: "F029", value: "cash-on-deliver" }, { label: "", code: "F090", value: "other-pay" }, { label: "", code: "F0CD", value: "tosend" }, { label: "", code: "F097", value: "pending-payment" }, { label: "", code: "F091", value: "paid" }, { label: "", code: "F004", value: "aim" }, { label: "", code: "F04A", value: "discount" }, { label: "", code: "F073", value: "idcard" }, { label: "", code: "F0AD", value: "replay" }, { label: "", code: "F0BD", value: "shrink" } ]; // { // label: "", // code: "F000", // value: "add-o" // }, // { // label: "", // code: "F001", // value: "add-square" // }, // { // label: "", // code: "F002", // value: "add" // }, // { // label: "", // code: "F003", // value: "after-sale" // }, // { // label: "", // code: "F004", // value: "aim" // }, // { // label: "", // code: "F005", // value: "alipay" // }, // { // label: "", // code: "F006", // value: "apps-o" // }, // { // label: "", // code: "F00B", // value: "ascending" // }, // { // label: "", // code: "F00C", // value: "audio" // }, // { // label: "", // code: "F00D", // value: "award-o" // }, // { // label: "", // code: "F00E", // value: "award" // }, // { // label: "", // code: "F00F", // value: "bag-o" // }, // { // label: "", // code: "F010", // value: "bag" // }, // { // label: "", // code: "F011", // value: "balance-list-o" // }, // { // label: "", // code: "F012", // value: "balance-list" // }, // { // label: "", // code: "F013", // value: "balance-o" // }, // { // label: "", // code: "F014", // value: "balance-pay" // }, // { // label: "", // code: "F015", // value: "bar-chart-o" // }, // { // label: "", // code: "F016", // value: "bars" // }, // { // label: "", // code: "F017", // value: "bell" // }, // { // label: "", // code: "F018", // value: "bill-o" // }, // { // label: "", // code: "F019", // value: "bill" // }, // { // label: "", // code: "F01A", // value: "birthday-cake-o" // }, // { // label: "", // code: "F01B", // value: "bookmark-o" // }, // { // label: "", // code: "F01C", // value: "bookmark" // }, // { // label: "", // code: "F01D", // value: "browsing-history-o" // }, // { // label: "", // code: "F01E", // value: "browsing-history" // }, // { // label: "", // code: "F01F", // value: "brush-o" // }, // { // label: "", // code: "F020", // value: "bulb-o" // }, // { // label: "", // code: "F021", // value: "bullhorn-o" // }, // { // label: "", // code: "F022", // value: "calender-o" // }, // { // label: "", // code: "F023", // value: "card" // }, // { // label: "", // code: "F024", // value: "cart-circle-o" // }, // { // label: "", // code: "F025", // value: "cart-circle" // }, // { // label: "", // code: "F026", // value: "cart-o" // }, // { // label: "", // code: "F027", // value: "cart" // }, // { // label: "", // code: "F028", // value: "cash-back-record" // }, // { // label: "", // code: "F029", // value: "cash-on-deliver" // }, // { // label: "", // code: "F02A", // value: "cashier-o" // }, // { // label: "", // code: "F02B", // value: "certificate" // }, // { // label: "", // code: "F02C", // value: "chart-trending-o" // }, // { // label: "", // code: "F02D", // value: "chat-o" // }, // { // label: "", // code: "F02E", // value: "chat" // }, // { // label: "", // code: "F02F", // value: "checked" // }, // { // label: "", // code: "F030", // value: "circle" // }, // { // label: "", // code: "F031", // value: "clear" // }, // { // label: "", // code: "F032", // value: "clock-o" // }, // { // label: "", // code: "F033", // value: "clock" // }, // { // label: "", // code: "F034", // value: "close" // }, // { // label: "", // code: "F035", // value: "closed-eye" // }, // { // label: "", // code: "F036", // value: "cluster-o" // }, // { // label: "", // code: "F037", // value: "cluster" // }, // { // label: "", // code: "F038", // value: "column" // }, // { // label: "", // code: "F039", // value: "comment-circle-o" // }, // { // label: "", // code: "F03A", // value: "comment-circle" // }, // { // label: "", // code: "F03B", // value: "comment-o" // }, // { // label: "", // code: "F03C", // value: "comment" // }, // { // label: "", // code: "F03D", // value: "completed" // }, // { // label: "", // code: "F03E", // value: "contact" // }, // { // label: "", // code: "F03F", // value: "coupon-o" // }, // { // label: "", // code: "F040", // value: "coupon" // }, // { // label: "", // code: "F041", // value: "credit-pay" // }, // { // label: "", // code: "F043", // value: "debit-pay" // }, // { // label: "", // code: "F044", // value: "delete" // }, // { // label: "", // code: "F045", // value: "descending" // }, // { // label: "", // code: "F046", // value: "description" // }, // { // label: "", // code: "F047", // value: "desktop-o" // }, // { // label: "", // code: "F048", // value: "diamond-o" // }, // { // label: "", // code: "F049", // value: "diamond" // }, // { // label: "", // code: "F04A", // value: "discount" // }, // { // label: "", // code: "F04B", // value: "down" // }, // { // label: "", // code: "F04C", // value: "ecard-pay" // }, // { // label: "", // code: "F04D", // value: "edit" // }, // { // label: "", // code: "F04E", // value: "ellipsis" // }, // { // label: "", // code: "F04F", // value: "empty" // }, // { // label: "", // code: "F050", // value: "envelop-o" // }, // { // label: "", // code: "F051", // value: "exchange" // }, // { // label: "", // code: "F052", // value: "expand-o" // }, // { // label: "", // code: "F053", // value: "expand" // }, // { // label: "", // code: "F054", // value: "eye-o" // }, // { // label: "", // code: "F055", // value: "eye" // }, // { // label: "", // code: "F057", // value: "failure" // }, // { // label: "", // code: "F058", // value: "filter-o" // }, // { // label: "", // code: "F059", // value: "fire-o" // }, // { // label: "", // code: "F05A", // value: "fire" // }, // { // label: "", // code: "F05B", // value: "flag-o" // }, // { // label: "", // code: "F05C", // value: "flower-o" // }, // { // label: "", // code: "F05D", // value: "free-postage" // }, // { // label: "", // code: "F05E", // value: "friends-o" // }, // { // label: "", // code: "F05F", // value: "friends" // }, // { // label: "", // code: "F060", // value: "gem-o" // }, // { // label: "", // code: "F061", // value: "gem" // }, // { // label: "", // code: "F062", // value: "gift-card-o" // }, // { // label: "", // code: "F063", // value: "gift-card" // }, // { // label: "", // code: "F064", // value: "gift-o" // }, // { // label: "", // code: "F065", // value: "gift" // }, // { // label: "", // code: "F066", // value: "gold-coin-o" // }, // { // label: "", // code: "F067", // value: "gold-coin" // }, // { // label: "", // code: "F068", // value: "good-job-o" // }, // { // label: "", // code: "F069", // value: "good-job" // }, // { // label: "", // code: "F06A", // value: "goods-collect-o" // }, // { // label: "", // code: "F06B", // value: "goods-collect" // }, // { // label: "", // code: "F06C", // value: "graphic" // }, // { // label: "", // code: "F06D", // value: "home-o" // }, // { // label: "", // code: "F06E", // value: "hot-o" // }, // { // label: "", // code: "F06F", // value: "hot-sale-o" // }, // { // label: "", // code: "F070", // value: "hot-sale" // }, // { // label: "", // code: "F071", // value: "hot" // }, // { // label: "", // code: "F072", // value: "hotel-o" // }, // { // label: "", // code: "F073", // value: "idcard" // }, // { // label: "", // code: "F074", // value: "info-o" // }, // { // label: "", // code: "F075", // value: "info" // }, // { // label: "", // code: "F076", // value: "invition" // }, // { // label: "", // code: "F077", // value: "label-o" // }, // { // label: "", // code: "F078", // value: "label" // }, // { // label: "", // code: "F079", // value: "like-o" // }, // { // label: "", // code: "F07A", // value: "like" // }, // { // label: "", // code: "F07B", // value: "live" // }, // { // label: "", // code: "F07D", // value: "location" // }, // { // label: "", // code: "F07E", // value: "lock" // }, // { // label: "", // code: "F07F", // value: "logistics" // }, // { // label: "", // code: "F080", // value: "manager-o" // }, // { // label: "", // code: "F081", // value: "manager" // }, // { // label: "", // code: "F082", // value: "map-marked" // }, // { // label: "", // code: "F083", // value: "medel-o" // }, // { // label: "", // code: "F084", // value: "medel" // }, // { // label: "", // code: "F085", // value: "more-o" // }, // { // label: "", // code: "F086", // value: "more" // }, // { // label: "", // code: "F087", // value: "music-o" // }, // { // label: "", // code: "F088", // value: "music" // }, // { // label: "", // code: "F089", // value: "new-arrival-o" // }, // { // label: "", // code: "F08A", // value: "new-arrival" // }, // { // label: "", // code: "F08B", // value: "new-o" // }, // { // label: "", // code: "F08C", // value: "new" // }, // { // label: "", // code: "F08D", // value: "newspaper-o" // }, // { // label: "", // code: "F08E", // value: "notes-o" // }, // { // label: "", // code: "F08F", // value: "orders-o" // }, // { // label: "", // code: "F090", // value: "other-pay" // }, // { // label: "", // code: "F091", // value: "paid" // }, // { // label: "", // code: "F092", // value: "passed" // }, // { // label: "", // code: "F093", // value: "pause-circle-o" // }, // { // label: "", // code: "F094", // value: "pause-circle" // }, // { // label: "", // code: "F095", // value: "pause" // }, // { // label: "", // code: "F096", // value: "peer-pay" // }, // { // label: "", // code: "F097", // value: "pending-payment" // }, // { // label: "", // code: "F098", // value: "phone-circle-o" // }, // { // label: "", // code: "F099", // value: "phone-circle" // }, // { // label: "", // code: "F09A", // value: "phone-o" // }, // { // label: "", // code: "F09B", // value: "phone" // }, // { // label: "", // code: "F09C", // value: "photo-o" // }, // { // label: "", // code: "F09D", // value: "photo" // }, // { // label: "", // code: "F09E", // value: "photograph" // }, // { // label: "", // code: "F09F", // value: "play-circle-o" // }, // { // label: "", // code: "F0A0", // value: "play-circle" // }, // { // label: "", // code: "F0A1", // value: "play" // }, // { // label: "", // code: "F0A3", // value: "point-gift-o" // }, // { // label: "", // code: "F0A4", // value: "point-gift" // }, // { // label: "", // code: "F0A5", // value: "points" // }, // { // label: "", // code: "F0A6", // value: "printer" // }, // { // label: "", // code: "F0A7", // value: "qr-invalid" // }, // { // label: "", // code: "F0A8", // value: "qr" // }, // { // label: "", // code: "F0A9", // value: "question-o" // }, // { // label: "", // code: "F0AA", // value: "question" // }, // { // label: "", // code: "F0AB", // value: "records" // }, // { // label: "", // code: "F0AC", // value: "refund-o" // }, // { // label: "", // code: "F0AD", // value: "replay" // }, // { // label: "", // code: "F0AE", // value: "scan" // }, // { // label: "", // code: "F0AF", // value: "search" // }, // { // label: "", // code: "F0B0", // value: "send-gift-o" // }, // { // label: "", // code: "F0B1", // value: "send-gift" // }, // { // label: "", // code: "F0B2", // value: "service-o" // }, // { // label: "", // code: "F0B3", // value: "service" // }, // { // label: "", // code: "F0B4", // value: "setting-o" // }, // { // label: "", // code: "F0B5", // value: "setting" // }, // { // label: "", // code: "F0B6", // value: "share" // }, // { // label: "", // code: "F0B7", // value: "shop-collect-o" // }, // { // label: "", // code: "F0B8", // value: "shop-collect" // }, // { // label: "", // code: "F0B9", // value: "shop-o" // }, // { // label: "", // code: "F0BA", // value: "shop" // }, // { // label: "", // code: "F0BB", // value: "shopping-cart-o" // }, // { // label: "", // code: "F0BC", // value: "shopping-cart" // }, // { // label: "", // code: "F0BD", // value: "shrink" // }, // { // label: "", // code: "F0BE", // value: "sign" // }, // { // label: "", // code: "F0BF", // value: "smile-comment-o" // }, // { // label: "", // code: "F0C0", // value: "smile-comment" // }, // { // label: "", // code: "F0C1", // value: "smile-o" // }, // { // label: "", // code: "F0C2", // value: "smile" // }, // { // label: "", // code: "F0C4", // value: "star" // }, // { // label: "", // code: "F0C5", // value: "stop-circle-o" // }, // { // label: "", // code: "F0C6", // value: "stop-circle" // }, // { // label: "", // code: "F0C7", // value: "stop" // }, // { // label: "", // code: "F0C9", // value: "thumb-circle-o" // }, // { // label: "", // code: "F0CA", // value: "thumb-circle" // }, // { // label: "", // code: "F0CB", // value: "todo-list-o" // }, // { // label: "", // code: "F0CC", // value: "todo-list" // }, // { // label: "", // code: "F0CD", // value: "tosend" // }, // { // label: "", // code: "F0CE", // value: "tv-o" // }, // { // label: "", // code: "F0CF", // value: "umbrella-circle" // }, // { // label: "", // code: "F0D0", // value: "underway-o" // }, // { // label: "", // code: "F0D1", // value: "underway" // }, // { // label: "", // code: "F0D2", // value: "upgrade" // }, // { // label: "", // code: "F0D3", // value: "user-circle-o" // }, // { // label: "", // code: "F0D4", // value: "user-o" // }, // { // label: "", // code: "F0D5", // value: "video-o" // }, // { // label: "", // code: "F0D6", // value: "video" // }, // { // label: "", // code: "F0D7", // value: "vip-card-o" // }, // { // label: "", // code: "F0D8", // value: "vip-card" // }, // { // label: "", // code: "F0D9", // value: "volume-o" // }, // { // label: "", // code: "F0DA", // value: "volume" // }, // { // label: "", // code: "F0DB", // value: "wap-home-o" // }, // { // label: "", // code: "F0DC", // value: "wap-home" // }, // { // label: "", // code: "F0DD", // value: "wap-nav" // }, // { // label: "", // code: "F0DE", // value: "warn-o" // }, // { // label: "", // code: "F0DF", // value: "warning-o" // }, // { // label: "", // code: "F0E0", // value: "warning" // }, // { // label: "", // code: "F0E1", // value: "weapp-nav" // }, // { // label: "", // code: "F0E2", // value: "wechat" // }, // { // label: "", // code: "F0E3", // value: "youzan-shield" // } // ];
the_stack
import React from "react"; import {render, wait, screen, fireEvent} from "@testing-library/react"; import {waitFor} from "@testing-library/dom"; import userEvent from "@testing-library/user-event"; import {BrowserRouter as Router} from "react-router-dom"; import Modeling from "./Modeling"; import {AuthoritiesContext} from "../util/authorities"; import authorities from "../assets/mock-data/authorities.testutils"; import {ModelingContext} from "../util/modeling-context"; import {ModelingTooltips} from "../config/tooltips.config"; import {getEntityTypes} from "../assets/mock-data/modeling/modeling"; import {isModified, notModified, isModifiedTableView, notModifiedTableView} from "../assets/mock-data/modeling/modeling-context-mock"; import {primaryEntityTypes, publishDraftModels, updateEntityModels} from "../api/modeling"; import {ConfirmationType} from "../types/common-types"; import tiles from "../config/tiles.config"; import {getViewSettings} from "../util/user-context"; import {act} from "react-dom/test-utils"; import "jest-canvas-mock"; jest.mock("../api/modeling"); const mockPrimaryEntityType = primaryEntityTypes as jest.Mock; const mockUpdateEntityModels = updateEntityModels as jest.Mock; const mockPublishDraftModels = publishDraftModels as jest.Mock; const mockDevRolesService = authorities.DeveloperRolesService; const mockOpRolesService = authorities.OperatorRolesService; const mockHCUserRolesService = authorities.HCUserRolesService; const renderView = (view) => { let contextValue = view === "table" ? isModifiedTableView : isModified; return ( <AuthoritiesContext.Provider value={mockDevRolesService}> <ModelingContext.Provider value={contextValue}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); }; describe("Modeling Page", () => { afterEach(() => { jest.clearAllMocks(); }); test("Modeling: with mock data, renders modified Alert component and Dev role can click add, edit, and publish", async () => { mockPrimaryEntityType.mockResolvedValueOnce({status: 200, data: getEntityTypes}); mockUpdateEntityModels.mockResolvedValueOnce({status: 200}); mockPublishDraftModels.mockResolvedValueOnce({status: 200}); let getByText, getByLabelText; await act(async () => { const renderResults = render( <AuthoritiesContext.Provider value={mockDevRolesService}> <ModelingContext.Provider value={isModifiedTableView}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); getByText = renderResults.getByText; getByLabelText = renderResults.getByLabelText; }); await wait(() => expect(mockPrimaryEntityType).toHaveBeenCalledTimes(2)); expect(getByText(tiles.model.intro)).toBeInTheDocument(); // tile intro text expect(getByText("Entity Types")).toBeInTheDocument(); expect(getByLabelText("add-entity")).toBeInTheDocument(); expect(getByText("Instances")).toBeInTheDocument(); expect(getByText("Last Processed")).toBeInTheDocument(); expect(getByLabelText("entity-modified-alert")).toBeInTheDocument(); // test add, publish icons display correct tooltip when enabled fireEvent.mouseOver(getByText("Add")); await wait(() => expect(getByText(ModelingTooltips.addNewEntity)).toBeInTheDocument()); fireEvent.mouseOver(getByLabelText("publish-to-database")); await wait(() => expect(getByText(ModelingTooltips.publish)).toBeInTheDocument()); userEvent.click(screen.getByTestId("AnotherModel-span")); expect(screen.getByText("Edit Entity Type")).toBeInTheDocument(); userEvent.click(getByText("Add")); expect(getByText(/Add Entity Type/i)).toBeInTheDocument(); userEvent.click(getByLabelText("publish-to-database")); userEvent.click(screen.getByLabelText(`confirm-${ConfirmationType.PublishAll}-yes`)); expect(mockPublishDraftModels).toHaveBeenCalledTimes(1); // userEvent.click(getByText("Revert All")); // userEvent.click(screen.getByLabelText(`confirm-${ConfirmationType.RevertAll}-yes`)); // expect(mockPrimaryEntityType).toHaveBeenCalledTimes(2); }); test("Modeling: with mock data, no Alert component renders and operator role can not click add", async () => { mockPrimaryEntityType.mockResolvedValueOnce({status: 200, data: getEntityTypes}); let getByText, getByLabelText, queryByLabelText; await act(async () => { const renderResults = render( <AuthoritiesContext.Provider value={mockOpRolesService}> <ModelingContext.Provider value={notModifiedTableView}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); getByText = renderResults.getByText; getByLabelText = renderResults.getByLabelText; queryByLabelText = renderResults.queryByLabelText; }); await wait(() => expect(mockPrimaryEntityType).toHaveBeenCalledTimes(2)); expect(getByText("Entity Types")).toBeInTheDocument(); expect(getByText("Instances")).toBeInTheDocument(); expect(getByText("Last Processed")).toBeInTheDocument(); expect(getByLabelText("add-entity")).toBeDisabled(); // test add, save, revert icons display correct tooltip when disabled fireEvent.mouseOver(getByText("Add")); await wait(() => expect(getByText(ModelingTooltips.addNewEntity + " " + ModelingTooltips.noWriteAccess)).toBeInTheDocument()); fireEvent.mouseOver(getByText("Publish")); await wait(() => expect(getByText(ModelingTooltips.publish + " " + ModelingTooltips.noWriteAccess)).toBeInTheDocument()); expect(queryByLabelText("entity-modified-alert")).toBeNull(); }); test("Modeling: can not see data if user does not have entity model reader role", async () => { mockPrimaryEntityType.mockResolvedValueOnce({status: 200, data: getEntityTypes}); const {queryByText, queryByLabelText} = render( <AuthoritiesContext.Provider value={mockHCUserRolesService}> <ModelingContext.Provider value={notModified}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); await wait(() => expect(mockPrimaryEntityType).toHaveBeenCalledTimes(0)); expect(queryByText("Entity Types")).toBeNull(); expect(queryByText("Instances")).toBeNull(); expect(queryByText("Last Processed")).toBeNull(); expect(queryByLabelText("add-entity")).toBeNull(); expect(queryByLabelText("publish-to-database")).toBeNull(); expect(queryByLabelText("entity-modified-alert")).toBeNull(); }); }); describe("getViewSettings", () => { beforeEach(() => { window.sessionStorage.clear(); jest.restoreAllMocks(); }); const sessionStorageMock = (() => { let store = {}; return { getItem(key) { return store[key] || null; }, setItem(key, value) { store[key] = value.toString(); }, removeItem(key) { delete store[key]; }, clear() { store = {}; } }; })(); Object.defineProperty(window, "sessionStorage", { value: sessionStorageMock }); it("should get entity expanded rows from session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({model: {entityExpandedRows: ["Customer,"]}})); const actualValue = getViewSettings(); expect(actualValue).toEqual({model: {entityExpandedRows: ["Customer,"]}}); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); it("should get property expanded rows from session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({model: {propertyExpandedRows: ["shipping,31"]}})); const actualValue = getViewSettings(); expect(actualValue).toEqual({model: {propertyExpandedRows: ["shipping,31"]}}); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); it("should get entity and property expanded rows from session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); window.sessionStorage.setItem("dataHubViewSettings", JSON.stringify({model: {entityExpandedRows: ["Customer,"], propertyExpandedRows: ["shipping,31"]}})); const actualValue = getViewSettings(); expect(actualValue).toEqual({model: {entityExpandedRows: ["Customer,"], propertyExpandedRows: ["shipping,31"]}}); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); it("should get empty object if no info in session storage", () => { const getItemSpy = jest.spyOn(window.sessionStorage, "getItem"); const actualValue = getViewSettings(); expect(actualValue).toEqual({}); expect(window.sessionStorage.getItem).toBeCalledWith("dataHubViewSettings"); expect(getItemSpy).toBeCalledWith("dataHubViewSettings"); }); }); describe("Graph view page", () => { afterEach(() => { jest.clearAllMocks(); }); it("Modeling: graph view renders properly", async () => { mockPrimaryEntityType.mockResolvedValueOnce({status: 200, data: getEntityTypes}); mockUpdateEntityModels.mockResolvedValueOnce({status: 200}); const {getByText, getByLabelText} = render( <AuthoritiesContext.Provider value={mockDevRolesService}> <ModelingContext.Provider value={isModified}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); await waitFor(() => expect(mockPrimaryEntityType).toHaveBeenCalled()); expect(getByText(tiles.model.intro)).toBeInTheDocument(); // tile intro text expect(getByLabelText("switch-view")).toBeInTheDocument(); expect(getByLabelText("switch-view-graph")).toBeChecked(); // Graph view is checked by default. expect(getByText("Entity Types")).toBeInTheDocument(); expect(getByLabelText("graph-view-filter-input")).toBeInTheDocument(); userEvent.click(getByLabelText("add-entity-type-relationship")); await waitFor(() => { expect(getByLabelText("add-entity-type")).toBeInTheDocument(); expect(getByLabelText("add-relationship")).toBeInTheDocument(); }); userEvent.hover(getByLabelText("publish-to-database")); await waitFor(() => expect(getByText(ModelingTooltips.publish)).toBeInTheDocument()); userEvent.hover(getByLabelText("graph-export")); await waitFor(() => expect(getByText(ModelingTooltips.exportGraph)).toBeInTheDocument()); }); it("can toggle between graph view and table view properly", async () => { mockPrimaryEntityType.mockResolvedValueOnce({status: 200, data: getEntityTypes}); mockUpdateEntityModels.mockResolvedValueOnce({status: 200}); const {getByText, getByLabelText, queryByLabelText, rerender} = render( <AuthoritiesContext.Provider value={mockDevRolesService}> <ModelingContext.Provider value={isModified}> <Router> <Modeling/> </Router> </ModelingContext.Provider> </AuthoritiesContext.Provider> ); await waitFor(() => expect(mockPrimaryEntityType).toHaveBeenCalled()); expect(getByText(tiles.model.intro)).toBeInTheDocument(); // tile intro text let graphViewButton = getByLabelText("switch-view-graph"); let tableViewButton = getByLabelText("switch-view-table"); let filterInput = getByLabelText("graph-view-filter-input"); let addEntityOrRelationshipBtn = getByLabelText("add-entity-type-relationship"); let publishToDatabaseBtn = getByLabelText("publish-to-database"); let graphExportIcon = getByLabelText("graph-export"); expect(getByLabelText("switch-view")).toBeInTheDocument(); expect(graphViewButton).toBeChecked(); // Graph view is checked by default. expect(getByText("Entity Types")).toBeInTheDocument(); expect(filterInput).toBeInTheDocument(); expect(addEntityOrRelationshipBtn).toBeInTheDocument(); expect(publishToDatabaseBtn).toBeInTheDocument(); expect(graphExportIcon).toBeInTheDocument(); expect(queryByLabelText("add-entity")).not.toBeInTheDocument(); expect(queryByLabelText("Instances")).not.toBeInTheDocument(); userEvent.click(tableViewButton); // switch to table view rerender(renderView("table")); expect(getByLabelText("add-entity")).toBeInTheDocument(); expect(getByText("Instances")).toBeInTheDocument(); expect(getByText("Last Processed")).toBeInTheDocument(); expect(queryByLabelText("graph-view-filter-input")).not.toBeInTheDocument(); expect(queryByLabelText("add-entity-type-relationship")).not.toBeInTheDocument(); expect(queryByLabelText("graph-export")).not.toBeInTheDocument(); userEvent.click(graphViewButton); // switch back to graph view rerender(renderView("graph")); expect(graphViewButton).toBeChecked(); expect(filterInput).toBeVisible(); expect(addEntityOrRelationshipBtn).toBeVisible(); expect(publishToDatabaseBtn).toBeVisible(); expect(graphExportIcon).toBeVisible(); }); });
the_stack
import React, { createContext } from 'react'; import {SwipeEndEvent, SwipeEvent, SwipeStartEvent} from 'web-gesture-events'; import { clamp, matchRoute, includesRoute } from './common/utils'; import Navigation from './Navigation'; import {ScreenChild} from './index'; import {AnimationLayerDataContext} from './AnimationLayerData'; import { MotionProgressDetail } from './MotionEvents'; import { SwipeDirection } from './common/types'; export const Motion = createContext(0); interface AnimationLayerProps { children: ScreenChild | ScreenChild[]; currentPath: string; lastPath: string | null; navigation: Navigation; backNavigating: boolean; onGestureNavigationEnd: Function; onGestureNavigationStart: Function; swipeDirection: SwipeDirection; hysteresis: number; minFlingVelocity: number; swipeAreaWidth: number; disableDiscovery: boolean; disableBrowserRouting: boolean; } interface AnimationLayerState { currentPath: string; children: ScreenChild | ScreenChild[]; progress: number; shouldPlay: boolean; gestureNavigating: boolean; shouldAnimate: boolean; startX: number; startY: number; paths: (string | RegExp | undefined)[], swipeDirection: SwipeDirection; swipeAreaWidth: number; minFlingVelocity: number; hysteresis: number; disableDiscovery: boolean; } // type of children coerces type in React.Children.map such that 'path' is available on props export default class AnimationLayer extends React.Component<AnimationLayerProps, AnimationLayerState> { private onSwipeStartListener = this.onSwipeStart.bind(this); private onSwipeListener = this.onSwipe.bind(this); private onSwipeEndListener = this.onSwipeEnd.bind(this); static contextType = AnimationLayerDataContext; context!: React.ContextType<typeof AnimationLayerDataContext>; state: AnimationLayerState = { currentPath: this.props.currentPath, children: this.props.children, progress: 0, shouldPlay: true, gestureNavigating: false, shouldAnimate: true, startX: 0, startY: 0, paths: [], swipeDirection: 'right', swipeAreaWidth: 100, minFlingVelocity: 400, hysteresis: 50, disableDiscovery: false } static getDerivedStateFromProps(nextProps: AnimationLayerProps, state: AnimationLayerState): AnimationLayerState | null { if (nextProps.currentPath !== state.currentPath) { if (!state.shouldAnimate) { return { ...state, currentPath: nextProps.currentPath, shouldAnimate: true }; } const paths = [...state.paths]; let nextPath: string | undefined = nextProps.currentPath; let currentPath: string | undefined = state.currentPath; // === '' when AnimationLayer first mounts let nextMatched = false; let currentMatched = false; let swipeDirection: SwipeDirection | undefined; let swipeAreaWidth: number | undefined; let minFlingVelocity: number | undefined; let hysteresis: number | undefined; let disableDiscovery: boolean | undefined; let children = React.Children.map( nextProps.children, (child: ScreenChild) => { if (React.isValidElement(child)) { if (!state.paths.length) paths.push(child.props.path); if (state.paths.length) { if (!includesRoute(nextPath, paths) && state.paths.includes(undefined)) { nextPath = undefined; } if (currentPath !== '' && !includesRoute(currentPath, paths) && state.paths.includes(undefined)) { currentPath = undefined; } } if (matchRoute(child.props.path, nextPath)) { if (!nextMatched) { nextMatched = true; const {config} = child.props; swipeDirection = config?.swipeDirection; swipeAreaWidth = config?.swipeAreaWidth; hysteresis = config?.hysteresis; disableDiscovery = config?.disableDiscovery; minFlingVelocity = config?.minFlingVelocity; return React.cloneElement(child, {...child.props, in: true, out: false}) as ScreenChild; } } if (matchRoute(child.props.path, currentPath)) { if (!currentMatched) { currentMatched = true; return React.cloneElement(child, {...child.props, out: true, in: false}) as ScreenChild; } } } } ).sort((child, _) => matchRoute(child.props.path, nextPath) ? 1 : -1); // current screen mounts first return { ...state, paths: paths, children: children, currentPath: nextProps.currentPath, swipeDirection: swipeDirection || nextProps.swipeDirection, swipeAreaWidth: swipeAreaWidth || nextProps.swipeAreaWidth, hysteresis: hysteresis || nextProps.hysteresis, disableDiscovery: disableDiscovery === undefined ? nextProps.disableDiscovery : disableDiscovery, minFlingVelocity: minFlingVelocity || nextProps.minFlingVelocity } } return null; } componentDidMount() { this.context.onProgress = (_progress: number) => { const progress = this.props.backNavigating && !this.state.gestureNavigating ? 99 - _progress : _progress; this.setState({progress: clamp(progress, 0, 100)}); const progressEvent = new CustomEvent<MotionProgressDetail>('motion-progress', { detail: { progress: progress } }); window.queueMicrotask(() => { dispatchEvent(progressEvent); }); } window.addEventListener('swipestart', this.onSwipeStartListener); } componentDidUpdate(prevProps: AnimationLayerProps, prevState: AnimationLayerState) { if (!React.Children.count(this.state.children)) { const children = React.Children.map(this.props.children, (child: ScreenChild) => { if (!React.isValidElement(child)) return undefined; if (matchRoute(child.props.path, undefined)) return React.cloneElement(child, {...child.props, in: true, out: false}) as ScreenChild; }); this.setState({children: children}); } if (prevProps.currentPath !== this.state.currentPath) { if (!this.state.gestureNavigating && prevState.shouldAnimate) { this.context.play = true; this.context.backNavigating = this.props.backNavigating; this.context.animate(); // children changes committed now animate } } } componentWillUnmount() { window.removeEventListener('swipestart', this.onSwipeStartListener); } onGestureSuccess(state: Pick<AnimationLayerState, 'swipeAreaWidth' | 'swipeDirection' | 'hysteresis' | 'disableDiscovery' | 'minFlingVelocity'>) { this.setState(state); } onSwipeStart(ev: SwipeStartEvent) { if (this.state.disableDiscovery) return; if (this.context.isPlying) return; let swipePos: number; // 1D switch(this.state.swipeDirection) { case "left": case "right": swipePos = ev.x; break; case "up": case "down": swipePos = ev.y; // x or y depending on if swipe direction is horizontal or vertical break; } if (ev.direction === this.state.swipeDirection && swipePos < this.state.swipeAreaWidth) { // if only one child return if (!this.props.lastPath) return; // if gesture region in touch path return for (let target of ev.composedPath().reverse()) { if ('classList' in target && (target as HTMLElement).classList.length) { if ((target as HTMLElement).classList.contains('gesture-region')) return; if (target === ev.gestureTarget) break; } } let currentPath: string | undefined = this.props.currentPath; let lastPath: string | undefined = this.props.lastPath; let currentMatched = false; let lastMatched = false; let swipeDirection: SwipeDirection | undefined; let swipeAreaWidth: number | undefined; let minFlingVelocity: number | undefined; let hysteresis: number | undefined; let disableDiscovery: boolean | undefined; const children = React.Children.map( this.props.children, (child: ScreenChild) => { if (!this.props.lastPath) return undefined; if (!includesRoute(currentPath, this.state.paths) && this.state.paths.includes(undefined)) { currentPath = undefined; } if (!includesRoute(lastPath, this.state.paths) && this.state.paths.includes(undefined)) { lastPath = undefined; } if (React.isValidElement(child)) { if (matchRoute(child.props.path, currentPath)) { if (!currentMatched) { currentMatched = true; const element = React.cloneElement(child, {...child.props, in: true, out: false}); return element as ScreenChild; } } if (matchRoute(child.props.path, lastPath)) { if (!lastMatched) { lastMatched = true; const {config} = child.props; swipeDirection = config?.swipeDirection; swipeAreaWidth = config?.swipeAreaWidth; hysteresis = config?.hysteresis; disableDiscovery = config?.disableDiscovery; minFlingVelocity = config?.minFlingVelocity; const element = React.cloneElement(child, {...child.props, in: false, out: true}); return element as ScreenChild; } } } } ).sort((firstChild) => matchRoute(firstChild.props.path, currentPath) ? -1 : 1); this.onGestureSuccess = this.onGestureSuccess.bind(this, { swipeDirection: swipeDirection || this.props.swipeDirection, swipeAreaWidth: swipeAreaWidth || this.props.swipeAreaWidth, hysteresis: hysteresis || this.props.hysteresis, disableDiscovery: disableDiscovery === undefined ? this.props.disableDiscovery : disableDiscovery, minFlingVelocity: minFlingVelocity || this.props.minFlingVelocity }); window.addEventListener('go-back', this.onGestureSuccess as unknown as EventListener, {once: true}); this.props.onGestureNavigationStart(); this.setState({ shouldPlay: false, gestureNavigating: true, children: children, startX: ev.x, startY: ev.y }, () => { const motionStartEvent = new CustomEvent('motion-progress-start'); this.context.gestureNavigating = true; this.context.playbackRate = -1; this.context.play = false; this.context.backNavigating = this.props.backNavigating; this.context.animate(); window.dispatchEvent(motionStartEvent); window.addEventListener('swipe', this.onSwipeListener); window.addEventListener('swipeend', this.onSwipeEndListener); }); } } onSwipe(ev: SwipeEvent) { if (this.state.shouldPlay) return; let progress: number; switch(this.state.swipeDirection) { case "left": case "right": { // left or right const width = window.innerWidth; const x = clamp(ev.x - this.state.startX, 10); progress = (-(x - width) / width) * 100; if (this.state.swipeDirection === "left") progress = 100 - progress; break; } case "up": case "down": { const height = window.innerHeight; const y = clamp(ev.y - this.state.startY, 10); if (y < 0) alert(y); progress = (-(y - height) / height) * 100; if (this.state.swipeDirection === "up") progress = 100 - progress; break; } } this.context.progress = clamp(progress, 0.1, 100); } onSwipeEnd(ev: SwipeEndEvent) { if (this.state.shouldPlay) return; let onEnd = null; const motionEndEvent = new CustomEvent('motion-progress-end'); if ((100 - this.state.progress) > this.state.hysteresis || ev.velocity > this.state.minFlingVelocity) { if (ev.velocity >= this.state.minFlingVelocity) { this.context.playbackRate = -5; } else { this.context.playbackRate = -1; } onEnd = () => { this.context.reset(); this.props.onGestureNavigationEnd(); this.setState({gestureNavigating: false}); window.dispatchEvent(motionEndEvent); } this.setState({shouldPlay: true, shouldAnimate: false}); } else { this.context.playbackRate = 0.5; onEnd = () => { window.removeEventListener('go-back', this.onGestureSuccess as unknown as EventListener); this.context.reset(); window.dispatchEvent(motionEndEvent); } this.setState({shouldPlay: true, gestureNavigating: false}); } this.setState({startX: 0, startY: 0}); this.context.onEnd = onEnd; this.context.play = true; window.removeEventListener('swipe', this.onSwipeListener); window.removeEventListener('swipeend', this.onSwipeEndListener); } render() { return ( <Motion.Provider value={this.state.progress}> {this.state.children} </Motion.Provider> ); } }
the_stack
import { isServer } from '../executionEnvironment'; import * as _ from 'underscore'; import { isPromise } from './utils'; import { isAnyQueryPending } from '../mongoCollection'; import { loggerConstructor } from '../utils/logging' // TODO: It would be nice if callbacks could be enabled or disabled by collection const logger = loggerConstructor(`callbacks`) export class CallbackChainHook<IteratorType,ArgumentsType extends any[]> { name: string constructor(name: string) { this.name = name; } add = (fn: (doc: IteratorType, ...args: ArgumentsType)=>IteratorType|Promise<IteratorType>|undefined|void) => { addCallback(this.name, fn); } remove = (fn: (doc: IteratorType, ...args: ArgumentsType)=>IteratorType|Promise<IteratorType>|undefined|void) => { removeCallback(this.name, fn); } runCallbacks = ({iterator, properties, ignoreExceptions}: {iterator: IteratorType, properties: ArgumentsType, ignoreExceptions?: boolean}): Promise<IteratorType> => { return runCallbacks({ name: this.name, iterator, properties, ignoreExceptions }); } } export class CallbackHook<ArgumentsType extends any[]> { name: string constructor(name: string) { this.name = name; } add = (fn: (...args: ArgumentsType)=>void|Promise<void>) => { addCallback(this.name, fn); } runCallbacksAsync = async (properties: ArgumentsType): Promise<void> => { await runCallbacksAsync({ name: this.name, properties }); } } /** * @summary Format callback hook names */ const formatHookName = (hook: string|null|undefined): string => hook?.toLowerCase() || ""; /** * @summary Callback hooks provide an easy way to add extra steps to common operations. * @namespace Callbacks */ const Callbacks: Record<string,any> = {}; /** * @summary Add a callback function to a hook * @param {String} hook - The name of the hook * @param {Function} callback - The callback function */ export const addCallback = function (hook: string, callback) { const formattedHook = formatHookName(hook); // if callback array doesn't exist yet, initialize it if (typeof Callbacks[formattedHook] === 'undefined') { Callbacks[formattedHook] = []; } Callbacks[formattedHook].push(callback); if (Callbacks[formattedHook].length > 15) { // eslint-disable-next-line no-console console.log(`Warning: Excessively many callbacks (${Callbacks[formattedHook].length}) on hook ${formattedHook}.`); } return callback; }; /** * @summary Remove a callback from a hook * @param {string} hookName - The name of the hook * @param {Function} callback - A reference to the function which was previously * passed to addCallback. */ const removeCallback = function (hookName: string, callback) { const formattedHook = formatHookName(hookName); Callbacks[formattedHook] = _.reject(Callbacks[formattedHook], c => c === callback ); }; /** * @summary Successively run all of a hook's callbacks on an item * @param {String} hook - First argument: the name of the hook, or an array * @param {Object} item - Second argument: the post, comment, modifier, etc. on which to run the callbacks * @param {Any} args - Other arguments will be passed to each successive iteration * @param {Array} callbacks - Optionally, pass an array of callback functions instead of passing a hook name * @param {Boolean} ignoreExceptions - Only available as a named argument, default true. If true, exceptions * thrown from callbacks will be logged but otherwise ignored. If false, exceptions thrown from callbacks * will be rethrown. * @returns {Object} Returns the item after it's been through all the callbacks for this hook */ export const runCallbacks = function (this: any, options: { name: string, iterator?: any, properties?: any, ignoreExceptions?: boolean, }) { const hook = options.name; const formattedHook = formatHookName(hook); const item = options.iterator; const args = options.properties; let ignoreExceptions: boolean; if ("ignoreExceptions" in options) ignoreExceptions = !!options.ignoreExceptions; else ignoreExceptions = true; const callbacks = Callbacks[formattedHook]; // flag used to detect the callback that initiated the async context let asyncContext = false; let inProgressCallbackKey = markCallbackStarted(hook); if (typeof callbacks !== 'undefined' && !!callbacks.length) { // if the hook exists, and contains callbacks to run const runCallback = (accumulator, callback) => { logger(`\x1b[32m>> Running callback [${callback.name}] on hook [${formattedHook}]\x1b[0m`); try { const result = callback.apply(this, [accumulator].concat(args)); if (typeof result === 'undefined') { // if result of current iteration is undefined, don't pass it on // logger(`// Warning: Sync callback [${callback.name}] in hook [${hook}] didn't return a result!`) return accumulator; } else { return result; } } catch (error) { // eslint-disable-next-line no-console console.log(`\x1b[31m// error at callback [${callback.name}] in hook [${formattedHook}]\x1b[0m`); // eslint-disable-next-line no-console console.log(error); if (error.break || (error.data && error.data.break) || !ignoreExceptions) { throw error; } // pass the unchanged accumulator to the next iteration of the loop return accumulator; } }; const result = callbacks.reduce(function (accumulator, callback, index) { if (isPromise(accumulator)) { if (!asyncContext) { logger(`\x1b[32m>> Started async context in hook [${formattedHook}] by [${callbacks[index-1] && callbacks[index-1].name}]\x1b[0m`); asyncContext = true; } return new Promise((resolve, reject) => { accumulator .then(result => { try { // run this callback once we have the previous value resolve(runCallback(result, callback)); } catch (error) { // error will be thrown only for breaking errors, so throw it up in the promise chain reject(error); } }) .catch(reject); }); } else { return runCallback(accumulator, callback); } }, item); markCallbackFinished(inProgressCallbackKey, hook); return result; } else { // else, just return the item unchanged markCallbackFinished(inProgressCallbackKey, hook); return item; } }; // Run a provided list of callback functions, in a chain. This is similar to // runCallbacks (which does the same, except it gets the functions from a named // hook). This is used only by vulcan-forms, which previously was using // runCallbacks, but is new separated out in order to make runCallbacks more // refactor-able. export const runCallbacksList = function (this: any, options: { iterator?: any, properties?: any, callbacks: any, }) { const item = options.iterator; const args = options.properties; const ignoreExceptions = true; const callbacks = options.callbacks; // flag used to detect the callback that initiated the async context let asyncContext = false; if (typeof callbacks !== 'undefined' && !!callbacks.length) { const runCallback = (accumulator, callback) => { logger(`running callback ${callback.name}`) try { const result = callback.apply(this, [accumulator].concat(args)); if (typeof result === 'undefined') { // if result of current iteration is undefined, don't pass it on return accumulator; } else { return result; } } catch (error) { // eslint-disable-next-line no-console console.log(`error at callback [${callback.name}] in callbacks list`); // eslint-disable-next-line no-console console.log(error); if (error.break || (error.data && error.data.break) || !ignoreExceptions) { throw error; } // pass the unchanged accumulator to the next iteration of the loop return accumulator; } }; logger("Running callbacks list") return callbacks.reduce(function (accumulator, callback, index) { if (isPromise(accumulator)) { if (!asyncContext) { asyncContext = true; } return new Promise((resolve, reject) => { accumulator .then(result => { try { // run this callback once we have the previous value resolve(runCallback(result, callback)); } catch (error) { // error will be thrown only for breaking errors, so throw it up in the promise chain reject(error); } }) .catch(reject); }); } else { return runCallback(accumulator, callback); } }, item); } else { // else, just return the item unchanged return item; } } /** * @summary Successively run all of a hook's callbacks on an item, in async mode (only works on server) * @param {String} hook - First argument: the name of the hook * @param {Any} args - Other arguments will be passed to each successive iteration */ export const runCallbacksAsync = function (options: {name: string, properties: Array<any>}) { const hook = formatHookName(options.name); const args = options.properties; const callbacks = Array.isArray(hook) ? hook : Callbacks[hook]; if (isServer && typeof callbacks !== 'undefined' && !!callbacks.length) { let pendingDeferredCallbackStart = markCallbackStarted(hook); // use defer to avoid holding up client setTimeout(function () { // run all post submit server callbacks on post object successively callbacks.forEach(function (this: any, callback) { logger(`\x1b[32m>> Running async callback [${callback.name}] on hook [${hook}]\x1b[0m`); let pendingAsyncCallback = markCallbackStarted(hook); try { let callbackResult = callback.apply(this, args); if (isPromise(callbackResult)) { callbackResult .then( result => markCallbackFinished(pendingAsyncCallback, hook), exception => { markCallbackFinished(pendingAsyncCallback, hook) // eslint-disable-next-line no-console console.log(`Error running async callback [${callback.name}] on hook [${hook}]`); // eslint-disable-next-line no-console console.log(exception); throw exception; } ) } else { markCallbackFinished(pendingAsyncCallback, hook); } } finally { markCallbackFinished(pendingAsyncCallback, hook); } }); markCallbackFinished(pendingDeferredCallbackStart, hook); }, 0); } }; // For unit tests. Wait (in 20ms incremements) until there are no callbacks // in progress. Many database operations trigger asynchronous callbacks to do // things like generate notifications and add to search indexes; if you have a // unit test that depends on the results of these async callbacks, writing them // the naive way would create a race condition. But if you insert an // `await waitUntilCallbacksFinished()`, it will wait for all the background // processing to finish before proceeding with the rest of the test. // // This is NOT suitable for production (non-unit-test) use, because if other // threads/fibers are doing things which trigger callbacks, it could wait for // a long time. It DOES wait for callbacks that were triggered after // `waitUntilCallbacksFinished` was called, and that were triggered from // unrelated contexts. // // What this tracks specifically is that all callbacks which were registered // with `addCallback` and run with `runCallbacksAsync` have returned. Note that // it is possible for a callback to bypass this, by calling a function that // should have been await'ed without the await, effectively spawning a new // thread which isn't tracked. export const waitUntilCallbacksFinished = () => { return new Promise<void>(resolve => { function finishOrWait() { if (callbacksArePending() || isAnyQueryPending()) { setTimeout(finishOrWait, 20); } else { resolve(); } } finishOrWait(); }); }; // Dictionary of all outstanding callbacks (key is an ID, value is `true`). If // there are no outstanding callbacks, this should be an empty dictionary. let pendingCallbackKeys = {}; let pendingCallbackDescriptions: Record<string,number> = {}; // ID for a pending callback. Incremements with each call to // `markCallbackStarted`. let pendingCallbackKey = 0; // Count of the number of outstanding callbacks. Used to check that this isn't // leaking. let numCallbacksPending = 0; // When starting an async callback, assign it an ID, record the fact that it's // running, and return the ID. function markCallbackStarted(description: string): number { if (numCallbacksPending > 1000) { // eslint-disable-next-line no-console console.log(`Warning: Excessively many background callbacks running (numCallbacksPending=${numCallbacksPending}) while trying to add callback ${description}`); } numCallbacksPending++; if (pendingCallbackKey >= Number.MAX_SAFE_INTEGER) pendingCallbackKey = 0; else pendingCallbackKey++; pendingCallbackKeys[pendingCallbackKey] = true; if (description in pendingCallbackDescriptions) { pendingCallbackDescriptions[description]++; } else { pendingCallbackDescriptions[description] = 1; } return pendingCallbackKey; } // Record the fact that an async callback with the given ID has finished. function markCallbackFinished(id: number, description: string) { numCallbacksPending--; delete pendingCallbackKeys[id]; if (!pendingCallbackDescriptions[description] || pendingCallbackDescriptions[description]===1) { delete pendingCallbackDescriptions[description]; } else { pendingCallbackDescriptions[description]--; } } // Return whether there is at least one async callback running. function callbacksArePending(): boolean { for(let id in pendingCallbackKeys) { return true; } return false; } export function printInProgressCallbacks() { const callbacksInProgress = Object.keys(pendingCallbackDescriptions); // eslint-disable-next-line no-console console.log(`Callbacks in progress: ${callbacksInProgress.map(c => pendingCallbackDescriptions[c]!=1 ? `${c}(${pendingCallbackDescriptions[c]})` : c).join(", ")}`); }
the_stack
import { Token, TokenType } from "@abstractions/interactive-command-service"; import { InputStream } from "./input-stream"; /** * Parses the specified command into a token list * @param command Command to parse * @returns Parsed command */ export function parseCommand(command: string): Token[] { const tokens: Token[] = []; const input = new InputStream(command); const tokenStream = new TokenStream(input); let eof = false; do { const nextToken = tokenStream.get(); eof = nextToken.type === TokenType.Eof; if (!eof) { tokens.push(nextToken); } } while (!eof); return tokens; } /** * This class implements the tokenizer (lexer) of the Klive command parser. * It recognizes these tokens: * * Identifier * : idStart idContinuation* * ; * * idStart * : 'a'..'z' | 'A'..'Z' | '_' * ; * * idContinuation * : idStart | '0'..'9' | '-' | '$' | '.' | '!' | ':' | '#' * ; * * Variable * : '${' Identifier '}' * ; * * Option * : '-' idStart idContinuation* * ; * * Path * : pathStart pathContinuation* * ; * * pathStart * : 'a'..'z' | 'A'..'Z' | '_' | '/' | '\' | '.' | '*' | '?' * ; * * pathContinuation * : pathStart | ':' * ; * * String * : '"' (stringChar | escapeChar) '"' * ; * * stringChar * : [any characted except NL or CR] * ; * * escapeChar * : '\b' | '\f' | '\n' | '\r' | '\t' | '\v' | '\0' | '\'' | '\"' | '\\' * | '\x' hexadecimalDigit hexadecimalDigit * ; * * Number * : '-'? (decimalNumber | hexadecimalNumber | binaryNumber) * ; * * decimalNumber * : decimalDigit xDecimalDigit* * ; * * hexadecimalNumber * : '$' hexadecimalDigit xHexadecimalDigit* * ; * * binaryNumber * : '%' binarydigit xBinaryDigit* * ; * * decimalDigit * : '0'..'9' * ; * * xDecimalDigit * : decimalDigit | '_' | '''' * ; * * hexadecimalDigit * : '0'..'9' | 'a'..'f' | 'A'..'F' * ; * * xHexadecimalDigit * : hexadecimalDigit | '_' | '''' * ; * * binaryDigit * : '0' | '1' * ; * * xBinaryDigit * : binaryDigit | '_' | '''' * ; * * Argument * : [any characted except NL, CR, or other whitespace]+ * ; */ export class TokenStream { // --- Already fetched tokens private _ahead: Token[] = []; // --- Prefetched character (from the next token) private _prefetched: string | null = null; // --- Prefetched character position (from the next token) private _prefetchedPos: number | null = null; // --- Prefetched character column (from the next token) private _prefetchedColumn: number | null = null; /** * Initializes the tokenizer with the input stream * @param input Input source code stream */ constructor(public readonly input: InputStream) {} /** * Gets the specified part of the source code * @param start Start position * @param end End position */ getSourceSpan(start: number, end: number): string { return this.input.getSourceSpan(start, end); } /** * Fethches the next token without advancing to its position * @param ws If true, retrieve whitespaces too */ peek(ws = false): Token { return this.ahead(0, ws); } /** * * @param n Number of token positions to read ahead * @param ws If true, retrieve whitespaces too */ ahead(n = 1, ws = false): Token { if (n > 16) { throw new Error("Cannot look ahead more than 16 tokens"); } // --- Prefetch missing tokens while (this._ahead.length <= n) { const token = this.fetch(); if (isEof(token)) { return token; } if (ws || (!ws && !isWs(token))) { this._ahead.push(token); } } return this._ahead[n]; } /** * Fethces the nex token and advances the stream position * @param ws If true, retrieve whitespaces too */ get(ws = false): Token { if (this._ahead.length > 0) { const token = this._ahead.shift(); if (!token) { throw new Error("Token expected"); } return token; } while (true) { const token = this.fetch(); if (isEof(token) || ws || (!ws && !isWs(token))) { return token; } } } /** * Fetches the next token from the input stream */ private fetch(): Token { const lexer = this; const input = this.input; const startPos = this._prefetchedPos || input.position; const line = input.line; const startColumn = this._prefetchedColumn || input.column; let text = ""; let tokenType = TokenType.Eof; let lastEndPos = input.position; let lastEndColumn = input.column; let ch: string | null = null; let phase: LexerPhase = LexerPhase.Start; while (true) { // --- Get the next character ch = fetchNextChar(); // --- In case of EOF, return the current token data if (ch === null) { return makeToken(); } // --- Set the intial token type to unknown for the other characters if (tokenType === TokenType.Eof) { tokenType = TokenType.Unknown; } // --- Follow the lexer state machine switch (phase) { // ==================================================================== // Process the first character case LexerPhase.Start: switch (ch) { // --- Go on with whitespaces case " ": case "\t": phase = LexerPhase.InWhiteSpace; tokenType = TokenType.Ws; break; // --- New line case "\n": return completeToken(TokenType.NewLine); // --- Potential new line case "\r": phase = LexerPhase.PotentialNewLine; tokenType = TokenType.NewLine; break; case '"': phase = LexerPhase.String; break; case "-": phase = LexerPhase.OptionOrNumber; break; case "$": phase = LexerPhase.VariableOrHexaDecimal; break; case "%": phase = LexerPhase.Binary; break; default: if (isIdStart(ch)) { phase = LexerPhase.IdTail; tokenType = TokenType.Identifier; } else if (isDecimalDigit(ch)) { phase = LexerPhase.Decimal; tokenType = TokenType.DecimalLiteral; } else if (isPathStart(ch)) { phase = LexerPhase.PathTail; tokenType = TokenType.Path; } break; } break; // ==================================================================== // Process whitespaces, comments, and new line // --- Looking for the end of whitespace case LexerPhase.InWhiteSpace: if (ch !== " " && ch !== "\t") { return makeToken(); } break; // --- We already received a "\r", so this is a new line case LexerPhase.PotentialNewLine: if (ch === "\n") { return completeToken(TokenType.NewLine); } return makeToken(); // ==================================================================== // Identifier and keyword like tokens // --- Wait for the completion of an identifier case LexerPhase.IdTail: if (isIdContinuation(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } if (isPathContinuation(ch)) { phase = LexerPhase.PathTail; tokenType = TokenType.Path; } else { phase = LexerPhase.ArgumentTail; tokenType = TokenType.Argument; } break; case LexerPhase.PathTail: if (isPathContinuation(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } phase = LexerPhase.ArgumentTail; tokenType = TokenType.Argument; break; // ==================================================================== // Variables case LexerPhase.VariableOrHexaDecimal: if (ch === "{") { phase = LexerPhase.Variable; break; } else if (isHexadecimalDigit(ch)) { phase = LexerPhase.HexaDecimalTail; tokenType = TokenType.HexadecimalLiteral; } else { phase = LexerPhase.ArgumentTail; tokenType = TokenType.Argument; } break; // We already parsed "${" case LexerPhase.Variable: if (isIdStart(ch)) { phase = LexerPhase.VariableTail; } else { return completeToken(); } break; // We identified the start character of a variable, and wait for continuation case LexerPhase.VariableTail: if (isIdContinuation(ch)) { break; } return ch === "}" ? completeToken(TokenType.Variable) : completeToken(TokenType.Unknown); // ==================================================================== // --- Options case LexerPhase.OptionOrNumber: if (ch === "$") { phase = LexerPhase.Hexadecimal; } else if (ch === "%") { phase = LexerPhase.Binary; } else if (isDecimalDigit(ch)) { phase = LexerPhase.Decimal; tokenType = TokenType.DecimalLiteral; } else if (isIdStart(ch)) { phase = LexerPhase.OptionTail; tokenType = TokenType.Option; } else { tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; } break; case LexerPhase.OptionTail: if (isIdContinuation(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; break; case LexerPhase.ArgumentTail: if (isTokenSeparator(ch)) { return makeToken(); } break; // ==================================================================== // --- Literals // String data case LexerPhase.String: if (ch === '"') { return completeToken(TokenType.String); } else if (isRestrictedInString(ch)) { return completeToken(TokenType.Unknown); } else if (ch === "\\") { phase = LexerPhase.StringBackSlash; tokenType = TokenType.Unknown; } break; // Start of string character escape case LexerPhase.StringBackSlash: switch (ch) { case "b": case "f": case "n": case "r": case "t": case "v": case "0": case "'": case '"': case "\\": phase = LexerPhase.String; break; default: if (ch === "x") { phase = LexerPhase.StringHexa1; } else { phase = LexerPhase.String; } } break; // First hexadecimal digit of string character escape case LexerPhase.StringHexa1: if (isHexadecimalDigit(ch)) { phase = LexerPhase.StringHexa2; } else { return completeToken(TokenType.Unknown); } break; // Second hexadecimal digit of character escape case LexerPhase.StringHexa2: if (isHexadecimalDigit(ch)) { phase = LexerPhase.String; } else { return completeToken(TokenType.Unknown); } break; // The first character after "$" case LexerPhase.Hexadecimal: if (isHexadecimalDigit(ch)) { phase = LexerPhase.HexaDecimalTail; tokenType = TokenType.HexadecimalLiteral; } else { tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; } break; case LexerPhase.HexaDecimalTail: if (isXHexadecimalDigit(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; break; // The first character after "%" case LexerPhase.Binary: if (isBinaryDigit(ch)) { phase = LexerPhase.BinaryTail; tokenType = TokenType.BinaryLiteral; } else { tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; } break; case LexerPhase.BinaryTail: if (isXBinaryDigit(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; break; // The first decimal lieterl character case LexerPhase.Decimal: if (isDecimalDigit(ch)) { phase = LexerPhase.DecimalTail; tokenType = TokenType.DecimalLiteral; } else if (isTokenSeparator(ch)) { return makeToken(); } else { tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; } break; case LexerPhase.DecimalTail: if (isXDecimalDigit(ch)) { break; } if (isTokenSeparator(ch)) { return makeToken(); } tokenType = TokenType.Argument; phase = LexerPhase.ArgumentTail; break; // ==================================================================== // --- We cannot continue default: return makeToken(); } // --- Append the char to the current text appendTokenChar(); // --- Go on with parsing the next character } /** * Appends the last character to the token, and manages positions */ function appendTokenChar(): void { text += ch; lexer._prefetched = null; lexer._prefetchedPos = null; lexer._prefetchedColumn = null; lastEndPos = input.position; lastEndColumn = input.position; } /** * Fetches the next character from the input stream */ function fetchNextChar(): string | null { let ch: string; if (!lexer._prefetched) { lexer._prefetchedPos = input.position; lexer._prefetchedColumn = input.column; lexer._prefetched = input.get(); } return lexer._prefetched; } /** * Packs the specified type of token to send back * @param type */ function makeToken(): Token { return { text, type: tokenType, location: { startPos, endPos: lastEndPos, line, startColumn, endColumn: lastEndColumn, }, }; } /** * Add the last character to the token and return it */ function completeToken(suggestedType?: TokenType): Token { appendTokenChar(); // --- Send back the token if (suggestedType !== undefined) { tokenType = suggestedType; } return makeToken(); } } } /** * This enum indicates the current lexer phase */ enum LexerPhase { // Start getting a token Start = 0, // Collecting whitespace InWhiteSpace, // Waiting for "\n" after "\r" PotentialNewLine, // Waiting for Option or Number decision OptionOrNumber, // Waiting for a Vatiable or a hexadecimal number VariableOrHexaDecimal, // Waiting for an argument tail ArgumentTail, // Variable related phases Variable, VariableTail, // String-related parsing phases IdTail, String, StringBackSlash, StringHexa1, StringHexa2, StringTail, OptionTail, PathTail, Decimal, DecimalTail, Hexadecimal, HexaDecimalTail, Binary, BinaryTail, } /** * Tests if a token id EOF * @param t Token instance */ function isEof(t: Token): boolean { return t.type === TokenType.Eof; } /** * Tests if a token is whitespace * @param t Token instance */ function isWs(t: Token): boolean { return t.type <= TokenType.Ws; } // ---------------------------------------------------------------------------- // Character classification /** * Tests if a character is a letter * @param ch Character to test */ function isLetterOrDigit(ch: string): boolean { return ( (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || (ch >= "0" && ch <= "9") ); } /** * Tests if a character can be the start of an identifier * @param ch Character to test */ function isIdStart(ch: string): boolean { return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || ch === "_"; } /** * Tests if a character can be the continuation of an identifier * @param ch Character to test */ function isIdContinuation(ch: string): boolean { return ( isIdStart(ch) || isDecimalDigit(ch) || ch === "-" || ch === "$" || ch === "." || ch === "!" || ch === ":" || ch === "#" ); } /** * Tests if a character can be the start of a path * @param ch Character to test */ function isPathStart(ch: string): boolean { return ( (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || ch === "_" || ch === "/" || ch === "\\" || ch === "." || ch === "*" || ch === "?" ); } /** * Tests if a character can be the continuation of a path * @param ch Character to test */ function isPathContinuation(ch: string): boolean { return isPathStart(ch) || ch === ":"; } /** * Tests if a character is a decimal digit * @param ch Character to test */ function isDecimalDigit(ch: string): boolean { return ch >= "0" && ch <= "9"; } /** * Tests if a character is an extended decimal digit * @param ch Character to test */ function isXDecimalDigit(ch: string): boolean { return isDecimalDigit(ch) || ch === "_" || ch === "'"; } /** * Tests if a character is a hexadecimal digit * @param ch Character to test */ function isHexadecimalDigit(ch: string): boolean { return ( (ch >= "0" && ch <= "9") || (ch >= "A" && ch <= "F") || (ch >= "a" && ch <= "f") ); } /** * Tests if a character is a hexadecimal digit * @param ch Character to test */ function isXHexadecimalDigit(ch: string): boolean { return isHexadecimalDigit(ch) || ch === "_" || ch === "'"; } /** * Tests if a character is a binary digit * @param ch Character to test */ function isBinaryDigit(ch: string): boolean { return ch === "0" || ch === "1"; } /** * Tests if a character is an extended binary digit * @param ch Character to test */ function isXBinaryDigit(ch: string): boolean { return isBinaryDigit(ch) || ch === "_" || ch === "'"; } /** * Tests if a character is a token separator * @param ch Character to test */ function isTokenSeparator(ch: string): boolean { return ch === " " || ch === "\t" || ch === "\r" || ch === "\r"; } /** * Tests if a character is restricted in a string * @param ch Character to test */ function isRestrictedInString(ch: string): boolean { return ( ch === "\r" || ch === "\n" || ch === "\u0085" || ch === "\u2028" || ch === "\u2029" ); }
the_stack
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { GeneralDataService } from 'app/general-data.service'; import { Location, LocationType, VerifiableOrg, VerifiableOrgType, IssuerService, VerifiableClaim, VerifiableClaimType, DoingBusinessAs, blankLocation, blankOrgType, blankLocationType, blankIssuerService, blankClaimType } from '../data-types'; @Component({ selector: 'app-roadmap', templateUrl: '../../themes/_active/roadmap/roadmap.component.html', styleUrls: ['../../themes/_active/roadmap/roadmap.component.scss'] }) export class RoadmapComponent implements OnInit { public recipeId : string; public recordId : string = ''; public query : string = ''; public error : string = ''; public orgRecord; public recipe; public allResults; public results = []; public searchType = 'name'; public currentLang : string; public registerLink : string; private searchTimer; private sub; private page = 0; public more = false; public less = false; public none = false; public inited = false; public loading = false; public loaded = false; public dbas: DoingBusinessAs[]; public certs: any[]; public locations: Location[]; private preload; constructor( private dataService: GeneralDataService, private translate: TranslateService, private $route: ActivatedRoute, private $router: Router ) { } ngOnInit() { this.currentLang = this.translate.currentLang; this.preload = this.dataService.preloadData(['locations', 'locationtypes', 'verifiableclaimtypes', 'verifiableorgtypes']); this.$route.params.subscribe(params => { this.preload.then(() => this.loadRecipe(params.recipeId)); }); } loadRecipe(recipe) { this.recipeId = recipe; this.dataService.loadJson('assets/recipes/' + recipe + '.json').subscribe((data) => { // pre-index claim types by schema name with latest schema version let regTypes = <VerifiableClaimType[]>this.dataService.getOrgData('verifiableclaimtypes'); let typesBySchema = {}; if(regTypes) { for(let regType of regTypes) { if(regType.schemaName && regType.schemaVersion) { let sname = regType.schemaName; let other = typesBySchema[sname]; if(other && other.id < regType.id) continue; typesBySchema[sname] = regType; } } } if(typesBySchema['entity.person']) { this.registerLink = typesBySchema['entity.person'].issuerURL; } let ctypes = data['claimTypes'] || []; let ctype; let dependsMap = {}; data['claimTypes'] = []; ctypes.forEach((ctype_spec, idx) => { ctype = Object.assign({}, ctype_spec); ctype.cert = null; if(! ctype.schemaName || ! typesBySchema[ctype.schemaName]) return; ctype.regType = typesBySchema[ctype.schemaName]; if(! ctype.regLink) ctype.regLink = ctype.regType.issuerURL; dependsMap[ctype.schemaName] = ctype.depends || []; ctype.oldIdx = idx; data['claimTypes'].push(ctype); }); this.expandDepends(dependsMap); data['claimTypes'].sort(this.cmpDependClaims(dependsMap)); let dependIndex = {}; data['claimTypes'].forEach( (ctype, idx) => { dependIndex[ctype['schemaName']] = idx; }); // expand dependency information data['claimTypes'].forEach(ctype => { let claimDeps = []; if(ctype.schemaName in dependsMap) { dependsMap[ctype.schemaName].forEach(schema => { if(schema in dependIndex) claimDeps.push(dependIndex[schema]); }); } claimDeps.sort(); ctype['depends'] = claimDeps.length ? claimDeps : null; }); let dependsMapIdx = {}; for(let schema in dependsMap) { dependsMapIdx[dependIndex[schema]] = dependsMap[schema].map(schema => ''+dependIndex[schema]); } try { let tree = this.makeDependsTree(Object.keys(dependsMapIdx), dependsMapIdx); console.log('tree', tree); if(! tree[1].length) { // no remaining, tree should be good data['tree'] = tree[0]; } } catch(e) { console.error(e); } this.recipe = data; console.log('recipe', data); this.$route.queryParams.subscribe(params => { this.setParams(params.record, params.query); }); }, (failed) => { console.log('failed'); this.error = "An error occurred while loading the recipe."; }); } cmpDependClaims(dependsMap) { return (a, b) => { let schemaA = a.schemaName; let schemaB = b.schemaName; if(schemaA in dependsMap && ~dependsMap[schemaA].indexOf(schemaB)) return 1; if(schemaB in dependsMap && ~dependsMap[schemaB].indexOf(schemaA)) return -1; return (a.oldIdx == b.oldIdx ? 0 : (a.oldIdx < b.oldIdx ? 1 : -1)); } } makeDependsTree(claims, allDepends, remainDepends?, parents?, depth?) { let topClaims = []; let remain = []; if(! remainDepends) { remainDepends = new Set(Object.keys(allDepends)); } let nextDepends = new Set(remainDepends); let idx = 0; if(! depth) depth = 0; if(! parents) parents = []; // identify claims with no unsatisfied dependencies for(; idx < claims.length; idx++) { let claim = claims[idx]; let noRemain = true; let depends = allDepends[claim]; if(depends) { for(let dep of depends) { if(remainDepends.has(dep)) { noRemain = false; break; } } } if(noRemain) { topClaims.push(claim); nextDepends.delete(claim); } else { remain.push(claim); } } if(! topClaims.length) { return [[], remain]; } // initialize buckets for each parent of this level let buckets = []; // split top level claims into buckets topClaims.forEach(claim => { let parentClaims = []; if(parents.length) { parents.forEach(parentClaim => { if(~allDepends[claim].indexOf(parentClaim)) parentClaims.push(parentClaim); }); } let key = parentClaims.join(','); let found = null; for(let idx = 0; idx < buckets.length; idx++) { if(buckets[idx]['key'] === key) { found = idx; break; } } if(found === null) { found = buckets.length; buckets.push({'key': key, 'parents': parentClaims, 'nodes': [], 'next': []}); } let node = {'id': claim, 'children': [], 'descends': []}; if(remain.length) { let nodeDepends = new Set(remainDepends); nodeDepends.delete(claim); let nodeNext = this.makeDependsTree(remain, allDepends, nodeDepends, [claim], depth+1); node['children'] = nodeNext[0]; remain.forEach(claim => { if(! ~nodeNext[1].indexOf(claim)) { node['descends'].push(claim); nextDepends.delete(claim); } }); remain = nodeNext[1]; } buckets[found]['nodes'].push(node); }); // add additional levels to each bucket if needed buckets.forEach(bucket => { if(! remain.length) return; let bucketDepends = new Set(remainDepends); let nodeIds = bucket['nodes'].map(node => node['id']); nodeIds.forEach(id => bucketDepends.delete(id)); let bucketNext = this.makeDependsTree(remain, allDepends, bucketDepends, nodeIds, depth+1); bucket['next'] = bucketNext[0]; remain = bucketNext[1]; }); // assign remaining claims to additional levels let bottom = this.lastChildren(buckets); let levels = [buckets]; if(0 && buckets.length == 1) { // promote to top level (flatten hierarchy) levels = levels.concat(buckets[0]['next']); buckets[0]['next'] = []; } if(remain.length) { let nextLevels = this.makeDependsTree(remain, allDepends, nextDepends, bottom, depth+1); levels = levels.concat(nextLevels[0]); remain = nextLevels[1]; } return [levels, remain]; } lastChildren(buckets) { let bottom = []; buckets.forEach(bucket => { bucket['nodes'].forEach(node => { let lvlCount = node['children'].length; if(lvlCount) { bottom = bottom.concat(this.lastChildren(node['children'][lvlCount - 1])); } else { bottom.push(node['id']); } }); }); return bottom; } expandDepends(all_deps) { let found = true; while(found) { found = false; for(let dep in all_deps) { let deps = all_deps[dep]; let ndeps = new Set(); for(let extdep of deps) { if(! (extdep in all_deps)) continue; let extall = all_deps[extdep]; for(let extext of extall) { if(extext !== dep && extext !== extdep && ! ~deps.indexOf(extext)) { ndeps.add(extext); } } } if(ndeps.size) { all_deps[dep] = deps.concat(Array.from(ndeps)); found = true; } } } } setParams(record, q) { if(typeof q !== 'string') q = ''; this.recordId = record; if(this.query !== q || ! this.inited) { this.query = q; var search = (<HTMLInputElement>document.getElementById('searchInput')); if(search) search.value = this.query; this.preload.then(data => this.search()); } } initSearch() { var search = (<HTMLInputElement>document.getElementById('searchInput')); if(search) search.value = this.query; this.focusSearch(); } focusSearch() { var search = (<HTMLInputElement>document.getElementById('searchInput')); if(search) search.select(); } inputEvent(evt) { if(evt.type === 'focus') { evt.target.parentNode.classList.add('active'); } else if(evt.type === 'blur') { evt.target.parentNode.classList.remove('active'); } else if(evt.type === 'input') { this.updateSearch(evt); } } updateSearch(evt) { let q = evt.target.value; let navParams = { queryParams: {}, relativeTo: this.$route }; if(q !== undefined && q !== null) { q = q.trim(); if(q !== '') { navParams.queryParams['query'] = q; } } if (this.searchTimer) clearTimeout(this.searchTimer); this.searchTimer = setTimeout(() => { this.$router.navigate(['./'], navParams); }, 150); } search(setType? : string) { if(this.recordId) { this.loadRecord(); return; } let q = this.query.trim(); this.loading = true; if(setType) { this.searchType = setType; } if(q.length) { let srch; if(this.searchType === 'name') { srch = this.sub = this.dataService.searchOrgs(q); } else { srch = this.sub = this.dataService.searchLocs(q); } this.sub.then(data => this.returnSearch(data, srch)); this.sub.catch(err => this.searchError(err)); } else { this.sub = null; this.returnSearch([], this.sub); } } loadRecord() { this.dataService.loadVerifiableOrg(this.recordId).subscribe((record : VerifiableOrg) => { console.log('verified org:', record); this.loaded = !!record; if(! record) this.error = 'Record not found'; else { let orgType = <VerifiableOrgType>this.dataService.findOrgData('verifiableorgtypes', record.orgTypeId); record.type = orgType || blankOrgType(); record.typeName = orgType && orgType.description; let orgLocs = []; let claimLocs = {}; if(record.locations) { for(var i = 0; i < record.locations.length; i++) { let loc = <Location>Object.assign({}, record.locations[i]); let locType = <LocationType>this.dataService.findOrgData('locationtypes', loc.locationTypeId); loc.type = locType || blankLocationType(); loc.typeName = locType && locType.locType; if(loc.doingBusinessAsId) { let cid = loc.doingBusinessAsId; if(! claimLocs[cid]) claimLocs[cid] = []; claimLocs[cid].push(loc); } else { orgLocs.push(loc); } } } this.locations = orgLocs; console.log('locations', orgLocs); let dbas = []; if(Array.isArray(record.doingBusinessAs)) { for(var i = 0; i < record.doingBusinessAs.length; i++) { let dba = <DoingBusinessAs>Object.assign({}, record.doingBusinessAs[i]); dba.locations = claimLocs[dba.id] || []; dbas.push(dba); } } this.dbas = dbas; console.log('dbas', dbas); this.certs = this.dataService.formatClaims(record.claims); console.log('claims', this.certs); let certPos = {}; this.recipe.claimTypes.forEach( (ctype, idx) => { certPos[ctype.regType.id] = idx; }); for(let i = 0; i < this.certs.length; i++) { let cert = <VerifiableClaim>this.certs[i].top; if(cert.type.id in certPos) { this.recipe.claimTypes[certPos[cert.type.id]].cert = cert; } } } this.orgRecord = record; this.inited = true; }, err => { this.error = err; }); } setSearchType(evt) { if(this.searchType !== evt.target.value) { this.search(evt.target.value); } if(! this.query.trim().length) { this.focusSearch(); } } returnSearch(data, from) { this.orgRecord = null; if(from !== this.sub) return; this.page = 0; this.allResults = data; this.paginate(); this.loading = false; if(! this.inited) { this.inited = true; setTimeout(() => this.initSearch(), 100); } } searchError(err) { console.error(err); this.returnSearch([], this.sub); } paginate() { let rows = this.allResults || []; this.results = rows.slice(this.page * 10, (this.page + 1) * 10); this.more = (rows.length > (this.page + 1) * 10); this.less = (this.page > 0); this.none = (rows.length == 0); } prev() { this.page --; this.paginate(); } next() { this.page ++; this.paginate(); } getCred(claimType) { const url = `${claimType.regLink}?source=bcorgbook&source_id=${this.recordId}&org_id=${this.orgRecord.orgId}&lang=${this.currentLang}&recipe=${this.recipeId}`; console.log(`getCred() called. url: ${url}`); window.location.href = url; } }
the_stack
import { FunctionDesc } from "../src/functionDesc"; import { FileType } from "./types"; import * as ts from "typescript"; /** * Parse a source file and return descriptions of all functions present in the * source file. Each description includes the name of the function, and start and * end coordinates. For anonymous functions the name is "<anonymous>". * * @param source - the contents of a source file * @param filetype - the type of the source file (e.g. ECMAScript or TypeScript) * * @throws if the filetype is not supported, or if the source file cannot be parsed. */ export function parse(source: string, filetype: FileType): FunctionDesc[] { switch (filetype) { case "TypeScript": case "ECMAScript": case "TSX": case "JSX": return parseTS(source, filetype); default: throw Error(`Unsupported FileType provided: ${filetype}`); } } const tsScriptKind: ReadonlyMap<string, ts.ScriptKind> = new Map([ ["TypeScript", ts.ScriptKind.TS], ["ECMAScript", ts.ScriptKind.JS], ["TSX", ts.ScriptKind.TSX], ["JSX", ts.ScriptKind.JSX], ]); function parseTS(source: string, filetype: FileType): FunctionDesc[] { const scriptKind = tsScriptKind.get(filetype); const tsSource = ts.createSourceFile( "", source, ts.ScriptTarget.ESNext, true, // setParentNodes scriptKind ); validateScript(tsSource); const topLevelDesc = visitSourceNode(tsSource); const otherDescs = traverseNode(tsSource); return [topLevelDesc, ...otherDescs]; } let _program: ts.Program; function getExpensiveProgram() { return _program || (_program = ts.createProgram([""], {})); } function validateScript(tsSource: ts.SourceFile) { const program = getExpensiveProgram(); const diag = program.getSyntacticDiagnostics(tsSource); if (diag.length > 0) { throw Error(`Syntax error in source, ${diag[0].messageText}`); } } function traverseNode( source: ts.SourceFile, node: ts.Node = source ): FunctionDesc[] { const functionDescs: FunctionDesc[] = []; if ( ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node) ) { functionDescs.push(...visitFunctionNode(node, source)); } node.getChildren().forEach((c) => functionDescs.push(...traverseNode(source, c)) ); return functionDescs; } function visitFunctionNode( node: ts.FunctionLikeDeclaration, source: ts.SourceFile ): FunctionDesc[] { if (node.body) { const name = getFunctionName(node); const { startLine, startColumn, endLine, endColumn } = getPosition( node, source ); return [ new FunctionDesc(name, startLine, startColumn, endLine, endColumn), ]; } return []; } function visitSourceNode(source: ts.SourceFile): FunctionDesc { const name = "<top-level>"; const { startLine, startColumn, endLine, endColumn } = getPosition( source, source ); return new FunctionDesc(name, startLine, startColumn, endLine, endColumn); } function getPosition( range: ts.TextRange, source: ts.SourceFile ): { startLine: number; startColumn: number; endLine: number; endColumn: number; } { const { pos, end } = range; const { line: startLine, character: startColumn, } = source.getLineAndCharacterOfPosition(pos); const { line: endLine, character: endColumn, } = source.getLineAndCharacterOfPosition(end); return { startLine, startColumn, endLine, endColumn, }; } function getFunctionName(func: ts.FunctionLikeDeclaration): string { let nameText = "<anonymous>"; const name = func.name; if (name) { nameText = getNameText(name, func) || nameText; } else if (ts.isConstructorDeclaration(func)) { // set the name to "", the class name will be added later nameText = ""; } else { if (ts.isFunctionExpression(func) || ts.isArrowFunction(func)) { let parent = func.parent; if (ts.isParenthesizedExpression(parent)) { parent = parent.parent; } if ( ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isPropertyDeclaration(parent) ) { nameText = getNameText(parent.name, func) || nameText; } else if ( ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ) { if ( ts.isPropertyAccessExpression(parent.left) || ts.isElementAccessExpression(parent.left) ) { nameText = getLeftHandSideName(parent.left); } } } } const prefix = getPrefix(func); if (prefix) { return nameText === "" ? prefix : `${prefix}.${nameText}`; } return nameText; } function getPrefix(func: ts.FunctionLikeDeclaration): string | null { let propValue: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration = func; let prefix = null; // get class prefix if function is inside a class const classPrefix = getClassPrefix(func); if (classPrefix) { prefix = classPrefix; const classPropValue = getParentClassProperty(func); if (classPropValue) { // if the class is a property of an object literal, we want to // walk the object literal chain of the class instead of the function propValue = classPropValue; } else { // this means the class is not inside an object literal and we are done return prefix; } } // get object literal prefix if function (or enclosing class) // is inside an object literal const objectLiteralPrefix = getObjectLiteralPrefix(propValue); if (objectLiteralPrefix) { prefix = prefix ? `${objectLiteralPrefix}.${prefix}` : objectLiteralPrefix; } return prefix; } function isProperty( func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration ) { return ( (ts.isFunctionExpression(func) || ts.isArrowFunction(func) || ts.isClassExpression(func)) && (ts.isPropertyDeclaration(func.parent) || ts.isPropertyAssignment(func.parent)) ); } function getPropertyNodeForFunction( func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration ) { if ( ts.isMethodDeclaration(func) || ts.isGetAccessor(func) || ts.isSetAccessor(func) || ts.isConstructorDeclaration(func) ) { return func; } if ( ts.isFunctionExpression(func) || ts.isArrowFunction(func) || ts.isClassExpression(func) ) { if ( ts.isPropertyDeclaration(func.parent) || ts.isPropertyAssignment(func.parent) ) { return func.parent; } } return null; } function getObjectLiteralPrefix( func: ts.FunctionLikeDeclaration | ts.ClassLikeDeclaration ): string | null { const propertyNode = getPropertyNodeForFunction(func); // propertyNode === null means the function was neither a method nor a // property, so it is not part of an object literal or class declaration if (!propertyNode) { return null; } // if the function is a property, and either has a local name, // or is inside a class expression, we take the local name and // and do not prefix it with the object literal chain const isProp = isProperty(func); if (isProp) { if ( func.name !== undefined || ts.isClassExpression(propertyNode.parent) ) { return null; } } return getObjectLiteralPrefixR(propertyNode.parent); } function getObjectLiteralPrefixR( node: ts.Node, prefixWithObject = false ): string | null { const parent = node.parent; if (!parent) { return null; } if (ts.isPropertyAssignment(parent)) { const propertyAssignment = parent; const prefix = getObjectLiteralPrefixR( propertyAssignment.parent, true ); return `${prefix}.${getPropertyName(propertyAssignment.name)}`; } if (ts.isVariableDeclaration(parent)) { if (ts.isIdentifier(parent.name)) { return getPropertyName(parent.name); } } else if ( ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ) { if (ts.isIdentifier(parent.left)) { return getPropertyName(parent.left); } if ( ts.isPropertyAccessExpression(parent.left) || ts.isElementAccessExpression(parent.left) ) { return getLeftHandSideName(parent.left); } } return prefixWithObject ? "<Object>" : null; } function getParentClassProperty(func: ts.FunctionLikeDeclaration) { const propertyNode = getPropertyNodeForFunction(func); if (propertyNode) { const parent = propertyNode.parent; if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) { return parent; } } return null; } function getClassPrefix(func: ts.FunctionLikeDeclaration): string | null { const propertyNode = getPropertyNodeForFunction(func); if (!propertyNode) { return null; } const parent = propertyNode.parent; if (ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) { const className = getClassName(parent); const isProp = isProperty(func); if (isStatic(propertyNode)) { if (!isProp || func.name === undefined) { return className; } } else if (ts.isConstructorDeclaration(func)) { return className; } else if (!isProp) { return `${className}.prototype`; } } return null; } function getClassName(classNode: ts.ClassLikeDeclaration): string { // if class has a local name, use it and return, // not interested in left hand side if (classNode.name) { return classNode.name.text; } // try to get the name from the left hand side if (ts.isClassExpression(classNode)) { const parent = classNode.parent; if ( ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isPropertyDeclaration(parent) ) { if (ts.isPropertyName(parent.name)) { return getPropertyName(parent.name); } } else if ( ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ) { if ( ts.isPropertyAccessExpression(parent.left) || ts.isElementAccessExpression(parent.left) ) { return getLeftHandSideName(parent.left); } } } return "<anonymous>"; } function isStatic(func: ts.Node): boolean { if (func.modifiers) { return func.modifiers.some(({ kind }) => { return kind === ts.SyntaxKind.StaticKeyword; }); } return false; } function getLeftHandSideName(left: ts.Expression): string { if ( ts.isIdentifier(left) || ts.isStringLiteral(left) || ts.isNumericLiteral(left) ) { return left.text; } else if (ts.isPropertyAccessExpression(left)) { return getLeftHandSideName(left.expression) + "." + left.name.text; } else if (ts.isElementAccessExpression(left)) { return ( getLeftHandSideName(left.expression) + "." + computedName(left.argumentExpression) ); } return "<computed>"; } function getPropertyName(name: ts.PropertyName): string { switch (name.kind) { case ts.SyntaxKind.Identifier: case ts.SyntaxKind.StringLiteral: case ts.SyntaxKind.NumericLiteral: case ts.SyntaxKind.PrivateIdentifier: return name.text; case ts.SyntaxKind.ComputedPropertyName: return computedName(name.expression); } } function getNameText( name: ts.Node, func: ts.FunctionLikeDeclaration ): string | null { let nameText = null; if (ts.isPropertyName(name)) { nameText = getPropertyName(name); if (ts.isGetAccessor(func)) { return `get ${nameText}`; } if (ts.isSetAccessor(func)) { return `set ${nameText}`; } } if (ts.isPrivateIdentifier(name)) { nameText = name.text; } return nameText; } function computedName(expression: ts.Expression): string { if (ts.isIdentifier(expression)) { return `<computed: ${expression.text}>`; } else if ( ts.isStringLiteral(expression) || ts.isNumericLiteral(expression) ) { return expression.text; } return "<computed>"; }
the_stack
import * as BaseTypes from "./BaseTypes"; import * as RIVAProto from "./RIVAProto"; import * as ImgCache from "./ImgCache"; // // This class contains our canvas and the handlers for all of the graphics output code. // // // A simple graphics context. The canvas' context scheme is useless pretty much, // so we do our own. // class GraphCtx { constructor(toCopy : GraphCtx = null) { if (toCopy) { this.bgnColor = toCopy.bgnColor; this.bmpMode = toCopy.bmpMode; this.textColor = toCopy.textColor; this.fontStackSize = toCopy.fontStackSize; this.fontStackSize = toCopy.fontStackSize; this.shadowBlur = toCopy.shadowBlur; this.shadowOffsetX = toCopy.shadowOffsetX; this.shadowOffsetY = toCopy.shadowOffsetY; this.shadowColor = toCopy.shadowColor; } else { this.reset(); } } // Applies our stored settings to the passed context applyTo(tarCtx : CanvasRenderingContext2D) { // And set those values on our context object where applicable tarCtx.globalCompositeOperation = this.bmpMode; tarCtx.fillStyle = this.bgnColor; tarCtx.shadowBlur = this.shadowBlur; tarCtx.shadowOffsetX = this.shadowOffsetX; tarCtx.shadowOffsetY = this.shadowOffsetY; tarCtx.shadowColor = this.shadowColor; } reset() { this.bgnColor = "#FFFFFF"; this.bmpMode = "source-over"; this.fontStackSize = 0; this.clipStackSize = 0; this.textColor = "#000000"; this.shadowBlur = 0; this.shadowOffsetX = 0; this.shadowOffsetY = 0; this.shadowColor = "#000000"; } bgnColor : string; bmpMode : string; textColor : string; // Drop shadow related stuff shadowBlur : number; shadowOffsetX : number; shadowOffsetY : number; shadowColor : string; // Internal debugging stuff clipStackSize : number; fontStackSize : number; } // // Font info that we push/pop on our font stack. We pre-format out the info to // a string that can be set on the canvas to set up this particular font. // class FontInfo { constructor(fontMsg : Object) { if (fontMsg) { // Get out the raw values this.height = fontMsg[RIVAProto.kAttr_FontH]; this.faceName = fontMsg[RIVAProto.kAttr_FontFace]; this.isBold = (fontMsg[RIVAProto.kAttr_Flags] & RIVAProto.kFontFlag_Bold) !== 0; this.isItalic = (fontMsg[RIVAProto.kAttr_Flags] & RIVAProto.kFontFlag_Italic) !== 0; } else { this.height = 12; this.isBold = false; this.isItalic = false; this.faceName = "Verdana"; } // Format it the way we need to set on the canvas this.canvasFmt = ""; if (this.isItalic) this.canvasFmt += "italic "; if (this.isBold) this.canvasFmt += "bold "; this.canvasFmt += (this.height - 0.5) + "px "; this.canvasFmt += this.faceName; } faceName : string; height : number; isBold : boolean; isItalic : boolean; canvasFmt : string; } // // This is our drawing class. The main application passes all graphics commands to // us here to be processed. // export class GraphDraw { // Our canvas that we display on and the context object for it private showSurface : HTMLCanvasElement; private showCtx : CanvasRenderingContext2D; // // A secondary, offscreen canvas for double buffering, where we do all of the drawing // and masking and then blit it to the show context. // private drawSurface : HTMLCanvasElement; private drawCtx : CanvasRenderingContext2D; // // A tertiary canvas that is used for intermediate results in some more complex // operations, such as progress bars. And it's used for masking in color masked // image drawing. It is sized up as needed, since it almost never would need to be // full size. // private tmpSurface : HTMLCanvasElement; private tmpCtx : CanvasRenderingContext2D; // // When we get a StartDraw we save the update area. When we see the EndDraw we blit // this area from the drawing context to the display context. This effectively // provides our overall clipping, so we don't need to depend on a clipping path // for this (which causes lots of problems because of the stupid canvas anti- // aliasing that we can't prevent.) // private updateArea : BaseTypes.RIVAArea; // // A stack for nested clip areas the server sets on us. We just save them and update // the actual clip stack only when it is necessary, see below. // private clipStack : Array<BaseTypes.RIVAArea>; // // We don't want to rebuild the clip path every time the clip stack changes because // often there are multiple push or pop operations without any actual drawing in // between. So every time the stack is changed in such a way that would affect the // clip path, this is set. Upon receipt of a drawing command, if this is set we // rebuild the clip path and clear this flag. This is a substantial win in most // cases. // private clipPathRebuildNeeded : boolean; // A stack for fonts to be pushed and popped on us private fontStack : Array<FontInfo>; // The info object for the currently set font private curFont : FontInfo; // // The height of the currently set font, which we use for inter-line spacing when // doing multi-line text (we have to handle that ourselves.) We actually set it // to slightly higher than the font heigh to best match the Windows IV output. // private curFontHeight : number; // // Our own context stack and the current context object. We pop the top pof the // stack into the current context member. // private ctxStack : Array<GraphCtx>; private curContext : GraphCtx; // // The color of the HTML DIV surrounding our canvas. Because of the need to translate // the drawing canvas while drawing (to avoid stupid anti-aliasing) when we blit it to the // show canvas, it leaves a line on the right/bottom. After updating the canvas we draw // lines over that using the background color. Initially it's assumed to be white since // that is what we set in the CSS. After that the app will update us if it is changed by // the command that supports that. // private surroundColor : string = "#FFFFFF"; // The main app tells us if we should do debug logging private doDebug : boolean; constructor(doDebug : boolean) { // // Get our visible canvas from the DOM, and create our background drawing canvas // as well. // this.showSurface = <HTMLCanvasElement>document.getElementById("TemplateCont"); this.drawSurface = document.createElement("canvas"); // // Allocate our push/pop stacks, initially empty until something is pushed by // the server. // this.clipStack = new Array<BaseTypes.RIVAArea>(); this.fontStack = new Array<FontInfo>(); this.ctxStack = new Array<GraphCtx>(); // Allocate an initial current context object with default settings this.curContext = new GraphCtx(null); // And an initial font this.curFont = new FontInfo(null); // Store the passed debug flag this.doDebug = doDebug; // And call our reset method to set up our contexts to defaults this.resetContext(); } // // Called with any graphics command msgs we get. We just do a switch and pass each one // to its own private handler method, or handle it here if really simple. // // We also get a ref to the image cache in case we need to draw an image. // handleGraphicsCmd( opCode : RIVAProto.OpCodes, cmdMsg : Object, imgCache : ImgCache.ImgCache) : boolean { // // We handle any of the non-drawing ones separately because we want to be able // to potentially rebuild the clip path when a drawing command is received. // if (opCode >= RIVAProto.OpCodes.LastDrawing) { switch(opCode) { case RIVAProto.OpCodes.EndDraw : // Blit the update area from the buffering canvas to the display one this.showCtx.drawImage ( this.drawSurface, this.updateArea.x, this.updateArea.y, this.updateArea.width, this.updateArea.height, this.updateArea.x, this.updateArea.y, this.updateArea.width, this.updateArea.height ); // Fill in the right/bottom half line that our translation leaves unfilled this.setLRBoundaryColor(this.surroundColor); break; case RIVAProto.OpCodes.PopClipArea : this.popClipStack(); break; case RIVAProto.OpCodes.PopContext : this.popContext(); break; case RIVAProto.OpCodes.PopFont : // Just pop the top of the stack and set it as the current font if (this.fontStack.length) { this.curFont = this.fontStack.pop(); // We add two to better match Windows (this is our inter-line spacing) this.curFontHeight = this.curFont.height + 2; // Update the drawing context's font style from this new current font this.drawCtx.font = this.curFont.canvasFmt; } else { throw Error("Font stack underflow"); } break; case RIVAProto.OpCodes.PushContext : this.pushContext(); break; case RIVAProto.OpCodes.PushFont : // Format the font info out and push/set it this.pushFont(cmdMsg); break; case RIVAProto.OpCodes.PushClipArea : var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(cmdMsg[RIVAProto.kAttr_ClipArea]); tarArea.rounding = cmdMsg[RIVAProto.kAttr_Rounding]; tarArea.clipMode = <RIVAProto.ClipModes>cmdMsg[RIVAProto.kAttr_ClipMode]; this.pushClipArea(tarArea); break; case RIVAProto.OpCodes.SetColor : // Get the color to set var toSet : RIVAProto.DrawingColors = <RIVAProto.DrawingColors> ( cmdMsg[RIVAProto.kAttr_ToSet] ); // Just store them in our current context for later use if (toSet === RIVAProto.DrawingColors.Background) this.curContext.bgnColor = cmdMsg[RIVAProto.kAttr_Color]; else this.curContext.textColor = cmdMsg[RIVAProto.kAttr_Color]; break; case RIVAProto.OpCodes.StartDraw : // Clear the area that is going to be updated this.updateArea = new BaseTypes.RIVAArea(cmdMsg[RIVAProto.kAttr_UpdateArea]); this.drawCtx.clearRect ( this.updateArea.x, this.updateArea.y, this.updateArea.width, this.updateArea.height ); break; default : // Never handled it so return false return false; }; } else { // // If the clip stack has been modified in a way that affected the clip path // then we need to rebuild it. The rebuild method will clear the flag. // if (this.clipPathRebuildNeeded) this.rebuildClipArea(); switch(opCode) { case RIVAProto.OpCodes.AlphaBlit : this.alphaBlit(cmdMsg, imgCache); break; case RIVAProto.OpCodes.AlphaBlitST : this.alphaBlitST(cmdMsg, imgCache); break; case RIVAProto.OpCodes.DrawBitmap : this.drawBitmap(cmdMsg, imgCache); break; case RIVAProto.OpCodes.DrawBitmapST : this.drawBitmapST(cmdMsg, imgCache); break; case RIVAProto.OpCodes.DrawLine : this.drawLine(cmdMsg); break; case RIVAProto.OpCodes.DrawText : this.drawText(cmdMsg); break; case RIVAProto.OpCodes.DrawTextFX : this.drawTextFX(cmdMsg); break; case RIVAProto.OpCodes.DrawMultiText : this.drawMultiText(cmdMsg); break; case RIVAProto.OpCodes.DrawPBar : this.drawPBar(cmdMsg, imgCache); break; case RIVAProto.OpCodes.FillArea : this.fillArea(cmdMsg); break; case RIVAProto.OpCodes.FillWithBmp : this.fillWithBmp(cmdMsg, imgCache); break; case RIVAProto.OpCodes.GradientFill : this.gradientFill(cmdMsg); break; case RIVAProto.OpCodes.StrokeArea : this.strokeArea(cmdMsg); break; default : // Never handled it, so return false return false; }; } return true; } // // Called when we get a new template comand. We need to resize the canvas and // the drawing surfaces. // newTemplate(msgData : Object){ // Get the size of the new template var newSize : BaseTypes.RIVASize = new BaseTypes.RIVASize(msgData[RIVAProto.kAttr_Size]); // Set the drawing surface size this.drawSurface.width = newSize.width; this.drawSurface.height = newSize.height; this.drawSurface.style.width = newSize.width + "px"; this.drawSurface.style.height = newSize.height + "px"; // Do the same for the display and clipping surfaces this.showSurface.width = newSize.width; this.showSurface.height = newSize.height; this.showSurface.style.width = newSize.width + "px"; this.showSurface.style.height = newSize.height + "px"; // And reset our contect to get our canvases updated this.resetContext(); // // Initially fill the show surface with the surround color, so that we don't // get a flash of black before the template draws. // this.showCtx.fillStyle = this.surroundColor; this.showCtx.fillRect(0, 0, newSize.width, newSize.height); return newSize; } // // A helper to set the right and bottom half pixels with the parent DIV's background // color, since otherwise they woudln't get set because we translate the canvas over // half a pixel to get rid of the stupidity of how the canvas works. At the point // that this is called the translation has already been done, so we have to temporarily // undo it. // setLRBoundaryColor(newColor : string) { if (!newColor || (newColor === "")) newColor = "#FFFFFF"; // Save this as the new surround color this.surroundColor = newColor; this.showCtx.save(); this.drawCtx.translate(-0.5, -0.5); this.showCtx.fillStyle = this.surroundColor; this.showCtx.fillRect(this.drawSurface.width - 1, 0, 1, this.drawSurface.height); this.showCtx.fillRect(0, this.drawSurface.height - 1, this.drawSurface.width, 1); this.showCtx.restore(); } // ------------------------------------------------ // Handlers for each of the graphics commands, called by the main command // handler method above. // ------------------------------------------------ // // These are called to do a alpha blit of an image. We have one that just takes // an origin point. And another that takes the full source/target areas. // private alphaBlit(imgMsg : Object, imgCache : ImgCache.ImgCache) { // // Get the image from the image cache. In this case, we pass null for the target // image res, since we are drawing in the natural image size. So we let it // pick the default one. // var imgPath : string = imgMsg[RIVAProto.kAttr_Path]; var toDraw : HTMLImageElement = imgCache.findImg(imgPath); // If not found, give up now if (!toDraw) { if (this.doDebug) console.info("Image not found. Key=" + imgPath); return; } try { this.drawCtx.globalAlpha = imgMsg[RIVAProto.kAttr_ConstAlpha]; var tarPnt : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(imgMsg[RIVAProto.kAttr_ToPnt]); this.drawCtx.drawImage(toDraw, tarPnt.x, tarPnt.y); this.drawCtx.globalAlpha = 1.0; } catch(e) { this.drawCtx.globalAlpha = 1.0; } } private alphaBlitST(imgMsg : Object, imgCache : ImgCache.ImgCache) { // Get the image from the image cache. If not found, we do nothing var imgPath : string = imgMsg[RIVAProto.kAttr_Path]; var toDraw : HTMLImageElement = imgCache.findImg(imgPath); if (!toDraw) { if (this.doDebug) console.info("Image not found. Key=" + imgPath); return; } try { var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(imgMsg[RIVAProto.kAttr_TarArea]); var srcArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(imgMsg[RIVAProto.kAttr_SrcArea]); // Set our constant alpha to the global alpha of the context this.drawCtx.globalAlpha = imgMsg[RIVAProto.kAttr_ConstAlpha]; this.drawCtx.drawImage ( toDraw, srcArea.x, srcArea.y, srcArea.width, srcArea.height, tarArea.x, tarArea.y, tarArea.width, tarArea.height ); this.drawCtx.globalAlpha = 1.0; } catch(e) { this.drawCtx.globalAlpha = 1.0; throw(e); } } // // These are called to do a draw of an image. We have one that just takes // an origin point. And another that takes the full source/target areas. // private drawBitmap(imgMsg : Object, imgCache : ImgCache.ImgCache) { // // Get the image from the image cache. In this case, we pass null for the target // image res, since we are drawing in the natural image size. So we let it // pick the default one. // var imgPath : string = imgMsg[RIVAProto.kAttr_Path]; var toDraw : HTMLImageElement = imgCache.findImg(imgPath); // If not found, give up now if (!toDraw) { if (this.doDebug) console.info("Image not found. Key=" + imgPath); return; } // The target point to draw to var tarPnt : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(imgMsg[RIVAProto.kAttr_ToPnt]); // Get the mode out and convert that to a canvas equivalent var canvasMode : string = this.xlatBmpMode ( <RIVAProto.BmpModes>imgMsg[RIVAProto.kAttr_Mode] ); this.drawCtx.globalCompositeOperation = canvasMode; try { this.drawCtx.drawImage(toDraw, tarPnt.x, tarPnt.y); this.drawCtx.globalCompositeOperation = this.curContext.bmpMode; } catch(e) { this.drawCtx.globalCompositeOperation = this.curContext.bmpMode; throw(e); } } private drawBitmapST(imgMsg : Object, imgCache : ImgCache.ImgCache) { // // Get the image from the image cache. In this case, we pass null for the target // image res, since we are drawing in the natural image size. So we let it // pick the default one. // var imgPath : string = imgMsg[RIVAProto.kAttr_Path]; var toDraw : HTMLImageElement = imgCache.findImg(imgPath); // If not found, give up now if (!toDraw) { if (this.doDebug) console.info("Image not found. Key=" + imgPath); return; } // Get the source and target areas var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(imgMsg[RIVAProto.kAttr_TarArea]); var srcArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(imgMsg[RIVAProto.kAttr_SrcArea]); // Get the mode out and convert that to a canvas equivalent var canvasMode : string = this.xlatBmpMode ( <RIVAProto.BmpModes>imgMsg[RIVAProto.kAttr_Mode] ); this.drawCtx.globalCompositeOperation = canvasMode; try { this.drawCtx.drawImage ( toDraw, srcArea.x, srcArea.y, srcArea.width, srcArea.height, tarArea.x, tarArea.y, tarArea.width, tarArea.height ); this.drawCtx.globalCompositeOperation = this.curContext.bmpMode; } catch(e) { this.drawCtx.globalCompositeOperation = this.curContext.bmpMode; throw(e); } } // This is called when we get a draw line command private drawLine(textMsg : Object) { var saveStyle = this.drawCtx.strokeStyle; try { this.drawCtx.strokeStyle = textMsg[RIVAProto.kAttr_Color]; var fromPnt : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(textMsg[RIVAProto.kAttr_FromPnt]); var toPnt : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(textMsg[RIVAProto.kAttr_ToPnt]); this.drawCtx.beginPath(); this.drawCtx.moveTo(fromPnt.x, fromPnt.y); this.drawCtx.lineTo(toPnt.x, toPnt.y); this.drawCtx.stroke(); this.drawCtx.strokeStyle = saveStyle; } catch(e) { this.drawCtx.strokeStyle = saveStyle; throw(e); } } // // This is called to draw text in the normal (non-FX) sort of way, and for single // line text. There is a separate one for multi-line text. // private drawText(textMsg : Object) { var toDraw : string = textMsg[RIVAProto.kAttr_ToDraw]; var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(textMsg[RIVAProto.kAttr_TarArea]); var hJust : RIVAProto.HJustifys = <RIVAProto.HJustifys>textMsg[RIVAProto.kAttr_HJustify]; var vJust : RIVAProto.VJustifys = <RIVAProto.VJustifys>textMsg[RIVAProto.kAttr_VJustify]; // // In this case, we want to avoid having to redo the clip area just for this one // thing. So we will do a save/restore and just directly add the target area to the // clip path. The areas are never rounded in this case. We know any existing clip // stack is set since we are in a graphics operation. // this.drawCtx.save(); this.setRectPath(this.drawCtx, tarArea, true, 1, 1.5); this.drawCtx.clip(); try { // Make sure the current font style is set this.drawCtx.font = this.curFont.canvasFmt; // Make sure the curent context text color is set. this.drawCtx.fillStyle = this.curContext.textColor; // Call the single line helper, in fill mode this.drawSingleLineText ( toDraw, this.drawCtx, tarArea, hJust, vJust, false, null, null ); this.drawCtx.restore(); } catch(e) { this.drawCtx.restore(); throw(e); } } // // This is called when we get a command draw F/X style text. There's a lot going // on for this one, vastly complicated by the fact that we have to handle multi- // line text ourself. // private drawTextFX(textMsg : Object) { // Convert the formated area to an area object var toDraw : string = textMsg[RIVAProto.kAttr_ToDraw]; var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(textMsg[RIVAProto.kAttr_TarArea]); var fxType : RIVAProto.TextFXs = <RIVAProto.TextFXs>textMsg[RIVAProto.kAttr_Effect]; var pntOfs : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(textMsg[RIVAProto.kAttr_PntOffset]); var hJust : RIVAProto.HJustifys = <RIVAProto.HJustifys>textMsg[RIVAProto.kAttr_HJustify]; var vJust : RIVAProto.VJustifys = <RIVAProto.VJustifys>textMsg[RIVAProto.kAttr_VJustify]; var flags : number = textMsg[RIVAProto.kAttr_Flags]; // // In this case, we want to avoid having to redo the clip area just for this one // thing. So we will do a save/restore and just directly add the target area to the // clip path. The areas are never rounded in this case. This also means we don't // need to push our context, since we'll end up not changing anything. // this.drawCtx.save(); this.setRectPath(this.drawCtx, tarArea, true, 1, 1.5); this.drawCtx.clip(); try { // Make sure the current font style is set this.drawCtx.font = this.curFont.canvasFmt; // Depending on the F/X type we do different things switch(fxType) { case RIVAProto.TextFXs.DropShadow : // // This one is relatively normal. We set the canvas for drop shadow // style and just draw the text, adjusting the position to account // for the shadow offset, which can be negative or positive in either // axis. // this.drawCtx.shadowBlur = 6; this.drawCtx.shadowOffsetX = pntOfs.x; this.drawCtx.shadowOffsetY = pntOfs.y; this.drawCtx.shadowColor = textMsg[RIVAProto.kAttr_Color2]; // This uses the currently set fill color this.drawCtx.fillStyle = textMsg[RIVAProto.kAttr_Color]; // // Adjust the target area to account for the drop shadow and the // justification, since the text itself has to be bring inwards // so that the shadow ends up being what is justified. // var realArea : BaseTypes.RIVAArea = tarArea; if (pntOfs.x !== 0) realArea.deflate(Math.abs(pntOfs.x), 0); if (pntOfs.y !== 0) realArea.deflate(0, Math.abs(pntOfs.y)) // Adjust the target a bit more for the blur size if (hJust === RIVAProto.HJustifys.Left) realArea.x += 3; else if (hJust === RIVAProto.HJustifys.Right) realArea.x -= 3; if (vJust === RIVAProto.VJustifys.Top) realArea.y += 3; else if (vJust === RIVAProto.VJustifys.Bottom) realArea.y -= 3; if (flags & RIVAProto.kTextFXFlag_NoWrap) this.drawSingleLineText ( toDraw, this.drawCtx, realArea, hJust, vJust, false, null, null ); else this.drawMultiLineText(toDraw, this.drawCtx, realArea, hJust, vJust, false); break; case RIVAProto.TextFXs.GaussianBlur : break; case RIVAProto.TextFXs.Gradient : // Then draw the text in the fill style, passing along the gradient colors if (flags & RIVAProto.kTextFXFlag_NoWrap) this.drawSingleLineText ( toDraw, this.drawCtx, tarArea, hJust, vJust, false, textMsg[RIVAProto.kAttr_Color], textMsg[RIVAProto.kAttr_Color2] ); else this.drawMultiLineText(toDraw, this.drawCtx, tarArea, hJust, vJust, false); break; case RIVAProto.TextFXs.GradientRefl : break; default : throw(Error("Unknown text F/X type")); }; this.drawCtx.restore(); } catch(e) { this.drawCtx.restore(); throw(e); } } // // There's no means to do multi-line text in the Canvas API, so we have to do it // ourself. // private drawMultiText(textMsg : Object) { // Get the text to draw var toDraw : string = textMsg[RIVAProto.kAttr_ToDraw]; // Convert the formatted area to an area object var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(textMsg[RIVAProto.kAttr_TarArea]); // This uses the currently set fill color. Don't need to restore since it's the current value this.drawCtx.fillStyle = this.curContext.textColor; // // In this case, we want to avoid having to redo the clip area just for this one // thing. So we will do a save/restore and just directly add the target area to the // clip path. The areas are never rounded in this case. This also means we don't // need to push our context, since we'll end up not changing anything. // this.drawCtx.save(); this.setRectPath(this.drawCtx, tarArea, true, 1, 1.5); this.drawCtx.clip(); try { // Make sure the current font style is set this.drawCtx.font = this.curFont.canvasFmt; this.drawMultiLineText ( toDraw, this.drawCtx, tarArea, <RIVAProto.HJustifys>textMsg[RIVAProto.kAttr_HJustify], <RIVAProto.VJustifys>textMsg[RIVAProto.kAttr_VJustify], false ); this.drawCtx.restore(); } catch(e) { this.drawCtx.restore(); throw(e); } } // // This is called to draw a progress bar. We get the basic image, and we // have to use that to create the masked image, and then draw as much of // that as required to indicate the current percentage value, filling the // rest with the background color. // // We have to use a separate canvas to do this, then we'll blit it back. // private drawPBar(pbarMsg : Object, imgCache : ImgCache.ImgCache) { // Get the image from the image cache. If not found, we do nothing var imgPath : string = pbarMsg[RIVAProto.kAttr_Path]; var toDraw : HTMLImageElement = imgCache.findImg(imgPath); if (!toDraw) return; // Get the source and target areas, and the percentage value var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(pbarMsg[RIVAProto.kAttr_TarArea]); var srcArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(pbarMsg[RIVAProto.kAttr_SrcArea]); var pbPercent : number = pbarMsg[RIVAProto.kAttr_Percent]; // Use the temp buffering canvas for the fill var dbufFill : HTMLCanvasElement = this.getDBufCanvas(srcArea.size()); var fillCtx : CanvasRenderingContext2D = dbufFill.getContext("2d"); // // Now get the two colors and do a gradient fill of the area. We have to convert // the generic direction enum to one of our gradient enums and flip the colors // as required. And we need to figure out the area that we need to fill, based // on color and direction. // var pbDir : RIVAProto.Dirs = <RIVAProto.Dirs>pbarMsg[RIVAProto.kAttr_Dir]; var clr1 : string; var clr2 : string; var perArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(null); var fillArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(null); var fillDir : RIVAProto.GradDirs; switch(pbDir) { case RIVAProto.Dirs.Down : fillDir = RIVAProto.GradDirs.Vertical; clr1 = pbarMsg[RIVAProto.kAttr_Color]; clr2 = pbarMsg[RIVAProto.kAttr_Color2]; break; case RIVAProto.Dirs.Left : fillDir = RIVAProto.GradDirs.Horizontal; clr1 = pbarMsg[RIVAProto.kAttr_Color]; clr2 = pbarMsg[RIVAProto.kAttr_Color2]; break; case RIVAProto.Dirs.Right : fillDir = RIVAProto.GradDirs.Horizontal; clr2 = pbarMsg[RIVAProto.kAttr_Color]; clr1 = pbarMsg[RIVAProto.kAttr_Color2]; break; case RIVAProto.Dirs.Up : fillDir = RIVAProto.GradDirs.Vertical; clr2 = pbarMsg[RIVAProto.kAttr_Color]; clr1 = pbarMsg[RIVAProto.kAttr_Color2]; break; default : throw(Error("Unknown Dir value")); }; // Do two optimizations for 0 and 100%, else the general scenario if (pbPercent === 0) { fillArea.width = srcArea.width; fillArea.height = srcArea.height; } else if (pbPercent === 100) { perArea.width = srcArea.width; perArea.height = srcArea.height; } else { switch(pbDir) { case RIVAProto.Dirs.Down : // Percent area goes from bottom, up by percentage perArea.width = srcArea.width; perArea.height = Math.floor(srcArea.height * pbPercent); perArea.y = srcArea.bottom() - perArea.height; // Fill area gets the reset fillArea.width = srcArea.width; fillArea.height = srcArea.height - perArea.height; break; case RIVAProto.Dirs.Left : // Percent area goes from left over by percentage amount perArea.height = srcArea.height; perArea.width = Math.floor(srcArea.width * pbPercent); // Fill area gets the rest fillArea.height = srcArea.height; fillArea.x = perArea.right() + 1; fillArea.width = srcArea.width - perArea.width; break; case RIVAProto.Dirs.Right : // Percent area goes from right back by percentage amount perArea.height = srcArea.height; perArea.width = Math.floor(srcArea.width * pbPercent); perArea.x = srcArea.right() - perArea.width; fillArea.height = srcArea.height; fillArea.width = srcArea.width - perArea.width; break; case RIVAProto.Dirs.Up : // Percent area goes from top, down by percentage amount perArea.width = srcArea.width; perArea.height = Math.floor(srcArea.height * pbPercent); // Fill area gets the reset fillArea.width = srcArea.width; fillArea.y = perArea.bottom() + 1; fillArea.height = srcArea.height - perArea.height; break; default : throw(Error("Unknown Dir value")); }; } this.pushContext(); try { // Gradient fill the percent area if not 0% // fillCtx.globalAlpha = 1.0; // this.drawCtx.globalAlpha = 1.0; // And do a regular fill on the fill area if not 100% if (pbPercent !== 100) { fillCtx.clearRect(0, 0, srcArea.width, srcArea.height); fillCtx.globalCompositeOperation = "source-over"; fillCtx.drawImage(toDraw, 0, 0); fillCtx.globalCompositeOperation = "source-in"; fillCtx.fillStyle = pbarMsg[RIVAProto.kAttr_BgnColor]; fillCtx.fillRect(fillArea.x, fillArea.y, fillArea.width, fillArea.height); this.drawCtx.drawImage ( dbufFill, fillArea.x, fillArea.y, fillArea.width, fillArea.height, tarArea.x + fillArea.x, tarArea.y + fillArea.y, fillArea.width, fillArea.height ); } if (pbPercent !== 0) { fillCtx.clearRect(0, 0, srcArea.width, srcArea.height); fillCtx.globalCompositeOperation = "source-over"; fillCtx.drawImage(toDraw, 0, 0); fillCtx.globalCompositeOperation = "source-in"; this.doGradientFill(fillCtx, fillDir, perArea, clr1, clr2); this.drawCtx.drawImage ( dbufFill, perArea.x, perArea.y, perArea.width, perArea.height, tarArea.x + perArea.x, tarArea.y + perArea.y, perArea.width, perArea.height ); } this.popContext(); } catch(e) { this.popContext(); throw(e); } } // // This is called to do an area fill. We inflate the area by one because the canvas // doesn't include the boundary while the IV assumes it does. // private fillArea(fillMsg : Object) { var saveStyle = this.drawCtx.fillStyle; try { this.drawCtx.fillStyle = fillMsg[RIVAProto.kAttr_Color]; var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(fillMsg[RIVAProto.kAttr_TarArea]); var rounding = fillMsg[RIVAProto.kAttr_Rounding]; if (rounding !== 0) { // We have to do rounded ones, so set the rounded path and then fill it this.setRoundedPath(this.drawCtx, tarArea, rounding, true, 0.5, 0.5); this.drawCtx.fill(); } else { this.setRectPath(this.drawCtx, tarArea, true, 0.5, 0.5); this.drawCtx.fill(); } this.drawCtx.fillStyle = saveStyle; } catch(e) { this.drawCtx.fillStyle = saveStyle; throw(e); } } // // This guy does a tiled blit of an image, to fill the passed area. We get a point that // represents the origin point in the pattern, but currently it's not used. The target // area is the whole area to fill, since we need to know where the fill starts. We just // allow clipping to get rid of any that aren't needed. // private fillWithBmp(fillMsg : Object, imgCache : ImgCache.ImgCache) { // Get the image from the image cache. If not found, we do nothing var imgPath : string = fillMsg[RIVAProto.kAttr_Path]; var toDraw : ImgCache.ImgCacheItem = imgCache.findItem(imgPath); if (!toDraw) return; // Get the target area to fill var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(fillMsg[RIVAProto.kAttr_TarArea]); // // Adjust it to account for canvas silliness, for reasons unknown. It only seems to // be required on IE, but doesn't hurt any others. // tarArea.x -= 0.5; tarArea.y -= 1; tarArea.width += 1; tarArea.height += 1; // // In this case, we want to avoid having to redo the clip area just for this one // thing. So we will do a save/restore and just directly add the target area to the // clip path. The areas are never rounded in this case. This also means we don't // need to push our context, since we'll end up not changing anything. // this.drawCtx.save(); this.setRectPath(this.drawCtx, tarArea, true, 1.5, 1.5); this.drawCtx.clip(); try { // Start out at the origin of the target area var curOrg : BaseTypes.RIVAPoint = new BaseTypes.RIVAPoint(null); curOrg.set(tarArea.x, tarArea.y); // Do a double loop until the current origin Y ends up past the target area bottom var endBottom : number = tarArea.bottom(); var endRight : number = tarArea.right(); // These are never alpha based or have transparency, so just a simple copy while (curOrg.y <= endBottom) { curOrg.x = tarArea.x; while (curOrg.x <= endRight) { this.drawCtx.drawImage(toDraw.imgElem, curOrg.x, curOrg.y); curOrg.x += toDraw.imgRes.width; } curOrg.y += toDraw.imgRes.height; } this.drawCtx.restore(); } catch(e) { this.drawCtx.restore(); throw(e); } } // // This is called to do a gradient area fill. The IV supports four directions, which // are easy to convert to the two points needed for the canvas. // // The message includes a rounding value, but the IV engine never uses that because // the CIDGraphDev graphics device interface doesn't support it. The IV engine just // sets a rounded clip and does a fill for now. // private gradientFill(fillMsg : Object) { // Get the target area var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(fillMsg[RIVAProto.kAttr_TarArea]); // Convert the direction var fillDir : RIVAProto.GradDirs = <RIVAProto.GradDirs>fillMsg[RIVAProto.kAttr_Dir]; // Call the private helper that does the actual work this.doGradientFill ( this.drawCtx, fillDir, tarArea, fillMsg[RIVAProto.kAttr_Color], fillMsg[RIVAProto.kAttr_Color2] ); } // Stroke an area, handing rounding if needed strokeArea(msgData : Object) { var saveLine = this.drawCtx.lineWidth; var saveStyle = this.drawCtx.strokeStyle; try { // We have to add half a pixel to get appropriate results this.drawCtx.lineWidth = msgData[RIVAProto.kAttr_Width] + 0.5; this.drawCtx.strokeStyle = msgData[RIVAProto.kAttr_Color]; var tarArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(msgData[RIVAProto.kAttr_TarArea]); var rounding = msgData[RIVAProto.kAttr_Rounding]; if (rounding !== 0) { // Set the rounded path and then we can stroke it this.setRoundedPath(this.drawCtx, tarArea, rounding, true); this.drawCtx.stroke(); } else { this.setRectPath(this.drawCtx, tarArea, true); this.drawCtx.stroke(); } this.drawCtx.lineWidth = saveLine; this.drawCtx.strokeStyle = saveStyle; } catch(e) { this.drawCtx.lineWidth = saveLine; this.drawCtx.strokeStyle = saveStyle; throw(e); } } // ------------------------------------------------ // Helper methods used by the other drawing stuff above. None of these will do any // clipping or push/pop the context, assuming that the caller does anything that // is needed. // ------------------------------------------------ private doGradientFill( tarCtx : CanvasRenderingContext2D, fillDir : RIVAProto.GradDirs, tarArea : BaseTypes.RIVAArea, clr1 : string, clr2 : string) { var saveStyle = tarCtx.fillStyle; try { // Depending on the direction, set up the two points var newGrad : CanvasGradient = null; switch(fillDir) { case RIVAProto.GradDirs.DownDiagonal : newGrad = tarCtx.createLinearGradient ( tarArea.x, tarArea.y, tarArea.right(), tarArea.bottom() ); break; case RIVAProto.GradDirs.Horizontal : newGrad = tarCtx.createLinearGradient ( tarArea.x, tarArea.y, tarArea.right(), tarArea.y ); break; case RIVAProto.GradDirs.UpDiagonal : newGrad = tarCtx.createLinearGradient ( tarArea.x, tarArea.bottom(), tarArea.right(), tarArea.y ); break; case RIVAProto.GradDirs.Vertical : newGrad = tarCtx.createLinearGradient ( tarArea.x, tarArea.y, tarArea.x, tarArea.bottom() ); break; default : throw(Error("Unknown gradient fill direction")); }; // Add the two color stops required newGrad.addColorStop(0, clr1); newGrad.addColorStop(1, clr2); // Set the gradient and do the fill tarCtx.fillStyle = newGrad; tarCtx.fillRect(tarArea.x, tarArea.y, tarArea.width, tarArea.height); tarCtx.fillStyle = saveStyle; } catch(e) { tarCtx.fillStyle = saveStyle; throw(e); } } // // The canvas doesn't support multi-line text, so we have to do it ourself. And // this is greatly complicated by the fact that we have to deal with multi-line // text in a variable of scenarios. Sometimes we need to draw it, sometimes we // need to make it into a clip path that we can fill, sometimes we need to line // stroke it. Sometimes we might need to draw it into a separate canvas for // manipulation and we'll blit it back later. // // So this helper method does the grunt work of either filling or stroking the // text into a target area. // // The caller has to: // // 1. Set any clip area he wants // 2. Set the fill style if we are drawing // 3. Set the stroke style if outlining // 4. Set the font that is to be used // // We return the ultimate area of the text, some of which of course may be off // of the target area and hence clipped. The horziontal is always just the target // area. it's only the vertical that is adjusted. // drawMultiLineText( toDraw : string, tarCtx : CanvasRenderingContext2D, tarArea : BaseTypes.RIVAArea, hJust : RIVAProto.HJustifys, vJust : RIVAProto.VJustifys, strokeIt : boolean) { // // Optimize if the string is empty. Otherwise, we will have words, since deal with // white space as well. // if (toDraw.length === 0) return; // // Split the input into separate words. But, we have to keep the actual spaces as // words as well, so we can't just do split(). The spaces are important. And we need // to treat new lines as separate words, and expand tabs to spaces. // var words : Array<string> = new Array<string>(); var curWord : string; var charInd : number = 0; var charCnt : number = toDraw.length; while (charInd < charCnt) { // Get the first character of this round var curChar : number = toDraw.charCodeAt(charInd++); // Based on what it is, we know what to do next if (curChar === 0xD) { // The next char should be LF, so eat that and push them both charInd++; words.push("\r\n"); } else if (curChar === 0x9) { // Push four spaces words.push(" "); } else if (curChar === 0x20) { // Make this and any subsequent spaces a word curWord = " "; while (charInd < charCnt) { curChar = toDraw.charCodeAt(charInd); if (curChar != 0x20) break; curWord += " "; charInd++; } words.push(curWord); } else { // Make any subsequent non-spaces a word curWord = String.fromCharCode(curChar); while (charInd < charCnt) { curChar = toDraw.charCodeAt(charInd); if ((curChar === 0x20) || (curChar === 0xD) || (curChar === 0x9)) break; curWord += String.fromCharCode(curChar); charInd++; } words.push(curWord); } } var areaWidth = tarArea.width; var leftPos : number = tarArea.x; tarCtx.textAlign = "left"; tarCtx.textBaseline = "top"; // Now measure all of the words var wordLens : Array<number> = new Array<number>(); for (var wInd : number = 0; wInd < words.length; wInd++) wordLens.push(tarCtx.measureText(words[wInd]).width); // // We have to break it into lines, because we need to position the whole // thing vertically. So we need to now how many lines we have before we // start. We remember the lengths so we don't have to do them again when // we draw. // var curWidth : number = 0; var lines : Array<string> = new Array<string>(); var lineLens : Array<number> = new Array<number>(); var totalLineHeight : number = 0; { var curLine : string; var curWordInd : number = 0; var curWordWidth : number = 0; var spaceWidth : number = tarCtx.measureText(' ').width; while (curWordInd < words.length) { // Let's accumulate a line's worth of text curLine = ""; curWidth = 0; while (curWordInd < words.length) { var curWord = words[curWordInd]; // If a new line, then break out if (curWord === "\r\n") { curWordInd++ break; } // Get the current word width var testWidth = wordLens[curWordInd]; // // If that is beyond the width, then we can't do this word, unless it's // the only word on this line (though maybe clipped due to length.) If // we didn't force at least one word, we'd never move forward and get // caught in a loop. // if ((curWidth + testWidth > areaWidth) && (curWidth != 0)) break; curLine += curWord; curWidth += testWidth; curWordInd++; } totalLineHeight += this.curFontHeight; lines.push(curLine); lineLens.push(curWidth); } } // // Calculate where the first line will go. It may be up above the target // area, which is fine. We'll ignore those when we draw below. // var curYPos : number = 0; var bottomPos : number = tarArea.bottom() + 1; switch(vJust) { case RIVAProto.VJustifys.Top : // We just start at the top of the area curYPos = tarArea.y; break; case RIVAProto.VJustifys.Center : // Calculate half the full text height, minus the mid point of the area curYPos = tarArea.vCenter() - (totalLineHeight / 2); break; case RIVAProto.VJustifys.Bottom : // The bottom of the area minus the total line height curYPos = bottomPos - totalLineHeight; break; default : alert("Unknown vertical text justification"); break; }; // // Now let's loop through the lines and draw them. We will just move down // one text height each time, and position the line correcty in the // horizontal direction. // var curXPos : number; var topPos : number = tarArea.y; for (var lineInd : number = 0; lineInd < lines.length; lineInd++) { // If this line is fully above the top, then skip it. Else draw it if (curYPos + this.curFontHeight > topPos) { switch(hJust) { case RIVAProto.HJustifys.Left : curXPos = tarArea.x; break; case RIVAProto.HJustifys.Center : curXPos = tarArea.hCenter() - (lineLens[lineInd] / 2); break; case RIVAProto.HJustifys.Right : curXPos = tarArea.right() - lineLens[lineInd]; break; default : alert("Unknown horizontal text justification"); break; }; // Either stroke or fill if (strokeIt) tarCtx.strokeText(lines[lineInd], curXPos, curYPos); else tarCtx.fillText(lines[lineInd], curXPos, curYPos); } // Move down one text height curYPos += this.curFontHeight; // If we have now gone beyond the bottom, we can stop if (curYPos > bottomPos) break; } } // // As above for multi-line text, this is a helper to handle the various types // of scenarios where we need to draw single line text. Sometimes to draw it, // sometimes to stroke it. The caller provides a context to draw into, which // may be ours or may be one used for double buffering. // // The caller must: // // 1. Set any clip area he wants // 2. Set the fill style if we are drawing // 3. Set the stroke style if outlining // 4. Set the font that is to be used // // They can give us two gradient colors optionally. If they are not null, then we // will apply that gradient to where the actual text ended up being drawn. // drawSingleLineText( toDraw : string, tarCtx : CanvasRenderingContext2D, tarArea : BaseTypes.RIVAArea, hJust : RIVAProto.HJustifys, vJust : RIVAProto.VJustifys, strokeIt : boolean, gradClr1 : string, gradClr2 : string) { var saveAlign = tarCtx.textAlign; var saveBaseline = tarCtx.textBaseline; var saveStyle = strokeIt ? tarCtx.strokeStyle : tarCtx.fillStyle; try { // // For horizontal, we start wtih the left area position, and we always draw // left aligned. We'll adjust the left position as needed. // var leftPos : number = tarArea.x; tarCtx.textAlign = "left"; switch(hJust) { case RIVAProto.HJustifys.Left : // It's already OK break; case RIVAProto.HJustifys.Center : var textMtr : TextMetrics = tarCtx.measureText(toDraw); leftPos = tarArea.hCenter() - (Math.floor(textMtr.width) / 2); break; case RIVAProto.HJustifys.Right : var textMtr : TextMetrics = tarCtx.measureText(toDraw); leftPos = tarArea.right() - (Math.floor(textMtr.width) + 1); break; default : alert("Unknown horizontal text justification"); break; }; // // We always draw with the baseline set to middle and adjust the y // ourself, to put it where we want. We will adjust the bottom position // as required. // tarCtx.textBaseline = "middle"; var bottomPos : number; switch(vJust) { case RIVAProto.VJustifys.Top : // // We have to set the bottom point to the top plus half the height of // the text. // bottomPos = tarArea.y + (this.curFontHeight / 2); break; case RIVAProto.VJustifys.Center : // The bottom position is vertical bottomPos = tarArea.vCenter(); break; case RIVAProto.VJustifys.Bottom : bottomPos = tarArea.bottom() - ((this.curFontHeight / 2) + 1); break; default : alert("Unknown vertical text justification"); break; }; // If we have a gradient, then set it up for where the actual text went if (gradClr1 && gradClr2) { var gradFill : CanvasGradient = tarCtx.createLinearGradient ( tarArea.x, bottomPos - (this.curFontHeight / 2), tarArea.x, bottomPos + (this.curFontHeight / 2) ); gradFill.addColorStop(0, gradClr1); gradFill.addColorStop(1, gradClr2); if (strokeIt) tarCtx.strokeStyle = gradFill; else tarCtx.fillStyle = gradFill; } if (strokeIt) tarCtx.strokeText(toDraw, leftPos, bottomPos); else tarCtx.fillText(toDraw, leftPos, bottomPos); tarCtx.textAlign = saveAlign; tarCtx.textBaseline = saveBaseline; if (strokeIt) tarCtx.strokeStyle = saveStyle; else tarCtx.fillStyle = saveStyle; } catch(e) { tarCtx.textAlign = saveAlign; tarCtx.textBaseline = saveBaseline; if (strokeIt) tarCtx.strokeStyle = saveStyle; else tarCtx.fillStyle = saveStyle; throw(e); } } // // These methods handle pushing and popping the clip stack. They will check to see // if the change is important (see class comments above) and comit any outstanding // operations (within the clipping regime they would have been drawn in.) // popClipStack() { try { var curTop : number = this.clipStack.length; if (curTop !== 0) { var prevArea = this.clipStack.pop(); curTop--; // // If the stack is empty now, or the previous area and the new top are // not equal, then remember we need to rebuild it. // if ((this.clipStack.length === 0) || !prevArea.sameArea(this.clipStack[curTop - 1])) this.clipPathRebuildNeeded = true; } else { throw Error("The clip area stack underflowed"); } } catch(e) { if (this.doDebug) console.error("Exception in pop clip stack: " + e); } } private pushClipArea(newArea : BaseTypes.RIVAArea) { var copyArea : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(); copyArea.setFrom(newArea); this.clipStack.push(copyArea); // // If the new area is different from the current stop of stack then set the // rebuild needed flag. // var curTop : number = this.clipStack.length; if ((curTop === 1) || !this.clipStack[curTop - 2].sameArea(newArea)) this.clipPathRebuildNeeded = true; } rebuildClipArea() { // Clear the rebuild needed flag now this.clipPathRebuildNeeded = false; // // Do a restore to get rid of any previous clip area, and save again. Re-apply // the current context and font, since this will whack it. // this.drawCtx.restore(); this.drawCtx.save(); this.curContext.applyTo(this.drawCtx); this.drawCtx.font = this.curFont.canvasFmt; // While doing this, we untranslate this.drawCtx.translate(-0.5, -0.5); // // Now we just apply them in sequence. The default is that they combine according // to their overlapping areas, which is what we want. // // The clip paths are non-inclusive so we inflate it, plus we add an extra 0.5 to // the lower/right sides because it seems required to avoid issues. // for (var index = 0; index < this.clipStack.length; index++) { var curArea = this.clipStack[index]; if (curArea.rounding !== 0) this.setRoundedPath(this.drawCtx, curArea, curArea.rounding, true, 1, 1.5); else this.setRectPath(this.drawCtx, curArea, true, 1, 1.5); this.drawCtx.clip(); } // Now restore the translation this.drawCtx.translate(0.5, 0.5); } // // Pops our context stack, storing the popped value as our current context, and // applies the stored settings to the context. // popContext() { this.curContext = this.ctxStack.pop(); this.curContext.applyTo(this.drawCtx); // Make sure we've kept our stacks in sync if (this.fontStack.length != this.curContext.fontStackSize) { alert("Font stack size mismatch on pop"); } if (this.clipStack.length != this.curContext.clipStackSize) { alert("Clip stack size mismatch on pop"); } } // Pushes a copy of our current context onto the context stack pushContext() { // Push a copy of our current context object var newCtx : GraphCtx = new GraphCtx(this.curContext); // // Save the current size of the other stacks so that we can verify // later upon pop that correct nesting has been maintained. // newCtx.fontStackSize = this.fontStack.length; newCtx.clipStackSize = this.clipStack.length; this.ctxStack.push(newCtx); } // Called when we get a push font command private pushFont(fontMsg : Object) { // Push the current font this.fontStack.push(this.curFont); // Create a new font object from the incoming msg and store as the new font this.curFont = new FontInfo(fontMsg); // // Set our inter-line spacing, which we set to two larger than the set height // to better match Windows' output. // this.curFontHeight = this.curFont.height + 2; // Set the new font styles on the canvas this.drawCtx.font = this.curFont.canvasFmt; } // // (re)sets our graphical context info to defaults. We set up our context info // and get a new context object to insure we start with a clean slate. // resetContext() { this.clipStack.length = 0; this.fontStack.length = 0; this.ctxStack.length = 0; // Create our display and drawing contexts from their respective canvi this.drawCtx = this.drawSurface.getContext("2d", { alpha : false }); this.showCtx = this.showSurface.getContext("2d", { alpha : false }); // We want image smoothing off this.drawCtx.imageSmoothingEnabled = false; // Default other things this.drawCtx.lineWidth = 1; // // Now, get around the stupid way the canvas deals with lines. NOTE that we don't // do the show context because our blits will go to the translated position in // his coordinate system, so it will already be translated. // this.drawCtx.translate(0.5, 0.5); // Store a default font this.curFont = new FontInfo(null); this.drawCtx.font = this.curFont.canvasFmt; this.curFontHeight = this.curFont.height; // Reset our current context to be a new initial one this.curContext.reset(); // Do an initial save of the context now this.drawCtx.save(); } // Set a path around an area. setRectPath(tarCtx : CanvasRenderingContext2D, tarRect : BaseTypes.RIVAArea, doPath : boolean, offsetUL : number = 0, offsetLR : number = 0) { var x = tarRect.x - offsetUL; var y = tarRect.y - offsetUL; var right = tarRect.right() + offsetLR; var bottom = tarRect.bottom() + offsetLR; if (doPath) tarCtx.beginPath(); tarCtx.moveTo(x, y); tarCtx.lineTo(right, y); tarCtx.lineTo(right, bottom); tarCtx.lineTo(x, bottom); tarCtx.lineTo(x, y); if (doPath) tarCtx.closePath(); } // // The canvas doesn't support rounded rectanges, so we do it ourself. We need // to do this for both stroking and filling, so we split this out. This sets // the path. They caller can ask us to begin/close path around it or they can // use as part of a larger path. // setRoundedPath( tarCtx : CanvasRenderingContext2D, tarArea : BaseTypes.RIVAArea, rounding : number, doPath : boolean, offsetUL : number = 0, offsetLR : number = 0) { // We have to implement this ourself if (tarArea.width < 2 * rounding) rounding = tarArea.width / 2; if (tarArea.height < 2 * rounding) rounding = tarArea.height / 2; var x = tarArea.x - offsetUL; var y= tarArea.y - offsetUL; var right = tarArea.right() + offsetLR; var bottom = tarArea.bottom() + offsetLR; if (doPath) tarCtx.beginPath(); tarCtx.moveTo(x + rounding, y); tarCtx.arcTo(right, y, right, bottom, rounding); tarCtx.arcTo(right, bottom, x, bottom, rounding); tarCtx.arcTo(x, bottom, x, y, rounding); tarCtx.arcTo(x, y, right, y, rounding); if (doPath) tarCtx.closePath(); } // Translate a RIVA bitmap mode into a canvas global composite mode xlatBmpMode(toXlat : RIVAProto.BmpModes) : string { var retVal : string; switch(toXlat) { case RIVAProto.BmpModes.SrcCopy : retVal = "source-over"; break; case RIVAProto.BmpModes.DstInvert : case RIVAProto.BmpModes.PatCopy : case RIVAProto.BmpModes.PatInvert : case RIVAProto.BmpModes.SrcAnd : case RIVAProto.BmpModes.SrcErase : case RIVAProto.BmpModes.SrcPaint : default : console.error("Unknown bitmap mode"); retVal = "source-over"; break; }; return retVal; } // // Called to get our temp buffering canvas, faulting it in or upsizing it // if needed. // getDBufCanvas(reqSize : BaseTypes.RIVASize) : HTMLCanvasElement { if (!this.tmpSurface || (this.tmpSurface.width < reqSize.width) || (this.tmpSurface.height < reqSize.height)) { this.tmpSurface = document.createElement("canvas"); // Set the size and the style size to match this.tmpSurface.width = reqSize.width; this.tmpSurface.height = reqSize.height; // And set the size of the canvas element to match this.tmpSurface.style.width = reqSize.width + "px"; this.tmpSurface.style.height = reqSize.height + "px"; } return this.tmpSurface; } }
the_stack
import { Awaitable, Context, Log, MiniflareError, ThrowingEventTarget, TypedEventListener, ValueOf, prefixError, } from "@miniflare/shared"; import { Response as BaseResponse } from "undici"; import { DOMException } from "./domexception"; import { Request, Response, fetch, withWaitUntil } from "./http"; export type FetchErrorCode = | "ERR_RESPONSE_TYPE" // respondWith returned non Response promise | "ERR_NO_UPSTREAM" // No upstream for passThroughOnException() | "ERR_NO_HANDLER" // No "fetch" event listener registered | "ERR_NO_RESPONSE"; // No "fetch" event listener called respondWith export class FetchError extends MiniflareError<FetchErrorCode> {} const SUGGEST_HANDLER = 'calling addEventListener("fetch", ...)'; const SUGGEST_HANDLER_MODULES = "exporting a default object containing a `fetch` function property"; const SUGGEST_RES = "calling `event.respondWith()` with a `Response` or `Promise<Response>` in your handler"; const SUGGEST_RES_MODULES = "returning a `Response` in your handler"; const SUGGEST_GLOBAL_BINDING_MODULES = "Attempted to access binding using global in modules." + "\nYou must use the 2nd `env` parameter passed to exported " + "handlers/Durable Object constructors, or `context.env` with " + "Pages Functions."; const kResponse = Symbol("kResponse"); const kPassThrough = Symbol("kPassThrough"); const kWaitUntil = Symbol("kWaitUntil"); const kSent = Symbol("kSent"); export class FetchEvent extends Event { readonly request: Request; [kResponse]?: Promise<Response | BaseResponse>; [kPassThrough] = false; readonly [kWaitUntil]: Promise<unknown>[] = []; [kSent] = false; constructor(type: "fetch", init: { request: Request }) { super(type); this.request = init.request; } respondWith(response: Awaitable<Response | BaseResponse>): void { if (!(this instanceof FetchEvent)) { throw new TypeError("Illegal invocation"); } if (this[kResponse]) { throw new DOMException( "FetchEvent.respondWith() has already been called; it can only be called once.", "InvalidStateError" ); } if (this[kSent]) { throw new DOMException( "Too late to call FetchEvent.respondWith(). It must be called synchronously in the event handler.", "InvalidStateError" ); } this.stopImmediatePropagation(); this[kResponse] = Promise.resolve(response); } passThroughOnException(): void { if (!(this instanceof FetchEvent)) { throw new TypeError("Illegal invocation"); } this[kPassThrough] = true; } waitUntil(promise: Awaitable<any>): void { if (!(this instanceof FetchEvent)) { throw new TypeError("Illegal invocation"); } this[kWaitUntil].push(Promise.resolve(promise)); } } export class ScheduledEvent extends Event { readonly scheduledTime: number; readonly cron: string; readonly [kWaitUntil]: Promise<unknown>[] = []; constructor( type: "scheduled", init: { scheduledTime: number; cron: string } ) { super(type); this.scheduledTime = init.scheduledTime; this.cron = init.cron; } waitUntil(promise: Promise<any>): void { if (!(this instanceof ScheduledEvent)) { throw new TypeError("Illegal invocation"); } this[kWaitUntil].push(promise); } } export class ExecutionContext { readonly #event: FetchEvent | ScheduledEvent; constructor(event: FetchEvent | ScheduledEvent) { this.#event = event; } passThroughOnException(): void { if (!(this instanceof ExecutionContext)) { throw new TypeError("Illegal invocation"); } if (this.#event instanceof FetchEvent) this.#event.passThroughOnException(); } waitUntil(promise: Awaitable<any>): void { if (!(this instanceof ExecutionContext)) { throw new TypeError("Illegal invocation"); } this.#event.waitUntil(promise); } } export class ScheduledController { constructor( public readonly scheduledTime: number, public readonly cron: string ) {} } export type ModuleFetchListener = ( request: Request, env: Context, ctx: ExecutionContext ) => Response | Promise<Response>; export type ModuleScheduledListener = ( controller: ScheduledController, env: Context, ctx: ExecutionContext ) => any; export const kAddModuleFetchListener = Symbol("kAddModuleFetchListener"); export const kAddModuleScheduledListener = Symbol( "kAddModuleScheduledListener" ); export const kDispatchFetch = Symbol("kDispatchFetch"); export const kDispatchScheduled = Symbol("kDispatchScheduled"); export const kDispose = Symbol("kDispose"); export class PromiseRejectionEvent extends Event { readonly promise: Promise<any>; readonly reason?: any; constructor( type: "unhandledrejection" | "rejectionhandled", init: { promise: Promise<any>; reason?: any } ) { super(type, { cancelable: true }); this.promise = init.promise; this.reason = init.reason; } } export type WorkerGlobalScopeEventMap = { fetch: FetchEvent; scheduled: ScheduledEvent; unhandledrejection: PromiseRejectionEvent; rejectionhandled: PromiseRejectionEvent; }; export class WorkerGlobalScope extends ThrowingEventTarget<WorkerGlobalScopeEventMap> {} // true will be added to this set if #logUnhandledRejections is true so we // don't remove the listener on removeEventListener, and know to dispose it. type PromiseListenerSetMember = | TypedEventListener<PromiseRejectionEvent> | boolean; type PromiseListener = | { name: "unhandledRejection"; set: Set<PromiseListenerSetMember>; listener: (reason: any, promise: Promise<any>) => void; } | { name: "rejectionHandled"; set: Set<PromiseListenerSetMember>; listener: (promise: Promise<any>) => void; }; export class ServiceWorkerGlobalScope extends WorkerGlobalScope { readonly #log: Log; readonly #bindings: Context; readonly #modules?: boolean; readonly #logUnhandledRejections?: boolean; #calledAddFetchEventListener = false; readonly #unhandledRejection: PromiseListener; readonly #rejectionHandled: PromiseListener; // Global self-references readonly global = this; readonly self = this; constructor( log: Log, globals: Context, bindings: Context, modules?: boolean, logUnhandledRejections?: boolean ) { super(); this.#log = log; this.#bindings = bindings; this.#modules = modules; this.#logUnhandledRejections = logUnhandledRejections; this.#unhandledRejection = { name: "unhandledRejection", set: new Set(), listener: this.#unhandledRejectionListener, }; this.#rejectionHandled = { name: "rejectionHandled", set: new Set(), listener: this.#rejectionHandledListener, }; // If we're logging unhandled rejections, register the process-wide listener if (this.#logUnhandledRejections) { this.#maybeAddPromiseListener(this.#unhandledRejection, true); } // Only including bindings in global scope if not using modules Object.assign(this, globals); if (modules) { // Error when trying to access bindings using the global in modules mode for (const key of Object.keys(bindings)) { // @cloudflare/kv-asset-handler checks the typeof these keys which // triggers an access. We want this typeof to return "undefined", not // throw, so skip these specific keys. if (key === "__STATIC_CONTENT" || key === "__STATIC_CONTENT_MANIFEST") { break; } Object.defineProperty(this, key, { get() { throw new ReferenceError( `${key} is not defined.\n${SUGGEST_GLOBAL_BINDING_MODULES}` ); }, }); } } else { Object.assign(this, bindings); } } addEventListener = <Type extends keyof WorkerGlobalScopeEventMap>( type: Type, listener: TypedEventListener<WorkerGlobalScopeEventMap[Type]> | null, options?: AddEventListenerOptions | boolean ): void => { if (this.#modules) { throw new TypeError( "Global addEventListener() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module." ); } if (type === "fetch") this.#calledAddFetchEventListener = true; // Register process wide unhandledRejection/rejectionHandled listeners if // not already done so if (type === "unhandledrejection" && listener) { this.#maybeAddPromiseListener(this.#unhandledRejection, listener); } if (type === "rejectionhandled" && listener) { this.#maybeAddPromiseListener(this.#rejectionHandled, listener); } super.addEventListener(type, listener, options); }; removeEventListener = <Type extends keyof WorkerGlobalScopeEventMap>( type: Type, listener: TypedEventListener<WorkerGlobalScopeEventMap[Type]> | null, options?: EventListenerOptions | boolean ): void => { if (this.#modules) { throw new TypeError( "Global removeEventListener() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module." ); } // Unregister process wide rejectionHandled/unhandledRejection listeners if // no longer needed and not already done so if (type === "unhandledrejection" && listener) { this.#maybeRemovePromiseListener(this.#unhandledRejection, listener); } if (type === "rejectionhandled" && listener) { this.#maybeRemovePromiseListener(this.#rejectionHandled, listener); } super.removeEventListener(type, listener, options); }; dispatchEvent = (event: ValueOf<WorkerGlobalScopeEventMap>): boolean => { if (this.#modules) { throw new TypeError( "Global dispatchEvent() cannot be used in modules. Instead, event " + "handlers should be declared as exports on the root module." ); } return super.dispatchEvent(event); }; [kAddModuleFetchListener](listener: ModuleFetchListener): void { this.#calledAddFetchEventListener = true; super.addEventListener("fetch", (e) => { const ctx = new ExecutionContext(e); const res = listener(e.request, this.#bindings, ctx); e.respondWith(res); }); } [kAddModuleScheduledListener](listener: ModuleScheduledListener): void { super.addEventListener("scheduled", (e) => { const controller = new ScheduledController(e.scheduledTime, e.cron); const ctx = new ExecutionContext(e); const res = listener(controller, this.#bindings, ctx); if (res !== undefined) e.waitUntil(Promise.resolve(res)); }); } async [kDispatchFetch]<WaitUntil extends any[] = unknown[]>( request: Request, proxy = false ): Promise<Response<WaitUntil>> { // No need to clone request if not proxying, no chance we'll need to send // it somewhere else const event = new FetchEvent("fetch", { request: proxy ? request.clone() : request, }); let res: Response | BaseResponse | undefined; try { super.dispatchEvent(event); // `event[kResponse]` may be `undefined`, but `await undefined` is still // `undefined` res = await event[kResponse]; } catch (e: any) { if (event[kPassThrough]) { this.#log.warn(e.stack); } else { throw e; } } finally { event[kSent] = true; } if (res !== undefined) { // noinspection SuspiciousTypeOfGuard const validRes = res instanceof Response || res instanceof BaseResponse; if (!validRes) { const suggestion = this.#modules ? SUGGEST_RES_MODULES : SUGGEST_RES; throw new FetchError( "ERR_RESPONSE_TYPE", `Fetch handler didn't respond with a Response object.\nMake sure you're ${suggestion}.` ); } // noinspection ES6MissingAwait const waitUntil = Promise.all(event[kWaitUntil]) as Promise<WaitUntil>; return withWaitUntil(res, waitUntil); } if (!proxy) { if (event[kPassThrough]) { throw new FetchError( "ERR_NO_UPSTREAM", "No upstream to pass-through to specified.\nMake sure you've set the `upstream` option." ); } else if (this.#calledAddFetchEventListener) { // Technically we'll get this error if we addEventListener and then // removeEventListener, but that seems extremely unlikely, and you // probably know what you're doing if you're calling removeEventListener // on the global const suggestion = this.#modules ? SUGGEST_RES_MODULES : SUGGEST_RES; throw new FetchError( "ERR_NO_RESPONSE", `No fetch handler responded and no upstream to proxy to specified.\nMake sure you're ${suggestion}.` ); } else { const suggestion = this.#modules ? SUGGEST_HANDLER_MODULES : SUGGEST_HANDLER; throw new FetchError( "ERR_NO_HANDLER", `No fetch handler defined and no upstream to proxy to specified.\nMake sure you're ${suggestion}.` ); } } // noinspection ES6MissingAwait const waitUntil = Promise.all(event[kWaitUntil]) as Promise<WaitUntil>; return withWaitUntil(await fetch(request), waitUntil); } async [kDispatchScheduled]<WaitUntil extends any[] = any[]>( scheduledTime?: number, cron?: string ): Promise<WaitUntil> { const event = new ScheduledEvent("scheduled", { scheduledTime: scheduledTime ?? Date.now(), cron: cron ?? "", }); super.dispatchEvent(event); return (await Promise.all(event[kWaitUntil])) as WaitUntil; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types #maybeAddPromiseListener(listener: PromiseListener, member: any): void { if (listener.set.size === 0) { this.#log.verbose(`Adding process ${listener.name} listener...`); process.prependListener(listener.name as any, listener.listener as any); } listener.set.add(member); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types #maybeRemovePromiseListener(listener: PromiseListener, member: any): void { const registered = listener.set.size > 0; listener.set.delete(member); if (registered && listener.set.size === 0) { this.#log.verbose(`Removing process ${listener.name} listener...`); process.removeListener(listener.name, listener.listener); } } #resetPromiseListener(listener: PromiseListener): void { if (listener.set.size > 0) { this.#log.verbose(`Removing process ${listener.name} listener...`); process.removeListener(listener.name, listener.listener); } listener.set.clear(); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types #unhandledRejectionListener = (reason: any, promise: Promise<any>): void => { const event = new PromiseRejectionEvent("unhandledrejection", { reason, promise, }); const notCancelled = super.dispatchEvent(event); // If the event wasn't preventDefault()ed, if (notCancelled) { if (this.#logUnhandledRejections) { // log if we're logging unhandled rejections this.#log.error(prefixError("Unhandled Promise Rejection", reason)); } else { // ...otherwise, remove the listener and cause an unhandled promise // rejection again. This should terminate the program. this.#resetPromiseListener(this.#unhandledRejection); // noinspection JSIgnoredPromiseFromCall Promise.reject(reason); } } }; #rejectionHandledListener = (promise: Promise<any>): void => { // Node.js doesn't give us the reason :( const event = new PromiseRejectionEvent("rejectionhandled", { promise }); super.dispatchEvent(event); }; [kDispose](): void { this.#resetPromiseListener(this.#unhandledRejection); this.#resetPromiseListener(this.#rejectionHandled); } }
the_stack
import { noMatch } from "./noMatch"; import { History } from "history"; export type Compute<A extends any> = A extends Function ? A : { [K in keyof A]: A[K]; } & {}; export type KeysMatching<TObject, TCondition> = { [TKey in keyof TObject]: TObject[TKey] extends TCondition ? TKey : never; }[keyof TObject]; export type KeysDiffering<TObject, TCondition> = { [TKey in keyof TObject]: TObject[TKey] extends TCondition ? never : TKey; }[keyof TObject]; export type ErrorDef = { errorCode: number; getDetails: (...args: any[]) => string[]; }; export type BuildPathDefErrorContext = { routeName: string; rawPath: string; }; /** * Object for configuring a custom query string serializer. You likely * do not need this level of customization for your application. * * @see https://typehero.org/type-route/docs/api-reference/types/query-string-serializer */ export type QueryStringSerializer = { /** * Accepts the query string (without the leading ?) and returns * a mapping of parameter names to unserialized parameter values. * Individual parameter value serializer take care of the parsing * parameter values. A null value indicates an empty array. * * @see https://typehero.org/type-route/docs/api-reference/types/query-string-serializer */ parse: (raw: string) => Record<string, string | null>; /** * Accepts an object keyed by query parameter names and generates * a stringified version of the object. A null value indicates an * empty array. * * @see https://typehero.org/type-route/docs/api-reference/types/query-string-serializer */ stringify: ( queryParams: Record< string, { valueSerializerId?: string; array: boolean; value: string | null } > ) => string; }; export type ParamDefKind = "path" | "query" | "state"; /** * Object for configuring a custom parameter value serializer. * * @see https://typehero.org/type-route/docs/api-reference/types/value-serializer */ export type ValueSerializer<TValue = unknown> = { id?: string; urlEncode?: boolean; parse(raw: string): TValue | typeof noMatch; stringify(value: TValue): string; }; export type ParamDef<TParamDefKind, TValue = unknown> = { ["~internal"]: { type: "ParamDef"; kind: TParamDefKind; valueSerializer: ValueSerializer<TValue>; array: boolean; optional: boolean; default: TValue | undefined; trailing?: boolean; }; }; export type UmbrellaParamDef = ParamDef<ParamDefKind>; export type RouterContext = { queryStringSerializer: QueryStringSerializer; navigate: NavigateFunction; arraySeparator: string; history: History; routeDefs: UmbrellaRouteDefCollection; routes: Record<string, UmbrellaRouteBuilder>; baseUrl: string; }; export type ParamDefCollection<TParamDefKind> = { [parameterName: string]: ParamDef<TParamDefKind>; }; export type UmbrellaParamDefCollection = ParamDefCollection<ParamDefKind>; export type PathParamDef<TValue = unknown> = ParamDef<"path", TValue>; export type NamedPathParamDef<TValue = unknown> = PathParamDef<TValue> & { paramName: string; }; export type RouterLocation = { fullPath: string; path?: string; query?: string; state?: Record<string, string>; }; export type PathSegmentDef = { leading: string; trailing: string; namedParamDef: NamedPathParamDef | null; }; export type PathDef = PathSegmentDef[]; export type ParamIdCollection = { [paramName: string]: string; }; export type GetRawPath = ( paramIdCollection: ParamIdCollection ) => string | string[]; export type PathParamNames<TParamDefCollection> = KeysMatching< TParamDefCollection, { ["~internal"]: { kind: "path" } } >; type OptionalParamNames<TParamDefCollection> = KeysMatching< TParamDefCollection, { ["~internal"]: { optional: true } } >; type RequiredParamNames<TParamDefCollection> = KeysMatching< TParamDefCollection, { ["~internal"]: { optional: false } } >; type RequiredOutputParamsNames<TParamDefCollection> = | RequiredParamNames<TParamDefCollection> | KeysDiffering< TParamDefCollection, { ["~internal"]: { optional: true; default: undefined } } >; type OptionalOutputParamsNames<TParamDefCollection> = Exclude< keyof TParamDefCollection, RequiredOutputParamsNames<TParamDefCollection> >; export type ParamValue<TParamDef> = TParamDef extends { "~internal": { array: boolean; valueSerializer: ValueSerializer<infer TValue>; }; } ? TParamDef["~internal"]["array"] extends true ? TValue[] : TValue : never; type InputRouteParams<TParamDefCollection> = Compute< Pick< { [TParamName in keyof TParamDefCollection]: ParamValue< TParamDefCollection[TParamName] >; }, RequiredParamNames<TParamDefCollection> > & Pick< { [TParamName in keyof TParamDefCollection]?: ParamValue< TParamDefCollection[TParamName] >; }, OptionalParamNames<TParamDefCollection> > >; type OutputRouteParams<TParamDefCollection> = Compute< Pick< { [TParamName in keyof TParamDefCollection]?: ParamValue< TParamDefCollection[TParamName] >; }, OptionalOutputParamsNames<TParamDefCollection> > & Pick< { [TParamName in keyof TParamDefCollection]: ParamValue< TParamDefCollection[TParamName] >; }, RequiredOutputParamsNames<TParamDefCollection> > >; export type PathParams<TParamDefCollection> = { [TParamName in PathParamNames<TParamDefCollection>]: string; }; export type PathFn<TParamDefCollection> = ( x: PathParams<TParamDefCollection> ) => string | string[]; export type RouteDef<TParamDefCollection> = { ["~internal"]: { type: "RouteDef"; params: TParamDefCollection; path: PathFn<TParamDefCollection>; }; /** * Create a new route definition by extending the current one. * * @see https://typehero.org/type-route/docs/api-reference/route-definition/extend */ extend<TExtensionParamDefCollection>( params: TExtensionParamDefCollection, path: PathFn<TExtensionParamDefCollection> ): RouteDef<TParamDefCollection & TExtensionParamDefCollection>; /** * Create a new route definition by extending the current one. * * @see https://typehero.org/type-route/docs/api-reference/route-definition/extend */ extend(path: string | string[]): RouteDef<TParamDefCollection>; }; export type UmbrellaRouteDef = RouteDef<UmbrellaParamDefCollection>; export type NavigateFunction = ( route: UmbrellaRoute, primaryPath: boolean ) => void; export type OnClickHandler = (event?: any) => void; export type Link = { href: string; onClick: OnClickHandler; }; type RouteParamsFunction<TParamDefCollection, TReturnType> = KeysMatching< TParamDefCollection, {} > extends never ? () => TReturnType : RequiredParamNames<TParamDefCollection> extends never ? (params?: InputRouteParams<TParamDefCollection>) => TReturnType : (params: InputRouteParams<TParamDefCollection>) => TReturnType; export type Match = { params: Record<string, unknown>; numExtraneousParams: number; primaryPath: boolean; }; export type RouteBuilder<TRouteName, TParamDefCollection> = RouteParamsFunction< TParamDefCollection, Route<TRouteName, TParamDefCollection> > & { /** * Name of the route */ name: TRouteName; ["~internal"]: { type: "RouteBuilder"; match: (args: { routerLocation: RouterLocation; queryStringSerializer: QueryStringSerializer; arraySeparator: string; }) => Match | false; pathDefs: PathDef[]; Route: Route<TRouteName, TParamDefCollection>; }; }; export type UmbrellaRouteBuilder = RouteBuilder< string, UmbrellaParamDefCollection >; export type ClickEvent = { preventDefault?: () => void; button?: number | null; defaultPrevented?: boolean | null; metaKey?: boolean | null; altKey?: boolean | null; ctrlKey?: boolean | null; shiftKey?: boolean | null; target?: { target?: string | null } | null; }; export type Action = "push" | "replace" | "pop"; export type LocationState = { state?: Record<string, string>; } | null; export type RouteDefCollectionRoute< TRouteDefCollection > = TRouteDefCollection extends Record<string, RouteDef<any>> ? | { [TRouteName in keyof TRouteDefCollection]: Route< TRouteName, TRouteDefCollection[TRouteName]["~internal"]["params"] >; }[keyof TRouteDefCollection] | NotFoundRoute : never; export type NotFoundRoute = Route<false, {}>; export type Route<TName, TParamDefCollection> = { /** * Name of the route. */ name: TName; /** * Route parameters. */ params: OutputRouteParams<TParamDefCollection>; /** * How the current route was navigated to. * - "push" indicates your application added this route. * - "replace" also indicates your application added this route. * - "pop" indicates the browser navigated to this route (think * back/forward buttons) * - null indicates the route has not yet been navigated to or * its action was not able to be determined (as is the case with * session.getInitialRoute() ) */ action: Action | null; /** * Helper for constructing links * * @see https://typehero.org/type-route/docs/guides/rendering-links */ link: Link; /** * The href of the current route without domain but including * path, query string, and hash. */ href: string; /** * Pushes a new route onto the history stack, increasing its length by one. * If there were any entries in the stack after the current one, they are * lost. */ push: () => void; /** * Replaces the current route in the history stack with this one. */ replace: () => void; }; /** * Helper to retrieve a Route type. * * @see https://typehero.org/type-route/docs/api-reference/types/route */ export type GetRoute<T> = T extends { ["~internal"]: { Route: any } } ? T["~internal"]["Route"] : T extends Record<string, { ["~internal"]: { Route: any } }> ? T[keyof T]["~internal"]["Route"] | NotFoundRoute : never; export type UmbrellaRoute = Route<string | false, Record<string, any>>; export type NavigationHandler<TRouteDefCollection> = ( route: RouteDefCollectionRoute<TRouteDefCollection> ) => void; export type UmbrellaNavigationHandler = NavigationHandler< UmbrellaRouteDefCollection >; type Unblock = () => void; export type Blocker<TRouteDefCollection> = (update: { /** * The route that would have been navigated to had navigation * not been blocked. */ route: RouteDefCollectionRoute<TRouteDefCollection>; /** * Retry the navigation attempt. Typically is used after getting * user confirmation to leave and then unblocking navigation. */ retry: () => void; }) => void; export type UmbrellaBlocker = Blocker<UmbrellaRouteDefCollection>; /** * Functions for interacting with the current history session. */ export type RouterSession<TRouteDefCollection> = { /** * Manually add a new item to the history stack. */ push(href: string, state?: any): void; /** * Replace the currently active item in the history stack. */ replace(href: string, state?: any): void; /** * Get the initial route. Useful for bootstrapping your application. */ getInitialRoute(): RouteDefCollectionRoute<TRouteDefCollection>; /** * Move back in history the specified amount. */ back(amount?: number): void; /** * Move forward in history the specified amount. */ forward(amount?: number): void; /** * Reconfigures the underlying history instance. Can be useful * when using server-side rendering. * * @see https://typehero.org/type-route/docs/guides/server-side-rendering */ reset(options: SessionOpts): void; /** * Blocks navigation and registers a listener that is called when * navigation is blocked. Returns a function to unblock navigation. * * @see https://typehero.org/type-route/docs/guides/preventing-navigation */ block(blocker: Blocker<TRouteDefCollection>): Unblock; /** * Registers a listener that is called when navigation occurs. * Returns a function to remove the navigation listener. */ listen(handler: NavigationHandler<TRouteDefCollection>): Unlisten; }; export type UmbrellaRouterSession = RouterSession<UmbrellaRouteDefCollection>; export type MemoryHistorySessionOpts = { type: "memory"; /** * An array of urls representing the what items should * start in history when the router is created. This can be useful * in a variety of scenarios including server-side rendering * (https://typehero.org/type-route/docs/guides/server-side-rendering). */ initialEntries?: string[]; /** * The index of the current url entry when the router is created. */ initialIndex?: number; }; export type HashHistorySessionOpts = { type: "hash"; /** * Provide a custom window function to operate on. Can be useful when * using the route in an iframe. */ window?: Window; }; export type BrowserHistorySessionOpts = { type: "browser"; /** * Provide a custom window function to operate on. Can be useful when * using the route in an iframe. */ window?: Window; }; export type SessionOpts = | HashHistorySessionOpts | MemoryHistorySessionOpts | BrowserHistorySessionOpts; export type QueryStringArrayFormat = | "singleKey" | "singleKeyWithBracket" | "multiKey" | "multiKeyWithBracket"; export type ArrayFormat = { /** * Separator to use for array parameter types. By default "," */ separator?: string; /** * Query string serialization method. * * @see https://typehero.org/type-route/docs/guides/custom-query-string */ queryString?: QueryStringArrayFormat; }; export type RouterOpts = { /** * Options for what variety of browser history session you're using. * There are three types with additional options depending on the * session type: "browser", "hash", and "memory". */ session?: SessionOpts; /** * A custom serializer/deserializer for the query string. This is an * advanced feature your application likely does not need. * * @see https://typehero.org/type-route/docs/guides/custom-query-string */ queryStringSerializer?: QueryStringSerializer; /** * Object used to configure how arrays are serialized to the url. */ arrayFormat?: ArrayFormat; /** * A path segment that precedes every route in your application. When using a "hash" * router this segment will come before the "#" symbol. */ baseUrl?: string; /** * If the application should scroll to the top of the page when a new route * is pushed onto the history stack. Defaults to true for applications running * in a web browser. */ scrollToTop?: boolean; }; export type Unlisten = { (): void; }; export type UmbrellaRouteDefCollection = Record<string, UmbrellaRouteDef>; export type CoreRouter< TRouteDefCollection extends { [routeName: string]: any } > = { /** * Collection of route builders. */ routes: { /** * Call routes.[routeName](params) to construct a route object. */ [TRouteName in keyof TRouteDefCollection]: RouteBuilder< TRouteName, TRouteDefCollection[TRouteName]["~internal"]["params"] >; }; session: RouterSession<TRouteDefCollection>; }; export type UmbrellaCoreRouter = CoreRouter<UmbrellaRouteDefCollection>; export type RouteGroup<T extends any[] = any[]> = { ["~internal"]: { type: "RouteGroup"; Route: T[number]["~internal"]["Route"]; }; routeNames: T[number]["~internal"]["Route"]["name"][]; /** * Accepts a route and returns whether or not it is part * of this group. * * @see https://typehero.org/type-route/docs/api-reference/route-group/has */ has(route: Route<any, any>): route is T[number]["~internal"]["Route"]; };
the_stack
import React, { Fragment } from "react"; // @ts-ignore import { SortableProperties } from "@elastic/eui/lib/services"; // @ts-ignore import { Comparators, EuiBasicTable, EuiCodeEditor, EuiModal, EuiModalBody, EuiModalFooter, EuiModalHeader, EuiModalHeaderTitle, EuiOverlayMask, EuiPanel, EuiPortal, EuiSearchBar, EuiSideNav } from "@elastic/eui"; import { EuiButton, EuiButtonIcon, EuiContextMenu, EuiFlexGroup, EuiFlexItem, EuiLink, EuiPopover, EuiTable, EuiTableBody, EuiTableHeader, EuiTableHeaderCell, EuiTablePagination, EuiTableRow, EuiTableRowCell, EuiText, Pager } from "@elastic/eui"; import { findRootNode, getMessageString, getRowTree, isEmpty, Node, onDownloadFile, scrollToNode } from "../../utils/utils"; import "../../ace-themes/sql_console"; import { COLUMN_WIDTH, PAGE_OPTIONS, SMALL_COLUMN_WIDTH } from "../../utils/constants"; import { DataRow, ItemIdToExpandedRowMap, QueryMessage, QueryResult } from "../Main/main"; import _ from "lodash"; const DoubleScrollbar = require('react-double-scrollbar'); interface QueryResultsBodyProps { language: string; queries: string[]; queryResultSelected: QueryResult; queryResultsJDBC: string; queryResultsCSV: string; queryResultsJSON: string; queryResultsTEXT: string; tabNames: string[]; selectedTabName: string; selectedTabId: string; searchQuery: string; sortableProperties: SortableProperties; messages: QueryMessage[]; pager: Pager; itemsPerPage: number; firstItemIndex: number; lastItemIndex: number; itemIdToExpandedRowMap: ItemIdToExpandedRowMap; sortedColumn: string; onChangeItemsPerPage: (itemsPerPage: number) => void; onChangePage: (pageIndex: number) => void; onQueryChange: (query: object) => void; updateExpandedMap: (map: ItemIdToExpandedRowMap) => void; getJson: (queries: string[]) => void; getJdbc: (queries: string[]) => void; getCsv: (queries: string[]) => void; getText: (queries: string[]) => void; onSort: (column: string, rows: DataRow[]) => DataRow[]; } interface QueryResultsBodyState { itemIdToSelectedMap: object; itemIdToOpenActionsPopoverMap: object; incremental: boolean; filters: boolean; itemIdToExpandedRowMap: ItemIdToExpandedRowMap; searchQuery: string; selectedItemMap: object; selectedItemName: string; selectedItemData: object; navView: boolean; isPopoverOpen: boolean; isDownloadPopoverOpen: boolean; isModalVisible: boolean; downloadErrorModal: any; } interface FieldValue { hasExpandingRow: boolean; hasExpandingArray: boolean; value: string; link: string; } class QueryResultsBody extends React.Component<QueryResultsBodyProps, QueryResultsBodyState> { public items: DataRow[]; public columns: any[]; public panels: any[]; public expandedRowColSpan: number; constructor(props: QueryResultsBodyProps) { super(props); this.state = { itemIdToSelectedMap: {}, itemIdToOpenActionsPopoverMap: {}, incremental: true, filters: false, itemIdToExpandedRowMap: this.props.itemIdToExpandedRowMap, searchQuery: this.props.searchQuery, selectedItemMap: {}, selectedItemName: "", selectedItemData: {}, navView: false, isPopoverOpen: false, isDownloadPopoverOpen: false, isModalVisible: false, downloadErrorModal: {} }; this.expandedRowColSpan = 0; this.items = []; this.columns = []; this.panels = [ { id: 0, items: [ { name: "Download JSON", onClick: () => { this.onDownloadJSON(); } }, { name: "Download JDBC", onClick: () => { this.onDownloadJDBC(); } }, { name: "Download CSV", onClick: () => { this.onDownloadCSV(); } }, { name: "Download Text", onClick: () => { this.onDownloadText(); } } ] } ]; } setIsModalVisible(visible: boolean): void { this.setState({ isModalVisible: visible }) } getModal = (errorMessage: string): any => { const closeModal = () => this.setIsModalVisible(false); let modal = ( <EuiOverlayMask onClick={closeModal}> <EuiModal onClose={closeModal}> <EuiModalHeader> <EuiModalHeaderTitle>Error</EuiModalHeaderTitle> </EuiModalHeader> <EuiModalBody> <EuiText> {errorMessage} </EuiText> </EuiModalBody> <EuiModalFooter> <EuiButton onClick={closeModal} fill> Close </EuiButton> </EuiModalFooter> </EuiModal> </EuiOverlayMask> ); return modal; } // Actions for Download files onDownloadJSON() { if (this.props.language == 'PPL') { this.setState({ downloadErrorModal: this.getModal("PPL result in JSON format is not supported, please select JDBC format."), }) this.setIsModalVisible(true); return; } if (!this.props.queryResultsJSON) { this.props.getJson(this.props.queries); } setTimeout(() => { const jsonObject = JSON.parse(this.props.queryResultsJSON); const data = JSON.stringify(jsonObject, undefined, 4); onDownloadFile(data, "json", this.props.selectedTabName + ".json"); }, 2000); }; onDownloadJDBC = (): void => { if (!this.props.queryResultsJDBC) { this.props.getJdbc(this.props.queries); } setTimeout(() => { const jsonObject = JSON.parse(this.props.queryResultsJDBC); const data = JSON.stringify(jsonObject, undefined, 4); onDownloadFile(data, "json", this.props.selectedTabName + ".json"); }, 2000); }; onDownloadCSV = (): void => { if (this.props.language == 'PPL') { this.setState({ downloadErrorModal: this.getModal("PPL result in CSV format is not supported, please select JDBC format."), }) this.setIsModalVisible(true); return; } if (!this.props.queryResultsCSV) { this.props.getCsv(this.props.queries); } setTimeout(() => { const data = this.props.queryResultsCSV; onDownloadFile(data, "csv", this.props.selectedTabName + ".csv"); }, 2000); }; onDownloadText = (): void => { if (this.props.language == 'PPL') { this.setState({ downloadErrorModal: this.getModal("PPL result in Text format is not supported, please select JDBC format."), }) this.setIsModalVisible(true); return; } if (!this.props.queryResultsTEXT) { this.props.getText(this.props.queries); } setTimeout(() => { const data = this.props.queryResultsTEXT; onDownloadFile(data, "plain", this.props.selectedTabName + ".txt"); }, 2000); }; // Actions for Downloads Button onDownloadButtonClick = (): void => { this.setState(prevState => ({ isDownloadPopoverOpen: !prevState.isDownloadPopoverOpen })); }; closeDownloadPopover = (): void => { this.setState({ isDownloadPopoverOpen: false }); }; // It filters table values that conatins the given items getItems(records: DataRow[]) { const matchingItems = this.props.searchQuery ? this.searchItems(records, this.props.searchQuery) : records; let field: string = ""; if (_.get(this.props.sortedColumn, this.columns)) { field = this.props.sortedColumn; } return this.sortDataRows(matchingItems, field); } searchItems(dataRows: DataRow[], searchQuery: string): DataRow[] { let rows: { [key: string]: any }[] = []; for (const row of dataRows) { rows.push(row.data) } const searchResult = EuiSearchBar.Query.execute(searchQuery, rows); let result: DataRow[] = []; for (const row of searchResult) { let dataRow: DataRow = { // rowId does not matter here since the data rows would be sorted later rowId: 0, data: row } result.push(dataRow) } return result; } onSort(prop: string): void { this.items = this.props.onSort(prop, this.items); this.renderRows(this.items, this.columns, this.props.itemIdToExpandedRowMap); } sortDataRows(dataRows: DataRow[], field: string): DataRow[] { const property = this.props.sortableProperties.getSortablePropertyByName(field); const copy = [...dataRows]; let comparator = (a: DataRow, b: DataRow) => { if (typeof property === "undefined") { return 0; } let dataA = a.data; let dataB = b.data; if (dataA[field] && dataB[field]) { if (dataA[field] > dataB[field]) { return 1; } if (dataA[field] < dataB[field]) { return -1; } } return 0; } if (!this.props.sortableProperties.isAscendingByName(field)) { Comparators.reverse(comparator); } return copy.sort(comparator); } // It processes field values and determines whether it should link to an expanded row or an expanded array getFieldValue(fieldValue: any, field: string): FieldValue { let hasExpandingRow: boolean = false; let hasExpandingArray: boolean = false; let value: string = ""; let link: string = ""; if (fieldValue === null) { return { hasExpandingRow: hasExpandingRow, value: "", hasExpandingArray, link }; } if (typeof fieldValue === "boolean") { return { hasExpandingRow: hasExpandingRow, value: String(fieldValue), hasExpandingArray, link } } // Not an object or array if (typeof fieldValue !== "object") { return { hasExpandingRow: hasExpandingRow, value: fieldValue, hasExpandingArray, link }; } // Array of strings or objects if (Array.isArray(fieldValue)) { if (typeof fieldValue[0] !== "object") { hasExpandingArray = true; link = field.concat(": [", fieldValue.length.toString(), "]"); } else { hasExpandingRow = true; link = field.concat(": {", fieldValue.length.toString(), "}"); } } // Single object else { hasExpandingRow = true; link = field.concat(": {1}"); } return { hasExpandingRow: hasExpandingRow, hasExpandingArray: hasExpandingArray, value: value, link: link }; } addExpandingNodeIcon(node: Node, expandedRowMap: ItemIdToExpandedRowMap) { return ( <EuiButtonIcon style={{ marginLeft: -4 }} onClick={() => this.toggleNodeData(node, expandedRowMap)} aria-label={ expandedRowMap[node.nodeId] && expandedRowMap[node.nodeId].expandedRow ? "Collapse" : "Expand" } iconType={ expandedRowMap[node.nodeId] && expandedRowMap[node.nodeId].expandedRow ? "minusInCircle" : "plusInCircle" } /> ); } addExpandingSideNavIcon(node: Node, expandedRowMap: ItemIdToExpandedRowMap) { if (!node.parent) { return; } return ( <EuiButtonIcon onClick={() => this.updateExpandedRowMap(node, expandedRowMap)} aria-label={ expandedRowMap[node.parent!.nodeId] && expandedRowMap[node.parent!.nodeId].selectedNodes && expandedRowMap[node.parent!.nodeId].selectedNodes.hasOwnProperty(node.nodeId) ? "Collapse" : "Expand" } iconType={ expandedRowMap[node.parent!.nodeId] && expandedRowMap[node.parent!.nodeId].selectedNodes && expandedRowMap[node.parent!.nodeId].selectedNodes.hasOwnProperty(node.nodeId) ? "minusInCircle" : "plusInCircle" } /> ); } addExpandingIconColumn(columns: any[]) { const expandIconColumn = [ { id: "expandIcon", label: "", isSortable: false, width: "30px" } ]; columns = expandIconColumn.concat(columns); return columns; } updateSelectedNodes(parentNode: Node, selectedNode: Node, expandedRowMap: ItemIdToExpandedRowMap, keepOpen = false) { if (!parentNode) { return expandedRowMap; } const parentNodeId = parentNode.nodeId; if ( expandedRowMap[parentNodeId] && expandedRowMap[parentNodeId].selectedNodes && expandedRowMap[parentNodeId].selectedNodes!.hasOwnProperty(selectedNode.nodeId) && !keepOpen ) { delete expandedRowMap[parentNodeId].selectedNodes[selectedNode.nodeId]; } else { if (!expandedRowMap[parentNodeId].selectedNodes) { expandedRowMap[parentNodeId].selectedNodes = {}; } expandedRowMap[parentNodeId].selectedNodes[selectedNode.nodeId] = selectedNode.data; } return expandedRowMap; } updateExpandedRow(node: Node, expandedRowMap: ItemIdToExpandedRowMap) { let newItemIdToExpandedRowMap = expandedRowMap; if (expandedRowMap[node.nodeId]) { newItemIdToExpandedRowMap[node.nodeId].expandedRow = ( <div id={node.nodeId} style={{ padding: "0 0 20px 19px" }}> {this.renderNav(node, node.name, expandedRowMap)} </div> ); } return newItemIdToExpandedRowMap; } updateExpandedRowMap(node: Node | undefined, expandedRowMap: ItemIdToExpandedRowMap, keepOpen = false) { if (!node) { return expandedRowMap; } let newItemIdToExpandedRowMap = this.updateSelectedNodes(node.parent, node, expandedRowMap, keepOpen); const rootNode = findRootNode(node, expandedRowMap); if (expandedRowMap[rootNode.nodeId]) { newItemIdToExpandedRowMap = this.updateExpandedRow(node.parent, newItemIdToExpandedRowMap); newItemIdToExpandedRowMap = this.updateExpandedRow(rootNode, newItemIdToExpandedRowMap); } this.props.updateExpandedMap(newItemIdToExpandedRowMap); } toggleNodeData = (node: Node, expandedRowMap: ItemIdToExpandedRowMap) => { let newItemIdToExpandedRowMap = expandedRowMap; const rootNode = findRootNode(node, expandedRowMap); if (expandedRowMap[node.nodeId] && expandedRowMap[node.nodeId].expandedRow) { delete newItemIdToExpandedRowMap[node.nodeId].expandedRow; } else if (node.children && node.children.length > 0) { newItemIdToExpandedRowMap = this.updateExpandedRow(node, expandedRowMap); } if (rootNode !== node) { newItemIdToExpandedRowMap = this.updateExpandedRow(rootNode, expandedRowMap); } this.props.updateExpandedMap(newItemIdToExpandedRowMap); }; getChildrenItems(nodes: Node[], parentNode: Node, expandedRowMap: ItemIdToExpandedRowMap) { const itemList: any[] = []; if (nodes.length === 0 && parentNode.data) { const renderedData = this.renderNodeData(parentNode, expandedRowMap); itemList.push( this.createItem(expandedRowMap, parentNode, renderedData, { items: [], }) ); } for (let i = 0; i < nodes.length; i++) { itemList.push( this.createItem(expandedRowMap, nodes[i], nodes[i].name, { icon: this.addExpandingSideNavIcon(nodes[i], expandedRowMap), items: this.getChildrenItems( nodes[i].children, nodes[i], expandedRowMap ) }) ); } return itemList; } createItem = (expandedRowMap: ItemIdToExpandedRowMap, node: Node, name: any, items = {}) => { const nodeId = node.nodeId; let isSelected: boolean | undefined = false; if (!isEmpty(node.parent)) { isSelected = expandedRowMap[node.parent!.nodeId] && expandedRowMap[node.parent!.nodeId].selectedNodes && expandedRowMap[node.parent!.nodeId].selectedNodes!.hasOwnProperty(nodeId); } return { ...items, id: nodeId, name, isSelected: isSelected, onClick: () => console.log('open side nav'), }; }; /************* Render Functions *************/ renderMessagesTab(): JSX.Element { return ( <EuiCodeEditor className={ this.props.messages && this.props.messages.length > 0 ? this.props.messages[0].className : "successful-message" } mode="text" theme="sql_console" width="100%" value={getMessageString(this.props.messages, this.props.tabNames)} showPrintMargin={false} readOnly={true} setOptions={{ fontSize: "14px", readOnly: true, highlightActiveLine: false, highlightGutterLine: false }} aria-label="Code Editor" /> ); } renderHeaderCells(columns: any[]) { return columns.map((field: any) => { const label: string = field.id === "expandIcon" ? field.label : field; const colwidth = field.id === "expandIcon" ? SMALL_COLUMN_WIDTH : COLUMN_WIDTH; return ( <EuiTableHeaderCell key={label} width={colwidth} // onSort={this.onSort.bind(this, label)} // isSorted={this.props.sortedColumn === label} // isSortAscending={this.props.sortableProperties.isAscendingByName(label)} > {label} </EuiTableHeaderCell> ); }); } // Inner tables sorting is not enabled renderHeaderCellsWithNoSorting(columns: any[]) { return columns.map((field: any) => { const label = field.id === "expandIcon" ? field.label : field; const colwidth = field.id === "expandIcon" ? field.width : COLUMN_WIDTH; return ( <EuiTableHeaderCell key={label} width={colwidth}> {label} </EuiTableHeaderCell> ); }); } renderRow(item: DataRow, columns: string[], rowId: string, expandedRowMap: ItemIdToExpandedRowMap) { let rows: any[] = []; const data = item.data; // If the data is an array or an object we add it to the expandedRowMap if (data && ((typeof data === "object" && !isEmpty(data)) || (Array.isArray(data) && data.length > 0)) ) { let rowItems: any[] = []; if (Array.isArray(data)) { rowItems = data; } else { rowItems.push(data); } for (let i = 0; i < rowItems.length; i++) { let rowItem = rowItems[i]; let tableCells: Array<any> = []; const tree = getRowTree(rowId, rowItem, expandedRowMap); // Add nodes to expandedRowMap if (!expandedRowMap[rowId] || !expandedRowMap[rowId].nodes) { expandedRowMap[rowId] = { nodes: tree }; } const expandingNode = tree && tree._root.children.length > 0 ? this.addExpandingNodeIcon(tree._root, expandedRowMap) : ""; if (columns.length > 0) { columns.map((field: any) => { // Table cell if (field.id !== "expandIcon") { const fieldObj = this.getFieldValue(rowItem[field], field); let fieldValue: any; // If field is expandable if (fieldObj.hasExpandingRow || fieldObj.hasExpandingArray) { const fieldNode = expandedRowMap[tree._root.nodeId].nodes._root.children.find((node: Node) => node.name === field); fieldValue = ( <span> {" "} {fieldObj.value} <EuiLink color="primary" onClick={() => { this.updateExpandedRowMap( fieldNode, expandedRowMap, true ); scrollToNode(tree._root.nodeId); }} > {fieldObj.link} </EuiLink> </span> ); } else { fieldValue = fieldObj.value; } tableCells.push( <EuiTableRowCell key={`rowCell-${field}-${rowId}`} truncateText={false} textOnly={true} > {fieldValue} </EuiTableRowCell> ); } // Expanding icon cell else { tableCells.push( <EuiTableRowCell id={tree._root.nodeId} key={`rowCell-expandIconRow-${rowId}`}> {expandingNode} </EuiTableRowCell> ); } }); } else { const fieldObj = this.getFieldValue(rowItem, ""); tableCells.push( <EuiTableRowCell key={`rowCell-default-${rowId}`} truncateText={false} textOnly={true}> {fieldObj.value} </EuiTableRowCell> ); } const tableRow = <EuiTableRow key={`row-${rowId}`} data-test-subj={'tableRow'}>{tableCells}</EuiTableRow>; let row = <Fragment key={`row-wrapper-${rowId}`}>{tableRow}</Fragment>; if (expandedRowMap[rowId] && expandedRowMap[rowId].expandedRow) { const tableRow = ( <EuiTableRow className="expanded-row" key={`expanded-row-${rowId}`}> {tableCells}{" "} </EuiTableRow> ); const expandedRow = ( <EuiTableRow key={`row-${rowId}`}>{expandedRowMap[rowId].expandedRow}</EuiTableRow> ); row = ( <Fragment key={`row-wrapper-${rowId}`}> {tableRow} {expandedRow} </Fragment> ); } rows.push(row); } } return rows; } renderRows(items: DataRow[], columns: string[], expandedRowMap: ItemIdToExpandedRowMap) { let rows: any[] = []; if (items) { for ( let itemIndex = this.props.firstItemIndex; itemIndex <= this.props.lastItemIndex; itemIndex++ ) { const item = items[itemIndex]; if (item) { const rowId = item.rowId; const rowsForItem = this.renderRow( item, columns, rowId.toString(10), expandedRowMap ); rows.push(rowsForItem); } } } return rows; } renderSearchBar() { const search = { box: { incremental: this.state.incremental, placeholder: "Search keyword", schema: true } }; return ( <div className="search-bar"> <EuiSearchBar onChange={this.props.onQueryChange} query={this.props.searchQuery} {...search} /> </div> ); } renderNodeData = (node: Node, expandedRowMap: ItemIdToExpandedRowMap) => { let items: any[] = []; let columns: string[] = []; let records: any[] = []; const data = node.data; if (Array.isArray(data)) { items = data; columns = typeof items[0] === "object" ? Object.keys(items[0]) : []; } else if (typeof data === "object") { records.push(data); items = records; columns = this.addExpandingIconColumn(Object.keys(data)); } let dataRow: DataRow = { rowId: 0, data: items }; return ( <div> <EuiTable className="sideNav-table"> <EuiTableHeader className="table-header"> {this.renderHeaderCellsWithNoSorting(columns)} </EuiTableHeader> <EuiTableBody> {this.renderRow(dataRow, columns, node.nodeId.toString(), expandedRowMap)} </EuiTableBody> </EuiTable> </div> ); }; renderNav(node: Node, table_name: string, expandedRowMap: ItemIdToExpandedRowMap) { const sideNav = [ { items: this.getChildrenItems(node.children, node, expandedRowMap), id: node.nodeId, name: node.name, isSelected: false, onClick: () => console.log('open side nav'), } ]; return ( <EuiSideNav mobileTitle="Navigate within $APP_NAME" items={sideNav} className="sideNavItem__items" style={{ width: "300px", padding: "0 0 20px 9px" }} /> ); } render() { // Action button with list of downloads const downloadsButton = ( <EuiButton iconType="arrowDown" iconSide="right" size="s" onClick={this.onDownloadButtonClick} > Download </EuiButton> ); let modal; if (this.state.isModalVisible) { modal = this.state.downloadErrorModal; } if ( // this.props.selectedTabId === MESSAGE_TAB_LABEL || this.props.queryResultSelected == undefined ) { return this.renderMessagesTab(); } else { if (this.props.queryResultSelected) { this.items = this.getItems(this.props.queryResultSelected.records); //Adding an extra empty column for the expanding icon this.columns = this.addExpandingIconColumn(this.props.queryResultSelected.fields); this.expandedRowColSpan = this.columns.length; } return ( <div> {this.props.language === 'SQL' && ( <> <EuiFlexGroup alignItems="flexStart" style={{ padding: 20, paddingBottom: 0 }}> {/*Table name*/} <EuiFlexItem> <EuiText className="table-name"> <h4> {this.props.selectedTabName} <span className="table-item-count">{` (${this.items.length})`}</span> </h4> </EuiText> <div className="search-panel"> {/*Search Bar*/} {this.renderSearchBar()} </div> </EuiFlexItem> {/*Download button*/} <EuiFlexItem grow={false}> <div className="download-container"> <EuiPopover className="download-button-container" id="singlePanel" button={downloadsButton} isOpen={this.state.isDownloadPopoverOpen} closePopover={this.closeDownloadPopover} panelPaddingSize="none" anchorPosition="downLeft" > <EuiContextMenu initialPanelId={0} panels={this.panels} /> </EuiPopover> </div> </EuiFlexItem> </EuiFlexGroup> {modal} </> )} {/*Table*/} <div className="sql-console-results-container"> {/*Add a scrollbar on top of the table*/} <DoubleScrollbar> <EuiFlexGroup gutterSize="none"> <EuiFlexItem> <EuiTable> <EuiTableHeader className="table-header"> {this.renderHeaderCells(this.columns)} </EuiTableHeader> <EuiTableBody> {this.renderRows( this.items, this.columns, this.props.itemIdToExpandedRowMap )} </EuiTableBody> </EuiTable> </EuiFlexItem> </EuiFlexGroup> </DoubleScrollbar> </div> <div className="pagination-container"> <EuiTablePagination activePage={this.props.pager.getCurrentPageIndex()} itemsPerPage={this.props.itemsPerPage} itemsPerPageOptions={PAGE_OPTIONS} pageCount={this.props.pager.getTotalPages()} onChangeItemsPerPage={this.props.onChangeItemsPerPage} onChangePage={this.props.onChangePage} /> </div> </div> ); } } } export default QueryResultsBody;
the_stack
import {createAction} from '@reduxjs/toolkit'; import ActionTypes from 'constants/action-types'; import {Merge} from '../reducers/types'; import {ExportImage} from '../reducers/ui-state-updaters'; /** TOGGLE_SIDE_PANEL */ export type ToggleSidePanelUpdaterAction = { payload: string; }; /** * Toggle active side panel * @memberof uiStateActions * @param id id of side panel to be shown, one of `layer`, `filter`, `interaction`, `map` * @public */ export const toggleSidePanel: ( id: string ) => Merge< ToggleSidePanelUpdaterAction, {type: typeof ActionTypes.TOGGLE_SIDE_PANEL} > = createAction(ActionTypes.TOGGLE_SIDE_PANEL, (id: string) => ({payload: id})); /** TOGGLE_MODAL */ export type ToggleModalUpdaterAction = { payload: string | null; }; /** * Show and hide modal dialog * @memberof uiStateActions * @param id - id of modal to be shown, null to hide modals. One of: * - [`DATA_TABLE_ID`](../constants/default-settings.md#data_table_id) * - [`DELETE_DATA_ID`](../constants/default-settings.md#delete_data_id) * - [`ADD_DATA_ID`](../constants/default-settings.md#add_data_id) * - [`EXPORT_IMAGE_ID`](../constants/default-settings.md#export_image_id) * - [`EXPORT_DATA_ID`](../constants/default-settings.md#export_data_id) * - [`ADD_MAP_STYLE_ID`](../constants/default-settings.md#add_map_style_id) * @public */ export const toggleModal: ( id: ToggleModalUpdaterAction['payload'] ) => Merge<ToggleModalUpdaterAction, {type: typeof ActionTypes.TOGGLE_MODAL}> = createAction( ActionTypes.TOGGLE_MODAL, (id: ToggleModalUpdaterAction['payload']) => ({ payload: id }) ); /** SHOW_EXPORT_DROPDOWN */ export type ShowExportDropdownUpdaterAction = { payload: string; }; /** * Hide and show side panel header dropdown, activated by clicking the share link on top of the side panel * @memberof uiStateActions * @param id - id of the dropdown * @public */ export const showExportDropdown: ( id: ShowExportDropdownUpdaterAction['payload'] ) => Merge< ShowExportDropdownUpdaterAction, {type: typeof ActionTypes.SHOW_EXPORT_DROPDOWN} > = createAction( ActionTypes.SHOW_EXPORT_DROPDOWN, (id: ShowExportDropdownUpdaterAction['payload']) => ({payload: id}) ); /** * Hide side panel header dropdown, activated by clicking the share link on top of the side panel * @memberof uiStateActions * @public */ export const hideExportDropdown: () => { type: typeof ActionTypes.HIDE_EXPORT_DROPDOWN; } = createAction(ActionTypes.HIDE_EXPORT_DROPDOWN); /** TOGGLE_MAP_CONTROL */ export type ToggleMapControlUpdaterAction = { payload: { panelId: string; index: number; }; }; /** * Toggle active map control panel * @memberof uiStateActions * @param panelId - map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`](#default_map_controls) * @public */ export const toggleMapControl: ( panelId: ToggleMapControlUpdaterAction['payload']['panelId'], index: ToggleMapControlUpdaterAction['payload']['index'] ) => Merge< ToggleMapControlUpdaterAction, {type: typeof ActionTypes.TOGGLE_MAP_CONTROL} > = createAction( ActionTypes.TOGGLE_MAP_CONTROL, ( panelId: ToggleMapControlUpdaterAction['payload']['panelId'], index: ToggleMapControlUpdaterAction['payload']['index'] ) => ({ payload: { panelId, index } }) ); /** SET_MAP_CONTROL_VISIBILITY */ export type setMapControlVisibilityUpdaterAction = { payload: { panelId: string; show: boolean; }; }; /** * Toggle active map control panel * @memberof uiStateActions * @param panelId - map control panel id, one of the keys of: [`DEFAULT_MAP_CONTROLS`](#default_map_controls) * @public */ export const setMapControlVisibility: ( panelId: setMapControlVisibilityUpdaterAction['payload']['panelId'], show: setMapControlVisibilityUpdaterAction['payload']['show'] ) => Merge< setMapControlVisibilityUpdaterAction, {type: typeof ActionTypes.SET_MAP_CONTROL_VISIBILITY} > = createAction( ActionTypes.SET_MAP_CONTROL_VISIBILITY, ( panelId: setMapControlVisibilityUpdaterAction['payload']['panelId'], show: setMapControlVisibilityUpdaterAction['payload']['show'] ) => ({ payload: { panelId, show } }) ); /** OPEN_DELETE_MODAL */ export type OpenDeleteModalUpdaterAction = { payload: string; }; /** * Toggle active map control panel * @memberof uiStateActions * @param datasetId - `id` of the dataset to be deleted * @public */ export const openDeleteModal: ( datasetId: OpenDeleteModalUpdaterAction['payload'] ) => Merge< OpenDeleteModalUpdaterAction, {type: typeof ActionTypes.OPEN_DELETE_MODAL} > = createAction( ActionTypes.OPEN_DELETE_MODAL, (datasetId: OpenDeleteModalUpdaterAction['payload']) => ({payload: datasetId}) ); /** ADD_NOTIFICATION */ export type AddNotificationUpdaterAction = { payload: object; }; /** * Add a notification to be displayed. * Existing notification will be updated in case of matching id. * @memberof uiStateActions * @param notification - The `notification` object to be added or updated * @public */ export const addNotification: ( notification: AddNotificationUpdaterAction['payload'] ) => Merge< AddNotificationUpdaterAction, { type: typeof ActionTypes.ADD_NOTIFICATION; } > = createAction( ActionTypes.ADD_NOTIFICATION, (notification: AddNotificationUpdaterAction['payload']) => ({payload: notification}) ); /** REMOVE_NOTIFICATION */ export type RemoveNotificationUpdaterAction = { payload: string; }; /** * Remove a notification * @memberof uiStateActions * @param id - `id` of the notification to be removed * @public */ export const removeNotification: ( id: RemoveNotificationUpdaterAction['payload'] ) => Merge< RemoveNotificationUpdaterAction, {type: typeof ActionTypes.REMOVE_NOTIFICATION} > = createAction( ActionTypes.REMOVE_NOTIFICATION, (id: RemoveNotificationUpdaterAction['payload']) => ({payload: id}) ); /** SET_EXPORT_IMAGE_SETTING */ export type SetExportImageSettingUpdaterAction = { payload: Partial<ExportImage>; }; /** * Set `exportImage` settings: ratio, resolution, legend * @memberof uiStateActions * @param newSetting - {ratio: '1x'} * @public */ export const setExportImageSetting: ( newSetting: SetExportImageSettingUpdaterAction['payload'] ) => Merge< SetExportImageSettingUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_IMAGE_SETTING} > = createAction( ActionTypes.SET_EXPORT_IMAGE_SETTING, (newSetting: SetExportImageSettingUpdaterAction['payload']) => ({payload: newSetting}) ); /** * Start exporting image flow * @memberof uiStateActions * @public */ export const startExportingImage: (options?: { ratio?: string; resolution?: string; legend?: string; center?: boolean; }) => Merge< SetExportImageSettingUpdaterAction, {type: typeof ActionTypes.START_EXPORTING_IMAGE} > = createAction(ActionTypes.START_EXPORTING_IMAGE, (payload: any) => ({payload})); /** SET_EXPORT_IMAGE_DATA_URI */ export type SetExportImageDataUriUpdaterAction = { payload: string; }; /** * Set `exportImage.setExportImageDataUri` to a dataUri * @memberof uiStateActions * @param dataUri - export image data uri * @public */ export const setExportImageDataUri: ( dataUri: SetExportImageDataUriUpdaterAction['payload'] ) => Merge< SetExportImageDataUriUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_IMAGE_DATA_URI} > = createAction( ActionTypes.SET_EXPORT_IMAGE_DATA_URI, (dataUri: SetExportImageDataUriUpdaterAction['payload']) => ({payload: dataUri}) ); /** SET_EXPORT_IMAGE_ERROR */ export type SetExportImageErrorUpdaterAction = { payload: Error; }; /** * Set Export image error * @memberof uiStateActions * @public */ export const setExportImageError: ( error: SetExportImageErrorUpdaterAction['payload'] ) => Merge< SetExportImageErrorUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_IMAGE_ERROR} > = createAction( ActionTypes.SET_EXPORT_IMAGE_ERROR, (error: SetExportImageErrorUpdaterAction['payload']) => ({payload: error}) ); /** * Delete cached export image * @memberof uiStateActions * @public */ export const cleanupExportImage: () => { type: typeof ActionTypes.CLEANUP_EXPORT_IMAGE; } = createAction(ActionTypes.CLEANUP_EXPORT_IMAGE); /** SET_EXPORT_SELECTED_DATASET */ export type SetExportSelectedDatasetUpdaterAction = { payload: string; }; /** * Set selected dataset for export * @memberof uiStateActions * @param datasetId - dataset id * @public */ export const setExportSelectedDataset: ( datasetId: SetExportSelectedDatasetUpdaterAction['payload'] ) => Merge< SetExportSelectedDatasetUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_SELECTED_DATASET} > = createAction( ActionTypes.SET_EXPORT_SELECTED_DATASET, (datasetId: SetExportSelectedDatasetUpdaterAction['payload']) => ({payload: datasetId}) ); /** SET_EXPORT_DATA_TYPE */ export type SetExportDataTypeUpdaterAction = { payload: string; }; /** * Set data format for exporting data * @memberof uiStateActions * @param dataType - one of `'text/csv'` * @public */ export const setExportDataType: ( dataType: SetExportDataTypeUpdaterAction['payload'] ) => Merge< SetExportDataTypeUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_DATA_TYPE} > = createAction( ActionTypes.SET_EXPORT_DATA_TYPE, (dataType: SetExportDataTypeUpdaterAction['payload']) => ({payload: dataType}) ); /** SET_EXPORT_FILTERED */ export type SetExportFilteredUpdaterAction = { payload: boolean; }; /** * Whether to export filtered data, `true` or `false` * @memberof uiStateActions * @param payload - set `true` to ony export filtered data * @public */ export const setExportFiltered: ( exportFiltered: SetExportFilteredUpdaterAction['payload'] ) => Merge< SetExportFilteredUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_FILTERED} > = createAction( ActionTypes.SET_EXPORT_FILTERED, (payload: SetExportFilteredUpdaterAction['payload']) => ({payload}) ); /** * Whether to including data in map config, toggle between `true` or `false` * @memberof uiStateActions * @public */ export const setExportData: () => {type: typeof ActionTypes.SET_EXPORT_DATA} = createAction( ActionTypes.SET_EXPORT_DATA ); /** SET_USER_MAPBOX_ACCESS_TOKEN */ export type SetUserMapboxAccessTokenUpdaterAction = { payload: string; }; /** * Whether we export a mapbox access token used to create a single map html file * @memberof uiStateActions * @param payload - mapbox access token * @public */ export const setUserMapboxAccessToken: ( payload: SetUserMapboxAccessTokenUpdaterAction['payload'] ) => Merge< SetUserMapboxAccessTokenUpdaterAction, {type: typeof ActionTypes.SET_USER_MAPBOX_ACCESS_TOKEN} > = createAction( ActionTypes.SET_USER_MAPBOX_ACCESS_TOKEN, (payload: SetUserMapboxAccessTokenUpdaterAction['payload']) => ({payload}) ); /** SET_EXPORT_MAP_FORMAT */ export type SetExportMapFormatUpdaterAction = { payload: string; }; /** * Set the export map format (html, json) * @memberOf uiStateActions * @param payload - map format * @public */ export const setExportMapFormat: ( mapFormat: SetExportMapFormatUpdaterAction['payload'] ) => Merge< SetExportMapFormatUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_MAP_FORMAT} > = createAction( ActionTypes.SET_EXPORT_MAP_FORMAT, (payload: SetExportMapFormatUpdaterAction['payload']) => ({payload}) ); /** SET_EXPORT_MAP_HTML_MODE */ export type SetExportHTMLMapModeUpdaterAction = { payload: string; }; /** * Set the HTML mode to use to export HTML mode * @memberOf uiStateActions * @param payload - map mode */ export const setExportHTMLMapMode: ( mode: SetExportHTMLMapModeUpdaterAction['payload'] ) => Merge< SetExportHTMLMapModeUpdaterAction, {type: typeof ActionTypes.SET_EXPORT_MAP_HTML_MODE} > = createAction( ActionTypes.SET_EXPORT_MAP_HTML_MODE, (payload: SetExportHTMLMapModeUpdaterAction['payload']) => ({payload}) ); /** SET_LOCALE */ export type SetLocaleUpdaterAction = { payload: {locale: string}; }; /** * Set `locale` value * @memberof uiStateActions * @param locale - locale of the UI * @public */ export const setLocale: ( locale: SetLocaleUpdaterAction['payload']['locale'] ) => Merge<SetLocaleUpdaterAction, {type: typeof ActionTypes.SET_LOCALE}> = createAction( ActionTypes.SET_LOCALE, (locale: SetLocaleUpdaterAction['payload']['locale']) => ({ payload: { locale } }) ); /** TOGGLE_LAYER_PANEL_LIST_VIEW */ export type ToggleLayerPanelListViewAction = { payload: string; }; /** * Toggle layer panel list view * @memberof uiStateActions * @param listView layer panel listView value. Can be 'list' or 'sortByDataset' * @public */ export const toggleLayerPanelListView: ( listView: ToggleLayerPanelListViewAction['payload'] ) => Merge< ToggleLayerPanelListViewAction, {type: typeof ActionTypes.TOGGLE_LAYER_PANEL_LIST_VIEW} > = createAction( ActionTypes.TOGGLE_LAYER_PANEL_LIST_VIEW, (listView: ToggleLayerPanelListViewAction['payload']) => ({payload: listView}) ); /** * This declaration is needed to group actions in docs */ /** * Actions handled mostly by `uiState` reducer. * They manage UI changes in tha app, such as open and close side panel, * switch between tabs in the side panel, open and close modal dialog for exporting data / images etc. * It also manges which settings are selected during image and map export * * @public */ /* eslint-disable no-unused-vars */ // @ts-ignore const uiStateActions = null; /* eslint-enable no-unused-vars */
the_stack
import { Component, ContentChild, ContentChildren, Directive, ElementRef, EventEmitter, Injectable, Input, Output, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, } from '@angular/core'; import { async, ComponentFixture, TestBed, } from '@angular/core/testing'; import { FormControl, FormControlDirective } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { isMockedNgDefOf } from '../common/func.is-mocked-ng-def-of'; import { MockBuilder } from '../mock-builder/mock-builder'; import { ngMocks } from '../mock-helper/mock-helper'; import { MockRender } from '../mock-render/mock-render'; import { MockDirective, MockDirectives } from './mock-directive'; import { MockedDirective } from './types'; @Injectable() class TargetService {} @Directive({ exportAs: 'foo', selector: '[exampleDirective]', }) class ExampleDirective { @Input() public exampleDirective = ''; @Output() public readonly someOutput = new EventEmitter<boolean>(); @Input('bah') public something = ''; protected s: any; public performAction(s: string) { this.s = s; return this; } } @Directive({ providers: [TargetService], selector: '[exampleStructuralDirective]', }) class ExampleStructuralDirective { @Input() public exampleStructuralDirective = true; } @Directive({ selector: '[getters-and-setters]', }) class GettersAndSettersDirective { @Input() public normalInput?: boolean; public normalProperty = false; protected value: any; public get myGetter() { return true; } public set mySetter(value: string) { this.value = value; } public normalMethod(): boolean { return this.myGetter; } } @Component({ selector: 'example-component-container', template: ` <div [exampleDirective]="'bye'" [bah]="'hi'" #f="foo" (someOutput)="emitted = $event" ></div> <div exampleDirective></div> <div id="example-structural-directive" *exampleStructuralDirective="true" > hi </div> <input [formControl]="fooControl" /> <div getters-and-setters></div> `, }) class ExampleComponentContainer { @ViewChild(ExampleDirective, {} as any) public childDirective?: ExampleDirective; public emitted = false; public readonly foo = new FormControl(''); public performActionOnChild(s: string): void { if (this.childDirective) { this.childDirective.performAction(s); } } } describe('MockDirective', () => { let component: ExampleComponentContainer; let fixture: ComponentFixture<ExampleComponentContainer>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ExampleComponentContainer, MockDirective(FormControlDirective), MockDirective(ExampleDirective), MockDirective(ExampleStructuralDirective), MockDirective(GettersAndSettersDirective), ], }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ExampleComponentContainer); component = fixture.componentInstance; fixture.detectChanges(); }); it('should have use a selector of the original component', () => { const element = fixture.debugElement.query( By.directive(ExampleDirective), ); expect(element).not.toBeNull(); }); it('should have the input set on the mock component', () => { const debugElement = fixture.debugElement.query( By.directive(ExampleDirective), ); const element = debugElement.injector.get(ExampleDirective); expect(element.something).toEqual('hi'); expect(element.exampleDirective).toEqual('bye'); }); it('triggers output bound behavior for extended outputs', () => { const debugElement = fixture.debugElement.query( By.directive(ExampleDirective), ); const element = debugElement.injector.get(ExampleDirective); element.someOutput.emit(true); expect(component.emitted).toEqual(true); }); it('should memoize the return value by argument', () => { expect(MockDirective(ExampleDirective)).toEqual( MockDirective(ExampleDirective), ); expect(MockDirective(ExampleDirective)).not.toEqual( ExampleDirective, ); }); it('can mock formControlDirective from angular', () => { // Some angular directives set up their metadata in a different way than @Directive does // I found that FormControlDirective is one of those weird directives. // Since I do not know how they did it, I don't know how to test it except to write this // Test around a known-odd directive. const debugElement = fixture.debugElement.query( By.directive(ExampleDirective), ); expect(debugElement).not.toBeNull(); }); it('should display structural directive content', () => { const mockDirective = ngMocks.findInstance( fixture.debugElement, ExampleStructuralDirective, ) as MockedDirective<ExampleStructuralDirective>; // structural directives should be rendered first. mockDirective.__render(); fixture.detectChanges(); expect(mockDirective.exampleStructuralDirective).toBeTruthy(); const debugElement = fixture.debugElement.query( By.css('#example-structural-directive'), ); expect(debugElement.nativeElement.innerHTML).toContain('hi'); }); it('renders with true', async () => { await MockBuilder(ExampleComponentContainer).mock( ExampleStructuralDirective, { render: true, }, ); expect(() => MockRender(ExampleComponentContainer)).not.toThrow(); }); it('renders with $implicit', async () => { await MockBuilder(ExampleComponentContainer).mock( ExampleStructuralDirective, { render: { $implicit: true, }, }, ); expect(() => MockRender(ExampleComponentContainer)).not.toThrow(); }); it('should set ViewChild directives correctly', () => { fixture.detectChanges(); expect(component.childDirective).toBeTruthy(); }); it('should allow spying of viewchild directive methods', () => { const spy = component.childDirective ? component.childDirective.performAction : null; component.performActionOnChild('test'); expect(spy).toHaveBeenCalledWith('test'); }); it('should set getters and setters to undefined instead of function', () => { const mockDirective = ngMocks.findInstance( fixture.debugElement, GettersAndSettersDirective, ) as MockedDirective<GettersAndSettersDirective>; expect(() => mockDirective.__render()).not.toThrow(); expect(mockDirective.normalMethod).toBeDefined(); expect(mockDirective.myGetter).not.toBeDefined(); expect(mockDirective.mySetter).not.toBeDefined(); expect(mockDirective.normalProperty).not.toBeDefined(); }); it('mocks several directives', () => { const mocks = MockDirectives( GettersAndSettersDirective, ExampleStructuralDirective, ); expect(mocks.length).toEqual(2); expect( isMockedNgDefOf(mocks[0], GettersAndSettersDirective, 'd'), ).toBeTruthy(); expect( isMockedNgDefOf(mocks[1], ExampleStructuralDirective, 'd'), ).toBeTruthy(); }); it('A9 correct mocking of ContentChild, ContentChildren, ViewChild, ViewChildren ISSUE #109', () => { @Directive({ selector: 'never', }) class MyClass { @ContentChild('i1', { read: TemplateRef } as any) public o1?: TemplateRef<any>; @ContentChildren('i2', { read: TemplateRef } as any) public o2?: QueryList<TemplateRef<any>>; @ViewChild('i3', { read: TemplateRef } as any) public o3?: TemplateRef<any>; @ViewChildren('i4', { read: TemplateRef } as any) public o4?: QueryList<TemplateRef<any>>; @ContentChild('i5', { read: ElementRef } as any) public o5?: ElementRef; @ContentChildren('i6', { read: ElementRef } as any) public o6?: QueryList<ElementRef>; @ViewChild('i7', { read: ElementRef } as any) public o7?: ElementRef; @ViewChildren('i8', { read: ElementRef } as any) public o8?: QueryList<ElementRef>; } const actual = MockDirective(MyClass) as any; expect(actual.__prop__metadata__).toEqual({ o1: [ jasmine.objectContaining({ selector: 'i1', isViewQuery: false, read: TemplateRef, ngMetadataName: 'ContentChild', }), ], o2: [ jasmine.objectContaining({ selector: 'i2', isViewQuery: false, read: TemplateRef, ngMetadataName: 'ContentChildren', }), ], o3: [ jasmine.objectContaining({ selector: 'i3', isViewQuery: true, read: TemplateRef, ngMetadataName: 'ViewChild', }), ], o4: [ jasmine.objectContaining({ selector: 'i4', isViewQuery: true, read: TemplateRef, ngMetadataName: 'ViewChildren', }), ], o5: [ jasmine.objectContaining({ selector: 'i5', isViewQuery: false, read: ElementRef, ngMetadataName: 'ContentChild', }), ], o6: [ jasmine.objectContaining({ selector: 'i6', isViewQuery: false, read: ElementRef, ngMetadataName: 'ContentChildren', }), ], o7: [ jasmine.objectContaining({ selector: 'i7', isViewQuery: true, read: ElementRef, ngMetadataName: 'ViewChild', }), ], o8: [ jasmine.objectContaining({ selector: 'i8', isViewQuery: true, read: ElementRef, ngMetadataName: 'ViewChildren', }), ], __ngMocksVcr_o1: [ jasmine.objectContaining({ selector: 'i1', isViewQuery: false, read: ViewContainerRef, ngMetadataName: 'ContentChild', }), ], __ngMocksVcr_o2: [ jasmine.objectContaining({ selector: 'i2', isViewQuery: false, read: ViewContainerRef, ngMetadataName: 'ContentChildren', }), ], __ngMocksVcr_o5: [ jasmine.objectContaining({ selector: 'i5', isViewQuery: false, read: ViewContainerRef, ngMetadataName: 'ContentChild', }), ], __ngMocksVcr_o6: [ jasmine.objectContaining({ selector: 'i6', isViewQuery: false, read: ViewContainerRef, ngMetadataName: 'ContentChildren', }), ], }); }); });
the_stack
import { EventEmitter, Input, Output, Directive } from '@angular/core'; import { PoLanguageService, poLocaleDefault } from '@po-ui/ng-components'; import { poModalPasswordRecoveryLiterals } from './literals/i18n/po-modal-password-recovery-literals'; import { PoModalPasswordRecoveryType } from './enums/po-modal-password-recovery-type.enum'; const PoModalPasswordRecoveryDefaultMaxLength = 15; const PoModalPasswordRecoveryDefaultMinLength = 15; const PoModalPasswordRecoveryDefaultPhone = '(99) 99999-9999'; const PoModalPasswordRecoveryTypeDefault: PoModalPasswordRecoveryType = PoModalPasswordRecoveryType.Email; /** * @description * * O componente `po-modal-password-recovery` é utilizado como template para solicitação de troca de senha. * * É composto por uma modal que possui três telas, cada uma com as seguintes características: * * - A primeira possui campos para preenchimento de email ou número de telefone; * - Tela com campo para preenchimento de código SMS enviado para o número de telefone enviado; * - A terceira se trata de uma confirmação de envio de link para a caixa de email do usuário. * * * A propriedade `p-url-recovery` automatiza a rotina do componente e simplifica o processo * para recuperação de senha, bastando definir uma url para requisição dos recursos. * Seu detalhamento para uso pode ser visto logo abaixo em *propriedades*. * Caso julgue necessário, pode-se também definir manualmente a rotina do componente. * * * Para a modal de digitação de código SMS, é possível definir uma mensagem de erro * customizada com a propriedade `p-code-error` e há um link para * reenvio de código por SMS. Ao reenviar, o evento `p-code-submit` envia um objeto com o telefone do usuário e a quantidade * de vezes em que o usuário fez a solicitação de reenvio. * * > É indicada a utilização da tela de digitação para envio de código SMS apenas * se a opção por envio SMS for disponibilizada para o usuário. * * * A modal de confirmação contém uma ação de reenvio e o evento `p-submit` * é quem passa o objeto contendo o email em conjunto com a quantidade de tentativas de reenvio. * * > A tela de confirmação é indicada para quando o usuário solicitar a troca através do email. * * > Os textos das modals são pré-definidos, imutáveis e são traduzidos de acordo com o idioma do *browser* (pt, en e es) * * Para que as imagens sejam exibidas corretamente, é necessário incluir o caminho delas ao projeto. Para isso, edite * o *assets* no arquivo **angular.json** da aplicação na seguinte ordem: * ``` * "assets": [ * "src/assets", * "src/favicon.ico", * { * "glob": "**\/*", * "input": "node_modules/@po-ui/style/images", * "output": "assets/images" * } * ] * ``` */ @Directive() export abstract class PoModalPasswordRecoveryBaseComponent { /** * @optional * * @description * * Definição de mensagem de erro customizada para quando o usuário passar um código SMS inválido ou errado. */ @Input('p-code-error') codeError: string; /** * @optional * * @description * * Endpoint usado pelo template para requisição do recurso. Quando preenchido, * o métodos `p-submit` e `p-submit-code` serão ignorados e o componente adquirirá automatização * para o processo de solicitação de troca de senha. * * ### Processos * Ao digitar um valor válido no campo de email/telefone e pressionar **enviar**, * o componente fará uma requisição `POST` na url especificada nesta propriedade passando o objeto contendo o valor definido pelo usuário. * * ``` * body { * email: email, * retry?: retry * } * ``` * * * #### Recuperação por email * Para a recuperação de senha por **email**, o código de resposta HTTP de status esperado é `204`. * * Em caso de **sucesso**, será exibida a modal de confirmação de e-mail para o usuário. * * * > A ação **Reenviar** na tela de confirmação efetua uma nova requisição * passando-se o objeto com incremento para o valor da propriedade **retry**. * * *Processo finalizado.* * * * #### Recuperação por SMS * Se a opção de recuperação for por **SMS**, o código de status de sucesso deve ser `200`. * Em caso de **sucesso**, abre-se a modal de digitação de código SMS e a resposta * desta requisição deve retornar uma definição de dados abaixo: * * ``` * 200: * { * hash: hash, * urlValidationCode?: url * } * ``` * * * - O **hash** será o código de validação da solicitação do SMS para ser enviado juntamente com o código de verificação do SMS; * - **urlValidationCode** é a url usada para validação do código enviado por SMS. * * * > Caso não seja passado urlValidationCode, o endpoint usado para validação do código será `<p-url-recovery>/validation`. * * * #### Validação do código SMS * Ao digitar um valor válido no campo de código SMS e pressionar **continuar**, o componente fará uma requisição `POST` contendo: * * ``` * POST /<p-url-recovery>/validation OU /<urlValidationCode> * Body { * hash: hash, * code: code * } * ``` * * * O código de resposta HTTP de status esperado é `200`. * * Em caso de **erro** na validação do código SMS, a modal se mantém com o campo para digitação * de código SMS * * * > Pode-se atribuir a mensagem de erro (message) para o atributo `p-code-error` conforme retorno abaixo: * * ``` * 400 * { * error { * message: 'Error Message' * } * } * ``` * * * Em caso de **sucesso**, espera-se a resposta desta requisição retornando a seguinte definição: * * ``` * 200: * { * token: token, * urlChangePassword?: url * } * ``` * * * - **token**: Token de alteração de senha; * - **urlChangePassword**: url para o formulário de alteração de senha. * * * O componente está configurado para redirecionar para a url estabelecida em `urlChangePassword`. * * > Caso não seja passado valor para urlChangePassword, * a url usada para validação será a `<p-url-recovery>/changePassword?token=<token>`. * * *Processo finalizado.* */ @Input('p-url-recovery') urlRecovery?: string; /** * @optional * * @description * * Ação contendo como parâmetro o código enviado por SMS e digitado pelo usuário. * * > Esta propriedade será ignorada se for definido valor para a propriedade `p-url-recovery`. */ @Output('p-code-submit') codeSubmit = new EventEmitter<any>(); /** * @optional * * @description * * Ação contendo o email como parâmetro e que é executada quando o usuário clica sobres os botões de 'enviar' e 'reenviar' e-mail. * * > Esta propriedade será ignorada se for definido valor para a propriedade `p-url-recovery`. */ @Output('p-submit') submit = new EventEmitter<any>(); email: string; maxLength = PoModalPasswordRecoveryDefaultMaxLength; minLength = PoModalPasswordRecoveryDefaultMinLength; modalPasswordRecoveryTypeAll: boolean; phone: string; smsCode: string; smsCodeErrorMessage: string; literals: { cancelButton: string; closeButton: string; continueButton: string; email: string; emailErrorMessagePhrase: string; emailSentConfirmationPhrase: string; emailSentTitle: string; forgotPasswordTitle: string; insertCode: string; insertEmail: string; insertPhone: string; phoneErrorMessagePhrase: string; prepositionIn: string; prepositionOr: string; recoveryPasswordPhrase: string; resendEmailButton: string; resendSmsCodePhrase: string; sendAgain: string; sendAgainPhrase: string; sendButton: string; sms: string; smsCode: string; smsCodeErrorMessagePhrase: string; sentSmsCodePhrase: string; supportContact: string; telephone: string; typeCodeTitle: string; } = poModalPasswordRecoveryLiterals[poLocaleDefault]; private _contactEmail: string; private _phoneMask = PoModalPasswordRecoveryDefaultPhone; private _type: PoModalPasswordRecoveryType = PoModalPasswordRecoveryTypeDefault; /** * @optional * * @description * * Definição do e-mail que é exibido na mensagem para contato de suporte. */ @Input('p-contact-email') set contactEmail(value: string) { this._contactEmail = value; this.smsCodeErrorMessage = this.concatenateSMSErrorMessage(value); } get contactEmail() { return this._contactEmail; } /** * @optional * * @description * * Definição da mascara do campo de telefone. * * @default `(99) 99999-9999` */ @Input('p-phone-mask') set phoneMask(value: string) { this._phoneMask = value || PoModalPasswordRecoveryDefaultPhone; this.minLength = this.maxLength = this._phoneMask.length; } get phoneMask() { return this._phoneMask; } /** * @optional * * @description * * Define o tipo de recuperação de senha que será exibido. * * @default `PoModalPasswordRecoveryType.Email` * */ @Input('p-type') set type(value: PoModalPasswordRecoveryType) { this._type = (<any>Object).values(PoModalPasswordRecoveryType).includes(value) ? value : PoModalPasswordRecoveryTypeDefault; } get type() { return this._type; } constructor(languageService: PoLanguageService) { this.literals = { ...this.literals, ...poModalPasswordRecoveryLiterals[languageService.getShortLanguage()] }; } private concatenateSMSErrorMessage(value: string) { const literalCodeErrorMessage = this.literals.smsCodeErrorMessagePhrase; return value && value !== '' ? `${literalCodeErrorMessage} ${this.literals.prepositionIn} ${value}.` : literalCodeErrorMessage; } /** * Acão para conclusão de processo e fechamento da modal. Indica-se sua utilização * para após o envio e validação do código SMS enviado pelo usuário. * * > Nas modals em que há a ação de 'cancelar' dispensa-se o uso desta ação pois o componente já trata o fechamento da modal. */ abstract completed(): void; /** * Abre a modal de preenchimento de email ou número de telefone para solicitação de troca de senha. */ abstract open(): void; /** * Abre a modal de confirmação de envio de email. */ abstract openConfirmation(): void; /** * Abre a modal de preenchimento do código SMS enviado ao usuário. */ abstract openSmsCode(): void; }
the_stack
import angular, {ICompileService, IRootScopeService, ITimeoutService} from 'angular' import 'angular-mocks' import { expect } from 'chai' describe('Columns', function () { // Load the module with MainController beforeEach(function () { angular.mock.module('gantt', 'gantt.labels') }) let Gantt let $rootScope: IRootScopeService let $compile: ICompileService let $timeout: ITimeoutService let mockData = [ // Order is optional. If not specified it will be assigned automatically { 'name': 'Milestones', 'height': '3em', classes: 'gantt-row-milestone', 'color': '#45607D', 'tasks': [ // Dates can be specified as string, timestamp or javascript date object. The data attribute can be used to attach a custom object { 'name': 'Kickoff', 'color': '#93C47D', 'from': '2013-10-07T09:00:00', 'to': '2013-10-07T10:00:00', 'data': 'Can contain any custom data or object' }, { 'name': 'Concept approval', 'color': '#93C47D', 'from': new Date(2013, 9, 18, 18, 0, 0), 'to': new Date(2013, 9, 18, 18, 0, 0), 'est': new Date(2013, 9, 16, 7, 0, 0), 'lct': new Date(2013, 9, 19, 0, 0, 0) }, { 'name': 'Development finished', 'color': '#93C47D', 'from': new Date(2013, 10, 15, 18, 0, 0), 'to': new Date(2013, 10, 15, 18, 0, 0) }, { 'name': 'Shop is running', 'color': '#93C47D', 'from': new Date(2013, 10, 22, 12, 0, 0), 'to': new Date(2013, 10, 22, 12, 0, 0) }, { 'name': 'Go-live', 'color': '#93C47D', 'from': new Date(2013, 10, 29, 16, 0, 0), 'to': new Date(2013, 10, 29, 16, 0, 0) } ], 'data': 'Can contain any custom data or object' }, { 'name': 'Status meetings', 'tasks': [ { 'name': 'Demo', 'color': '#9FC5F8', 'from': new Date(2013, 9, 25, 15, 0, 0), 'to': new Date(2013, 9, 25, 18, 30, 0) }, { 'name': 'Demo', 'color': '#9FC5F8', 'from': new Date(2013, 10, 1, 15, 0, 0), 'to': new Date(2013, 10, 1, 18, 0, 0) }, { 'name': 'Demo', 'color': '#9FC5F8', 'from': new Date(2013, 10, 8, 15, 0, 0), 'to': new Date(2013, 10, 8, 18, 0, 0) }, { 'name': 'Demo', 'color': '#9FC5F8', 'from': new Date(2013, 10, 15, 15, 0, 0), 'to': new Date(2013, 10, 15, 18, 0, 0) }, { 'name': 'Demo', 'color': '#9FC5F8', 'from': new Date(2013, 10, 24, 9, 0, 0), 'to': new Date(2013, 10, 24, 10, 0, 0) } ] }, { 'name': 'Kickoff', 'tasks': [ { 'name': 'Day 1', 'color': '#9FC5F8', 'from': new Date(2013, 9, 7, 9, 0, 0), 'to': new Date(2013, 9, 7, 17, 0, 0), 'progress': {'percent': 100, 'color': '#3C8CF8'} }, { 'name': 'Day 2', 'color': '#9FC5F8', 'from': new Date(2013, 9, 8, 9, 0, 0), 'to': new Date(2013, 9, 8, 17, 0, 0), 'progress': {'percent': 100, 'color': '#3C8CF8'} }, { 'name': 'Day 3', 'color': '#9FC5F8', 'from': new Date(2013, 9, 9, 8, 30, 0), 'to': new Date(2013, 9, 9, 12, 0, 0), 'progress': {'percent': 100, 'color': '#3C8CF8'} } ] }, { 'name': 'Create concept', 'tasks': [ { 'name': 'Create concept', 'color': '#F1C232', 'from': new Date(2013, 9, 10, 8, 0, 0), 'to': new Date(2013, 9, 16, 18, 0, 0), 'est': new Date(2013, 9, 8, 8, 0, 0), 'lct': new Date(2013, 9, 18, 20, 0, 0), 'progress': 100 } ] }, { 'name': 'Finalize concept', 'tasks': [ { 'name': 'Finalize concept', 'color': '#F1C232', 'from': new Date(2013, 9, 17, 8, 0, 0), 'to': new Date(2013, 9, 18, 18, 0, 0), 'progress': 100 } ] }, { 'name': 'Sprint 1', 'tasks': [ { 'name': 'Product list view', 'color': '#F1C232', 'from': new Date(2013, 9, 21, 8, 0, 0), 'to': new Date(2013, 9, 25, 15, 0, 0), 'progress': 25 } ] }, { 'name': 'Sprint 2', 'tasks': [ { 'name': 'Order basket', 'color': '#F1C232', 'from': new Date(2013, 9, 28, 8, 0, 0), 'to': new Date(2013, 10, 1, 15, 0, 0) } ] }, { 'name': 'Sprint 3', 'tasks': [ { 'name': 'Checkout', 'color': '#F1C232', 'from': new Date(2013, 10, 4, 8, 0, 0), 'to': new Date(2013, 10, 8, 15, 0, 0) } ] }, { 'name': 'Sprint 4', 'tasks': [ { 'name': 'Login&Singup and admin view', 'color': '#F1C232', 'from': new Date(2013, 10, 11, 8, 0, 0), 'to': new Date(2013, 10, 15, 15, 0, 0) } ] }, { 'name': 'Setup server', 'tasks': [ { 'name': 'HW', 'color': '#F1C232', 'from': new Date(2013, 10, 18, 8, 0, 0), 'to': new Date(2013, 10, 18, 12, 0, 0) } ] }, { 'name': 'Config server', 'tasks': [ { 'name': 'SW / DNS/ Backups', 'color': '#F1C232', 'from': new Date(2013, 10, 18, 12, 0, 0), 'to': new Date(2013, 10, 21, 18, 0, 0) } ] }, { 'name': 'Deployment', 'tasks': [ { 'name': 'Depl. & Final testing', 'color': '#F1C232', 'from': new Date(2013, 10, 21, 8, 0, 0), 'to': new Date(2013, 10, 22, 12, 0, 0), 'classes': 'gantt-task-deployment' } ] }, { 'name': 'Workshop', 'tasks': [ { 'name': 'On-side education', 'color': '#F1C232', 'from': new Date(2013, 10, 24, 9, 0, 0), 'to': new Date(2013, 10, 25, 15, 0, 0) } ] }, { 'name': 'Content', 'tasks': [ { 'name': 'Supervise content creation', 'color': '#F1C232', 'from': new Date(2013, 10, 26, 9, 0, 0), 'to': new Date(2013, 10, 29, 16, 0, 0) } ] }, { 'name': 'Documentation', 'tasks': [ { 'name': 'Technical/User documentation', 'color': '#F1C232', 'from': new Date(2013, 10, 26, 8, 0, 0), 'to': new Date(2013, 10, 28, 18, 0, 0) } ] } ] beforeEach(inject(['$rootScope', '$compile', '$timeout', 'Gantt', function ($tRootScope: IRootScopeService, $tCompile: ICompileService, $tTimeout: ITimeoutService, tGantt) { Gantt = tGantt $rootScope = $tRootScope $compile = $tCompile $timeout = $tTimeout }])) it('should have first and last columns to right position', function () { let width = 350 let $scope = $rootScope.$new() $scope.ganttElementWidth = width $scope.data = angular.copy(mockData) let $element = angular.element() let gantt = new Gantt($scope, $element) gantt.loadData($scope.data) $scope.$digest() gantt.initialized() let columnsManager = gantt.columnsManager let firstColumn = columnsManager.getColumnByPosition(0) let firstColumm2 = columnsManager.getFirstColumn() expect(firstColumn).to.be.equal(firstColumm2) let lastColumn = columnsManager.getColumnByPosition(width - 1) let lastColumn2 = columnsManager.getLastColumn() expect(lastColumn).to.be.equal(lastColumn2) } ) function expectValidDateFromPosition (gantt, width, ganttStartDate, ganttEndDate, x) { let ganttDate = gantt.getDateByPosition(x) let ganttX = gantt.getPositionByDate(ganttDate) expect(ganttX).to.be.closeTo(x, 0.1) let totalDuration = ganttEndDate.diff(ganttStartDate, 'milliseconds') let leftDuration = ganttDate.diff(ganttStartDate, 'milliseconds') if (ganttStartDate.isDST() && !ganttDate.isDST()) { leftDuration -= 3600000 } else if (!ganttStartDate.isDST() && ganttDate.isDST()) { leftDuration += 3600000 } if (ganttStartDate.isDST() && !ganttEndDate.isDST()) { totalDuration -= 3600000 } else if (!ganttStartDate.isDST() && ganttEndDate.isDST()) { totalDuration += 3600000 } if (x === 0) { expect(leftDuration).to.be.equal(0) } else { let ratio = leftDuration * (width / x) / totalDuration expect(ratio).to.be.closeTo(1, 0.1) } } it('should compute valid dates from range positions', function () { let width = 350 let $scope = $rootScope.$new() $scope.ganttElementWidth = width $scope.data = angular.copy(mockData) $scope.columnMagnet = undefined let $element = angular.element() let gantt = new Gantt($scope, $element) gantt.loadData($scope.data) $scope.$digest() gantt.initialized() let toDate let fromDate angular.forEach($scope.data, function (row) { if (row.tasks !== undefined) { angular.forEach(row.tasks, function (task) { if (fromDate === undefined || fromDate > task.from) { fromDate = task.from } if (toDate === undefined || toDate < task.to) { toDate = task.to } }) } }) let timeUnit = gantt.options.value('viewScale') fromDate.startOf(timeUnit) toDate.startOf(timeUnit).add(1, timeUnit) let ganttStartDate = gantt.getDateByPosition(0) let ganttEndDate = gantt.getDateByPosition(width - 1) expect(ganttStartDate.isSame(fromDate)).to.be.ok expect(ganttEndDate.isSame(toDate)).to.be.ok for (let i = 1; i < width; i++) { expectValidDateFromPosition(gantt, width, ganttStartDate, ganttEndDate, i) } } ) it('should compute valid dates from previous positions', function () { let width = 350 let $scope = $rootScope.$new() $scope.ganttElementWidth = width $scope.data = angular.copy(mockData) $scope.columnMagnet = undefined let $element = angular.element() let gantt = new Gantt($scope, $element) gantt.loadData($scope.data) $scope.$digest() gantt.initialized() let toDate let fromDate angular.forEach($scope.data, function (row) { if (row.tasks !== undefined) { angular.forEach(row.tasks, function (task) { if (fromDate === undefined || fromDate > task.from) { fromDate = task.from } if (toDate === undefined || toDate < task.to) { toDate = task.to } }) } }) let timeUnit = gantt.options.value('viewScale') fromDate.startOf(timeUnit) toDate.startOf(timeUnit).add(1, timeUnit) let ganttStartDate = gantt.getDateByPosition(0) let ganttEndDate = gantt.getDateByPosition(width - 1) expect(ganttStartDate.isSame(fromDate)).to.be.ok expect(ganttEndDate.isSame(toDate)).to.be.ok for (let i = 0; i > -width; i--) { expectValidDateFromPosition(gantt, width, ganttStartDate, ganttEndDate, i) } } ) it('should compute valid dates from next positions', function () { let width = 350 let $scope = $rootScope.$new() $scope.ganttElementWidth = width $scope.data = angular.copy(mockData) $scope.columnMagnet = undefined let $element = angular.element() let gantt = new Gantt($scope, $element) gantt.loadData($scope.data) $scope.$digest() gantt.initialized() let toDate let fromDate angular.forEach($scope.data, function (row) { if (row.tasks !== undefined) { angular.forEach(row.tasks, function (task) { if (fromDate === undefined || fromDate > task.from) { fromDate = task.from } if (toDate === undefined || toDate < task.to) { toDate = task.to } }) } }) let timeUnit = gantt.options.value('viewScale') fromDate.startOf(timeUnit) toDate.startOf(timeUnit).add(1, timeUnit) let ganttStartDate = gantt.getDateByPosition(0) let ganttEndDate = gantt.getDateByPosition(width - 1) expect(ganttStartDate.isSame(fromDate)).to.be.ok expect(ganttEndDate.isSame(toDate)).to.be.ok for (let i = width; i < 2 * width; i++) { expectValidDateFromPosition(gantt, width, ganttStartDate, ganttEndDate, i) } } ) it('should work with custom comparators', function () { let width = 350 let $scope = $rootScope.$new() $scope.ganttElementWidth = width $scope.data = angular.copy(mockData) $scope.columnMagnet = undefined $scope.filterRow = {'name': 'Status meetings'} $scope.filterRowComparator = function (actual, expected) { return expected === actual } let $element = angular.element() let gantt = new Gantt($scope, $element) gantt.loadData($scope.data) $scope.$digest() gantt.initialized() gantt.api.rows.refresh() expect(gantt.rowsManager.filteredRows.length).to.be.eq(1) } ) })
the_stack
import { expect } from "chai"; import * as faker from "faker"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { PrimitiveValue, PropertyDescription, PropertyRecord } from "@itwin/appui-abstract"; import { IModelConnection } from "@itwin/core-frontend"; import { Content, ContentDescriptorRequestOptions, ContentRequestOptions, Descriptor, FIELD_NAMES_SEPARATOR, KeySet, Paged, RegisteredRuleset, SelectionInfo, } from "@itwin/presentation-common"; import { createRandomECInstanceKey, createRandomRuleset, createTestContentDescriptor, createTestContentItem, createTestNestedContentField, createTestPropertiesContentField, createTestPropertyInfo, createTestSimpleContentField, PromiseContainer, ResolvablePromise, } from "@itwin/presentation-common/lib/cjs/test"; import { Presentation, PresentationManager, RulesetManager } from "@itwin/presentation-frontend"; import { CacheInvalidationProps, ContentDataProvider, ContentDataProviderProps } from "../../presentation-components/common/ContentDataProvider"; import { mockPresentationManager } from "../_helpers/UiComponents"; /** * The Provider class is used to make protected [[ContentDataProvider]] * function public so the tests can call and spy on them. */ class Provider extends ContentDataProvider { constructor(props: ContentDataProviderProps) { super(props); } public override invalidateCache(props: CacheInvalidationProps) { super.invalidateCache(props); } public override shouldRequestContentForEmptyKeyset() { return super.shouldRequestContentForEmptyKeyset(); } public override async getDescriptorOverrides() { return super.getDescriptorOverrides(); } } describe("ContentDataProvider", () => { let rulesetId: string; let displayType: string; let provider: Provider; let invalidateCacheSpy: sinon.SinonSpy<[CacheInvalidationProps], void>; let presentationManagerMock: moq.IMock<PresentationManager>; let rulesetsManagerMock: moq.IMock<RulesetManager>; const imodelMock = moq.Mock.ofType<IModelConnection>(); const imodelKey = "test-imodel-Key"; before(() => { rulesetId = faker.random.word(); displayType = faker.random.word(); }); beforeEach(() => { const mocks = mockPresentationManager(); rulesetsManagerMock = mocks.rulesetsManager; presentationManagerMock = mocks.presentationManager; Presentation.setPresentationManager(presentationManagerMock.object); imodelMock.reset(); imodelMock.setup((x) => x.key).returns(() => imodelKey); provider = new Provider({ imodel: imodelMock.object, ruleset: rulesetId, displayType, enableContentAutoUpdate: true }); invalidateCacheSpy = sinon.spy(provider, "invalidateCache"); }); afterEach(() => { provider.dispose(); Presentation.terminate(); }); describe("constructor", () => { it("sets display type", () => { const type = faker.random.word(); const p = new Provider({ imodel: imodelMock.object, ruleset: rulesetId, displayType: type }); expect(p.displayType).to.eq(type); }); it("sets paging size", () => { const pagingSize = faker.random.number(); const p = new Provider({ imodel: imodelMock.object, ruleset: rulesetId, displayType, pagingSize }); expect(p.pagingSize).to.be.eq(pagingSize); }); it("registers ruleset", async () => { rulesetsManagerMock.setup(async (x) => x.add(moq.It.isAny())).returns(async (r) => new RegisteredRuleset(r, "test", () => { })); const ruleset = await createRandomRuleset(); const p = new Provider({ imodel: imodelMock.object, ruleset, displayType }); expect(p.rulesetId).to.eq(ruleset.id); rulesetsManagerMock.verify(async (x) => x.add(ruleset), moq.Times.once()); }); it("disposes registered ruleset after provided is disposed before registration completes", async () => { const registerPromise = new ResolvablePromise<RegisteredRuleset>(); rulesetsManagerMock.setup(async (x) => x.add(moq.It.isAny())).returns(async () => registerPromise); const ruleset = await createRandomRuleset(); const p = new Provider({ imodel: imodelMock.object, ruleset, displayType }); p.dispose(); const rulesetDisposeSpy = sinon.spy(); await registerPromise.resolve(new RegisteredRuleset(ruleset, "test", rulesetDisposeSpy)); expect(rulesetDisposeSpy).to.be.calledOnce; }); }); describe("dispose", () => { it("disposes registered ruleset", async () => { const registerPromise = new ResolvablePromise<RegisteredRuleset>(); rulesetsManagerMock.setup(async (x) => x.add(moq.It.isAny())).returns(async () => registerPromise); const ruleset = await createRandomRuleset(); const p = new Provider({ imodel: imodelMock.object, ruleset, displayType }); const rulesetDisposeSpy = sinon.spy(); await registerPromise.resolve(new RegisteredRuleset(ruleset, "test", rulesetDisposeSpy)); expect(rulesetDisposeSpy).to.not.be.called; p.dispose(); expect(rulesetDisposeSpy).to.be.calledOnce; }); }); describe("rulesetId", () => { it("returns rulesetId provider is initialized with", () => { expect(provider.rulesetId).to.eq(rulesetId); }); it("sets a different rulesetId and clears caches", () => { const newId = `${rulesetId} (changed)`; provider.rulesetId = newId; expect(provider.rulesetId).to.eq(newId); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("doesn't clear caches if setting to the same rulesetId", () => { const newId = `${rulesetId}`; provider.rulesetId = newId; expect(provider.rulesetId).to.eq(newId); expect(invalidateCacheSpy).to.not.be.called; }); }); describe("imodel", () => { it("returns imodel provider is initialized with", () => { expect(provider.imodel).to.eq(imodelMock.object); }); it("sets a different imodel and clears caches", () => { const newConnection = moq.Mock.ofType<IModelConnection>(); provider.imodel = newConnection.object; expect(provider.imodel).to.eq(newConnection.object); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("doesn't clear caches if setting to the same imodel", () => { provider.imodel = imodelMock.object; expect(provider.imodel).to.eq(imodelMock.object); expect(invalidateCacheSpy).to.not.be.called; }); }); describe("selectionInfo", () => { it("sets a different selectionInfo and clears caches", () => { const info1: SelectionInfo = { providerName: "a" }; provider.selectionInfo = info1; expect(provider.selectionInfo).to.eq(info1); invalidateCacheSpy.resetHistory(); const info2: SelectionInfo = { providerName: "b" }; provider.selectionInfo = info2; expect(provider.selectionInfo).to.eq(info2); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("doesn't clear caches if setting to the same selectionInfo", () => { const info1: SelectionInfo = { providerName: "a" }; provider.selectionInfo = info1; expect(provider.selectionInfo).to.eq(info1); invalidateCacheSpy.resetHistory(); provider.selectionInfo = info1; expect(provider.selectionInfo).to.eq(info1); expect(invalidateCacheSpy).to.not.be.called; }); }); describe("keys", () => { it("sets keys and clears caches", () => { const keys = new KeySet([createRandomECInstanceKey()]); provider.keys = keys; expect(provider.keys).to.eq(keys); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("doesn't clear caches if keys didn't change", () => { const keys = new KeySet(); provider.keys = keys; invalidateCacheSpy.resetHistory(); provider.keys = keys; expect(invalidateCacheSpy).to.not.be.called; }); it("sets keys and clears caches when keys change in place", () => { const keys = new KeySet(); provider.keys = keys; invalidateCacheSpy.resetHistory(); keys.add(createRandomECInstanceKey()); provider.keys = keys; expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); }); describe("getContentDescriptor", () => { const selection: SelectionInfo = { providerName: "test" }; beforeEach(() => { provider.keys = new KeySet([createRandomECInstanceKey()]); }); it("requests presentation manager for descriptor and returns its copy", async () => { const result = createTestContentDescriptor({ displayType, fields: [] }); presentationManagerMock .setup(async (x) => x.getContentDescriptor(moq.It.isObjectWith<ContentDescriptorRequestOptions<IModelConnection, KeySet>>({ imodel: imodelMock.object, rulesetOrId: rulesetId, displayType, selection }))) .returns(async () => result) .verifiable(); provider.selectionInfo = selection; const descriptor = await provider.getContentDescriptor(); presentationManagerMock.verifyAll(); expect(descriptor).to.not.eq(result); expect(descriptor).to.deep.eq(result); }); it("requests presentation manager for descriptor when keyset is empty and `shouldRequestContentForEmptyKeyset()` returns `true`", async () => { provider.keys = new KeySet(); provider.shouldRequestContentForEmptyKeyset = () => true; presentationManagerMock .setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => undefined) .verifiable(); const descriptor = await provider.getContentDescriptor(); presentationManagerMock.verifyAll(); expect(descriptor).to.be.undefined; }); it("doesn't request presentation manager for descriptor when keyset is empty and `shouldRequestContentForEmptyKeyset()` returns `false`", async () => { provider.keys = new KeySet(); presentationManagerMock .setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => undefined) .verifiable(moq.Times.never()); const descriptor = await provider.getContentDescriptor(); presentationManagerMock.verifyAll(); expect(descriptor).to.be.undefined; }); it("handles undefined descriptor returned by presentation manager", async () => { presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => undefined); const descriptor = await provider.getContentDescriptor(); expect(descriptor).to.be.undefined; }); it("memoizes result", async () => { const resultPromiseContainer = new PromiseContainer<Descriptor>(); presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => resultPromiseContainer.promise) .verifiable(moq.Times.once()); const requests = [provider.getContentDescriptor(), provider.getContentDescriptor()]; const result = createTestContentDescriptor({ fields: [] }); resultPromiseContainer.resolve(result); const descriptors = await Promise.all(requests); descriptors.forEach((descriptor) => expect(descriptor).to.deep.eq(result)); presentationManagerMock.verifyAll(); }); }); describe("getContentSetSize", () => { beforeEach(() => { provider.keys = new KeySet([createRandomECInstanceKey()]); }); it("returns 0 when manager returns undefined descriptor", async () => { presentationManagerMock.setup(async (x) => x.getContentSetSize(moq.It.isAny())) .verifiable(moq.Times.never()); const size = await provider.getContentSetSize(); presentationManagerMock.verifyAll(); expect(size).to.eq(0); }); it("requests presentation manager for size", async () => { const result = new PromiseContainer<{ content: Content, size: number }>(); presentationManagerMock.setup(async (x) => x.getContentAndSize(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: 10 } }))) .returns(async () => result.promise) .verifiable(); provider.pagingSize = 10; const contentAndContentSize = { content: new Content(createTestContentDescriptor({ fields: [] }), []), size: faker.random.number() }; result.resolve(contentAndContentSize); const size = await provider.getContentSetSize(); expect(size).to.eq(contentAndContentSize.size); presentationManagerMock.verifyAll(); }); it("memoizes result", async () => { const resultPromiseContainer = new PromiseContainer<{ content: Content, size: number }>(); presentationManagerMock.setup(async (x) => x.getContentAndSize(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: 10 } }))) .returns(async () => resultPromiseContainer.promise) .verifiable(moq.Times.once()); provider.pagingSize = 10; const requests = [provider.getContentSetSize(), provider.getContentSetSize()]; const result = { content: new Content(createTestContentDescriptor({ fields: [] }), []), size: faker.random.number() }; resultPromiseContainer.resolve(result); const sizes = await Promise.all(requests); sizes.forEach((size) => expect(size).to.eq(result.size)); presentationManagerMock.verifyAll(); }); it("requests size and first page when paging size is set", async () => { const resultPromiseContainer = new PromiseContainer<{ content: Content, size: number }>(); const pagingSize = 20; presentationManagerMock.setup(async (x) => x.getContentAndSize(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: pagingSize } }))) .returns(async () => resultPromiseContainer.promise) .verifiable(moq.Times.once()); provider.pagingSize = pagingSize; const result = { content: new Content(createTestContentDescriptor({ fields: [] }), []), size: faker.random.number() }; resultPromiseContainer.resolve(result); const size = await provider.getContentSetSize(); expect(size).to.eq(result.size); presentationManagerMock.verifyAll(); }); it("returns content size equal to content set size when page options are undefined", async () => { const descriptor = createTestContentDescriptor({ fields: [] }); const content = new Content(descriptor, [createTestContentItem({ values: {}, displayValues: {} })]); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: undefined }))) .returns(async () => content) .verifiable(moq.Times.once()); presentationManagerMock.setup(async (x) => x.getContentSetSize(moq.It.isAny())) .verifiable(moq.Times.never()); const size = await provider.getContentSetSize(); presentationManagerMock.verifyAll(); expect(size).to.equal(content.contentSet.length); }); }); describe("getContent", () => { beforeEach(() => { provider.keys = new KeySet([createRandomECInstanceKey()]); }); it("returns undefined when manager returns undefined content", async () => { presentationManagerMock.setup(async (x) => x.getContent(moq.It.isAny())) .returns(async () => undefined) .verifiable(); const c = await provider.getContent(); presentationManagerMock.verifyAll(); expect(c).to.be.undefined; }); it("requests presentation manager for content", async () => { const descriptor = createTestContentDescriptor({ fields: [] }); const result: { content: Content, size: number } = { content: new Content(descriptor, []), size: 1, }; presentationManagerMock.setup(async (x) => x.getContentAndSize(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: 10 } }))) .returns(async () => result) .verifiable(); const c = await provider.getContent({ start: 0, size: 10 }); presentationManagerMock.verifyAll(); expect(c).to.deep.eq(result.content); }); it("memoizes result", async () => { const resultContentFirstPagePromise0 = new PromiseContainer<Content>(); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: undefined }))) .returns(async () => resultContentFirstPagePromise0.promise) .verifiable(moq.Times.once()); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: undefined, size: 0 } }))) .verifiable(moq.Times.never()); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: undefined } }))) .verifiable(moq.Times.never()); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: 0 } }))) .verifiable(moq.Times.never()); const resultContentFirstPagePromise1 = new PromiseContainer<{ content: Content, size: number }>(); presentationManagerMock.setup(async (x) => x.getContentAndSize(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 0, size: 1 } }))) .returns(async () => resultContentFirstPagePromise1.promise) .verifiable(moq.Times.once()); const resultContentNonFirstPagePromise = new PromiseContainer<Content>(); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ paging: { start: 1, size: 0 } }))) .returns(async () => resultContentNonFirstPagePromise.promise) .verifiable(moq.Times.once()); const requests = [ provider.getContent(undefined), provider.getContent({ start: undefined, size: 0 }), provider.getContent({ start: 0, size: undefined }), provider.getContent({ start: 0, size: 0 }), provider.getContent({ start: 0, size: 1 }), provider.getContent({ start: 1, size: 0 }), ]; // for first 4 requests const descriptor = createTestContentDescriptor({ fields: [] }); const nonPagedContentStartingAt0Response = new Content(descriptor, [createTestContentItem({ label: "1", values: {}, displayValues: {} })]); // for 5'th request const pagedContentAndSizeResponse = { content: new Content(descriptor, [createTestContentItem({ label: "2", values: {}, displayValues: {} })]), size: 1, }; // for 6'th request const nonPagedContentStartingAt1Response = new Content(descriptor, [createTestContentItem({ label: "3", values: {}, displayValues: {} })]); resultContentFirstPagePromise0.resolve(nonPagedContentStartingAt0Response); resultContentFirstPagePromise1.resolve(pagedContentAndSizeResponse); resultContentNonFirstPagePromise.resolve(nonPagedContentStartingAt1Response); const responses = await Promise.all(requests); expect(responses[0]) .to.deep.eq(responses[1], "responses[1] should eq responses[0]") .to.deep.eq(responses[2], "responses[2] should eq responses[0]") .to.deep.eq(responses[3], "responses[3] should eq responses[0]") .to.deep.eq(nonPagedContentStartingAt0Response, "responses[0], responses[1], responses[2] and responses[3] should eq nonPagedContentStartingAt0Response"); expect(responses[4]).to.deep.eq(pagedContentAndSizeResponse.content, "responses[4] should eq pagedContentAndSizeResponse.content"); expect(responses[5]).to.deep.eq(nonPagedContentStartingAt1Response, "responses[5] should eq nonPagedContentStartingAt1Response"); presentationManagerMock.verifyAll(); }); it("doesn't request for content when keyset is empty and `shouldRequestContentForEmptyKeyset()` returns `false`", async () => { provider.keys = new KeySet(); await provider.getContent(); presentationManagerMock.verify(async (x) => x.getContentDescriptor(moq.It.isAny()), moq.Times.never()); presentationManagerMock.verify(async (x) => x.getContent(moq.It.isAny()), moq.Times.never()); presentationManagerMock.verify(async (x) => x.getContentAndSize(moq.It.isAny()), moq.Times.never()); }); }); describe("getFieldByPropertyRecord", () => { let propertyRecord: PropertyRecord; before(() => { const value: PrimitiveValue = { displayValue: "displayValue", value: "rawValue", valueFormat: 0, }; const description: PropertyDescription = { name: "propertyName", displayLabel: "labelString", typename: "number", editor: undefined, }; propertyRecord = new PropertyRecord(value, description); propertyRecord.isReadonly = false; }); beforeEach(() => { provider.keys = new KeySet([createRandomECInstanceKey()]); }); it("return undefined if descriptor is not set", async () => { presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => undefined) .verifiable(moq.Times.once()); const field = await provider.getFieldByPropertyRecord(propertyRecord); presentationManagerMock.verifyAll(); expect(field).to.be.undefined; }); it("return undefined when field is not found", async () => { const descriptor = createTestContentDescriptor({ fields: [] }); presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())) .returns(async () => descriptor) .verifiable(moq.Times.once()); const resultField = await provider.getFieldByPropertyRecord(propertyRecord); presentationManagerMock.verifyAll(); expect(resultField).to.be.undefined; }); it("return a field", async () => { const field = createTestPropertiesContentField({ name: "test-field", properties: [{ property: createTestPropertyInfo({ name: "test-property" }), }], }); const descriptor = createTestContentDescriptor({ fields: [field] }); propertyRecord.property.name = "test-field"; presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())).returns(async () => descriptor).verifiable(moq.Times.once()); const resultField = await provider.getFieldByPropertyRecord(propertyRecord); presentationManagerMock.verifyAll(); expect(resultField).to.eq(field); }); it("return a nested field", async () => { const nestedField = createTestSimpleContentField({ name: "nested-field" }); const nestingField = createTestNestedContentField({ name: "nesting-field", nestedFields: [nestedField], }); const descriptor = createTestContentDescriptor({ fields: [nestingField] }); propertyRecord.property.name = `${nestingField.name}${FIELD_NAMES_SEPARATOR}${nestedField.name}`; presentationManagerMock.setup(async (x) => x.getContentDescriptor(moq.It.isAny())).returns(async () => descriptor).verifiable(moq.Times.once()); const resultField = await provider.getFieldByPropertyRecord(propertyRecord); presentationManagerMock.verifyAll(); expect(resultField).to.eq(nestedField); }); }); describe("reacting to updates", () => { it("doesn't react to imodel content updates to unrelated rulesets", () => { presentationManagerMock.object.onIModelContentChanged.raiseEvent({ rulesetId: "unrelated", updateInfo: "FULL", imodelKey }); expect(invalidateCacheSpy).to.not.be.called; }); it("doesn't react to imodel content updates to unrelated imodels", () => { presentationManagerMock.object.onIModelContentChanged.raiseEvent({ rulesetId, updateInfo: "FULL", imodelKey: "unrelated" }); expect(invalidateCacheSpy).to.not.be.called; }); it("invalidates cache when imodel content change happens to related ruleset", () => { presentationManagerMock.object.onIModelContentChanged.raiseEvent({ rulesetId, updateInfo: "FULL", imodelKey }); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("doesn't react to unrelated ruleset modifications", async () => { const ruleset = new RegisteredRuleset(await createRandomRuleset(), "", () => { }); rulesetsManagerMock.object.onRulesetModified.raiseEvent(ruleset, { ...ruleset.toJSON() }); expect(invalidateCacheSpy).to.not.be.called; }); it("invalidates cache when related ruleset is modified", async () => { const ruleset = new RegisteredRuleset({ ...(await createRandomRuleset()), id: rulesetId }, "", () => { }); rulesetsManagerMock.object.onRulesetModified.raiseEvent(ruleset, { ...ruleset.toJSON() }); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); it("invalidates cache when related ruleset variables change", () => { presentationManagerMock.object.vars("").onVariableChanged.raiseEvent("var_id", "prev", "curr"); expect(invalidateCacheSpy).to.be.calledOnceWith(CacheInvalidationProps.full()); }); }); describe("diagnostics", () => { it("passes diagnostics options to presentation manager", async () => { const diagnosticsHandler = sinon.stub(); provider.dispose(); provider = new Provider({ imodel: imodelMock.object, ruleset: rulesetId, displayType, ruleDiagnostics: { severity: "error", handler: diagnosticsHandler }, }); sinon.stub(provider, "shouldRequestContentForEmptyKeyset").returns(true); const descriptor = createTestContentDescriptor({ fields: [] }); const content = new Content(descriptor, [createTestContentItem({ values: {}, displayValues: {} })]); presentationManagerMock.setup(async (x) => x.getContent(moq.It.isObjectWith<Paged<ContentRequestOptions<IModelConnection, Descriptor, KeySet>>>({ diagnostics: { editor: "error", handler: diagnosticsHandler } }))) .returns(async () => content) .verifiable(moq.Times.once()); await provider.getContentSetSize(); presentationManagerMock.verifyAll(); }); }); });
the_stack
import * as ts from 'typescript'; import * as tsickle from './tsickle'; /** * Adjusts the given CustomTransformers with additional transformers * to fix bugs in TypeScript. */ export function createCustomTransformers(given: ts.CustomTransformers): ts.CustomTransformers { if (!given.after && !given.before) { return given; } const before = given.before || []; before.unshift(addFileContexts); before.push(prepareNodesBeforeTypeScriptTransform); const after = given.after || []; after.unshift(emitMissingSyntheticCommentsAfterTypescriptTransform); return {before, after}; } /** * Transform that adds the FileContext to the TransformationContext. */ function addFileContexts(context: ts.TransformationContext) { return (sourceFile: ts.SourceFile) => { (context as TransformationContext).fileContext = new FileContext(sourceFile); return sourceFile; }; } function assertFileContext(context: TransformationContext, sourceFile: ts.SourceFile): FileContext { if (!context.fileContext) { throw new Error( `Illegal State: FileContext not initialized. ` + `Did you forget to add the "firstTransform" as first transformer? ` + `File: ${sourceFile.fileName}`); } if (context.fileContext.file.fileName !== sourceFile.fileName) { throw new Error( `Illegal State: File of the FileContext does not match. File: ${sourceFile.fileName}`); } return context.fileContext; } /** * An extended version of the TransformationContext that stores the FileContext as well. */ interface TransformationContext extends ts.TransformationContext { fileContext?: FileContext; } /** * A context that stores information per file to e.g. allow communication * between transformers. * There is one ts.TransformationContext per emit, * but files are handled sequentially by all transformers. Thefore we can * store file related information on a property on the ts.TransformationContext, * given that we reset it in the first transformer. */ class FileContext { /** * Stores the parent node for all processed nodes. * This is needed for nodes from the parse tree that are used * in a synthetic node as must not modify these, even though they * have a new parent now. */ syntheticNodeParents = new Map<ts.Node, ts.Node|undefined>(); importOrReexportDeclarations: Array<ts.ExportDeclaration|ts.ImportDeclaration> = []; lastCommentEnd = -1; constructor(public file: ts.SourceFile) {} } /** * Transform that needs to be executed right before TypeScript's transform. * * This prepares the node tree to workaround some bugs in the TypeScript emitter. */ function prepareNodesBeforeTypeScriptTransform(context: ts.TransformationContext) { return (sourceFile: ts.SourceFile) => { const fileCtx = assertFileContext(context, sourceFile); const nodePath: ts.Node[] = []; visitNode(sourceFile); return sourceFile; function visitNode(node: ts.Node) { const startNode = node; const parent = nodePath[nodePath.length - 1]; if (node.flags & ts.NodeFlags.Synthesized) { // Set `parent` for synthetic nodes as well, // as otherwise the TS emit will crash for decorators. // Note: don't update the `parent` of original nodes, as: // 1) we don't want to change them at all // 2) TS emit becomes errorneous in some cases if we add a synthetic parent. // see https://github.com/Microsoft/TypeScript/issues/17384 node.parent = parent; } fileCtx.syntheticNodeParents.set(node, parent); const originalNode = ts.getOriginalNode(node); // Needed so that e.g. `module { ... }` prints the variable statement // before the closure. // See https://github.com/Microsoft/TypeScript/issues/17596 // tslint:disable-next-line:no-any as `symbol` is @internal in typescript. (node as any).symbol = (originalNode as any).symbol; if (originalNode && node.kind === ts.SyntaxKind.ExportDeclaration) { const originalEd = originalNode as ts.ExportDeclaration; const ed = node as ts.ExportDeclaration; if (!!originalEd.exportClause !== !!ed.exportClause) { // Tsickle changes `export * ...` into named exports. // In this case, don't set the original node for the ExportDeclaration // as otherwise TypeScript does not emit the exports. // See https://github.com/Microsoft/TypeScript/issues/17597 ts.setOriginalNode(node, undefined); } } if (node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ExportDeclaration) { const ied = node as ts.ImportDeclaration | ts.ExportDeclaration; if (ied.moduleSpecifier) { fileCtx.importOrReexportDeclarations.push(ied); } } // recurse nodePath.push(node); node.forEachChild(visitNode); nodePath.pop(); } }; } /** * Transform that needs to be executed after TypeScript's transform. * * This fixes places where the TypeScript transformer does not * emit synthetic comments. * * See https://github.com/Microsoft/TypeScript/issues/17594 */ function emitMissingSyntheticCommentsAfterTypescriptTransform(context: ts.TransformationContext) { return (sourceFile: ts.SourceFile) => { const fileContext = assertFileContext(context, sourceFile); const nodePath: ts.Node[] = []; visitNode(sourceFile); (context as TransformationContext).fileContext = undefined; return sourceFile; function visitNode(node: ts.Node) { if (node.kind === ts.SyntaxKind.Identifier) { const parent1 = fileContext.syntheticNodeParents.get(node); const parent2 = parent1 && fileContext.syntheticNodeParents.get(parent1); const parent3 = parent2 && fileContext.syntheticNodeParents.get(parent2); if (parent1 && parent1.kind === ts.SyntaxKind.PropertyDeclaration) { // TypeScript ignores synthetic comments on (static) property declarations // with initializers. // find the parent ExpressionStatement like MyClass.foo = ... const expressionStmt = lastNodeWith(nodePath, (node) => node.kind === ts.SyntaxKind.ExpressionStatement); if (expressionStmt) { ts.setSyntheticLeadingComments( expressionStmt, ts.getSyntheticLeadingComments(parent1) || []); } } else if ( parent3 && parent3.kind === ts.SyntaxKind.VariableStatement && tsickle.hasModifierFlag(parent3, ts.ModifierFlags.Export)) { // TypeScript ignores synthetic comments on exported variables. // find the parent ExpressionStatement like exports.foo = ... const expressionStmt = lastNodeWith(nodePath, (node) => node.kind === ts.SyntaxKind.ExpressionStatement); if (expressionStmt) { ts.setSyntheticLeadingComments( expressionStmt, ts.getSyntheticLeadingComments(parent3) || []); } } } // TypeScript ignores synthetic comments on reexport / import statements. const moduleName = extractModuleNameFromRequireVariableStatement(node); if (moduleName && fileContext.importOrReexportDeclarations) { // Locate the original import/export declaration via the // text range. const importOrReexportDeclaration = fileContext.importOrReexportDeclarations.find(ied => ied.pos === node.pos); if (importOrReexportDeclaration) { ts.setSyntheticLeadingComments( node, ts.getSyntheticLeadingComments(importOrReexportDeclaration) || []); } // Need to clear the textRange for ImportDeclaration / ExportDeclaration as // otherwise TypeScript would emit the original comments even if we set the // ts.EmitFlag.NoComments. (see also resetNodeTextRangeToPreventDuplicateComments below) ts.setSourceMapRange(node, {pos: node.pos, end: node.end}); ts.setTextRange(node, {pos: -1, end: -1}); } nodePath.push(node); node.forEachChild(visitNode); nodePath.pop(); } }; } function extractModuleNameFromRequireVariableStatement(node: ts.Node): string|null { if (node.kind !== ts.SyntaxKind.VariableStatement) { return null; } const varStmt = node as ts.VariableStatement; const decls = varStmt.declarationList.declarations; let init: ts.Expression|undefined; if (decls.length !== 1 || !(init = decls[0].initializer) || init.kind !== ts.SyntaxKind.CallExpression) { return null; } const callExpr = init as ts.CallExpression; if (callExpr.expression.kind !== ts.SyntaxKind.Identifier || (callExpr.expression as ts.Identifier).text !== 'require' || callExpr.arguments.length !== 1) { return null; } const moduleExpr = callExpr.arguments[0]; if (moduleExpr.kind !== ts.SyntaxKind.StringLiteral) { return null; } return (moduleExpr as ts.StringLiteral).text; } function lastNodeWith(nodes: ts.Node[], predicate: (node: ts.Node) => boolean): ts.Node|null { for (let i = nodes.length - 1; i >= 0; i--) { const node = nodes[i]; if (predicate(node)) { return node; } } return null; } /** * Convert comment text ranges before and after a node * into ts.SynthesizedComments for the node and prevent the * comment text ranges to be emitted, to allow * changing these comments. * * This function takes a visitor to be able to do some * state management after the caller is done changing a node. */ export function visitNodeWithSynthesizedComments<T extends ts.Node>( context: ts.TransformationContext, sourceFile: ts.SourceFile, node: T, visitor: (node: T) => T): T { if (node.flags & ts.NodeFlags.Synthesized) { return visitor(node); } if (node.kind === ts.SyntaxKind.Block) { const block = node as ts.Node as ts.Block; node = visitNodeStatementsWithSynthesizedComments( context, sourceFile, node, block.statements, (node, stmts) => visitor(ts.updateBlock(block, stmts) as ts.Node as T)); } else if (node.kind === ts.SyntaxKind.SourceFile) { node = visitNodeStatementsWithSynthesizedComments( context, sourceFile, node, sourceFile.statements, (node, stmts) => visitor(updateSourceFileNode(sourceFile, stmts) as ts.Node as T)); } else { const fileContext = assertFileContext(context, sourceFile); const leadingLastCommentEnd = synthesizeLeadingComments(sourceFile, node, fileContext.lastCommentEnd); const trailingLastCommentEnd = synthesizeTrailingComments(sourceFile, node); if (leadingLastCommentEnd !== -1) { fileContext.lastCommentEnd = leadingLastCommentEnd; } node = visitor(node); if (trailingLastCommentEnd !== -1) { fileContext.lastCommentEnd = trailingLastCommentEnd; } } return resetNodeTextRangeToPreventDuplicateComments(node); } /** * Reset the text range for some special nodes as otherwise TypeScript * would always emit the original comments for them. * See https://github.com/Microsoft/TypeScript/issues/17594 * * @param node */ function resetNodeTextRangeToPreventDuplicateComments<T extends ts.Node>(node: T): T { ts.setEmitFlags(node, (ts.getEmitFlags(node) || 0) | ts.EmitFlags.NoComments); // See also addSyntheticCommentsAfterTsTransformer. // Note: Don't reset the textRange for ts.ExportDeclaration / ts.ImportDeclaration // until after the TypeScript transformer as we need the source location // to map the generated `require` calls back to the original // ts.ExportDeclaration / ts.ImportDeclaration nodes. let allowTextRange = node.kind !== ts.SyntaxKind.ClassDeclaration && node.kind !== ts.SyntaxKind.VariableDeclaration && !(node.kind === ts.SyntaxKind.VariableStatement && tsickle.hasModifierFlag(node, ts.ModifierFlags.Export)); if (node.kind === ts.SyntaxKind.PropertyDeclaration) { allowTextRange = false; const pd = node as ts.Node as ts.PropertyDeclaration; // TODO(tbosch): Using pd.initializer! as the typescript typings before 2.4.0 // are incorrect. Remove this once we upgrade to TypeScript 2.4.0. node = ts.updateProperty( pd, pd.decorators, pd.modifiers, resetTextRange(pd.name) as ts.PropertyName, pd.type, pd.initializer!) as ts.Node as T; } if (!allowTextRange) { node = resetTextRange(node); } return node; function resetTextRange<T extends ts.Node>(node: T): T { if (!(node.flags & ts.NodeFlags.Synthesized)) { // need to clone as we don't want to modify source nodes, // as the parsed SourceFiles could be cached! node = ts.getMutableClone(node); } const textRange = {pos: node.pos, end: node.end}; ts.setSourceMapRange(node, textRange); ts.setTextRange(node, {pos: -1, end: -1}); return node; } } /** * Reads in the leading comment text ranges of the given node, * converts them into `ts.SyntheticComment`s and stores them on the node. * * Note: This would be greatly simplified with https://github.com/Microsoft/TypeScript/issues/17615. * * @param lastCommentEnd The end of the last comment * @return The end of the last found comment, -1 if no comment was found. */ function synthesizeLeadingComments( sourceFile: ts.SourceFile, node: ts.Node, lastCommentEnd: number): number { const parent = node.parent; const sharesStartWithParent = parent && parent.kind !== ts.SyntaxKind.Block && parent.kind !== ts.SyntaxKind.SourceFile && parent.getFullStart() === node.getFullStart(); if (sharesStartWithParent || lastCommentEnd >= node.getStart()) { return -1; } const adjustedNodeFullStart = Math.max(lastCommentEnd, node.getFullStart()); const leadingComments = getAllLeadingCommentRanges(sourceFile, adjustedNodeFullStart, node.getStart()); if (leadingComments && leadingComments.length) { ts.setSyntheticLeadingComments(node, synthesizeCommentRanges(sourceFile, leadingComments)); return node.getStart(); } return -1; } /** * Reads in the trailing comment text ranges of the given node, * converts them into `ts.SyntheticComment`s and stores them on the node. * * Note: This would be greatly simplified with https://github.com/Microsoft/TypeScript/issues/17615. * * @return The end of the last found comment, -1 if no comment was found. */ function synthesizeTrailingComments(sourceFile: ts.SourceFile, node: ts.Node): number { const parent = node.parent; const sharesEndWithParent = parent && parent.kind !== ts.SyntaxKind.Block && parent.kind !== ts.SyntaxKind.SourceFile && parent.getEnd() === node.getEnd(); if (sharesEndWithParent) { return -1; } const trailingComments = ts.getTrailingCommentRanges(sourceFile.text, node.getEnd()); if (trailingComments && trailingComments.length) { ts.setSyntheticTrailingComments(node, synthesizeCommentRanges(sourceFile, trailingComments)); return trailingComments[trailingComments.length - 1].end; } return -1; } /** * Convert leading/trailing detached comment ranges of statement arrays * (e.g. the statements of a ts.SourceFile or ts.Block) into * `ts.NonEmittedStatement`s with `ts.SynthesizedComment`s and * prepends / appends them to the given statement array. * This is needed to allow changing these comments. * * This function takes a visitor to be able to do some * state management after the caller is done changing a node. */ function visitNodeStatementsWithSynthesizedComments<T extends ts.Node>( context: ts.TransformationContext, sourceFile: ts.SourceFile, node: T, statements: ts.NodeArray<ts.Statement>, visitor: (node: T, statements: ts.NodeArray<ts.Statement>) => T): T { const leading = synthesizeDetachedLeadingComments(sourceFile, node, statements); const trailing = synthesizeDetachedTrailingComments(sourceFile, node, statements); if (leading.commentStmt || trailing.commentStmt) { statements = ts.setTextRange(ts.createNodeArray(statements), {pos: -1, end: -1}); if (leading.commentStmt) { statements.unshift(leading.commentStmt); } if (trailing.commentStmt) { statements.push(trailing.commentStmt); } const fileContext = assertFileContext(context, sourceFile); if (leading.lastCommentEnd !== -1) { fileContext.lastCommentEnd = leading.lastCommentEnd; } node = visitor(node, statements); if (trailing.lastCommentEnd !== -1) { fileContext.lastCommentEnd = trailing.lastCommentEnd; } return node; } return visitor(node, statements); } /** * Convert leading detached comment ranges of statement arrays * (e.g. the statements of a ts.SourceFile or ts.Block) into a * `ts.NonEmittedStatement` with `ts.SynthesizedComment`s. * * A Detached leading comment is the first comment in a SourceFile / Block * that is separated with a newline from the first statement. * * Note: This would be greatly simplified with https://github.com/Microsoft/TypeScript/issues/17615. */ function synthesizeDetachedLeadingComments( sourceFile: ts.SourceFile, node: ts.Node, statements: ts.NodeArray<ts.Statement>): {commentStmt: ts.Statement|null, lastCommentEnd: number} { let triviaEnd = statements.end; if (statements.length) { triviaEnd = statements[0].getStart(); } const detachedComments = getDetachedLeadingCommentRanges(sourceFile, statements.pos, triviaEnd); if (!detachedComments.length) { return {commentStmt: null, lastCommentEnd: -1}; } const lastCommentEnd = detachedComments[detachedComments.length - 1].end; const commentStmt = createNotEmittedStatement(sourceFile); ts.setEmitFlags(commentStmt, ts.EmitFlags.CustomPrologue); ts.setSyntheticTrailingComments( commentStmt, synthesizeCommentRanges(sourceFile, detachedComments)); return {commentStmt, lastCommentEnd}; } /** * Convert trailing detached comment ranges of statement arrays * (e.g. the statements of a ts.SourceFile or ts.Block) into a * `ts.NonEmittedStatement` with `ts.SynthesizedComment`s. * * A Detached trailing comment are all comments after the first newline * the follows the last statement in a SourceFile / Block. * * Note: This would be greatly simplified with https://github.com/Microsoft/TypeScript/issues/17615. */ function synthesizeDetachedTrailingComments( sourceFile: ts.SourceFile, node: ts.Node, statements: ts.NodeArray<ts.Statement>): {commentStmt: ts.Statement|null, lastCommentEnd: number} { let trailingCommentStart = statements.end; if (statements.length) { const lastStmt = statements[statements.length - 1]; const lastStmtTrailingComments = ts.getTrailingCommentRanges(sourceFile.text, lastStmt.end); if (lastStmtTrailingComments && lastStmtTrailingComments.length) { trailingCommentStart = lastStmtTrailingComments[lastStmtTrailingComments.length - 1].end; } } const detachedComments = getAllLeadingCommentRanges(sourceFile, trailingCommentStart, node.end); if (!detachedComments || !detachedComments.length) { return {commentStmt: null, lastCommentEnd: -1}; } const lastCommentEnd = detachedComments[detachedComments.length - 1].end; const commentStmt = createNotEmittedStatement(sourceFile); ts.setEmitFlags(commentStmt, ts.EmitFlags.CustomPrologue); ts.setSyntheticLeadingComments( commentStmt, synthesizeCommentRanges(sourceFile, detachedComments)); return {commentStmt, lastCommentEnd}; } /** * Calculates the the detached leading comment ranges in an area of a SourceFile. * @param sourceFile The source file * @param start Where to start scanning * @param end Where to end scanning */ // Note: This code is based on compiler/comments.ts in TypeScript function getDetachedLeadingCommentRanges( sourceFile: ts.SourceFile, start: number, end: number): ts.CommentRange[] { const leadingComments = getAllLeadingCommentRanges(sourceFile, start, end); if (!leadingComments || !leadingComments.length) { return []; } const detachedComments: ts.CommentRange[] = []; let lastComment: ts.CommentRange|undefined = undefined; for (const comment of leadingComments) { if (lastComment) { const lastCommentLine = getLineOfPos(sourceFile, lastComment.end); const commentLine = getLineOfPos(sourceFile, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so // far. break; } } detachedComments.push(comment); lastComment = comment; } if (detachedComments.length) { // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. const lastCommentLine = getLineOfPos(sourceFile, detachedComments[detachedComments.length - 1].end); const nodeLine = getLineOfPos(sourceFile, end); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments return detachedComments; } } return []; } function getLineOfPos(sourceFile: ts.SourceFile, pos: number): number { return ts.getLineAndCharacterOfPosition(sourceFile, pos).line; } /** * Converts `ts.CommentRange`s into `ts.SynthesizedComment`s * @param sourceFile * @param parsedComments */ function synthesizeCommentRanges( sourceFile: ts.SourceFile, parsedComments: ts.CommentRange[]): ts.SynthesizedComment[] { const synthesizedComments: ts.SynthesizedComment[] = []; parsedComments.forEach(({kind, pos, end, hasTrailingNewLine}, commentIdx) => { let commentText = sourceFile.text.substring(pos, end).trim(); if (kind === ts.SyntaxKind.MultiLineCommentTrivia) { commentText = commentText.replace(/(^\/\*)|(\*\/$)/g, ''); } else if (kind === ts.SyntaxKind.SingleLineCommentTrivia) { if (commentText.startsWith('///')) { // tripple-slash comments are typescript specific, ignore them in the output. return; } commentText = commentText.replace(/(^\/\/)/g, ''); } synthesizedComments.push({kind, text: commentText, hasTrailingNewLine, pos: -1, end: -1}); }); return synthesizedComments; } /** * Creates a non emitted statement that can be used to store synthesized comments. */ function createNotEmittedStatement(sourceFile: ts.SourceFile) { const stmt = ts.createNotEmittedStatement(sourceFile); ts.setOriginalNode(stmt, undefined); ts.setTextRange(stmt, {pos: 0, end: 0}); return stmt; } /** * Returns the leading comment ranges in the source file that start at the given position. * This is the same as `ts.getLeadingCommentRanges`, except that it does not skip * comments before the first newline in the range. * * @param sourceFile * @param start Where to start scanning * @param end Where to end scanning */ function getAllLeadingCommentRanges( sourceFile: ts.SourceFile, start: number, end: number): ts.CommentRange[] { // exeute ts.getLeadingCommentRanges with pos = 0 so that it does not skip // comments until the first newline. const commentRanges = ts.getLeadingCommentRanges(sourceFile.text.substring(start, end), 0) || []; return commentRanges.map(cr => ({ hasTrailingNewLine: cr.hasTrailingNewLine, kind: cr.kind as number, pos: cr.pos + start, end: cr.end + start })); } /** * This is a version of `ts.updateSourceFileNode` that works * well with property decorators. * See https://github.com/Microsoft/TypeScript/issues/17384 * * @param sf * @param statements */ export function updateSourceFileNode( sf: ts.SourceFile, statements: ts.NodeArray<ts.Statement>): ts.SourceFile { if (statements === sf.statements) { return sf; } // Note: Need to clone the original file (and not use `ts.updateSourceFileNode`) // as otherwise TS fails when resolving types for decorators. sf = ts.getMutableClone(sf); sf.statements = statements; return sf; } /** * This is a version of `ts.visitEachChild` that does not visit children of types, * as this leads to errors in TypeScript < 2.4.0 and as types are not emitted anyways. */ export function visitEachChildIgnoringTypes<T extends ts.Node>( node: T, visitor: ts.Visitor, context: ts.TransformationContext): T { if (isTypeNodeKind(node.kind) || node.kind === ts.SyntaxKind.IndexSignature) { return node; } return ts.visitEachChild(node, visitor, context); } // Copied from TypeScript export function isTypeNodeKind(kind: ts.SyntaxKind) { return (kind >= ts.SyntaxKind.FirstTypeNode && kind <= ts.SyntaxKind.LastTypeNode) || kind === ts.SyntaxKind.AnyKeyword || kind === ts.SyntaxKind.NumberKeyword || kind === ts.SyntaxKind.ObjectKeyword || kind === ts.SyntaxKind.BooleanKeyword || kind === ts.SyntaxKind.StringKeyword || kind === ts.SyntaxKind.SymbolKeyword || kind === ts.SyntaxKind.ThisKeyword || kind === ts.SyntaxKind.VoidKeyword || kind === ts.SyntaxKind.UndefinedKeyword || kind === ts.SyntaxKind.NullKeyword || kind === ts.SyntaxKind.NeverKeyword || kind === ts.SyntaxKind.ExpressionWithTypeArguments; }
the_stack
import { MockedResponse } from '@apollo/client/testing' import { fireEvent } from '@testing-library/react' import React from 'react' import { dataOrThrowErrors, getDocumentNode, gql } from '@sourcegraph/shared/src/graphql/graphql' import { MockedTestProvider, waitForNextApolloResponse } from '@sourcegraph/shared/src/testing/apollo' import { renderWithRouter, RenderWithRouterResult } from '@sourcegraph/shared/src/testing/render-with-router' import { TestConnectionQueryFields, TestConnectionQueryResult, TestConnectionQueryVariables, } from '../../../graphql-operations' import { useConnection } from './useConnection' const TEST_CONNECTION_QUERY = gql` query TestConnectionQuery($username: String!, $first: Int) { user(username: $username) { repositories(first: $first) { nodes { id name } totalCount pageInfo { endCursor hasNextPage } } } } fragment TestConnectionQueryFields on Repository { name id } ` const TestComponent = () => { const { connection, fetchMore, hasNextPage } = useConnection< TestConnectionQueryResult, TestConnectionQueryVariables, TestConnectionQueryFields >({ query: TEST_CONNECTION_QUERY, variables: { first: 1, username: 'username', }, getConnection: result => { const data = dataOrThrowErrors(result) if (!data.user) { throw new Error('User not found') } return data.user.repositories }, options: { useURL: true, }, }) return ( <> <ul> {connection?.nodes.map((node, index) => ( <li key={index}>{node.name}</li> ))} </ul> {connection?.totalCount && <p>Total count: {connection.totalCount}</p>} {hasNextPage && ( <button type="button" onClick={fetchMore}> Fetch more </button> )} </> ) } const generateMockRequest = ({ after, first, }: { after?: string first: number }): MockedResponse<TestConnectionQueryResult>['request'] => ({ query: getDocumentNode(TEST_CONNECTION_QUERY), variables: { username: 'username', after, first, }, }) const generateMockResult = ({ endCursor, hasNextPage, nodes, totalCount, }: { endCursor: string | null hasNextPage: boolean nodes: TestConnectionQueryFields[] totalCount: number }): MockedResponse<TestConnectionQueryResult>['result'] => ({ data: { user: { repositories: { nodes, pageInfo: { endCursor, hasNextPage, }, totalCount, }, }, }, }) describe('useConnection', () => { const fetchNextPage = async (renderResult: RenderWithRouterResult) => { const fetchMoreButton = renderResult.getByText('Fetch more') fireEvent.click(fetchMoreButton) // Skip loading state await waitForNextApolloResponse() } const mockResultNodes: TestConnectionQueryFields[] = [ { id: 'A', name: 'repo-A', }, { id: 'B', name: 'repo-B', }, { id: 'C', name: 'repo-C', }, { id: 'D', name: 'repo-D', }, ] const renderWithMocks = async (mocks: MockedResponse<TestConnectionQueryResult>[], route = '/') => { const renderResult = renderWithRouter( <MockedTestProvider mocks={mocks}> <TestComponent /> </MockedTestProvider>, { route } ) // Skip loading state await waitForNextApolloResponse() return renderResult } describe('Cursor based pagination', () => { const generateMockCursorResponses = ( nodes: TestConnectionQueryFields[] ): MockedResponse<TestConnectionQueryResult>[] => nodes.map((node, index) => { const isFirstPage = index === 0 const cursor = !isFirstPage ? String(index) : undefined return { request: generateMockRequest({ after: cursor, first: 1 }), result: generateMockResult({ nodes: [node], endCursor: String(index + 1), hasNextPage: index !== nodes.length - 1, totalCount: nodes.length, }), } }) const cursorMocks = generateMockCursorResponses(mockResultNodes) it('renders correct result', async () => { const queries = await renderWithMocks(cursorMocks) expect(queries.getAllByRole('listitem').length).toBe(1) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() expect(queries.getByText('Fetch more')).toBeVisible() expect(queries.history.location.search).toBe('') }) it('fetches next page of results correctly', async () => { const queries = await renderWithMocks(cursorMocks) // Fetch first page await fetchNextPage(queries) // Both pages are now displayed expect(queries.getAllByRole('listitem').length).toBe(2) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() expect(queries.getByText('Fetch more')).toBeVisible() // URL updates to match visible results expect(queries.history.location.search).toBe('?visible=2') }) it('fetches final page of results correctly', async () => { const queries = await renderWithMocks(cursorMocks) // Fetch all pages await fetchNextPage(queries) await fetchNextPage(queries) await fetchNextPage(queries) // All pages of results are displayed expect(queries.getAllByRole('listitem').length).toBe(4) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('repo-C')).toBeVisible() expect(queries.getByText('repo-D')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // Fetch more button is now no longer visible expect(queries.queryByText('Fetch more')).not.toBeInTheDocument() // URL updates to match visible results expect(queries.history.location.search).toBe('?visible=4') }) it('fetches correct amount of results when navigating directly with a URL', async () => { // We need to add an extra mock here, as we will derive a different `first` variable from `visible` in the URL. const mockFromVisible: MockedResponse<TestConnectionQueryResult> = { request: generateMockRequest({ first: 3 }), result: generateMockResult({ nodes: [mockResultNodes[0], mockResultNodes[1], mockResultNodes[2]], hasNextPage: true, endCursor: '3', totalCount: 4, }), } const queries = await renderWithMocks([...cursorMocks, mockFromVisible], '/?visible=3') // Renders 3 results without having to manually fetch expect(queries.getAllByRole('listitem').length).toBe(3) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('repo-C')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // Fetching next page should work as usual await fetchNextPage(queries) expect(queries.getAllByRole('listitem').length).toBe(4) expect(queries.getByText('repo-C')).toBeVisible() expect(queries.getByText('repo-D')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // URL should be overidden expect(queries.history.location.search).toBe('?visible=4') }) }) describe('Batch based pagination', () => { const batchedMocks: MockedResponse<TestConnectionQueryResult>[] = [ { request: generateMockRequest({ first: 1 }), result: generateMockResult({ nodes: [mockResultNodes[0]], endCursor: null, hasNextPage: true, totalCount: 4, }), }, { request: generateMockRequest({ first: 2 }), result: generateMockResult({ nodes: [mockResultNodes[0], mockResultNodes[1]], endCursor: null, hasNextPage: true, totalCount: 4, }), }, { request: generateMockRequest({ first: 4 }), result: generateMockResult({ nodes: mockResultNodes, endCursor: null, hasNextPage: false, totalCount: 4, }), }, ] it('renders correct result', async () => { const queries = await renderWithMocks(batchedMocks) expect(queries.getAllByRole('listitem').length).toBe(1) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() expect(queries.getByText('Fetch more')).toBeVisible() expect(queries.history.location.search).toBe('') }) it('fetches next page of results correctly', async () => { const queries = await renderWithMocks(batchedMocks) // Fetch first page await fetchNextPage(queries) // Both pages are now displayed expect(queries.getAllByRole('listitem').length).toBe(2) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() expect(queries.getByText('Fetch more')).toBeVisible() // URL updates to match the new request expect(queries.history.location.search).toBe('?first=2') }) it('fetches final page of results correctly', async () => { const queries = await renderWithMocks(batchedMocks) // Fetch both pages await fetchNextPage(queries) await fetchNextPage(queries) // All pages of results are displayed expect(queries.getAllByRole('listitem').length).toBe(4) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('repo-C')).toBeVisible() expect(queries.getByText('repo-D')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // Fetch more button is now no longer visible expect(queries.queryByText('Fetch more')).not.toBeInTheDocument() // URL updates to match the new request expect(queries.history.location.search).toBe('?first=4') }) it('fetches correct amount of results when navigating directly with a URL', async () => { const queries = await renderWithMocks(batchedMocks, '/?first=2') // Renders 2 results without having to manually fetch expect(queries.getAllByRole('listitem').length).toBe(2) expect(queries.getByText('repo-A')).toBeVisible() expect(queries.getByText('repo-B')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // Fetching next page should work as usual await fetchNextPage(queries) expect(queries.getAllByRole('listitem').length).toBe(4) expect(queries.getByText('repo-C')).toBeVisible() expect(queries.getByText('repo-D')).toBeVisible() expect(queries.getByText('Total count: 4')).toBeVisible() // URL should be overidden expect(queries.history.location.search).toBe('?first=4') }) }) })
the_stack
import type { ApiTypes } from '@polkadot/api-base/types'; import type { Bytes, Null, Option, Result, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types-codec'; import type { ITuple } from '@polkadot/types-codec/types'; import type { EthereumAddress } from '@polkadot/types/interfaces/eth'; import type { AccountId32, H256 } from '@polkadot/types/interfaces/runtime'; import type { FrameSupportScheduleLookupError, FrameSupportTokensMiscBalanceStatus, FrameSupportWeightsDispatchInfo, KusamaRuntimeProxyType, PalletDemocracyVoteAccountVote, PalletDemocracyVoteThreshold, PalletElectionProviderMultiPhaseElectionCompute, PalletImOnlineSr25519AppSr25519Public, PalletMultisigTimepoint, PalletStakingExposure, PolkadotParachainPrimitivesHrmpChannelId, PolkadotPrimitivesV1CandidateReceipt, PolkadotRuntimeParachainsDisputesDisputeLocation, PolkadotRuntimeParachainsDisputesDisputeResult, SpFinalityGrandpaAppPublic, SpRuntimeDispatchError, XcmV1MultiLocation, XcmV2Response, XcmV2TraitsError, XcmV2TraitsOutcome, XcmV2Xcm, XcmVersionedMultiAssets, XcmVersionedMultiLocation } from '@polkadot/types/lookup'; declare module '@polkadot/api-base/types/events' { export interface AugmentedEvents<ApiType extends ApiTypes> { auctions: { /** * An auction ended. All funds become unreserved. `[auction_index]` **/ AuctionClosed: AugmentedEvent<ApiType, [u32]>; /** * An auction started. Provides its index and the block number where it will begin to * close and the first lease period of the quadruplet that is auctioned. * `[auction_index, lease_period, ending]` **/ AuctionStarted: AugmentedEvent<ApiType, [u32, u32, u32]>; /** * A new bid has been accepted as the current winner. * `[who, para_id, amount, first_slot, last_slot]` **/ BidAccepted: AugmentedEvent<ApiType, [AccountId32, u32, u128, u32, u32]>; /** * Someone attempted to lease the same slot twice for a parachain. The amount is held in reserve * but no parachain slot has been leased. * `[parachain_id, leaser, amount]` **/ ReserveConfiscated: AugmentedEvent<ApiType, [u32, AccountId32, u128]>; /** * Funds were reserved for a winning bid. First balance is the extra amount reserved. * Second is the total. `[bidder, extra_reserved, total_amount]` **/ Reserved: AugmentedEvent<ApiType, [AccountId32, u128, u128]>; /** * Funds were unreserved since bidder is no longer active. `[bidder, amount]` **/ Unreserved: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * The winning offset was chosen for an auction. This will map into the `Winning` storage map. * `[auction_index, block_number]` **/ WinningOffset: AugmentedEvent<ApiType, [u32, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; bagsList: { /** * Moved an account from one bag to another. **/ Rebagged: AugmentedEvent<ApiType, [AccountId32, u64, u64]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; balances: { /** * A balance was set by root. **/ BalanceSet: AugmentedEvent<ApiType, [AccountId32, u128, u128]>; /** * Some amount was deposited (e.g. for transaction fees). **/ Deposit: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * An account was removed whose balance was non-zero but below ExistentialDeposit, * resulting in an outright loss. **/ DustLost: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * An account was created with some free balance. **/ Endowed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Some balance was reserved (moved from free to reserved). **/ Reserved: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Some balance was moved from the reserve of the first account to the second account. * Final argument indicates the destination balance type. **/ ReserveRepatriated: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128, FrameSupportTokensMiscBalanceStatus]>; /** * Some amount was removed from the account (e.g. for misbehavior). **/ Slashed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Transfer succeeded. **/ Transfer: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>; /** * Some balance was unreserved (moved from reserved to free). **/ Unreserved: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Some amount was withdrawn from the account (e.g. for transaction fees). **/ Withdraw: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; bounties: { /** * A bounty is awarded to a beneficiary. **/ BountyAwarded: AugmentedEvent<ApiType, [u32, AccountId32]>; /** * A bounty proposal is funded and became active. **/ BountyBecameActive: AugmentedEvent<ApiType, [u32]>; /** * A bounty is cancelled. **/ BountyCanceled: AugmentedEvent<ApiType, [u32]>; /** * A bounty is claimed by beneficiary. **/ BountyClaimed: AugmentedEvent<ApiType, [u32, u128, AccountId32]>; /** * A bounty expiry is extended. **/ BountyExtended: AugmentedEvent<ApiType, [u32]>; /** * New bounty proposal. **/ BountyProposed: AugmentedEvent<ApiType, [u32]>; /** * A bounty proposal was rejected; funds were slashed. **/ BountyRejected: AugmentedEvent<ApiType, [u32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; claims: { /** * Someone claimed some DOTs. `[who, ethereum_address, amount]` **/ Claimed: AugmentedEvent<ApiType, [AccountId32, EthereumAddress, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; council: { /** * A motion was approved by the required threshold. **/ Approved: AugmentedEvent<ApiType, [H256]>; /** * A proposal was closed because its threshold was reached or after its duration was up. **/ Closed: AugmentedEvent<ApiType, [H256, u32, u32]>; /** * A motion was not approved by the required threshold. **/ Disapproved: AugmentedEvent<ApiType, [H256]>; /** * A motion was executed; result will be `Ok` if it returned without error. **/ Executed: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>; /** * A single member did some action; result will be `Ok` if it returned without error. **/ MemberExecuted: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>; /** * A motion (given hash) has been proposed (by given account) with a threshold (given * `MemberCount`). **/ Proposed: AugmentedEvent<ApiType, [AccountId32, u32, H256, u32]>; /** * A motion (given hash) has been voted on by given account, leaving * a tally (yes votes and no votes given respectively as `MemberCount`). **/ Voted: AugmentedEvent<ApiType, [AccountId32, H256, bool, u32, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; crowdloan: { /** * A parachain has been moved to `NewRaise` **/ AddedToNewRaise: AugmentedEvent<ApiType, [u32]>; /** * All loans in a fund have been refunded. `[fund_index]` **/ AllRefunded: AugmentedEvent<ApiType, [u32]>; /** * Contributed to a crowd sale. `[who, fund_index, amount]` **/ Contributed: AugmentedEvent<ApiType, [AccountId32, u32, u128]>; /** * Create a new crowdloaning campaign. `[fund_index]` **/ Created: AugmentedEvent<ApiType, [u32]>; /** * Fund is dissolved. `[fund_index]` **/ Dissolved: AugmentedEvent<ApiType, [u32]>; /** * The configuration to a crowdloan has been edited. `[fund_index]` **/ Edited: AugmentedEvent<ApiType, [u32]>; /** * The result of trying to submit a new bid to the Slots pallet. **/ HandleBidResult: AugmentedEvent<ApiType, [u32, Result<Null, SpRuntimeDispatchError>]>; /** * A memo has been updated. `[who, fund_index, memo]` **/ MemoUpdated: AugmentedEvent<ApiType, [AccountId32, u32, Bytes]>; /** * The loans in a fund have been partially dissolved, i.e. there are some left * over child keys that still need to be killed. `[fund_index]` **/ PartiallyRefunded: AugmentedEvent<ApiType, [u32]>; /** * Withdrew full balance of a contributor. `[who, fund_index, amount]` **/ Withdrew: AugmentedEvent<ApiType, [AccountId32, u32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; democracy: { /** * A proposal_hash has been blacklisted permanently. **/ Blacklisted: AugmentedEvent<ApiType, [H256]>; /** * A referendum has been cancelled. **/ Cancelled: AugmentedEvent<ApiType, [u32]>; /** * An account has delegated their vote to another account. **/ Delegated: AugmentedEvent<ApiType, [AccountId32, AccountId32]>; /** * A proposal has been enacted. **/ Executed: AugmentedEvent<ApiType, [u32, Result<Null, SpRuntimeDispatchError>]>; /** * An external proposal has been tabled. **/ ExternalTabled: AugmentedEvent<ApiType, []>; /** * A proposal has been rejected by referendum. **/ NotPassed: AugmentedEvent<ApiType, [u32]>; /** * A proposal has been approved by referendum. **/ Passed: AugmentedEvent<ApiType, [u32]>; /** * A proposal could not be executed because its preimage was invalid. **/ PreimageInvalid: AugmentedEvent<ApiType, [H256, u32]>; /** * A proposal could not be executed because its preimage was missing. **/ PreimageMissing: AugmentedEvent<ApiType, [H256, u32]>; /** * A proposal's preimage was noted, and the deposit taken. **/ PreimageNoted: AugmentedEvent<ApiType, [H256, AccountId32, u128]>; /** * A registered preimage was removed and the deposit collected by the reaper. **/ PreimageReaped: AugmentedEvent<ApiType, [H256, AccountId32, u128, AccountId32]>; /** * A proposal preimage was removed and used (the deposit was returned). **/ PreimageUsed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>; /** * A motion has been proposed by a public account. **/ Proposed: AugmentedEvent<ApiType, [u32, u128]>; /** * An account has secconded a proposal **/ Seconded: AugmentedEvent<ApiType, [AccountId32, u32]>; /** * A referendum has begun. **/ Started: AugmentedEvent<ApiType, [u32, PalletDemocracyVoteThreshold]>; /** * A public proposal has been tabled for referendum vote. **/ Tabled: AugmentedEvent<ApiType, [u32, u128, Vec<AccountId32>]>; /** * An account has cancelled a previous delegation operation. **/ Undelegated: AugmentedEvent<ApiType, [AccountId32]>; /** * An external proposal has been vetoed. **/ Vetoed: AugmentedEvent<ApiType, [AccountId32, H256, u32]>; /** * An account has voted in a referendum **/ Voted: AugmentedEvent<ApiType, [AccountId32, u32, PalletDemocracyVoteAccountVote]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; electionProviderMultiPhase: { /** * The election has been finalized, with `Some` of the given computation, or else if the * election failed, `None`. **/ ElectionFinalized: AugmentedEvent<ApiType, [Option<PalletElectionProviderMultiPhaseElectionCompute>]>; /** * An account has been rewarded for their signed submission being finalized. **/ Rewarded: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * The signed phase of the given round has started. **/ SignedPhaseStarted: AugmentedEvent<ApiType, [u32]>; /** * An account has been slashed for submitting an invalid signed submission. **/ Slashed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * A solution was stored with the given compute. * * If the solution is signed, this means that it hasn't yet been processed. If the * solution is unsigned, this means that it has also been processed. * * The `bool` is `true` when a previous solution was ejected to make room for this one. **/ SolutionStored: AugmentedEvent<ApiType, [PalletElectionProviderMultiPhaseElectionCompute, bool]>; /** * The unsigned phase of the given round has started. **/ UnsignedPhaseStarted: AugmentedEvent<ApiType, [u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; gilt: { /** * A bid was successfully placed. **/ BidPlaced: AugmentedEvent<ApiType, [AccountId32, u128, u32]>; /** * A bid was successfully removed (before being accepted as a gilt). **/ BidRetracted: AugmentedEvent<ApiType, [AccountId32, u128, u32]>; /** * A bid was accepted as a gilt. The balance may not be released until expiry. **/ GiltIssued: AugmentedEvent<ApiType, [u32, u32, AccountId32, u128]>; /** * An expired gilt has been thawed. **/ GiltThawed: AugmentedEvent<ApiType, [u32, AccountId32, u128, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; grandpa: { /** * New authority set has been applied. **/ NewAuthorities: AugmentedEvent<ApiType, [Vec<ITuple<[SpFinalityGrandpaAppPublic, u64]>>]>; /** * Current authority set has been paused. **/ Paused: AugmentedEvent<ApiType, []>; /** * Current authority set has been resumed. **/ Resumed: AugmentedEvent<ApiType, []>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; hrmp: { /** * HRMP channel closed. `[by_parachain, channel_id]` **/ ChannelClosed: AugmentedEvent<ApiType, [u32, PolkadotParachainPrimitivesHrmpChannelId]>; /** * Open HRMP channel accepted. `[sender, recipient]` **/ OpenChannelAccepted: AugmentedEvent<ApiType, [u32, u32]>; /** * An HRMP channel request sent by the receiver was canceled by either party. * `[by_parachain, channel_id]` **/ OpenChannelCanceled: AugmentedEvent<ApiType, [u32, PolkadotParachainPrimitivesHrmpChannelId]>; /** * Open HRMP channel requested. * `[sender, recipient, proposed_max_capacity, proposed_max_message_size]` **/ OpenChannelRequested: AugmentedEvent<ApiType, [u32, u32, u32, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; identity: { /** * A name was cleared, and the given balance returned. **/ IdentityCleared: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * A name was removed and the given balance slashed. **/ IdentityKilled: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * A name was set or reset (which will remove all judgements). **/ IdentitySet: AugmentedEvent<ApiType, [AccountId32]>; /** * A judgement was given by a registrar. **/ JudgementGiven: AugmentedEvent<ApiType, [AccountId32, u32]>; /** * A judgement was asked from a registrar. **/ JudgementRequested: AugmentedEvent<ApiType, [AccountId32, u32]>; /** * A judgement request was retracted. **/ JudgementUnrequested: AugmentedEvent<ApiType, [AccountId32, u32]>; /** * A registrar was added. **/ RegistrarAdded: AugmentedEvent<ApiType, [u32]>; /** * A sub-identity was added to an identity and the deposit paid. **/ SubIdentityAdded: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>; /** * A sub-identity was removed from an identity and the deposit freed. **/ SubIdentityRemoved: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>; /** * A sub-identity was cleared, and the given deposit repatriated from the * main identity account to the sub-identity account. **/ SubIdentityRevoked: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; imOnline: { /** * At the end of the session, no offence was committed. **/ AllGood: AugmentedEvent<ApiType, []>; /** * A new heartbeat was received from `AuthorityId`. **/ HeartbeatReceived: AugmentedEvent<ApiType, [PalletImOnlineSr25519AppSr25519Public]>; /** * At the end of the session, at least one validator was found to be offline. **/ SomeOffline: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId32, PalletStakingExposure]>>]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; indices: { /** * A account index was assigned. **/ IndexAssigned: AugmentedEvent<ApiType, [AccountId32, u32]>; /** * A account index has been freed up (unassigned). **/ IndexFreed: AugmentedEvent<ApiType, [u32]>; /** * A account index has been frozen to its current account ID. **/ IndexFrozen: AugmentedEvent<ApiType, [u32, AccountId32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; multisig: { /** * A multisig operation has been approved by someone. **/ MultisigApproval: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed]>; /** * A multisig operation has been cancelled. **/ MultisigCancelled: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed]>; /** * A multisig operation has been executed. **/ MultisigExecuted: AugmentedEvent<ApiType, [AccountId32, PalletMultisigTimepoint, AccountId32, U8aFixed, Result<Null, SpRuntimeDispatchError>]>; /** * A new multisig operation has begun. **/ NewMultisig: AugmentedEvent<ApiType, [AccountId32, AccountId32, U8aFixed]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; offences: { /** * There is an offence reported of the given `kind` happened at the `session_index` and * (kind-specific) time slot. This event is not deposited for duplicate slashes. * \[kind, timeslot\]. **/ Offence: AugmentedEvent<ApiType, [U8aFixed, Bytes]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; paraInclusion: { /** * A candidate was backed. `[candidate, head_data]` **/ CandidateBacked: AugmentedEvent<ApiType, [PolkadotPrimitivesV1CandidateReceipt, Bytes, u32, u32]>; /** * A candidate was included. `[candidate, head_data]` **/ CandidateIncluded: AugmentedEvent<ApiType, [PolkadotPrimitivesV1CandidateReceipt, Bytes, u32, u32]>; /** * A candidate timed out. `[candidate, head_data]` **/ CandidateTimedOut: AugmentedEvent<ApiType, [PolkadotPrimitivesV1CandidateReceipt, Bytes, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; paras: { /** * A para has been queued to execute pending actions. `para_id` **/ ActionQueued: AugmentedEvent<ApiType, [u32, u32]>; /** * A code upgrade has been scheduled for a Para. `para_id` **/ CodeUpgradeScheduled: AugmentedEvent<ApiType, [u32]>; /** * Current code has been updated for a Para. `para_id` **/ CurrentCodeUpdated: AugmentedEvent<ApiType, [u32]>; /** * Current head has been updated for a Para. `para_id` **/ CurrentHeadUpdated: AugmentedEvent<ApiType, [u32]>; /** * A new head has been noted for a Para. `para_id` **/ NewHeadNoted: AugmentedEvent<ApiType, [u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; parasDisputes: { /** * A dispute has concluded for or against a candidate. * `\[para id, candidate hash, dispute result\]` **/ DisputeConcluded: AugmentedEvent<ApiType, [H256, PolkadotRuntimeParachainsDisputesDisputeResult]>; /** * A dispute has been initiated. \[candidate hash, dispute location\] **/ DisputeInitiated: AugmentedEvent<ApiType, [H256, PolkadotRuntimeParachainsDisputesDisputeLocation]>; /** * A dispute has timed out due to insufficient participation. * `\[para id, candidate hash\]` **/ DisputeTimedOut: AugmentedEvent<ApiType, [H256]>; /** * A dispute has concluded with supermajority against a candidate. * Block authors should no longer build on top of this head and should * instead revert the block at the given height. This should be the * number of the child of the last known valid block in the chain. **/ Revert: AugmentedEvent<ApiType, [u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; phragmenElection: { /** * A candidate was slashed by amount due to failing to obtain a seat as member or * runner-up. * * Note that old members and runners-up are also candidates. **/ CandidateSlashed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Internal error happened while trying to perform election. **/ ElectionError: AugmentedEvent<ApiType, []>; /** * No (or not enough) candidates existed for this round. This is different from * `NewTerm(\[\])`. See the description of `NewTerm`. **/ EmptyTerm: AugmentedEvent<ApiType, []>; /** * A member has been removed. This should always be followed by either `NewTerm` or * `EmptyTerm`. **/ MemberKicked: AugmentedEvent<ApiType, [AccountId32]>; /** * A new term with new_members. This indicates that enough candidates existed to run * the election, not that enough have has been elected. The inner value must be examined * for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond * slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to * begin with. **/ NewTerm: AugmentedEvent<ApiType, [Vec<ITuple<[AccountId32, u128]>>]>; /** * Someone has renounced their candidacy. **/ Renounced: AugmentedEvent<ApiType, [AccountId32]>; /** * A seat holder was slashed by amount by being forcefully removed from the set. **/ SeatHolderSlashed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; preimage: { /** * A preimage has ben cleared. **/ Cleared: AugmentedEvent<ApiType, [H256]>; /** * A preimage has been noted. **/ Noted: AugmentedEvent<ApiType, [H256]>; /** * A preimage has been requested. **/ Requested: AugmentedEvent<ApiType, [H256]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; proxy: { /** * An announcement was placed to make a call in the future. **/ Announced: AugmentedEvent<ApiType, [AccountId32, AccountId32, H256]>; /** * Anonymous account has been created by new proxy with given * disambiguation index and proxy type. **/ AnonymousCreated: AugmentedEvent<ApiType, [AccountId32, AccountId32, KusamaRuntimeProxyType, u16]>; /** * A proxy was added. **/ ProxyAdded: AugmentedEvent<ApiType, [AccountId32, AccountId32, KusamaRuntimeProxyType, u32]>; /** * A proxy was executed correctly, with the given. **/ ProxyExecuted: AugmentedEvent<ApiType, [Result<Null, SpRuntimeDispatchError>]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; recovery: { /** * Lost account has been successfully recovered by rescuer account. **/ AccountRecovered: AugmentedEvent<ApiType, [AccountId32, AccountId32]>; /** * A recovery process for lost account by rescuer account has been closed. **/ RecoveryClosed: AugmentedEvent<ApiType, [AccountId32, AccountId32]>; /** * A recovery process has been set up for an account. **/ RecoveryCreated: AugmentedEvent<ApiType, [AccountId32]>; /** * A recovery process has been initiated for lost account by rescuer account. **/ RecoveryInitiated: AugmentedEvent<ApiType, [AccountId32, AccountId32]>; /** * A recovery process has been removed for an account. **/ RecoveryRemoved: AugmentedEvent<ApiType, [AccountId32]>; /** * A recovery process for lost account by rescuer account has been vouched for by sender. **/ RecoveryVouched: AugmentedEvent<ApiType, [AccountId32, AccountId32, AccountId32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; registrar: { Deregistered: AugmentedEvent<ApiType, [u32]>; Registered: AugmentedEvent<ApiType, [u32, AccountId32]>; Reserved: AugmentedEvent<ApiType, [u32, AccountId32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; scheduler: { /** * The call for the provided hash was not found so the task has been aborted. **/ CallLookupFailed: AugmentedEvent<ApiType, [ITuple<[u32, u32]>, Option<Bytes>, FrameSupportScheduleLookupError]>; /** * Canceled some task. **/ Canceled: AugmentedEvent<ApiType, [u32, u32]>; /** * Dispatched some task. **/ Dispatched: AugmentedEvent<ApiType, [ITuple<[u32, u32]>, Option<Bytes>, Result<Null, SpRuntimeDispatchError>]>; /** * Scheduled some task. **/ Scheduled: AugmentedEvent<ApiType, [u32, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; session: { /** * New session has happened. Note that the argument is the session index, not the * block number as the type might suggest. **/ NewSession: AugmentedEvent<ApiType, [u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; slots: { /** * A para has won the right to a continuous set of lease periods as a parachain. * First balance is any extra amount reserved on top of the para's existing deposit. * Second balance is the total amount reserved. * `[parachain_id, leaser, period_begin, period_count, extra_reserved, total_amount]` **/ Leased: AugmentedEvent<ApiType, [u32, AccountId32, u32, u32, u128, u128]>; /** * A new `[lease_period]` is beginning. **/ NewLeasePeriod: AugmentedEvent<ApiType, [u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; society: { /** * A candidate was dropped (due to an excess of bids in the system). **/ AutoUnbid: AugmentedEvent<ApiType, [AccountId32]>; /** * A membership bid just happened. The given account is the candidate's ID and their offer * is the second. **/ Bid: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * A candidate has been suspended **/ CandidateSuspended: AugmentedEvent<ApiType, [AccountId32]>; /** * A member has been challenged **/ Challenged: AugmentedEvent<ApiType, [AccountId32]>; /** * A vote has been placed for a defending member **/ DefenderVote: AugmentedEvent<ApiType, [AccountId32, bool]>; /** * Some funds were deposited into the society account. **/ Deposit: AugmentedEvent<ApiType, [u128]>; /** * The society is founded by the given identity. **/ Founded: AugmentedEvent<ApiType, [AccountId32]>; /** * A group of candidates have been inducted. The batch's primary is the first value, the * batch in full is the second. **/ Inducted: AugmentedEvent<ApiType, [AccountId32, Vec<AccountId32>]>; /** * A member has been suspended **/ MemberSuspended: AugmentedEvent<ApiType, [AccountId32]>; /** * A new \[max\] member count has been set **/ NewMaxMembers: AugmentedEvent<ApiType, [u32]>; /** * A suspended member has been judged. **/ SuspendedMemberJudgement: AugmentedEvent<ApiType, [AccountId32, bool]>; /** * A candidate was dropped (by their request). **/ Unbid: AugmentedEvent<ApiType, [AccountId32]>; /** * Society is unfounded. **/ Unfounded: AugmentedEvent<ApiType, [AccountId32]>; /** * A candidate was dropped (by request of who vouched for them). **/ Unvouch: AugmentedEvent<ApiType, [AccountId32]>; /** * A vote has been placed **/ Vote: AugmentedEvent<ApiType, [AccountId32, AccountId32, bool]>; /** * A membership bid just happened by vouching. The given account is the candidate's ID and * their offer is the second. The vouching party is the third. **/ Vouch: AugmentedEvent<ApiType, [AccountId32, u128, AccountId32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; staking: { /** * An account has bonded this amount. \[stash, amount\] * * NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably, * it will not be emitted for staking rewards when they are added to stake. **/ Bonded: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * An account has stopped participating as either a validator or nominator. * \[stash\] **/ Chilled: AugmentedEvent<ApiType, [AccountId32]>; /** * The era payout has been set; the first balance is the validator-payout; the second is * the remainder from the maximum amount of reward. * \[era_index, validator_payout, remainder\] **/ EraPaid: AugmentedEvent<ApiType, [u32, u128, u128]>; /** * A nominator has been kicked from a validator. \[nominator, stash\] **/ Kicked: AugmentedEvent<ApiType, [AccountId32, AccountId32]>; /** * An old slashing report from a prior era was discarded because it could * not be processed. \[session_index\] **/ OldSlashingReportDiscarded: AugmentedEvent<ApiType, [u32]>; /** * The stakers' rewards are getting paid. \[era_index, validator_stash\] **/ PayoutStarted: AugmentedEvent<ApiType, [u32, AccountId32]>; /** * The nominator has been rewarded by this amount. \[stash, amount\] **/ Rewarded: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * One validator (and its nominators) has been slashed by the given amount. * \[validator, amount\] **/ Slashed: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * A new set of stakers was elected. **/ StakersElected: AugmentedEvent<ApiType, []>; /** * The election failed. No new era is planned. **/ StakingElectionFailed: AugmentedEvent<ApiType, []>; /** * An account has unbonded this amount. \[stash, amount\] **/ Unbonded: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance` * from the unlocking queue. \[stash, amount\] **/ Withdrawn: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; system: { /** * `:code` was updated. **/ CodeUpdated: AugmentedEvent<ApiType, []>; /** * An extrinsic failed. **/ ExtrinsicFailed: AugmentedEvent<ApiType, [SpRuntimeDispatchError, FrameSupportWeightsDispatchInfo]>; /** * An extrinsic completed successfully. **/ ExtrinsicSuccess: AugmentedEvent<ApiType, [FrameSupportWeightsDispatchInfo]>; /** * An account was reaped. **/ KilledAccount: AugmentedEvent<ApiType, [AccountId32]>; /** * A new account was created. **/ NewAccount: AugmentedEvent<ApiType, [AccountId32]>; /** * On on-chain remark happened. **/ Remarked: AugmentedEvent<ApiType, [AccountId32, H256]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; technicalCommittee: { /** * A motion was approved by the required threshold. **/ Approved: AugmentedEvent<ApiType, [H256]>; /** * A proposal was closed because its threshold was reached or after its duration was up. **/ Closed: AugmentedEvent<ApiType, [H256, u32, u32]>; /** * A motion was not approved by the required threshold. **/ Disapproved: AugmentedEvent<ApiType, [H256]>; /** * A motion was executed; result will be `Ok` if it returned without error. **/ Executed: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>; /** * A single member did some action; result will be `Ok` if it returned without error. **/ MemberExecuted: AugmentedEvent<ApiType, [H256, Result<Null, SpRuntimeDispatchError>]>; /** * A motion (given hash) has been proposed (by given account) with a threshold (given * `MemberCount`). **/ Proposed: AugmentedEvent<ApiType, [AccountId32, u32, H256, u32]>; /** * A motion (given hash) has been voted on by given account, leaving * a tally (yes votes and no votes given respectively as `MemberCount`). **/ Voted: AugmentedEvent<ApiType, [AccountId32, H256, bool, u32, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; technicalMembership: { /** * Phantom member, never used. **/ Dummy: AugmentedEvent<ApiType, []>; /** * One of the members' keys changed. **/ KeyChanged: AugmentedEvent<ApiType, []>; /** * The given member was added; see the transaction for who. **/ MemberAdded: AugmentedEvent<ApiType, []>; /** * The given member was removed; see the transaction for who. **/ MemberRemoved: AugmentedEvent<ApiType, []>; /** * The membership was reset; see the transaction for who the new set is. **/ MembersReset: AugmentedEvent<ApiType, []>; /** * Two members were swapped; see the transaction for who. **/ MembersSwapped: AugmentedEvent<ApiType, []>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; tips: { /** * A new tip suggestion has been opened. **/ NewTip: AugmentedEvent<ApiType, [H256]>; /** * A tip suggestion has been closed. **/ TipClosed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>; /** * A tip suggestion has reached threshold and is closing. **/ TipClosing: AugmentedEvent<ApiType, [H256]>; /** * A tip suggestion has been retracted. **/ TipRetracted: AugmentedEvent<ApiType, [H256]>; /** * A tip suggestion has been slashed. **/ TipSlashed: AugmentedEvent<ApiType, [H256, AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; treasury: { /** * Some funds have been allocated. **/ Awarded: AugmentedEvent<ApiType, [u32, u128, AccountId32]>; /** * Some of our funds have been burnt. **/ Burnt: AugmentedEvent<ApiType, [u128]>; /** * Some funds have been deposited. **/ Deposit: AugmentedEvent<ApiType, [u128]>; /** * New proposal. **/ Proposed: AugmentedEvent<ApiType, [u32]>; /** * A proposal was rejected; funds were slashed. **/ Rejected: AugmentedEvent<ApiType, [u32, u128]>; /** * Spending has finished; this is the amount that rolls over until next spend. **/ Rollover: AugmentedEvent<ApiType, [u128]>; /** * We have ended a spend period and will now allocate funds. **/ Spending: AugmentedEvent<ApiType, [u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; ump: { /** * Upward message executed with the given outcome. * \[ id, outcome \] **/ ExecutedUpward: AugmentedEvent<ApiType, [U8aFixed, XcmV2TraitsOutcome]>; /** * Upward message is invalid XCM. * \[ id \] **/ InvalidFormat: AugmentedEvent<ApiType, [U8aFixed]>; /** * The weight budget was exceeded for an individual upward message. * * This message can be later dispatched manually using `service_overweight` dispatchable * using the assigned `overweight_index`. * * \[ para, id, overweight_index, required \] **/ OverweightEnqueued: AugmentedEvent<ApiType, [u32, U8aFixed, u64, u64]>; /** * Upward message from the overweight queue was executed with the given actual weight * used. * * \[ overweight_index, used \] **/ OverweightServiced: AugmentedEvent<ApiType, [u64, u64]>; /** * Upward message is unsupported version of XCM. * \[ id \] **/ UnsupportedVersion: AugmentedEvent<ApiType, [U8aFixed]>; /** * Some upward messages have been received and will be processed. * \[ para, count, size \] **/ UpwardMessagesReceived: AugmentedEvent<ApiType, [u32, u32, u32]>; /** * The weight limit for handling upward messages was reached. * \[ id, remaining, required \] **/ WeightExhausted: AugmentedEvent<ApiType, [U8aFixed, u64, u64]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; utility: { /** * Batch of dispatches completed fully with no error. **/ BatchCompleted: AugmentedEvent<ApiType, []>; /** * Batch of dispatches did not complete fully. Index of first failing dispatch given, as * well as the error. **/ BatchInterrupted: AugmentedEvent<ApiType, [u32, SpRuntimeDispatchError]>; /** * A call was dispatched. **/ DispatchedAs: AugmentedEvent<ApiType, [Result<Null, SpRuntimeDispatchError>]>; /** * A single item within a Batch of dispatches has completed with no error. **/ ItemCompleted: AugmentedEvent<ApiType, []>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; vesting: { /** * An \[account\] has become fully vested. **/ VestingCompleted: AugmentedEvent<ApiType, [AccountId32]>; /** * The amount vested has been updated. This could indicate a change in funds available. * The balance given is the amount which is left unvested (and thus locked). **/ VestingUpdated: AugmentedEvent<ApiType, [AccountId32, u128]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; xcmPallet: { /** * Some assets have been placed in an asset trap. * * \[ hash, origin, assets \] **/ AssetsTrapped: AugmentedEvent<ApiType, [H256, XcmV1MultiLocation, XcmVersionedMultiAssets]>; /** * Execution of an XCM message was attempted. * * \[ outcome \] **/ Attempted: AugmentedEvent<ApiType, [XcmV2TraitsOutcome]>; /** * Expected query response has been received but the origin location of the response does * not match that expected. The query remains registered for a later, valid, response to * be received and acted upon. * * \[ origin location, id, expected location \] **/ InvalidResponder: AugmentedEvent<ApiType, [XcmV1MultiLocation, u64, Option<XcmV1MultiLocation>]>; /** * Expected query response has been received but the expected origin location placed in * storage by this runtime previously cannot be decoded. The query remains registered. * * This is unexpected (since a location placed in storage in a previously executing * runtime should be readable prior to query timeout) and dangerous since the possibly * valid response will be dropped. Manual governance intervention is probably going to be * needed. * * \[ origin location, id \] **/ InvalidResponderVersion: AugmentedEvent<ApiType, [XcmV1MultiLocation, u64]>; /** * Query response has been received and query is removed. The registered notification has * been dispatched and executed successfully. * * \[ id, pallet index, call index \] **/ Notified: AugmentedEvent<ApiType, [u64, u8, u8]>; /** * Query response has been received and query is removed. The dispatch was unable to be * decoded into a `Call`; this might be due to dispatch function having a signature which * is not `(origin, QueryId, Response)`. * * \[ id, pallet index, call index \] **/ NotifyDecodeFailed: AugmentedEvent<ApiType, [u64, u8, u8]>; /** * Query response has been received and query is removed. There was a general error with * dispatching the notification call. * * \[ id, pallet index, call index \] **/ NotifyDispatchError: AugmentedEvent<ApiType, [u64, u8, u8]>; /** * Query response has been received and query is removed. The registered notification could * not be dispatched because the dispatch weight is greater than the maximum weight * originally budgeted by this runtime for the query result. * * \[ id, pallet index, call index, actual weight, max budgeted weight \] **/ NotifyOverweight: AugmentedEvent<ApiType, [u64, u8, u8, u64, u64]>; /** * A given location which had a version change subscription was dropped owing to an error * migrating the location to our new XCM format. * * \[ location, query ID \] **/ NotifyTargetMigrationFail: AugmentedEvent<ApiType, [XcmVersionedMultiLocation, u64]>; /** * A given location which had a version change subscription was dropped owing to an error * sending the notification to it. * * \[ location, query ID, error \] **/ NotifyTargetSendFail: AugmentedEvent<ApiType, [XcmV1MultiLocation, u64, XcmV2TraitsError]>; /** * Query response has been received and is ready for taking with `take_response`. There is * no registered notification call. * * \[ id, response \] **/ ResponseReady: AugmentedEvent<ApiType, [u64, XcmV2Response]>; /** * Received query response has been read and removed. * * \[ id \] **/ ResponseTaken: AugmentedEvent<ApiType, [u64]>; /** * A XCM message was sent. * * \[ origin, destination, message \] **/ Sent: AugmentedEvent<ApiType, [XcmV1MultiLocation, XcmV1MultiLocation, XcmV2Xcm]>; /** * The supported version of a location has been changed. This might be through an * automatic notification or a manual intervention. * * \[ location, XCM version \] **/ SupportedVersionChanged: AugmentedEvent<ApiType, [XcmV1MultiLocation, u32]>; /** * Query response received which does not match a registered query. This may be because a * matching query was never registered, it may be because it is a duplicate response, or * because the query timed out. * * \[ origin location, id \] **/ UnexpectedResponse: AugmentedEvent<ApiType, [XcmV1MultiLocation, u64]>; /** * An XCM version change notification message has been attempted to be sent. * * \[ destination, result \] **/ VersionChangeNotified: AugmentedEvent<ApiType, [XcmV1MultiLocation, u32]>; /** * Generic event **/ [key: string]: AugmentedEvent<ApiType>; }; } // AugmentedEvents } // declare module
the_stack
import { KubeConfig } from "@kubernetes/client-node"; import { strict as assert } from "assert"; import * as yaml from "js-yaml"; import { ResourceCollection, Service, ConfigMap, Deployment, Namespace, V1ServicemonitorResource, withPodAntiAffinityRequired, StatefulSet, PersistentVolumeClaim, ServiceAccount } from "@opstrace/kubernetes"; import { State } from "../../reducer"; import { roundDownToOdd, select, getBucketName, min, roundDown } from "@opstrace/utils"; import { deepMerge, getControllerConfig, getControllerLokiConfigOverrides, getNodeCount } from "../../helpers"; import { DockerImages, getImagePullSecrets } from "@opstrace/controller-config"; import { log } from "@opstrace/utils"; export function LokiResources( state: State, kubeConfig: KubeConfig, namespace: string ): ResourceCollection { const collection = new ResourceCollection(); const { infrastructureName, target, region, gcp, logRetentionDays } = getControllerConfig(state); const dataBucketName = getBucketName({ clusterName: infrastructureName, suffix: "loki" }); const configBucketName = getBucketName({ clusterName: infrastructureName, suffix: "loki-config" }); const clusterName = infrastructureName; const deploymentConfig = { ruler: { resources: {}, replicas: select(getNodeCount(state), [ { "<=": 5, choose: 2 }, { "<=": Infinity, choose: 3 } ]) }, ingester: { resources: { // limits: { // cpu: "6", // memory: "128Gi" // }, // requests: { // cpu: "50m", // memory: "100Mi" // } }, replicas: select(getNodeCount(state), [ { "<=": 4, choose: 3 }, { "<=": 6, choose: 5 }, { "<=": 8, choose: 7 }, { "<=": 10, choose: 9 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, distributor: { resources: { // limits: { // cpu: "3", // memory: "500Mi" // }, // requests: { // cpu: "50m", // memory: "100Mi" // } }, replicas: select(getNodeCount(state), [ { "<=": 4, choose: 3 }, { "<=": 6, choose: 5 }, { "<=": 8, choose: 7 }, { "<=": 10, choose: 9 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, querier: { resources: { // limits: { // cpu: "12", // memory: "6Gi" // }, // requests: { // cpu: "50m", // memory: "100Mi" // } }, replicas: select(getNodeCount(state), [ { "<=": 6, choose: 3 }, { "<=": 9, choose: 5 }, { "<=": Infinity, choose: roundDownToOdd(getNodeCount(state) / 2) } ]) }, queryFrontend: { // more than 2 is not beneficial (less advantage of queueing requests in // front of queriers) replicas: 2 }, memcachedResults: { replicas: select(getNodeCount(state), [ { "<=": 4, choose: 2 }, { "<=": 9, choose: 3 }, { "<=": Infinity, choose: min(4, roundDown(getNodeCount(state) / 3)) } ]), resources: {} }, env: [] }; const memberlist_bind_port = 7947; const grpc_server_max_msg_size = 41943040; // default (4 MB) * 10 const lokiDefaultConfig = { server: { http_listen_port: 1080, grpc_server_max_recv_msg_size: grpc_server_max_msg_size, grpc_server_max_send_msg_size: grpc_server_max_msg_size, // https://github.com/grafana/loki/pull/4182/files grpc_server_max_concurrent_streams: 1000, grpc_server_ping_without_stream_allowed: true, grpc_server_min_time_between_pings: "10s" }, auth_enabled: true, chunk_store_config: { chunk_cache_config: { background: { writeback_buffer: 5000 }, memcached_client: { consistent_hash: true, host: `memcached.${namespace}.svc.cluster.local`, service: "memcached-client" } } }, limits_config: { enforce_metric_name: false, ingestion_rate_mb: 500, ingestion_burst_size_mb: 2000, // enforced in querier max_entries_limit_per_query: 60000, // Per-tenant entry limit per query // https://github.com/grafana/loki/blob/main/production/ksonnet/loki/config.libsonnet#L190-L198 reject_old_samples: true, reject_old_samples_max_age: "168h", max_query_length: `${(logRetentionDays + 1) * 24}h`, max_query_parallelism: 16, max_streams_per_user: 0, // Disabled in favor of the global limit max_global_streams_per_user: 10000, // 10k ingestion_rate_strategy: "global", max_cache_freshness_per_query: "10m" }, frontend: { compress_responses: true, tail_proxy_url: `http://querier.${namespace}.svc.cluster.local:1080` }, // The frontend_worker_config configures the worker - running within // the Loki querier - picking up and executing queries enqueued by // the query-frontend. frontend_worker: { frontend_address: `query-frontend.${namespace}.svc.cluster.local:9095`, grpc_client_config: { // Fix opstrace-prelaunch/issues/1289 // Enable backoff and retry when a rate limit is hit. backoff_on_ratelimits: true, // https://github.com/grafana/loki/blob/main/production/ksonnet/loki/config.libsonnet#L156 max_send_msg_size: grpc_server_max_msg_size } }, // https://github.com/grafana/loki/blob/main/production/ksonnet/loki/config.libsonnet#L160-L175 query_range: { split_queries_by_interval: "30m", align_queries_with_step: true, cache_results: true, max_retries: 5, results_cache: { cache: { memcached_client: { timeout: "500ms", consistent_hash: true, service: "memcached-client", host: `memcached-results.${namespace}.svc.cluster.local`, update_interval: "1m", max_idle_conns: 16 } } } }, // https://github.com/grafana/loki/blob/main/production/ksonnet/loki/config.libsonnet#L179-L181 querier: { query_ingesters_within: "4h" // twice the max-chunk age for safety buffer }, ingester: { chunk_retain_period: "5m", // default: 15m. How long to keep in mem after flush. chunk_target_size: 2000000, // ~2 MB (compressed). Flush criterion 1. For high-throughput log streams. max_chunk_age: "2h", // default: 1h. Flush criterion 2. Time window of timestamps in log entries. chunk_idle_period: "2h", // Flush criterion 3. Inactivity from Loki's point of view. max_returned_stream_errors: 25, // default: 10 // // Enabling wal requires setting this to 0 (zero). Otherwise ingesters // fail to start with this error message: // // caller=main.go:87 msg="validating config" err="invalid ingester config: // the use of the write ahead log (WAL) is incompatible with chunk // transfers. It's suggested to use the WAL. Please try setting // ingester.max-transfer-retries to 0 to disable transfers" // max_transfer_retries: 0, wal: { enabled: true, // Directory where the WAL data should be stored and/or recovered from. // Should point to a directory in the attached volume which is mounted // at "/loki". dir: "/loki/wal", // Maximum memory size the WAL may use during replay. After hitting this // it will flush data to storage before continuing. A unit suffix (KB, // MB, GB) may be applied. // // Default is 4GB. We set a lower value to have a faster process // bootstrap and especially to reduce memory usage because we also run // cortex ingesters on the same nodes and want to reduce the chances of // a OOM. replay_memory_ceiling: "1GB" }, lifecycler: { join_after: "30s", observe_period: "30s", num_tokens: 512, ring: { kvstore: { store: "memberlist" } } } }, distributor: { ring: { kvstore: { store: "memberlist" } } }, memberlist: { // https://github.com/cortexproject/cortex/blob/master/docs/configuration/config-file-reference.md#memberlist_config // https://grafana.com/docs/loki/latest/configuration/#memberlist_config // don't allow split-brain / individual components that think they are // not part of a cluster. abort_if_cluster_join_fails: true, bind_port: memberlist_bind_port, join_members: [ // use a kubernetes headless service for all distributor, ingester and // querier components `loki-gossip-ring.${namespace}.svc.cluster.local:${memberlist_bind_port}` ], // these settings are taken from examples in official documentation // https://github.com/grafana/loki/blob/master/docs/sources/configuration/examples.md max_join_backoff: "1m", max_join_retries: 20, min_join_backoff: "1s" }, schema_config: { configs: [ { from: "2020-08-01", index: { prefix: `${clusterName}_loki_index_`, // "BoltDB shipper works best with 24h periodic index files" period: "24h" }, object_store: target === "gcp" ? "gcs" : "s3", schema: "v11", store: "boltdb-shipper" } ] }, compactor: { working_directory: "/loki/compactor", shared_store: target === "gcp" ? "gcs" : "s3" }, ruler: { enable_api: true, alertmanager_url: `http://alertmanager.cortex.svc.cluster.local/alertmanager/`, enable_sharding: true, enable_alertmanager_v2: true, rule_path: "/tmp/rules", ring: { kvstore: { store: "memberlist" } }, storage: { type: target === "gcp" ? "gcs" : "s3", gcs: { bucket_name: configBucketName }, s3: { s3: `s3://${region}/${configBucketName}` } } }, storage_config: { boltdb_shipper: { active_index_directory: "/loki/index", shared_store: target === "gcp" ? "gcs" : "s3", cache_location: "/loki/boltdb-cache" }, gcs: { bucket_name: dataBucketName }, aws: { s3: `s3://${region}/${dataBucketName}` }, index_queries_cache_config: { memcached_client: { consistent_hash: true, host: `memcached-index-queries.${namespace}.svc.cluster.local`, service: "memcached-client" } } } }; const lokiConfigOverrides = getControllerLokiConfigOverrides(state); log.debug( `loki config overrides: ${JSON.stringify(lokiConfigOverrides, null, 2)}` ); const lokiConfig = deepMerge(lokiDefaultConfig, lokiConfigOverrides); collection.add( new Namespace( { apiVersion: "v1", kind: "Namespace", metadata: { name: namespace } }, kubeConfig ) ); let annotations = {}; let serviceAccountName: string | undefined = undefined; if (target === "gcp") { assert(gcp?.lokiServiceAccount); annotations = { "iam.gke.io/gcp-service-account": gcp.lokiServiceAccount }; serviceAccountName = "loki"; } collection.add( new ServiceAccount( { apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "loki", namespace, annotations: annotations } }, kubeConfig ) ); collection.add( new ConfigMap( { apiVersion: "v1", data: { "config.yaml": yaml.safeDump(lokiConfig) }, kind: "ConfigMap", metadata: { name: "loki", namespace } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.querier`, name: "querier" }, name: "querier", namespace }, spec: { ports: [ { name: "querier-http-metrics", port: 1080, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 1080 as any }, { name: "querier-grpc", port: 9095, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 9095 as any } ], selector: { name: "querier" } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { name: "loki-gossip-ring" }, name: "loki-gossip-ring", namespace }, spec: { clusterIP: "None", ports: [ { name: "loki-gossip-ring", port: memberlist_bind_port, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: memberlist_bind_port as any } ], selector: { memberlist: "loki-gossip-ring" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "querier", tenant: "system" }, name: "querier", namespace }, spec: { endpoints: [ { interval: "30s", port: "querier-http-metrics", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "querier" } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.distributor`, name: "distributor" }, name: "distributor", namespace }, spec: { ports: [ { name: "distributor-http-metrics", port: 1080, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 1080 as any }, { name: "distributor-grpc", port: 9095, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 9095 as any } ], selector: { name: "distributor" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "distributor", tenant: "system" }, name: "distributor", namespace }, spec: { endpoints: [ { interval: "30s", port: "distributor-http-metrics", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "distributor" } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.ingester`, name: "ingester" }, name: "ingester", namespace }, spec: { ports: [ { name: "ingester-http-metrics", port: 1080, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 1080 as any }, { name: "ingester-grpc", port: 9095, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 9095 as any } ], selector: { name: "ingester" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "ingester", tenant: "system" }, name: "ingester", namespace }, spec: { endpoints: [ { interval: "30s", port: "ingester-http-metrics", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "ingester" } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.compactor`, name: "compactor" }, name: "compactor", namespace }, spec: { ports: [ { name: "compactor-http-metrics", port: 1080, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 1080 as any }, { name: "compactor-grpc", port: 9095, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 9095 as any } ], selector: { name: "compactor" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "compactor", tenant: "system" }, name: "compactor", namespace }, spec: { endpoints: [ { interval: "30s", port: "compactor-http-metrics", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "compactor" } } } }, kubeConfig ) ); collection.add( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "distributor", namespace }, spec: { minReadySeconds: 10, replicas: deploymentConfig.distributor.replicas, revisionHistoryLimit: 10, selector: { matchLabels: { name: "distributor", app: "loki-gossip-ring" } }, template: { metadata: { labels: { name: "distributor", app: "loki-gossip-ring" } }, spec: { imagePullSecrets: getImagePullSecrets(), affinity: withPodAntiAffinityRequired({ name: "distributor" }), containers: [ { args: [ "-config.file=/etc/loki/config.yaml", "-target=distributor" ], env: deploymentConfig.env, image: DockerImages.loki, imagePullPolicy: "IfNotPresent", name: "distributor", ports: [ { containerPort: 1080, name: "http-metrics" }, { containerPort: 9095, name: "grpc" } ], // https://github.com/grafana/loki/blob/6d85c7c212f95c7fbf902b467edc46a5ec3555fd/production/helm/loki/values.yaml#L167-L171 readinessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, resources: deploymentConfig.distributor.resources, volumeMounts: [ { mountPath: "/etc/loki", name: "loki" } ] } ], volumes: [ { configMap: { name: "loki" }, name: "loki" } ] } } } }, kubeConfig ) ); collection.add( new StatefulSet( { apiVersion: "apps/v1", kind: "StatefulSet", metadata: { name: "ingester", namespace }, spec: { serviceName: "ingester", replicas: deploymentConfig.ingester.replicas, revisionHistoryLimit: 10, podManagementPolicy: "OrderedReady", selector: { matchLabels: { name: "ingester", memberlist: "loki-gossip-ring" } }, template: { metadata: { labels: { name: "ingester", memberlist: "loki-gossip-ring" } }, spec: { imagePullSecrets: getImagePullSecrets(), affinity: withPodAntiAffinityRequired({ name: "ingester" }), containers: [ { args: [ "-config.file=/etc/loki/config.yaml", "-target=ingester" ], env: deploymentConfig.env, image: DockerImages.loki, imagePullPolicy: "IfNotPresent", name: "ingester", ports: [ { containerPort: 1080, name: "http-metrics" }, { containerPort: 9095, name: "grpc" } ], readinessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, resources: deploymentConfig.ingester.resources, volumeMounts: [ { mountPath: "/etc/loki", name: "loki" }, { name: "datadir", mountPath: "/loki" } ] } ], serviceAccountName: serviceAccountName, securityContext: { fsGroup: 2000 }, // https://cortexmetrics.io/docs/guides/running-cortex-on-kubernetes/#take-extra-care-with-ingesters // The link is for cortex ingesters but loki ingesters share the // same architecture. terminationGracePeriodSeconds: 2400, volumes: [ { configMap: { name: "loki" }, name: "loki" }, { name: "datadir", persistentVolumeClaim: { claimName: "datadir" } } ] } }, volumeClaimTemplates: [ { metadata: { name: "datadir" }, spec: { storageClassName: "pd-ssd", accessModes: ["ReadWriteOnce"], resources: { requests: { storage: "10Gi" } } } } ] } }, kubeConfig ) ); collection.add( new PersistentVolumeClaim( { apiVersion: "v1", kind: "PersistentVolumeClaim", metadata: { name: "compactor-datadir-storage-claim", namespace }, spec: { storageClassName: "pd-ssd", accessModes: ["ReadWriteOnce"], resources: { requests: { storage: "10Gi" } } } }, kubeConfig ) ); collection.add( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "compactor", namespace }, spec: { revisionHistoryLimit: 10, // no more than one compactor instance at any given time, see // boltdb shipper docs replicas: 1, strategy: { type: "Recreate" }, selector: { matchLabels: { name: "compactor" } }, template: { metadata: { labels: { name: "compactor" } }, spec: { imagePullSecrets: getImagePullSecrets(), affinity: withPodAntiAffinityRequired({ name: "compactor" }), containers: [ { args: [ "-config.file=/etc/loki/config.yaml", "-target=compactor" ], env: deploymentConfig.env, image: DockerImages.loki, imagePullPolicy: "IfNotPresent", name: "compactor", ports: [ { containerPort: 1080, name: "http-metrics" }, { containerPort: 9095, name: "grpc" } ], readinessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, livenessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, resources: deploymentConfig.querier.resources, volumeMounts: [ { mountPath: "/etc/loki", name: "loki" }, { name: "datadir", mountPath: "/loki" } ] } ], securityContext: { fsGroup: 2000 }, serviceAccountName: serviceAccountName, volumes: [ { configMap: { name: "loki" }, name: "loki" }, { name: "datadir", persistentVolumeClaim: { claimName: "compactor-datadir-storage-claim" } } ] } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.ruler`, name: "ruler" }, name: "ruler", namespace }, spec: { ports: [ { name: "ruler-http-metrics", port: 1080, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 1080 as any }, { name: "ruler-grpc", port: 9095, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: 9095 as any } ], selector: { name: "ruler" } } }, kubeConfig ) ); collection.add( new StatefulSet( { apiVersion: "apps/v1", kind: "StatefulSet", metadata: { name: "ruler", namespace }, spec: { serviceName: "ruler", replicas: deploymentConfig.ruler.replicas, revisionHistoryLimit: 10, podManagementPolicy: "Parallel", selector: { matchLabels: { name: "ruler", memberlist: "loki-gossip-ring" } }, template: { metadata: { labels: { name: "ruler", memberlist: "loki-gossip-ring" } }, spec: { imagePullSecrets: getImagePullSecrets(), affinity: withPodAntiAffinityRequired({ name: "ruler" }), containers: [ { args: ["-config.file=/etc/loki/config.yaml", "-target=ruler"], env: deploymentConfig.env, image: DockerImages.loki, imagePullPolicy: "IfNotPresent", name: "ruler", ports: [ { containerPort: 1080, name: "http-metrics" }, { containerPort: 9095, name: "grpc" } ], readinessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, resources: deploymentConfig.ruler.resources, volumeMounts: [ { mountPath: "/etc/loki", name: "loki" }, { name: "ruler-data", mountPath: "/data" } ] } ], serviceAccountName: serviceAccountName, securityContext: { fsGroup: 2000 }, volumes: [ { configMap: { name: "loki" }, name: "loki" }, { name: "ruler-data", persistentVolumeClaim: { claimName: "ruler-data" } } ] } }, volumeClaimTemplates: [ { metadata: { name: "ruler-data" }, spec: { storageClassName: "pd-ssd", accessModes: ["ReadWriteOnce"], resources: { requests: { storage: "10Gi" } } } } ] } }, kubeConfig ) ); collection.add( new StatefulSet( { apiVersion: "apps/v1", kind: "StatefulSet", metadata: { name: "querier", namespace }, spec: { serviceName: "querier", replicas: deploymentConfig.querier.replicas, revisionHistoryLimit: 10, podManagementPolicy: "OrderedReady", selector: { matchLabels: { name: "querier", memberlist: "loki-gossip-ring" } }, template: { metadata: { labels: { name: "querier", memberlist: "loki-gossip-ring" } }, spec: { imagePullSecrets: getImagePullSecrets(), affinity: withPodAntiAffinityRequired({ name: "querier" }), containers: [ { args: [ "-config.file=/etc/loki/config.yaml", "-target=querier" ], env: deploymentConfig.env, image: DockerImages.loki, imagePullPolicy: "IfNotPresent", name: "querier", ports: [ { containerPort: 1080, name: "http-metrics" }, { containerPort: 9095, name: "grpc" } ], readinessProbe: { httpGet: { path: "/ready", // eslint-disable-next-line @typescript-eslint/no-explicit-any port: 1080 as any, scheme: "HTTP" }, initialDelaySeconds: 45, timeoutSeconds: 1, periodSeconds: 10, successThreshold: 1, failureThreshold: 3 }, resources: deploymentConfig.querier.resources, volumeMounts: [ { mountPath: "/etc/loki", name: "loki" }, { name: "cachedir", mountPath: "/loki" } ] } ], serviceAccountName: serviceAccountName, securityContext: { fsGroup: 2000 }, volumes: [ { configMap: { name: "loki" }, name: "loki" }, { name: "cachedir", persistentVolumeClaim: { claimName: "cachedir" } } ] } }, volumeClaimTemplates: [ { metadata: { name: "cachedir" }, spec: { storageClassName: "pd-ssd", accessModes: ["ReadWriteOnce"], resources: { requests: { storage: "10Gi" } } } } ] } }, kubeConfig ) ); collection.add( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "query-frontend", namespace }, spec: { replicas: deploymentConfig.queryFrontend.replicas, selector: { matchLabels: { name: "query-frontend" } }, template: { metadata: { labels: { name: "query-frontend" } }, spec: { affinity: withPodAntiAffinityRequired({ name: "query-frontend" }), containers: [ { name: "query-frontend", image: DockerImages.loki, imagePullPolicy: "IfNotPresent", args: [ "-target=query-frontend", "-config.file=/etc/loki/config.yaml" ], env: deploymentConfig.env, ports: [ { containerPort: 9095, name: "grpc" }, { containerPort: 1080, name: "http" } ], volumeMounts: [ { mountPath: "/etc/loki", name: "loki" } ] } ], volumes: [ { configMap: { name: "loki" }, name: "loki" } ] } } } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { job: `${namespace}.query-frontend`, name: "query-frontend" }, name: "query-frontend", namespace }, spec: { clusterIP: "None", ports: [ { port: 9095, name: "grcp" }, { port: 1080, name: "http" } ], selector: { name: "query-frontend" } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "query-frontend", tenant: "system" }, name: "query-frontend", namespace }, spec: { endpoints: [ { interval: "30s", port: "http", path: "/metrics" } ], jobLabel: "job", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "query-frontend" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached-results", tenant: "system" }, name: "memcached-results", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-results" } } } }, kubeConfig ) ); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { name: "memcached", tenant: "system" }, name: "memcached-index-writes", namespace }, spec: { endpoints: [ { interval: "30s", port: "exporter-http-metrics", path: "/metrics" } ], jobLabel: "name", namespaceSelector: { matchNames: [namespace] }, selector: { matchLabels: { name: "memcached-index-writes" } } } }, kubeConfig ) ); collection.add( new StatefulSet( { apiVersion: "apps/v1", kind: "StatefulSet", metadata: { name: "memcached-results", namespace }, spec: { replicas: deploymentConfig.memcachedResults.replicas, serviceName: "memcached-results", podManagementPolicy: "Parallel", selector: { matchLabels: { name: "memcached-results" } }, template: { metadata: { labels: { name: "memcached-results" } }, spec: { affinity: withPodAntiAffinityRequired({ name: "memcached-results" }), containers: [ { args: ["-m 4096", "-I 2m", "-c 1024", "-v"], image: DockerImages.memcached, imagePullPolicy: "IfNotPresent", name: "memcached", ports: [ { containerPort: 11211, name: "client" } ], resources: deploymentConfig.memcachedResults.resources }, { args: [ "--memcached.address=localhost:11211", "--web.listen-address=0.0.0.0:9150" ], image: DockerImages.memcachedExporter, imagePullPolicy: "IfNotPresent", name: "exporter", ports: [ { containerPort: 9150, name: "http-metrics" } ] } ] } }, updateStrategy: { type: "RollingUpdate" }, volumeClaimTemplates: [] } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { name: "memcached-results" }, name: "memcached-results", namespace }, spec: { clusterIP: "None", ports: [ { name: "memcached-client", port: 11211, targetPort: 11211 as any }, { name: "exporter-http-metrics", port: 9150, targetPort: 9150 as any } ], selector: { name: "memcached-results" } } }, kubeConfig ) ); return collection; }
the_stack
import * as React from 'react'; import { canUseDOM } from './util'; export interface KeyboardHandlerProps { /** Reference of the container to apply keyboard interaction */ containerRef: React.RefObject<any>; /** Callback returning an array of navigable elements to be traversable via vertical arrow keys. This array should not include non-navigable elements such as disabled elements. */ createNavigableElements: () => Element[]; /** Callback to determine if a given event is from the container. By default the function conducts a basic check to see if the containerRef contains the event target */ isEventFromContainer?: (event: KeyboardEvent) => boolean; /** Additional key handling outside of the included arrow keys, enter, and space handling */ additionalKeyHandler?: (event: KeyboardEvent) => void; /** Callback to determine if a given element from the navigable elements array is the active element of the page */ isActiveElement?: (navigableElement: Element) => boolean; /** Callback returning the focusable element of a given element from the navigable elements array */ getFocusableElement?: (navigableElement: Element) => Element; /** Valid sibling tags that horizontal arrow handling will focus */ validSiblingTags?: string[]; /** Flag indicating that the tabIndex of the currently focused element and next focused element should be updated, in the case of using a roving tabIndex */ updateTabIndex?: boolean; /** Flag indicating that the included vertical arrow key handling should be ignored */ noVerticalArrowHandling?: boolean; /** Flag indicating that the included horizontal arrow key handling should be ignored */ noHorizontalArrowHandling?: boolean; /** Flag indicating that the included enter key handling should be ignored */ noEnterHandling?: boolean; /** Flag indicating that the included space key handling should be ignored */ noSpaceHandling?: boolean; } /** * This function is a helper for handling basic arrow keyboard interactions. If a component already has its own key handler and event start up/tear down, this function may be easier to integrate in over the full component. * * @param {event} event Event triggered by the keyboard * @param {element[]} navigableElements Valid traversable elements of the container * @param {function} isActiveElement Callback to determine if a given element from the navigable elements array is the active element of the page * @param {function} getFocusableElement Callback returning the focusable element of a given element from the navigable elements array * @param {string[]} validSiblingTags Valid sibling tags that horizontal arrow handling will focus * @param {boolean} noVerticalArrowHandling Flag indicating that the included vertical arrow key handling should be ignored * @param {boolean} noHorizontalArrowHandling Flag indicating that the included horizontal arrow key handling should be ignored * @param {boolean} updateTabIndex Flag indicating that the tabIndex of the currently focused element and next focused element should be updated, in the case of using a roving tabIndex * @param {boolean} onlyTraverseSiblings Flag indicating that next focusable element of a horizontal movement will be this element's sibling */ export const handleArrows = ( event: KeyboardEvent, navigableElements: Element[], isActiveElement: (element: Element) => boolean = element => document.activeElement.contains(element), getFocusableElement: (element: Element) => Element = element => element, validSiblingTags: string[] = ['A', 'BUTTON', 'INPUT'], noVerticalArrowHandling: boolean = false, noHorizontalArrowHandling: boolean = false, updateTabIndex: boolean = true, onlyTraverseSiblings: boolean = true ) => { const activeElement = document.activeElement; const key = event.key; let moveTarget: Element = null; // Handle vertical arrow keys. If noVerticalArrowHandling is passed, skip this block if (!noVerticalArrowHandling) { if (['ArrowUp', 'ArrowDown'].includes(key)) { event.preventDefault(); event.stopImmediatePropagation(); // For menus in menus // Traverse navigableElements to find the element which is currently active let currentIndex = -1; // while (currentIndex === -1) { navigableElements.forEach((element, index) => { if (isActiveElement(element)) { // Once found, move up or down the array by 1. Determined by the vertical arrow key direction let increment = 0; // keep increasing the increment until you've tried the whole navigableElement while (!moveTarget && increment < navigableElements.length && increment * -1 < navigableElements.length) { key === 'ArrowUp' ? increment-- : increment++; currentIndex = index + increment; if (currentIndex >= navigableElements.length) { currentIndex = 0; } if (currentIndex < 0) { currentIndex = navigableElements.length - 1; } // Set the next target element (undefined if none found) moveTarget = getFocusableElement(navigableElements[currentIndex]); } } }); // } } } // Handle horizontal arrow keys. If noHorizontalArrowHandling is passed, skip this block if (!noHorizontalArrowHandling) { if (['ArrowLeft', 'ArrowRight'].includes(key)) { event.preventDefault(); event.stopImmediatePropagation(); // For menus in menus let currentIndex = -1; navigableElements.forEach((element, index) => { if (isActiveElement(element)) { const activeRow = navigableElements[index].querySelectorAll(validSiblingTags.join(',')); // all focusable elements in my row if (!activeRow.length || onlyTraverseSiblings) { let nextSibling = activeElement; // While a sibling exists, check each sibling to determine if it should be focussed while (nextSibling) { // Set the next checked sibling, determined by the horizontal arrow key direction nextSibling = key === 'ArrowLeft' ? nextSibling.previousElementSibling : nextSibling.nextElementSibling; if (nextSibling) { if (validSiblingTags.includes(nextSibling.tagName)) { // If the sibling's tag is included in validSiblingTags, set the next target element and break the loop moveTarget = nextSibling; break; } // If the sibling's tag is not valid, skip to the next sibling if possible } } } else { activeRow.forEach((focusableElement, index) => { if (event.target === focusableElement) { // Once found, move up or down the array by 1. Determined by the vertical arrow key direction const increment = key === 'ArrowLeft' ? -1 : 1; currentIndex = index + increment; if (currentIndex >= activeRow.length) { currentIndex = 0; } if (currentIndex < 0) { currentIndex = activeRow.length - 1; } // Set the next target element moveTarget = activeRow[currentIndex]; } }); } } }); } } if (moveTarget) { // If updateTabIndex is true, set the previously focussed element's tabIndex to -1 and the next focussed element's tabIndex to 0 // This updates the tabIndex for a roving tabIndex if (updateTabIndex) { (activeElement as HTMLElement).tabIndex = -1; (moveTarget as HTMLElement).tabIndex = 0; } // If a move target has been set by either arrow handler, focus that target (moveTarget as HTMLElement).focus(); } }; /** * This function is a helper for setting the initial tabIndexes in a roving tabIndex * * @param {HTMLElement[]} options Array of elements which should have a tabIndex of -1, except for the first element which will have a tabIndex of 0 */ export const setTabIndex = (options: HTMLElement[]) => { if (options && options.length > 0) { // Iterate the options and set the tabIndex to -1 on every option options.forEach((option: HTMLElement) => { option.tabIndex = -1; }); // Manually set the tabIndex of the first option to 0 options[0].tabIndex = 0; } }; export class KeyboardHandler extends React.Component<KeyboardHandlerProps> { static displayName = 'KeyboardHandler'; static defaultProps: KeyboardHandlerProps = { containerRef: null, createNavigableElements: () => null as Element[], isActiveElement: (navigableElement: Element) => document.activeElement === navigableElement, getFocusableElement: (navigableElement: Element) => navigableElement, validSiblingTags: ['BUTTON', 'A'], updateTabIndex: true, noHorizontalArrowHandling: false, noVerticalArrowHandling: false, noEnterHandling: false, noSpaceHandling: false }; componentDidMount() { if (canUseDOM) { window.addEventListener('keydown', this.keyHandler); } } componentWillUnmount() { if (canUseDOM) { window.removeEventListener('keydown', this.keyHandler); } } keyHandler = (event: KeyboardEvent) => { const { isEventFromContainer } = this.props; // If the passed keyboard event is not from the container, ignore the event by returning if (isEventFromContainer ? !isEventFromContainer(event) : !this._isEventFromContainer(event)) { return; } const { isActiveElement, getFocusableElement, noVerticalArrowHandling, noHorizontalArrowHandling, noEnterHandling, noSpaceHandling, updateTabIndex, validSiblingTags, additionalKeyHandler, createNavigableElements } = this.props; // Pass the event off to be handled by any custom handler additionalKeyHandler && additionalKeyHandler(event); // Initalize navigableElements from the createNavigableElements callback const navigableElements = createNavigableElements(); if (!navigableElements) { // eslint-disable-next-line no-console console.warn( 'No navigable elements have been passed to the KeyboardHandler. Keyboard navigation provided by this component will be ignored.' ); return; } const key = event.key; // Handle enter key. If noEnterHandling is passed, skip this block if (!noEnterHandling) { if (key === 'Enter') { event.preventDefault(); event.stopImmediatePropagation(); // For menus in menus (document.activeElement as HTMLElement).click(); } } // Handle space key. If noSpaceHandling is passed, skip this block if (!noSpaceHandling) { if (key === ' ') { event.preventDefault(); event.stopImmediatePropagation(); // For menus in menus (document.activeElement as HTMLElement).click(); } } // Inject helper handler for arrow navigation handleArrows( event, navigableElements, isActiveElement, getFocusableElement, validSiblingTags, noVerticalArrowHandling, noHorizontalArrowHandling, updateTabIndex ); }; _isEventFromContainer = (event: KeyboardEvent) => { const { containerRef } = this.props; return containerRef.current && containerRef.current.contains(event.target as HTMLElement); }; render() { return null as React.ReactNode; } }
the_stack
import { GlyphRenderer } from './GlyphRenderer'; import { LinkRenderLayer } from './renderLayer/LinkRenderLayer'; import { CursorRenderLayer } from './renderLayer/CursorRenderLayer'; import { acquireCharAtlas } from './atlas/CharAtlasCache'; import { WebglCharAtlas } from './atlas/WebglCharAtlas'; import { RectangleRenderer } from './RectangleRenderer'; import { IWebGL2RenderingContext } from './Types'; import { RenderModel, COMBINED_CHAR_BIT_MASK, RENDER_MODEL_BG_OFFSET, RENDER_MODEL_FG_OFFSET, RENDER_MODEL_INDICIES_PER_CELL } from './RenderModel'; import { Disposable } from 'common/Lifecycle'; import { Content, NULL_CELL_CHAR, NULL_CELL_CODE } from 'common/buffer/Constants'; import { Terminal, IEvent } from 'xterm'; import { IRenderLayer } from './renderLayer/Types'; import { IRenderDimensions, IRenderer, IRequestRedrawEvent } from 'browser/renderer/Types'; import { ITerminal, IColorSet } from 'browser/Types'; import { EventEmitter } from 'common/EventEmitter'; import { CellData } from 'common/buffer/CellData'; import { addDisposableDomListener } from 'browser/Lifecycle'; import { ICharacterJoinerService } from 'browser/services/Services'; import { CharData, ICellData } from 'common/Types'; import { AttributeData } from 'common/buffer/AttributeData'; export class WebglRenderer extends Disposable implements IRenderer { private _renderLayers: IRenderLayer[]; private _charAtlas: WebglCharAtlas | undefined; private _devicePixelRatio: number; private _model: RenderModel = new RenderModel(); private _workCell: CellData = new CellData(); private _canvas: HTMLCanvasElement; private _gl: IWebGL2RenderingContext; private _rectangleRenderer: RectangleRenderer; private _glyphRenderer: GlyphRenderer; public dimensions: IRenderDimensions; private _core: ITerminal; private _isAttached: boolean; private _onRequestRedraw = new EventEmitter<IRequestRedrawEvent>(); public get onRequestRedraw(): IEvent<IRequestRedrawEvent> { return this._onRequestRedraw.event; } private _onContextLoss = new EventEmitter<void>(); public get onContextLoss(): IEvent<void> { return this._onContextLoss.event; } constructor( private _terminal: Terminal, private _colors: IColorSet, private readonly _characterJoinerService: ICharacterJoinerService, preserveDrawingBuffer?: boolean ) { super(); this._core = (this._terminal as any)._core; this._renderLayers = [ new LinkRenderLayer(this._core.screenElement!, 2, this._colors, this._core), new CursorRenderLayer(this._core.screenElement!, 3, this._colors, this._core, this._onRequestRedraw) ]; this.dimensions = { scaledCharWidth: 0, scaledCharHeight: 0, scaledCellWidth: 0, scaledCellHeight: 0, scaledCharLeft: 0, scaledCharTop: 0, scaledCanvasWidth: 0, scaledCanvasHeight: 0, canvasWidth: 0, canvasHeight: 0, actualCellWidth: 0, actualCellHeight: 0 }; this._devicePixelRatio = window.devicePixelRatio; this._updateDimensions(); this._canvas = document.createElement('canvas'); const contextAttributes = { antialias: false, depth: false, preserveDrawingBuffer }; this._gl = this._canvas.getContext('webgl2', contextAttributes) as IWebGL2RenderingContext; if (!this._gl) { throw new Error('WebGL2 not supported ' + this._gl); } this.register(addDisposableDomListener(this._canvas, 'webglcontextlost', (e) => { this._onContextLoss.fire(e); })); this._core.screenElement!.appendChild(this._canvas); this._rectangleRenderer = new RectangleRenderer(this._terminal, this._colors, this._gl, this.dimensions); this._glyphRenderer = new GlyphRenderer(this._terminal, this._colors, this._gl, this.dimensions); // Update dimensions and acquire char atlas this.onCharSizeChanged(); this._isAttached = document.body.contains(this._core.screenElement!); } public dispose(): void { for (const l of this._renderLayers) { l.dispose(); } this._canvas.parentElement?.removeChild(this._canvas); super.dispose(); } public get textureAtlas(): HTMLCanvasElement | undefined { return this._charAtlas?.cacheCanvas; } public setColors(colors: IColorSet): void { this._colors = colors; // Clear layers and force a full render for (const l of this._renderLayers) { l.setColors(this._terminal, this._colors); l.reset(this._terminal); } this._rectangleRenderer.setColors(); this._glyphRenderer.setColors(); this._refreshCharAtlas(); // Force a full refresh this._model.clear(); } public onDevicePixelRatioChange(): void { // If the device pixel ratio changed, the char atlas needs to be regenerated // and the terminal needs to refreshed if (this._devicePixelRatio !== window.devicePixelRatio) { this._devicePixelRatio = window.devicePixelRatio; this.onResize(this._terminal.cols, this._terminal.rows); } } public onResize(cols: number, rows: number): void { // Update character and canvas dimensions this._updateDimensions(); this._model.resize(this._terminal.cols, this._terminal.rows); // Resize all render layers for (const l of this._renderLayers) { l.resize(this._terminal, this.dimensions); } // Resize the canvas this._canvas.width = this.dimensions.scaledCanvasWidth; this._canvas.height = this.dimensions.scaledCanvasHeight; this._canvas.style.width = `${this.dimensions.canvasWidth}px`; this._canvas.style.height = `${this.dimensions.canvasHeight}px`; // Resize the screen this._core.screenElement!.style.width = `${this.dimensions.canvasWidth}px`; this._core.screenElement!.style.height = `${this.dimensions.canvasHeight}px`; this._rectangleRenderer.onResize(); if (this._model.selection.hasSelection) { // Update selection as dimensions have changed this._rectangleRenderer.updateSelection(this._model.selection); } this._glyphRenderer.setDimensions(this.dimensions); this._glyphRenderer.onResize(); this._refreshCharAtlas(); // Force a full refresh this._model.clear(); } public onCharSizeChanged(): void { this.onResize(this._terminal.cols, this._terminal.rows); } public onBlur(): void { for (const l of this._renderLayers) { l.onBlur(this._terminal); } } public onFocus(): void { for (const l of this._renderLayers) { l.onFocus(this._terminal); } } public onSelectionChanged(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean): void { for (const l of this._renderLayers) { l.onSelectionChanged(this._terminal, start, end, columnSelectMode); } this._updateSelectionModel(start, end, columnSelectMode); this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 }); } public onCursorMove(): void { for (const l of this._renderLayers) { l.onCursorMove(this._terminal); } } public onOptionsChanged(): void { for (const l of this._renderLayers) { l.onOptionsChanged(this._terminal); } this._updateDimensions(); this._refreshCharAtlas(); } /** * Refreshes the char atlas, aquiring a new one if necessary. * @param terminal The terminal. * @param colorSet The color set to use for the char atlas. */ private _refreshCharAtlas(): void { if (this.dimensions.scaledCharWidth <= 0 && this.dimensions.scaledCharHeight <= 0) { // Mark as not attached so char atlas gets refreshed on next render this._isAttached = false; return; } const atlas = acquireCharAtlas(this._terminal, this._colors, this.dimensions.scaledCellWidth, this.dimensions.scaledCellHeight, this.dimensions.scaledCharWidth, this.dimensions.scaledCharHeight); if (!('getRasterizedGlyph' in atlas)) { throw new Error('The webgl renderer only works with the webgl char atlas'); } this._charAtlas = atlas as WebglCharAtlas; this._charAtlas.warmUp(); this._glyphRenderer.setAtlas(this._charAtlas); } public clearCharAtlas(): void { this._charAtlas?.clearTexture(); this._model.clear(); this._updateModel(0, this._terminal.rows - 1); this._onRequestRedraw.fire({ start: 0, end: this._terminal.rows - 1 }); } public clear(): void { for (const l of this._renderLayers) { l.reset(this._terminal); } } public registerCharacterJoiner(handler: (text: string) => [number, number][]): number { return -1; } public deregisterCharacterJoiner(joinerId: number): boolean { return false; } public renderRows(start: number, end: number): void { if (!this._isAttached) { if (document.body.contains(this._core.screenElement!) && (this._core as any)._charSizeService.width && (this._core as any)._charSizeService.height) { this._updateDimensions(); this._refreshCharAtlas(); this._isAttached = true; } else { return; } } // Update render layers for (const l of this._renderLayers) { l.onGridChanged(this._terminal, start, end); } // Tell renderer the frame is beginning if (this._glyphRenderer.beginFrame()) { this._model.clear(); this._updateSelectionModel(undefined, undefined); } // Update model to reflect what's drawn this._updateModel(start, end); // Render this._rectangleRenderer.render(); this._glyphRenderer.render(this._model, this._model.selection.hasSelection); } private _updateModel(start: number, end: number): void { const terminal = this._core; let cell: ICellData = this._workCell; for (let y = start; y <= end; y++) { const row = y + terminal.buffer.ydisp; const line = terminal.buffer.lines.get(row)!; this._model.lineLengths[y] = 0; const joinedRanges = this._characterJoinerService.getJoinedCharacters(row); for (let x = 0; x < terminal.cols; x++) { line.loadCell(x, cell); // If true, indicates that the current character(s) to draw were joined. let isJoined = false; let lastCharX = x; // Process any joined character ranges as needed. Because of how the // ranges are produced, we know that they are valid for the characters // and attributes of our input. if (joinedRanges.length > 0 && x === joinedRanges[0][0]) { isJoined = true; const range = joinedRanges.shift()!; // We already know the exact start and end column of the joined range, // so we get the string and width representing it directly cell = new JoinedCellData( cell, line!.translateToString(true, range[0], range[1]), range[1] - range[0] ); // Skip over the cells occupied by this range in the loop lastCharX = range[1] - 1; } const chars = cell.getChars(); let code = cell.getCode(); const i = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL; if (code !== NULL_CELL_CODE) { this._model.lineLengths[y] = x + 1; } // Nothing has changed, no updates needed if (this._model.cells[i] === code && this._model.cells[i + RENDER_MODEL_BG_OFFSET] === cell.bg && this._model.cells[i + RENDER_MODEL_FG_OFFSET] === cell.fg) { continue; } // Flag combined chars with a bit mask so they're easily identifiable if (chars.length > 1) { code |= COMBINED_CHAR_BIT_MASK; } // Cache the results in the model this._model.cells[i] = code; this._model.cells[i + RENDER_MODEL_BG_OFFSET] = cell.bg; this._model.cells[i + RENDER_MODEL_FG_OFFSET] = cell.fg; this._glyphRenderer.updateCell(x, y, code, cell.bg, cell.fg, chars); if (isJoined) { // Restore work cell cell = this._workCell; // Null out non-first cells for (x++; x < lastCharX; x++) { const j = ((y * terminal.cols) + x) * RENDER_MODEL_INDICIES_PER_CELL; this._glyphRenderer.updateCell(x, y, NULL_CELL_CODE, 0, 0, NULL_CELL_CHAR); this._model.cells[j] = NULL_CELL_CODE; this._model.cells[j + RENDER_MODEL_BG_OFFSET] = this._workCell.bg; this._model.cells[j + RENDER_MODEL_FG_OFFSET] = this._workCell.fg; } } } } this._rectangleRenderer.updateBackgrounds(this._model); if (this._model.selection.hasSelection) { // Model could be updated but the selection is unchanged this._glyphRenderer.updateSelection(this._model); } } private _updateSelectionModel(start: [number, number] | undefined, end: [number, number] | undefined, columnSelectMode: boolean = false): void { const terminal = this._terminal; // Selection does not exist if (!start || !end || (start[0] === end[0] && start[1] === end[1])) { this._model.clearSelection(); this._rectangleRenderer.updateSelection(this._model.selection); return; } // Translate from buffer position to viewport position const viewportStartRow = start[1] - terminal.buffer.active.viewportY; const viewportEndRow = end[1] - terminal.buffer.active.viewportY; const viewportCappedStartRow = Math.max(viewportStartRow, 0); const viewportCappedEndRow = Math.min(viewportEndRow, terminal.rows - 1); // No need to draw the selection if (viewportCappedStartRow >= terminal.rows || viewportCappedEndRow < 0) { this._model.clearSelection(); this._rectangleRenderer.updateSelection(this._model.selection); return; } this._model.selection.hasSelection = true; this._model.selection.columnSelectMode = columnSelectMode; this._model.selection.viewportStartRow = viewportStartRow; this._model.selection.viewportEndRow = viewportEndRow; this._model.selection.viewportCappedStartRow = viewportCappedStartRow; this._model.selection.viewportCappedEndRow = viewportCappedEndRow; this._model.selection.startCol = start[0]; this._model.selection.endCol = end[0]; this._rectangleRenderer.updateSelection(this._model.selection); } /** * Recalculates the character and canvas dimensions. */ private _updateDimensions(): void { // TODO: Acquire CharSizeService properly // Perform a new measure if the CharMeasure dimensions are not yet available if (!(this._core as any)._charSizeService.width || !(this._core as any)._charSizeService.height) { return; } // Calculate the scaled character width. Width is floored as it must be // drawn to an integer grid in order for the CharAtlas "stamps" to not be // blurry. When text is drawn to the grid not using the CharAtlas, it is // clipped to ensure there is no overlap with the next cell. // NOTE: ceil fixes sometime, floor does others :s this.dimensions.scaledCharWidth = Math.floor((this._core as any)._charSizeService.width * this._devicePixelRatio); // Calculate the scaled character height. Height is ceiled in case // devicePixelRatio is a floating point number in order to ensure there is // enough space to draw the character to the cell. this.dimensions.scaledCharHeight = Math.ceil((this._core as any)._charSizeService.height * this._devicePixelRatio); // Calculate the scaled cell height, if lineHeight is not 1 then the value // will be floored because since lineHeight can never be lower then 1, there // is a guarentee that the scaled line height will always be larger than // scaled char height. this.dimensions.scaledCellHeight = Math.floor(this.dimensions.scaledCharHeight * this._terminal.getOption('lineHeight')); // Calculate the y coordinate within a cell that text should draw from in // order to draw in the center of a cell. this.dimensions.scaledCharTop = this._terminal.getOption('lineHeight') === 1 ? 0 : Math.round((this.dimensions.scaledCellHeight - this.dimensions.scaledCharHeight) / 2); // Calculate the scaled cell width, taking the letterSpacing into account. this.dimensions.scaledCellWidth = this.dimensions.scaledCharWidth + Math.round(this._terminal.getOption('letterSpacing')); // Calculate the x coordinate with a cell that text should draw from in // order to draw in the center of a cell. this.dimensions.scaledCharLeft = Math.floor(this._terminal.getOption('letterSpacing') / 2); // Recalculate the canvas dimensions; scaled* define the actual number of // pixel in the canvas this.dimensions.scaledCanvasHeight = this._terminal.rows * this.dimensions.scaledCellHeight; this.dimensions.scaledCanvasWidth = this._terminal.cols * this.dimensions.scaledCellWidth; // The the size of the canvas on the page. It's very important that this // rounds to nearest integer and not ceils as browsers often set // window.devicePixelRatio as something like 1.100000023841858, when it's // actually 1.1. Ceiling causes blurriness as the backing canvas image is 1 // pixel too large for the canvas element size. this.dimensions.canvasHeight = Math.round(this.dimensions.scaledCanvasHeight / this._devicePixelRatio); this.dimensions.canvasWidth = Math.round(this.dimensions.scaledCanvasWidth / this._devicePixelRatio); // this.dimensions.scaledCanvasHeight = this.dimensions.canvasHeight * devicePixelRatio; // this.dimensions.scaledCanvasWidth = this.dimensions.canvasWidth * devicePixelRatio; // Get the _actual_ dimensions of an individual cell. This needs to be // derived from the canvasWidth/Height calculated above which takes into // account window.devicePixelRatio. CharMeasure.width/height by itself is // insufficient when the page is not at 100% zoom level as CharMeasure is // measured in CSS pixels, but the actual char size on the canvas can // differ. // this.dimensions.actualCellHeight = this.dimensions.canvasHeight / this._terminal.rows; // this.dimensions.actualCellWidth = this.dimensions.canvasWidth / this._terminal.cols; // This fixes 110% and 125%, not 150% or 175% though this.dimensions.actualCellHeight = this.dimensions.scaledCellHeight / this._devicePixelRatio; this.dimensions.actualCellWidth = this.dimensions.scaledCellWidth / this._devicePixelRatio; } } // TODO: Share impl with core export class JoinedCellData extends AttributeData implements ICellData { private _width: number; // .content carries no meaning for joined CellData, simply nullify it // thus we have to overload all other .content accessors public content: number = 0; public fg: number; public bg: number; public combinedData: string = ''; constructor(firstCell: ICellData, chars: string, width: number) { super(); this.fg = firstCell.fg; this.bg = firstCell.bg; this.combinedData = chars; this._width = width; } public isCombined(): number { // always mark joined cell data as combined return Content.IS_COMBINED_MASK; } public getWidth(): number { return this._width; } public getChars(): string { return this.combinedData; } public getCode(): number { // code always gets the highest possible fake codepoint (read as -1) // this is needed as code is used by caches as identifier return 0x1FFFFF; } public setFromCharData(value: CharData): void { throw new Error('not implemented'); } public getAsCharData(): CharData { return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; } }
the_stack
import Easing from './Easing' import Interpolation from './Interpolation' import {mainGroup} from './mainGroup' import Sequence from './Sequence' import now from './Now' import type {EasingFunction} from './Easing' import type {InterpolationFunction} from './Interpolation' import type Group from './Group' export class Tween<T extends UnknownProps> { private _isPaused = false private _pauseStart = 0 private _valuesStart: UnknownProps = {} private _valuesEnd: Record<string, number | string> = {} private _valuesStartRepeat: UnknownProps = {} private _duration = 1000 private _initialRepeat = 0 private _repeat = 0 private _repeatDelayTime?: number private _yoyo = false private _isPlaying = false private _reversed = false private _delayTime = 0 private _startTime = 0 private _easingFunction: EasingFunction = Easing.Linear.None private _interpolationFunction: InterpolationFunction = Interpolation.Linear // eslint-disable-next-line private _chainedTweens: Array<Tween<any>> = [] private _onStartCallback?: (object: T) => void private _onStartCallbackFired = false private _onUpdateCallback?: (object: T, elapsed: number) => void private _onRepeatCallback?: (object: T) => void private _onCompleteCallback?: (object: T) => void private _onStopCallback?: (object: T) => void private _id = Sequence.nextId() private _isChainStopped = false constructor(private _object: T, private _group: Group | false = mainGroup) {} getId(): number { return this._id } isPlaying(): boolean { return this._isPlaying } isPaused(): boolean { return this._isPaused } to(properties: UnknownProps, duration?: number): this { // TODO? restore this, then update the 07_dynamic_to example to set fox // tween's to on each update. That way the behavior is opt-in (there's // currently no opt-out). // for (const prop in properties) this._valuesEnd[prop] = properties[prop] this._valuesEnd = Object.create(properties) if (duration !== undefined) { this._duration = duration } return this } duration(d = 1000): this { this._duration = d return this } start(time: number = now()): this { if (this._isPlaying) { return this } // eslint-disable-next-line this._group && this._group.add(this as any) this._repeat = this._initialRepeat if (this._reversed) { // If we were reversed (f.e. using the yoyo feature) then we need to // flip the tween direction back to forward. this._reversed = false for (const property in this._valuesStartRepeat) { this._swapEndStartRepeatValues(property) this._valuesStart[property] = this._valuesStartRepeat[property] } } this._isPlaying = true this._isPaused = false this._onStartCallbackFired = false this._isChainStopped = false this._startTime = time this._startTime += this._delayTime this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat) return this } private _setupProperties( _object: UnknownProps, _valuesStart: UnknownProps, _valuesEnd: UnknownProps, _valuesStartRepeat: UnknownProps, ): void { for (const property in _valuesEnd) { const startValue = _object[property] const startValueIsArray = Array.isArray(startValue) const propType = startValueIsArray ? 'array' : typeof startValue const isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]) // If `to()` specifies a property that doesn't exist in the source object, // we should not set that property in the object if (propType === 'undefined' || propType === 'function') { continue } // Check if an Array was provided as property value if (isInterpolationList) { let endValues = _valuesEnd[property] as Array<number | string> if (endValues.length === 0) { continue } // handle an array of relative values endValues = endValues.map(this._handleRelativeValue.bind(this, startValue as number)) // Create a local copy of the Array with the start value at the front _valuesEnd[property] = [startValue].concat(endValues) } // handle the deepness of the values if ((propType === 'object' || startValueIsArray) && startValue && !isInterpolationList) { _valuesStart[property] = startValueIsArray ? [] : {} // eslint-disable-next-line for (const prop in startValue as object) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStart[property][prop] = startValue[prop] } _valuesStartRepeat[property] = startValueIsArray ? [] : {} // TODO? repeat nested values? And yoyo? And array values? // eslint-disable-next-line // @ts-ignore FIXME? this._setupProperties(startValue, _valuesStart[property], _valuesEnd[property], _valuesStartRepeat[property]) } else { // Save the starting value, but only once. if (typeof _valuesStart[property] === 'undefined') { _valuesStart[property] = startValue } if (!startValueIsArray) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStart[property] *= 1.0 // Ensures we're using numbers, not strings } if (isInterpolationList) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStartRepeat[property] = _valuesEnd[property].slice().reverse() } else { _valuesStartRepeat[property] = _valuesStart[property] || 0 } } } } stop(): this { if (!this._isChainStopped) { this._isChainStopped = true this.stopChainedTweens() } if (!this._isPlaying) { return this } // eslint-disable-next-line this._group && this._group.remove(this as any) this._isPlaying = false this._isPaused = false if (this._onStopCallback) { this._onStopCallback(this._object) } return this } end(): this { this._goToEnd = true this.update(Infinity) return this } pause(time: number = now()): this { if (this._isPaused || !this._isPlaying) { return this } this._isPaused = true this._pauseStart = time // eslint-disable-next-line this._group && this._group.remove(this as any) return this } resume(time: number = now()): this { if (!this._isPaused || !this._isPlaying) { return this } this._isPaused = false this._startTime += time - this._pauseStart this._pauseStart = 0 // eslint-disable-next-line this._group && this._group.add(this as any) return this } stopChainedTweens(): this { for (let i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { this._chainedTweens[i].stop() } return this } group(group = mainGroup): this { this._group = group return this } delay(amount = 0): this { this._delayTime = amount return this } repeat(times = 0): this { this._initialRepeat = times this._repeat = times return this } repeatDelay(amount?: number): this { this._repeatDelayTime = amount return this } yoyo(yoyo = false): this { this._yoyo = yoyo return this } easing(easingFunction: EasingFunction = Easing.Linear.None): this { this._easingFunction = easingFunction return this } interpolation(interpolationFunction: InterpolationFunction = Interpolation.Linear): this { this._interpolationFunction = interpolationFunction return this } // eslint-disable-next-line chain(...tweens: Array<Tween<any>>): this { this._chainedTweens = tweens return this } onStart(callback?: (object: T) => void): this { this._onStartCallback = callback return this } onUpdate(callback?: (object: T, elapsed: number) => void): this { this._onUpdateCallback = callback return this } onRepeat(callback?: (object: T) => void): this { this._onRepeatCallback = callback return this } onComplete(callback?: (object: T) => void): this { this._onCompleteCallback = callback return this } onStop(callback?: (object: T) => void): this { this._onStopCallback = callback return this } private _goToEnd = false /** * @returns true if the tween is still playing after the update, false * otherwise (calling update on a paused tween still returns true because * it is still playing, just paused). */ update(time = now(), autoStart = true): boolean { if (this._isPaused) return true let property let elapsed const endTime = this._startTime + this._duration if (!this._goToEnd && !this._isPlaying) { if (time > endTime) return false if (autoStart) this.start(time) } this._goToEnd = false if (time < this._startTime) { return true } if (this._onStartCallbackFired === false) { if (this._onStartCallback) { this._onStartCallback(this._object) } this._onStartCallbackFired = true } elapsed = (time - this._startTime) / this._duration elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed const value = this._easingFunction(elapsed) // properties transformations this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value) if (this._onUpdateCallback) { this._onUpdateCallback(this._object, elapsed) } if (elapsed === 1) { if (this._repeat > 0) { if (isFinite(this._repeat)) { this._repeat-- } // Reassign starting values, restart by making startTime = now for (property in this._valuesStartRepeat) { if (!this._yoyo && typeof this._valuesEnd[property] === 'string') { this._valuesStartRepeat[property] = // eslint-disable-next-line // @ts-ignore FIXME? this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]) } if (this._yoyo) { this._swapEndStartRepeatValues(property) } this._valuesStart[property] = this._valuesStartRepeat[property] } if (this._yoyo) { this._reversed = !this._reversed } if (this._repeatDelayTime !== undefined) { this._startTime = time + this._repeatDelayTime } else { this._startTime = time + this._delayTime } if (this._onRepeatCallback) { this._onRepeatCallback(this._object) } return true } else { if (this._onCompleteCallback) { this._onCompleteCallback(this._object) } for (let i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { // Make the chained tweens start exactly at the time they should, // even if the `update()` method was called way past the duration of the tween this._chainedTweens[i].start(this._startTime + this._duration) } this._isPlaying = false return false } } return true } private _updateProperties( _object: UnknownProps, _valuesStart: UnknownProps, _valuesEnd: UnknownProps, value: number, ): void { for (const property in _valuesEnd) { // Don't update properties that do not exist in the source object if (_valuesStart[property] === undefined) { continue } const start = _valuesStart[property] || 0 let end = _valuesEnd[property] const startIsArray = Array.isArray(_object[property]) const endIsArray = Array.isArray(end) const isInterpolationList = !startIsArray && endIsArray if (isInterpolationList) { _object[property] = this._interpolationFunction(end as Array<number>, value) } else if (typeof end === 'object' && end) { // eslint-disable-next-line // @ts-ignore FIXME? this._updateProperties(_object[property], start, end, value) } else { // Parses relative end values with start as base (e.g.: +10, -3) end = this._handleRelativeValue(start as number, end as number | string) // Protect against non numeric properties. if (typeof end === 'number') { // eslint-disable-next-line // @ts-ignore FIXME? _object[property] = start + (end - start) * value } } } } private _handleRelativeValue(start: number, end: number | string): number { if (typeof end !== 'string') { return end } if (end.charAt(0) === '+' || end.charAt(0) === '-') { return start + parseFloat(end) } else { return parseFloat(end) } } private _swapEndStartRepeatValues(property: string): void { const tmp = this._valuesStartRepeat[property] const endValue = this._valuesEnd[property] if (typeof endValue === 'string') { this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(endValue) } else { this._valuesStartRepeat[property] = this._valuesEnd[property] } this._valuesEnd[property] = tmp } } // eslint-disable-next-line export type UnknownProps = Record<string, any> export default Tween
the_stack
import { AxiosResponse } from 'axios'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import * as url from 'url'; import { v4 } from 'uuid'; import auth, { Auth } from '../../../../Auth'; import { Logger } from '../../../../cli'; import { CommandError, CommandOption } from '../../../../Command'; import GlobalOptions from '../../../../GlobalOptions'; import request from '../../../../request'; import GraphCommand from '../../../base/GraphCommand'; import commands from '../../commands'; interface CommandArgs { options: Options; } interface Options extends GlobalOptions { sourceFile: string; targetFile: string; } class FileConvertPdfCommand extends GraphCommand { // Graph's drive item URL of the source file private sourceFileGraphUrl?: string; public get name(): string { return commands.CONVERT_PDF; } public get description(): string { return 'Converts the specified file to PDF using Microsoft Graph'; } public commandAction(logger: Logger, args: CommandArgs, cb: (error?: any) => void): void { let sourceFileUrl: string = ''; // path to the local file that contains the PDF-converted source file let localTargetFilePath: string = args.options.targetFile; let sourceIsLocalFile: boolean = true; let targetIsLocalFile: boolean = true; let error: any; const isAppOnlyAuth: boolean | undefined = Auth.isAppOnlyAuth(auth.service.accessTokens[auth.defaultResource].accessToken); if (typeof isAppOnlyAuth === 'undefined') { return cb(new CommandError('Unable to determine authentication type')); } if (args.options.sourceFile.toLowerCase().startsWith('https://')) { sourceIsLocalFile = false; } if (args.options.targetFile.toLowerCase().startsWith('https://')) { localTargetFilePath = path.join(os.tmpdir(), v4()); targetIsLocalFile = false; if (this.debug) { logger.logToStderr(`Target set to a URL. Will store the temporary converted file at ${localTargetFilePath}`); } } this .getSourceFileUrl(logger, args, isAppOnlyAuth) .then((_sourceFileUrl: string): Promise<string> => { sourceFileUrl = _sourceFileUrl; return this.getGraphFileUrl(logger, sourceFileUrl, this.sourceFileGraphUrl); }) .then((graphFileUrl: string): Promise<any> => this.convertFile(logger, graphFileUrl)) .then(fileResponse => this.writeFileToDisk(logger, fileResponse, localTargetFilePath)) .then(_ => this.uploadConvertedFileIfNecessary(logger, targetIsLocalFile, localTargetFilePath, args.options.targetFile)) .then(_ => this.deleteRemoteSourceFileIfNecessary(logger, sourceIsLocalFile, sourceFileUrl), // catch the error from any of the previous promises so that we can // clean up resources in case something went wrong // if this.deleteRemoteSourceFileIfNecessary fails, it won't be caught // here, but rather at the end err => error = err ) .then(_ => { // if the target was a remote file, delete the local temp file if (!targetIsLocalFile) { if (this.verbose) { logger.logToStderr(`Deleting the temporary PDF file at ${localTargetFilePath}...`); } try { fs.unlinkSync(localTargetFilePath); } catch (e) { return cb(e); } } else { if (this.debug) { logger.logToStderr(`Target is a local path. Not deleting`); } } if (error) { this.handleRejectedODataJsonPromise(error, logger, cb); } else { cb(); } }, (rawRes: any): void => this.handleRejectedODataJsonPromise(rawRes, logger, cb)); } /** * Returns web URL of the file to convert to PDF. If the user specified a URL * in command's options, returns the specified URL. If the user specified * a local file, it will upload the file and return its web URL. If CLI * is authenticated as app-only, uploads the file to the default document * library in the root site. If the CLI is authenticated as user, uploads the * file to the user's OneDrive for Business * @param logger Logger instance * @param args Command args * @param isAppOnlyAuth True if CLI is authenticated in app-only mode * @returns Web URL of the file to upload */ private getSourceFileUrl(logger: Logger, args: CommandArgs, isAppOnlyAuth: boolean): Promise<string> { if (args.options.sourceFile.toLowerCase().startsWith('https://')) { return Promise.resolve(args.options.sourceFile); } if (this.verbose) { logger.logToStderr('Uploading local file temporarily for conversion...'); } const driveUrl: string = `${this.resource}/v1.0/${isAppOnlyAuth ? 'drive/root' : 'me/drive/root'}`; // we need the original file extension because otherwise Graph won't be able // to convert the file to PDF this.sourceFileGraphUrl = `${driveUrl}:/${v4()}${path.extname(args.options.sourceFile)}`; if (this.debug) { logger.logToStderr(`Source is a local file. Uploading to ${this.sourceFileGraphUrl}...`); } return this.uploadFile(args.options.sourceFile, this.sourceFileGraphUrl); } /** * Uploads the specified local file to a document library using Microsoft Graph * @param localFilePath Path to the local file to upload * @param targetGraphFileUrl Graph drive item URL of the file to upload * @returns Absolute URL of the uploaded file */ private uploadFile(localFilePath: string, targetGraphFileUrl: string): Promise<string> { const requestOptions: any = { url: `${targetGraphFileUrl}:/createUploadSession`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; return request .post<{ uploadUrl: string; expirationDateTime: string }>(requestOptions) .then((res: { uploadUrl: string; expirationDateTime: string }): Promise<{ webUrl: string }> => { const fileContents = fs.readFileSync(localFilePath); const requestOptions: any = { url: res.uploadUrl, headers: { 'x-anonymous': true, 'accept': 'application/json;odata.metadata=none', 'Content-Length': fileContents.length, 'Content-Range': `bytes 0-${fileContents.length - 1}/${fileContents.length}` }, data: fileContents, responseType: 'json' }; return request.put<{ webUrl: string }>(requestOptions); }) .then((res: { webUrl: string }) => res.webUrl); } /** * Gets Graph's drive item URL for the specified file. If the user specified * a local file to convert to PDF, returns the URL resolved while uploading * the file * * Example: * * fileWebUrl: * https://contoso.sharepoint.com/sites/Contoso/site/Shared%20Documents/file.docx * * returns: * https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com,9d1b2174-9906-43ec-8c9e-f8589de047af,f60c833e-71ce-4a5a-b90e-2a7fdb718397/drives/b!k6NJ6ubjYEehsullOeFTcuYME3w1S8xHoHziURdWlu-DWrqz1yBLQI7E7_4TN6fL/root:/file.docx * * @param logger Logger instance * @param fileWebUrl Web URL of the file for which to get drive item URL * @param fileGraphUrl If set, will return this URL without further action * @returns Graph's drive item URL for the specified file */ private getGraphFileUrl(logger: Logger, fileWebUrl: string, fileGraphUrl: string | undefined): Promise<string> { if (this.debug) { logger.logToStderr(`Resolving Graph drive item URL for ${fileWebUrl}`); } if (fileGraphUrl) { if (this.debug) { logger.logToStderr(`Returning previously resolved Graph drive item URL ${fileGraphUrl}`); } return Promise.resolve(fileGraphUrl); } const _url = url.parse(fileWebUrl); let siteId: string = ''; let driveRelativeFileUrl: string = ''; return this .getGraphSiteInfoFromFullUrl(_url.host as string, _url.path as string) .then(siteInfo => { siteId = siteInfo.id; let siteRelativeFileUrl: string = (_url.path as string).replace(siteInfo.serverRelativeUrl, ''); // normalize site-relative URLs for root site collections and root sites if (!siteRelativeFileUrl.startsWith('/')) { siteRelativeFileUrl = '/' + siteRelativeFileUrl; } const siteRelativeFileUrlChunks: string[] = siteRelativeFileUrl.split('/'); driveRelativeFileUrl = `/${siteRelativeFileUrlChunks.slice(2).join('/')}`; // chunk 0 is empty because the URL starts with / return this.getDriveId(logger, siteId, siteRelativeFileUrlChunks[1]); }) .then(driveId => { const graphUrl: string = `${this.resource}/v1.0/sites/${siteId}/drives/${driveId}/root:${driveRelativeFileUrl}`; if (this.debug) { logger.logToStderr(`Resolved URL ${graphUrl}`); } return graphUrl; }); } /** * Retrieves the Graph ID and server-relative URL of the specified (sub)site. * Automatically detects which path chunks correspond to (sub)site. * @param hostName SharePoint host name, eg. contoso.sharepoint.com * @param urlPath Server-relative file URL, eg. /sites/site/docs/file1.aspx * @returns ID and server-relative URL of the site denoted by urlPath */ private getGraphSiteInfoFromFullUrl(hostName: string, urlPath: string): Promise<{ id: string, serverRelativeUrl: string }> { const siteId: string = ''; const urlChunks: string[] = urlPath.split('/'); return new Promise((resolve: (siteInfo: { id: string; serverRelativeUrl: string }) => void, reject: (err: any) => void): void => { this.getGraphSiteInfo(hostName, urlChunks, 0, siteId, resolve, reject); }); } /** * Retrieves Graph site ID and server-relative URL of the site specified * using chunks from the URL path. Method is being called recursively as long * as it can successfully retrieve the site. When retrieving site fails, method * will return the last resolved site ID. If no site ID has been retrieved * (method fails on the first execution), it will call the reject callback. * @param hostName SharePoint host name, eg. contoso.sharepoint.com * @param urlChunks Array of chunks from server-relative URL, eg. ['sites', 'site', 'subsite', 'docs', 'file1.aspx'] * @param currentChunk Current chunk that's being tested, eg. sites * @param lastSiteId Last correctly resolved Graph site ID * @param resolve Callback method to call when resolving site info succeeded * @param reject Callback method to call when resolving site info failed * @returns Graph site ID and server-relative URL of the site specified through chunks */ private getGraphSiteInfo(hostName: string, urlChunks: string[], currentChunk: number, lastSiteId: string, resolve: (siteInfo: { id: string; serverRelativeUrl: string }) => void, reject: (err: any) => void): void { let currentPath: string = urlChunks.slice(0, currentChunk + 1).join('/'); if (currentPath.endsWith('/sites') || currentPath.endsWith('/teams') || currentPath.endsWith('/personal')) { return this.getGraphSiteInfo(hostName, urlChunks, ++currentChunk, '', resolve, reject); } if (!currentPath.startsWith('/')) { currentPath = '/' + currentPath; } const requestOptions: any = { url: `${this.resource}/v1.0/sites/${hostName}:${currentPath}?$select=id`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; request .get<{ id: string }>(requestOptions) .then((res: { id: string }) => { this.getGraphSiteInfo(hostName, urlChunks, ++currentChunk, res.id, resolve, reject); }, err => { if (lastSiteId) { let serverRelativeUrl: string = `${urlChunks.slice(0, currentChunk).join('/')}`; if (!serverRelativeUrl.startsWith('/')) { serverRelativeUrl = '/' + serverRelativeUrl; } resolve({ id: lastSiteId, serverRelativeUrl: serverRelativeUrl }); } else { reject(err); } }); } /** * Returns the Graph drive ID of the specified document library * @param graphSiteId Graph ID of the site where the document library is located * @param siteRelativeListUrl Server-relative URL of the document library, eg. /sites/site/Documents * @returns Graph drive ID of the specified document library */ private getDriveId(logger: Logger, graphSiteId: string, siteRelativeListUrl: string): Promise<string> { const requestOptions: any = { url: `${this.resource}/v1.0/sites/${graphSiteId}/drives?$select=webUrl,id`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'json' }; return request .get<{ value: { id: string; webUrl: string }[] }>(requestOptions) .then((res: { value: { id: string; webUrl: string }[] }) => { if (this.debug) { logger.logToStderr(`Searching for drive with a URL ending with /${siteRelativeListUrl}...`); } const drive = res.value.find(d => d.webUrl.endsWith(`/${siteRelativeListUrl}`)); if (!drive) { return Promise.reject('Drive not found'); } return Promise.resolve(drive.id); }); } /** * Requests conversion of a file to PDF using Microsoft Graph * @param logger Logger instance * @param graphFileUrl Graph drive item URL of the file to convert to PDF * @returns Response object with a URL in the Location header that contains * the file converted to PDF. The URL must be called anonymously */ private convertFile(logger: Logger, graphFileUrl: string): Promise<any> { if (this.verbose) { logger.logToStderr('Converting file...'); } const requestOptions: any = { url: `${graphFileUrl}:/content?format=pdf`, headers: { accept: 'application/json;odata.metadata=none' }, responseType: 'stream' }; return request.get(requestOptions); } /** * Writes the contents of the specified file stream to a local file * @param logger Logger instance * @param fileResponse Response with stream file contents * @param localFilePath Local file path where to store the file */ private writeFileToDisk(logger: Logger, fileResponse: AxiosResponse<any>, localFilePath: string): Promise<void> { if (this.verbose) { logger.logToStderr(`Writing converted PDF file to ${localFilePath}...`); } return new Promise((resolve, reject) => { // write the downloaded file to disk const writer = fs.createWriteStream(localFilePath); fileResponse.data.pipe(writer); writer.on('error', err => { reject(err); }); writer.on('close', () => { resolve(); }); }); } /** * If the user specified a URL as the targetFile, uploads the converted PDF * file to the specified location. If targetFile is a local path, doesn't do * anything. * @param logger Logger instance * @param targetIsLocalFile Boolean that denotes if user specified as the target location a local path * @param localFilePath Local file path to where the file to be uploaded is located * @param targetFileUrl Web URL of the file to upload */ private uploadConvertedFileIfNecessary(logger: Logger, targetIsLocalFile: boolean, localFilePath: string, targetFileUrl: string): Promise<void> { // if the target was a local path, we're done. // Otherwise, upload the file to the specified URL if (targetIsLocalFile) { if (this.debug) { logger.logToStderr('Specified target is a local file. Not uploading.'); } return Promise.resolve(); } if (this.verbose) { logger.logToStderr(`Uploading converted PDF file to ${targetFileUrl}...`); } return this .getGraphFileUrl(logger, targetFileUrl, undefined) .then(targetGraphFileUrl => this.uploadFile(localFilePath, targetGraphFileUrl)) .then(_ => Promise.resolve()); } /** * If the user specified local file to be converted to PDF, removes the file * that was temporarily upload to a document library for the conversion. * If the specified source file was a URL, doesn't do anything. * @param logger Logger instance * @param sourceIsLocalFile Boolean that denotes if user specified a local path as the source file * @param sourceFileUrl Web URL of the temporary source file to delete */ private deleteRemoteSourceFileIfNecessary(logger: Logger, sourceIsLocalFile: boolean, sourceFileUrl: string): Promise<void> { // if the source was a remote file, we're done, // otherwise delete the temporary uploaded file if (!sourceIsLocalFile) { if (this.debug) { logger.logToStderr('Source file was URL. Not removing.'); } return Promise.resolve(); } if (this.verbose) { logger.logToStderr(`Deleting the temporary file at ${sourceFileUrl}...`); } return this .getGraphFileUrl(logger, sourceFileUrl, this.sourceFileGraphUrl) .then((graphFileUrl: string): Promise<void> => { const requestOptions: any = { url: graphFileUrl, headers: { accept: 'application/json;odata.metadata=none' } }; return request.delete(requestOptions); }); } public options(): CommandOption[] { const options: CommandOption[] = [ { option: '-s, --sourceFile <sourceFile>' }, { option: '-t, --targetFile <targetFile>' } ]; const parentOptions: CommandOption[] = super.options(); return options.concat(parentOptions); } public validate(args: CommandArgs): boolean | string { if (!args.options.sourceFile.toLowerCase().startsWith('https://') && !fs.existsSync(args.options.sourceFile)) { // assume local path return `Specified source file ${args.options.sourceFile} doesn't exist`; } if (!args.options.targetFile.toLowerCase().startsWith('https://') && fs.existsSync(args.options.targetFile)) { // assume local path return `Another file found at ${args.options.targetFile}`; } return true; } } module.exports = new FileConvertPdfCommand();
the_stack
import * as d3Hierarchy from 'd3-hierarchy'; // ----------------------------------------------------------------------- // Preparatory Steps // ----------------------------------------------------------------------- let str: string; let num: number; let numOrUndefined: number | undefined; let size: [number, number]; let sizeOrNull: [number, number] | null; let idString: string | undefined; // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- interface HierarchyDatum { name: string; val: number; children?: Iterable<HierarchyDatum> | undefined; } let hierarchyRootDatum: HierarchyDatum = { name: 'n0', val: 10, children: [ { name: 'n11', val: 5 }, { name: 'n12', val: 4, children: [ { name: 'n121', val: 30 } ] } ] }; let hierarchyNodeArray: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = []; let hierarchyNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> | undefined; let hierarchyNode: d3Hierarchy.HierarchyNode<HierarchyDatum>; let hierarchyNodeOrUndefined: d3Hierarchy.HierarchyNode<HierarchyDatum> | undefined; let hierarchyPointNodeArray: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = []; let hierarchyPointNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> | undefined; let hierarchyPointNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>; let hierarchyRectangularNodeArray: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = []; let hierarchyRectangularNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> | undefined; let hierarchyRectangularNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>; let hierarchyCircularNodeArray: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = []; let hierarchyCircularNodeArrayOrUndefined: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> | undefined; let hierarchyCircularNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>; // Create Hierarchy Layout Root Node ===================================== let hierarchyRootNode: d3Hierarchy.HierarchyNode<HierarchyDatum>; hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum); hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum, (d) => { return d.children; }); hierarchyRootNode = d3Hierarchy.hierarchy(hierarchyRootDatum, (d) => { return d.children || null; }); // Use Hierarchy Node ==================================================== // data, depth, height --------------------------------------------------- hierarchyRootDatum = hierarchyRootNode.data; num = hierarchyRootNode.depth; num = hierarchyRootNode.height; // children, parent ------------------------------------------------------ hierarchyNodeArrayOrUndefined = hierarchyRootNode.children; let parentNode: d3Hierarchy.HierarchyNode<HierarchyDatum> | null; parentNode = hierarchyNodeArray.length ? hierarchyNodeArray[0].parent : null; parentNode = hierarchyNodeArray[0].parent; // id -------------------------------------------------------------------- idString = hierarchyRootNode.id; // ancestors(), descendants() -------------------------------------------- const ancestors: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.ancestors(); const descendants: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.descendants(); // leaves() -------------------------------------------------------------- hierarchyNodeArray = hierarchyRootNode.leaves(); // find() -------------------------------------------------------------- hierarchyNodeOrUndefined = hierarchyRootNode.find(node => !!node.value && node.value > 0); // path() ---------------------------------------------------------------- hierarchyNode = descendants[descendants.length - 1]; const path: Array<d3Hierarchy.HierarchyNode<HierarchyDatum>> = hierarchyRootNode.path(hierarchyNode); // links() and HierarchyLink<...> ---------------------------------------- let links: Array<d3Hierarchy.HierarchyLink<HierarchyDatum>>; links = hierarchyRootNode.links(); let link: d3Hierarchy.HierarchyLink<HierarchyDatum>; link = links[0]; hierarchyNode = link.source; hierarchyNode = link.target; // sum() and value ------------------------------------------------------- hierarchyRootNode = hierarchyRootNode.sum((d) => d.val); numOrUndefined = hierarchyRootNode.value; // count() and value ----------------------------------------------------- hierarchyRootNode = hierarchyRootNode.count(); numOrUndefined = hierarchyRootNode.value; // sort ------------------------------------------------------------------ hierarchyRootNode = hierarchyRootNode.sort((a, b) => { console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyNode<HierarchyDatum> return b.height - a.height || b.value! - a.value!; }); // each(), eachAfter(), eachBefore() ------------------------------------- hierarchyRootNode = hierarchyRootNode.each((node) => { console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }); hierarchyRootNode = hierarchyRootNode.each(function(node, index, thisNode) { const testProperty: number = this.testThisProperty; console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }, { testThisProperty: 5 }); hierarchyRootNode = hierarchyRootNode.eachAfter((node) => { console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }); hierarchyRootNode = hierarchyRootNode.eachAfter(function(node, index, thisNode) { const testProperty: number = this.testThisProperty; console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }, { testThisProperty: 5 }); hierarchyRootNode = hierarchyRootNode.eachBefore((node) => { console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }); hierarchyRootNode = hierarchyRootNode.eachBefore(function(node, index, thisNode) { const testProperty: number = this.testThisProperty; console.log('Raw value of node:', node.data.val); // node type is HierarchyNode<HierarchyDatum> console.log('Aggregated value of node:', node.value); // node type is HierarchyNode<HierarchyDatum> }, { testThisProperty: 5 }); // copy() ---------------------------------------------------------------- let copiedHierarchyNode: d3Hierarchy.HierarchyNode<HierarchyDatum>; copiedHierarchyNode = hierarchyRootNode.copy(); // ----------------------------------------------------------------------- // Stratify // ----------------------------------------------------------------------- interface HierarchyDatumWithParentId extends HierarchyDatum { parentId: string | null; } interface TabularHierarchyDatum { name: string; parentId: string | null; val: number; } let tabularData: TabularHierarchyDatum[]; tabularData = [ { name: 'n0', parentId: null, val: 10 }, { name: 'n11', parentId: 'n0', val: 5 }, { name: 'n12', parentId: 'n0', val: 4 }, { name: 'n121', parentId: 'n12', val: 30 } ]; let idStringAccessor: (d: TabularHierarchyDatum, i: number, data: TabularHierarchyDatum[]) => (string | null | '' | undefined); // Create Stratify Operator --------------------------------------------- let stratificatorizer: d3Hierarchy.StratifyOperator<TabularHierarchyDatum>; stratificatorizer = d3Hierarchy.stratify<TabularHierarchyDatum>(); // Configure Stratify Operator ------------------------------------------ // id(...) stratificatorizer = stratificatorizer.id((d) => { return d.name; // d is of type TabularHierarchyDatum }); stratificatorizer = stratificatorizer.id((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array<TabularHierarchyDatum> return d.name; // d is of type TabularHierarchyDatum }); idStringAccessor = stratificatorizer.id(); // parentId(...) stratificatorizer = stratificatorizer.parentId((d) => { return d.parentId; // d is of type TabularHierarchyDatum }); stratificatorizer = stratificatorizer.parentId((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array<TabularHierarchyDatum> return d.parentId; // d is of type TabularHierarchyDatum }); idStringAccessor = stratificatorizer.parentId(); // Use Stratify Operator ------------------------------------------------ const stratifiedRootNode: d3Hierarchy.HierarchyNode<TabularHierarchyDatum> = stratificatorizer(tabularData); const pId: string | null = stratifiedRootNode.data.parentId; // ----------------------------------------------------------------------- // Cluster // ----------------------------------------------------------------------- // Create cluster layout generator ======================================= let clusterLayout: d3Hierarchy.ClusterLayout<HierarchyDatumWithParentId>; clusterLayout = d3Hierarchy.cluster<HierarchyDatumWithParentId>(); // Configure cluster layout generator ==================================== // size() ---------------------------------------------------------------- clusterLayout = clusterLayout.size([200, 200]); sizeOrNull = clusterLayout.size(); // nodeSize() ------------------------------------------------------------ clusterLayout = clusterLayout.nodeSize([10, 10]); sizeOrNull = clusterLayout.nodeSize(); // separation() ---------------------------------------------------------- clusterLayout = clusterLayout.separation(function separation(a, b) { return a.data.parentId === b.data.parentId ? 1 : 2; // a and b are nodes of type HierarchyPointNode<HierarchyDatumWithParentId> }); let separationAccessor: (a: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>, b: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>) => number; separationAccessor = clusterLayout.separation(); // Use cluster layout generator ========================================== let clusterRootNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>; clusterRootNode = clusterLayout(stratifiedRootNode); // Use HierarchyPointNode ================================================ // x and y coordinates --------------------------------------------------- num = clusterRootNode.x; num = clusterRootNode.y; // data, depth, height --------------------------------------------------- const clusterDatum: HierarchyDatumWithParentId = clusterRootNode.data; num = clusterRootNode.depth; num = clusterRootNode.height; // children, parent ------------------------------------------------------ hierarchyPointNodeArrayOrUndefined = clusterRootNode.children; let parentPointNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId> | null; parentPointNode = hierarchyPointNodeArray.length ? hierarchyPointNodeArray[0].parent : null; parentPointNode = hierarchyPointNodeArray[0].parent; // id -------------------------------------------------------------------- idString = clusterRootNode.id; // ancestors(), descendants() -------------------------------------------- const pointNodeAncestors: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.ancestors(); const pointNodeDescendants: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.descendants(); // leaves() -------------------------------------------------------------- hierarchyPointNodeArray = clusterRootNode.leaves(); // path() ---------------------------------------------------------------- hierarchyPointNode = pointNodeDescendants[pointNodeDescendants.length - 1]; const clusterPath: Array<d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>> = clusterRootNode.path(hierarchyPointNode); // links() and HierarchyPointLink<...> ----------------------------------- let pointLinks: Array<d3Hierarchy.HierarchyPointLink<HierarchyDatumWithParentId>>; pointLinks = clusterRootNode.links(); let pointLink: d3Hierarchy.HierarchyPointLink<HierarchyDatumWithParentId>; pointLink = pointLinks[0]; hierarchyPointNode = pointLink.source; hierarchyPointNode = pointLink.target; // sum() and value ------------------------------------------------------- clusterRootNode = clusterRootNode.sum((d) => d.val); numOrUndefined = clusterRootNode.value; // count() and value ----------------------------------------------------- clusterRootNode = clusterRootNode.count(); numOrUndefined = clusterRootNode.value; // sort ------------------------------------------------------------------ clusterRootNode = clusterRootNode.sort((a, b) => { console.log('x-coordinates of a:', a.x, ' and b:', b.x); // a and b are of type HierarchyPointNode<HierarchyDatumWithParentId> console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyPointNode<HierarchyDatumWithParentId> return b.height - a.height || b.value! - a.value!; }); // each(), eachAfter(), eachBefore() ------------------------------------- clusterRootNode = clusterRootNode.each((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyPointNode<HierarchyDatumWithParentId> console.log('X-coordinate of node:', node.x); // node type is HierarchyPointNode<HierarchyDatumWithParentId> }); clusterRootNode = clusterRootNode.eachAfter((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyPointNode<HierarchyDatumWithParentId> console.log('X-coordinate of node:', node.x); // node type is HierarchyPointNode<HierarchyDatumWithParentId> }); clusterRootNode = clusterRootNode.eachBefore((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyPointNode<HierarchyDatumWithParentId> console.log('X-coordinate of node:', node.x); // node type is HierarchyPointNode<HierarchyDatumWithParentId> }); // copy() ---------------------------------------------------------------- let copiedClusterNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>; copiedClusterNode = clusterRootNode.copy(); // ----------------------------------------------------------------------- // Tree // ----------------------------------------------------------------------- // Create tree layout generator ========================================== let treeLayout: d3Hierarchy.TreeLayout<HierarchyDatumWithParentId>; treeLayout = d3Hierarchy.tree<HierarchyDatumWithParentId>(); // Configure tree layout generator ======================================= // size() ---------------------------------------------------------------- treeLayout = treeLayout.size([200, 200]); sizeOrNull = treeLayout.size(); // nodeSize() ------------------------------------------------------------ treeLayout = treeLayout.nodeSize([10, 10]); sizeOrNull = treeLayout.nodeSize(); // separation() ---------------------------------------------------------- treeLayout = treeLayout.separation(function separation(a, b) { return a.data.parentId === b.data.parentId ? 1 : 2; // a and b are nodes of type HierarchyPointNode<HierarchyDatumWithParentId> }); separationAccessor = treeLayout.separation(); // Use cluster layout generator ========================================== let treeRootNode: d3Hierarchy.HierarchyPointNode<HierarchyDatumWithParentId>; treeRootNode = treeLayout(stratifiedRootNode); // ----------------------------------------------------------------------- // Treemap // ----------------------------------------------------------------------- let numberRectangularNodeAccessor: (node: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>) => number; // Create treemap layout generator ======================================= let treemapLayout: d3Hierarchy.TreemapLayout<HierarchyDatumWithParentId>; treemapLayout = d3Hierarchy.treemap<HierarchyDatumWithParentId>(); // Configure treemap layout generator ==================================== // tile() ---------------------------------------------------------------- treemapLayout = treemapLayout.tile((node, x0, y0, x1, y1) => { console.log('x0 coordinate of node: ', node.x0); console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> num = x0; // number num = y0; // number num = x1; // number num = y1; // number // tile away }); treemapLayout = treemapLayout.tile(d3Hierarchy.treemapDice); let tilingFn: (node: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>, x0: number, y0: number, x1: number, y1: number) => void; tilingFn = treemapLayout.tile(); // size() ---------------------------------------------------------------- treemapLayout = treemapLayout.size([400, 200]); size = treemapLayout.size(); // round() --------------------------------------------------------------- treemapLayout = treemapLayout.round(true); let roundFlag: boolean = treemapLayout.round(); // padding() ------------------------------------------------------------- treemapLayout = treemapLayout.padding(1); treemapLayout = treemapLayout.padding((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.padding(); // paddingInner() -------------------------------------------------------- treemapLayout = treemapLayout.paddingInner(1); treemapLayout = treemapLayout.paddingInner((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingInner(); // paddingOuter() -------------------------------------------------------- treemapLayout = treemapLayout.paddingOuter(1); treemapLayout = treemapLayout.paddingOuter((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingOuter(); // paddingTop() ---------------------------------------------------------- treemapLayout = treemapLayout.paddingTop(1); treemapLayout = treemapLayout.paddingTop((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingTop(); // paddingRight() -------------------------------------------------------- treemapLayout = treemapLayout.paddingRight(1); treemapLayout = treemapLayout.paddingRight((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingRight(); // paddingBottom() ------------------------------------------------------- treemapLayout = treemapLayout.paddingBottom(1); treemapLayout = treemapLayout.paddingBottom((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingBottom(); // paddingLeft() --------------------------------------------------------- treemapLayout = treemapLayout.paddingLeft(1); treemapLayout = treemapLayout.paddingLeft((node) => { console.log('Node parent id: ', node.data.parentId); // type of node is HierarchyRectangularNode<HierarchyDatumWithParentId> return node.x0 > 10 ? 2 : 1; }); numberRectangularNodeAccessor = treemapLayout.paddingLeft(); // Use treemap layout generator ========================================== let treemapRootNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>; treemapRootNode = treemapLayout(stratifiedRootNode); // Tiling functions ====================================================== tilingFn = d3Hierarchy.treemapBinary; tilingFn = d3Hierarchy.treemapDice; tilingFn = d3Hierarchy.treemapSlice; tilingFn = d3Hierarchy.treemapSliceDice; // Tiling Factory functions treemapSquarify() and treemapResquarify() ==== let tilingFactoryFn: d3Hierarchy.RatioSquarifyTilingFactory; tilingFactoryFn = d3Hierarchy.treemapSquarify; tilingFactoryFn = d3Hierarchy.treemapSquarify.ratio(2); treemapLayout.tile(d3Hierarchy.treemapSquarify.ratio(2)); tilingFactoryFn = d3Hierarchy.treemapResquarify; tilingFactoryFn = d3Hierarchy.treemapResquarify.ratio(2); treemapLayout.tile(d3Hierarchy.treemapResquarify.ratio(2)); // Use HierarchyRectangularNode ========================================== // x and y coordinates --------------------------------------------------- num = treemapRootNode.x0; num = treemapRootNode.y0; num = treemapRootNode.x1; num = treemapRootNode.y1; // data, depth, height --------------------------------------------------- const treemapDatum: HierarchyDatumWithParentId = treemapRootNode.data; num = treemapRootNode.depth; num = treemapRootNode.height; // children, parent ------------------------------------------------------ hierarchyRectangularNodeArrayOrUndefined = treemapRootNode.children; let parentRectangularNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId> | null; parentRectangularNode = hierarchyRectangularNodeArray.length ? hierarchyRectangularNodeArray[0].parent : null; parentRectangularNode = hierarchyRectangularNodeArray[0].parent; // id -------------------------------------------------------------------- idString = treemapRootNode.id; // ancestors(), descendants() -------------------------------------------- const rectangularNodeAncestors: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.ancestors(); const rectangularNodeDescendants: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.descendants(); // leaves() -------------------------------------------------------------- hierarchyRectangularNodeArray = treemapRootNode.leaves(); // path() ---------------------------------------------------------------- hierarchyRectangularNode = rectangularNodeDescendants[rectangularNodeDescendants.length - 1]; const treemapPath: Array<d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>> = treemapRootNode.path(hierarchyRectangularNode); // links() and HierarchyRectangularLink<...> ----------------------------- let rectangularLinks: Array<d3Hierarchy.HierarchyRectangularLink<HierarchyDatumWithParentId>>; rectangularLinks = treemapRootNode.links(); let rectangularLink: d3Hierarchy.HierarchyRectangularLink<HierarchyDatumWithParentId>; rectangularLink = rectangularLinks[0]; hierarchyRectangularNode = rectangularLink.source; hierarchyRectangularNode = rectangularLink.target; // sum() and value ------------------------------------------------------- treemapRootNode = treemapRootNode.sum((d) => d.val); numOrUndefined = treemapRootNode.value; // count() and value ----------------------------------------------------- treemapRootNode = treemapRootNode.count(); numOrUndefined = treemapRootNode.value; // sort ------------------------------------------------------------------ treemapRootNode = treemapRootNode.sort((a, b) => { console.log('x0-coordinates of a:', a.x0, ' and b:', b.x0); // a and b are of type HierarchyRectangularNode<HierarchyDatumWithParentId> console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyRectangularNode<HierarchyDatumWithParentId> return b.height - a.height || b.value! - a.value!; }); // each(), eachAfter(), eachBefore() ------------------------------------- treemapRootNode = treemapRootNode.each((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> console.log('X0-coordinate of node:', node.x0); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> }); treemapRootNode = treemapRootNode.eachAfter((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> console.log('X0-coordinate of node:', node.x0); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> }); treemapRootNode = treemapRootNode.eachBefore((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> console.log('X0-coordinate of node:', node.x0); // node type is HierarchyRectangularNode<HierarchyDatumWithParentId> }); // copy() ---------------------------------------------------------------- let copiedTreemapNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>; copiedTreemapNode = treemapRootNode.copy(); // ----------------------------------------------------------------------- // Partition // ----------------------------------------------------------------------- // Create partition layout generator ===================================== let partitionLayout: d3Hierarchy.PartitionLayout<HierarchyDatumWithParentId>; partitionLayout = d3Hierarchy.partition<HierarchyDatumWithParentId>(); // Configure partition layout generator ================================== // size() ---------------------------------------------------------------- partitionLayout = partitionLayout.size([400, 200]); size = partitionLayout.size(); // round() --------------------------------------------------------------- partitionLayout = partitionLayout.round(true); roundFlag = partitionLayout.round(); // padding() ------------------------------------------------------------- partitionLayout = partitionLayout.padding(1); num = partitionLayout.padding(); // Use partition layout generator ======================================== let partitionRootNode: d3Hierarchy.HierarchyRectangularNode<HierarchyDatumWithParentId>; partitionRootNode = partitionLayout(stratifiedRootNode); // ----------------------------------------------------------------------- // Pack // ----------------------------------------------------------------------- type CircularAccessor = (node: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>) => number; let numberCircularNodeAccessor: CircularAccessor; let numberCircularNodeAccessorOrNull: CircularAccessor | null; // Create pack layout generator ========================================== let packLayout: d3Hierarchy.PackLayout<HierarchyDatumWithParentId>; packLayout = d3Hierarchy.pack<HierarchyDatumWithParentId>(); // Configure pack layout generator ======================================= // size() ---------------------------------------------------------------- packLayout = packLayout.size([400, 400]); size = packLayout.size(); // radius() -------------------------------------------------------------- packLayout = packLayout.radius(null); packLayout = packLayout.radius((node) => { console.log('Radius property of node before completing accessor: ', node.r); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Parent id of node: ', node.data.parentId); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId> return node.value!; }); numberCircularNodeAccessorOrNull = packLayout.radius(); // padding() ------------------------------------------------------------- packLayout = packLayout.padding(1); packLayout = packLayout.padding((node) => { console.log('Radius property of node: ', node.r); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Parent id of node: ', node.data.parentId); // node is of type HierarchyCircularNode<HierarchyDatumWithParentId> return node.value! > 10 ? 2 : 1; }); numberCircularNodeAccessor = packLayout.padding(); // Use partition layout generator ======================================== let packRootNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>; packRootNode = packLayout(stratifiedRootNode); // Use HierarchyCircularNode ============================================= // x and y coordinates and radius r -------------------------------------- num = packRootNode.x; num = packRootNode.y; num = packRootNode.r; // data, depth, height --------------------------------------------------- const packDatum: HierarchyDatumWithParentId = packRootNode.data; num = packRootNode.depth; num = packRootNode.height; // children, parent ------------------------------------------------------ hierarchyCircularNodeArrayOrUndefined = packRootNode.children; let parentCircularNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId> | null; parentCircularNode = hierarchyCircularNodeArray.length ? hierarchyCircularNodeArray[0].parent : null; parentCircularNode = hierarchyCircularNodeArray[0].parent; // id -------------------------------------------------------------------- idString = packRootNode.id; // ancestors(), descendants() -------------------------------------------- const circularNodeAncestors: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.ancestors(); const circularNodeDescendants: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.descendants(); // leaves() -------------------------------------------------------------- hierarchyCircularNodeArray = packRootNode.leaves(); // path() ---------------------------------------------------------------- hierarchyCircularNode = circularNodeDescendants[circularNodeDescendants.length - 1]; const packPath: Array<d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>> = packRootNode.path(hierarchyCircularNode); // links() and HierarchyRectangularLink<...> ----------------------------- let circularLinks: Array<d3Hierarchy.HierarchyCircularLink<HierarchyDatumWithParentId>>; circularLinks = packRootNode.links(); let circularLink: d3Hierarchy.HierarchyCircularLink<HierarchyDatumWithParentId>; circularLink = circularLinks[0]; hierarchyCircularNode = circularLink.source; hierarchyCircularNode = circularLink.target; // sum() and value ------------------------------------------------------- packRootNode = packRootNode.sum((d) => d.val); numOrUndefined = packRootNode.value; // count() and value ----------------------------------------------------- packRootNode = packRootNode.count(); numOrUndefined = packRootNode.value; // sort ------------------------------------------------------------------ packRootNode = packRootNode.sort((a, b) => { console.log('radius of a:', a.r, ' and b:', b.r); // a and b are of type HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Raw values in data of a and b:', a.data.val, ' and ', b.data.val); // a and b are of type HierarchyCircularNode<HierarchyDatumWithParentId> return b.height - a.height || b.value! - a.value!; }); // each(), eachAfter(), eachBefore() ------------------------------------- packRootNode = packRootNode.each((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Radius of node:', node.r); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> }); packRootNode = packRootNode.eachAfter((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Radius of node:', node.r); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> }); packRootNode = packRootNode.eachBefore((node) => { console.log('ParentId:', node.data.parentId); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> console.log('Radius of node:', node.r); // node type is HierarchyCircularNode<HierarchyDatumWithParentId> }); // copy() ---------------------------------------------------------------- let copiedPackNode: d3Hierarchy.HierarchyCircularNode<HierarchyDatumWithParentId>; copiedPackNode = packRootNode.copy(); // ----------------------------------------------------------------------- // Pack Siblings and Enclosure // ----------------------------------------------------------------------- const radius = [ { r: 10, v: 'a' }, { r: 30, v: 'b' }, { r: 20, v: 'c' } ]; // packSiblings const circles = d3Hierarchy.packSiblings(radius); str = circles[0].v; num = circles[0].r; num = circles[0].x; num = circles[0].y; // packEnclose const moreCircles = [ { r: 10, v: 'a', x: 0, y: 10 }, { r: 30, v: 'b', x: 5, y: 15 }, { r: 20, v: 'c', x: 7, y: 30 } ]; const circle = d3Hierarchy.packEnclose(moreCircles); num = circle.r; num = circle.x; num = circle.y; // $ExpectError str = circle.v; // fails, property 'v' does not exist // $ExpectError d3Hierarchy.packEnclose(radius);
the_stack
import { SketchFormat, Svgson, Frame, Gradient } from 'html2sketch'; import { calcFrameScale, normalizeWindingRule, pathToShapeGroup, } from 'html2sketch/parser/svgson'; import { svgPath, rect, compPath, singleRoundRect, unclosedRect, plus, } from '@test-utils'; describe('convertToCubicBezier', () => { it('svgPath转换正常', () => { if (!svgPath.shapes?.[0]) { return; } const points = pathToShapeGroup(svgPath.shapes[0].path); expect(points).toStrictEqual({ frame: { width: 736.652344, height: 814.2161138351329, x: 4, y: 4, }, shapes: [ // 不规则 compPath.shapePath, // 正方形 rect.shapePath, // 圆角矩形 singleRoundRect.shapePath, // 开放矩形 unclosedRect.shapePath, ], }); }); it('plus 转换正常', () => { const points = pathToShapeGroup(plus.path); expect(points).toStrictEqual({ frame: { height: 720, width: 76, x: 474, y: 151.99999999999997 }, shapes: [plus.shapePath], }); }); it('path不正确时报错', () => { const path = 'Z'; const t = () => { // eslint-disable-next-line no-useless-catch try { pathToShapeGroup(path); } catch (e) { throw e; } }; expect(t).toThrow( 'Error Path!\nData:Z\nPlease check whether the path is correct.', ); }); }); describe('calcFrameScale', () => { it('长宽比相等', () => { const originFrame = { x: 0, y: 0, width: 100, height: 100 }; const targetFrame = { x: 0, y: 0, width: 200, height: 200 }; const scale = calcFrameScale(originFrame, targetFrame); expect(scale).toBe(2); }); /** * Origin Target * *--------* *------* * | | -> | | * *--------* *------* */ it('源长宽比大于目标长宽比', () => { const originFrame = { x: 0, y: 0, width: 100, height: 50 }; const targetFrame = { x: 0, y: 0, width: 200, height: 200 }; const scale = calcFrameScale(originFrame, targetFrame); expect(scale).toBe(2); }); /** * Origin Target * *--------* *------* * | | | | * | | -> *------* * | | * *--------* */ it('源长宽比小于目标长宽比', () => { const originFrame = { x: 0, y: 0, width: 100, height: 200 }; const targetFrame = { x: 0, y: 0, width: 100, height: 100 }; const scale = calcFrameScale(originFrame, targetFrame); expect(scale).toBe(0.5); }); }); describe('normalizeWindingRule', () => { const { WindingRule } = SketchFormat; it('不传参返回 EvenOdd', () => { expect(normalizeWindingRule()).toBe(WindingRule.EvenOdd); }); it('传不正确的参返回 EvenOdd', () => { expect(normalizeWindingRule('123')).toBe(WindingRule.EvenOdd); expect(normalizeWindingRule('dxwqs')).toBe(WindingRule.EvenOdd); expect(normalizeWindingRule('sno-zero')).toBe(WindingRule.EvenOdd); }); it('传EvenOdd 返回 EvenOdd', () => { expect(normalizeWindingRule('EvenOdd')).toBe(WindingRule.EvenOdd); expect(normalizeWindingRule('evenodd')).toBe(WindingRule.EvenOdd); expect(normalizeWindingRule('even-odd')).toBe(WindingRule.EvenOdd); expect(normalizeWindingRule('EVENODD')).toBe(WindingRule.EvenOdd); }); it('传 NonZero 返回 NonZero', () => { expect(normalizeWindingRule('NonZero')).toBe(WindingRule.NonZero); expect(normalizeWindingRule('NONZERO')).toBe(WindingRule.NonZero); expect(normalizeWindingRule('nonzero')).toBe(WindingRule.NonZero); expect(normalizeWindingRule('non-zero')).toBe(WindingRule.NonZero); expect(normalizeWindingRule('no-zero')).toBe(WindingRule.NonZero); expect(normalizeWindingRule('nozero')).toBe(WindingRule.NonZero); }); }); describe('Svgson 解析器', () => { const svgson = Svgson.init(); describe('parseNodeToGroup', () => { it('没有 children 正常解析', () => { const gNode = { name: 'g', type: 'element', value: '', attributes: { id: 'Page-1', stroke: 'none', strokeWidth: '1', fill: 'none', fillRule: 'evenodd', style: '', }, children: [], }; const group = svgson.parseNodeToGroup(gNode); expect(group.layers).toHaveLength(0); }); it('有 children 解析正常', () => { const gNode = { name: 'g', type: 'element', value: '', attributes: { id: 'Page-1', stroke: 'none', strokeWidth: '1', fill: 'none', fillRule: 'evenodd', style: '', }, children: [ { name: 'ellipse', type: 'element', value: '', attributes: { id: 'Combined-Shape', fill: '#f1232f', cx: '100.519339', cy: '100.436681', rx: '23.6001926', ry: '23.580786', }, children: [], }, ], }; const group = svgson.parseNodeToGroup(gNode); expect(group.layers).toHaveLength(1); }); }); describe('parseNodeToEllipse', () => { it('没有填充 没有描边', () => { const node = { name: 'ellipse', type: 'element', value: '', attributes: { id: 'Combined-Shape', fill: '#f1232f', cx: '100', cy: '50', rx: '25', ry: '20', }, children: [], }; const ellipse = svgson.parseNodeToEllipse(node); expect(ellipse?.cx).toBe(100); expect(ellipse?.cy).toBe(50); }); }); describe('parseNodeToCircle', () => { it('没有填充 没有描边', () => { const node = { name: 'circle', type: 'element', value: '', attributes: { id: 'Combined-Shape', fill: '#f1232f', cx: '100', cy: '50', r: '25', }, children: [], }; const ellipse = svgson.parseNodeToCircle(node); expect(ellipse?.cx).toBe(100); expect(ellipse?.cy).toBe(50); expect(ellipse?.width).toBe(50); }); }); describe('parseNodeToRectangle', () => { it('非 rect 不解析', () => { const node = { name: 'x', type: 'element', value: '', attributes: {}, children: [], }; expect(svgson.parseNodeToRectangle(node)).toBeUndefined(); }); it('解析 rect', () => { const node = { name: 'rect', type: 'element', value: '', attributes: { id: 'Combined-Shape', fill: '#f1232f', x: '100', y: '50', width: '25', height: '25', }, children: [], }; const rectangle = svgson.parseNodeToRectangle(node)!; expect(rectangle.x).toBe(100); expect(rectangle.y).toBe(50); expect(rectangle.width).toBe(25); expect(rectangle.height).toBe(25); }); }); describe('parseNodeToText', () => { it('非 text 不解析', () => { const node = { name: 'x', type: 'element', value: '', attributes: {}, children: [], }; expect(svgson.parseNodeToText(node)).toBeUndefined(); }); it('解析文本', () => { const node = { name: 'text', type: 'element', value: '', attributes: { id: 'Combined-Shape', fill: '#f1232f', }, children: [ { name: 'text', type: 'value', value: '123', attributes: {}, children: [], }, ], }; const text = svgson.parseNodeToText(node)!; expect(text.text).toBe('123'); }); }); describe('parseSvgDefs', () => { it('渐变', () => { const node = { name: 'radialGradient', type: 'element', value: '', attributes: { id: 'b', cx: '50%', cy: '50%', r: '71.331%', fx: '50%', fy: '50%', gradientTransform: 'matrix(0 1 -.98305 0 .992 0)', }, children: [ { name: 'stop', type: 'element', value: '', attributes: { offset: '0%', stopColor: '#FFF', stopOpacity: '0', }, children: [], }, { name: 'stop', type: 'element', value: '', attributes: { offset: '36.751%', stopColor: '#EBFFFF', stopOpacity: '.021', }, children: [], }, { name: 'stop', type: 'element', value: '', attributes: { offset: '100%', stopColor: '#68FFFF', stopOpacity: '.16', }, children: [], }, ], }; const gradient = Svgson.parseSvgDefs(node) as Gradient; expect(gradient.class).toBe('gradient'); expect(gradient.type).toBe(1); expect(gradient.stops).toHaveLength(3); const [s1, s2, s3] = gradient.stops; expect(s1.color.hex).toBe('#FFFFFF'); expect(s2.color.hex).toBe('#EBFFFF'); expect(s2.color.alpha).toBe(0.021); expect(s2.offset).toEqual(0.36751); expect(s3.color.hex).toBe('#68FFFF'); expect(s3.offset).toEqual(1); expect(s3.color.alpha).toBe(0.16); }); }); describe('parseNodeAttrToStyle', () => { describe('解析描边', () => { it('解析描边和透明度', () => { const attr = { stroke: '#60acff', strokeWidth: '2.5', opacity: '.4', }; const style = svgson.parseNodeAttrToStyle(attr); expect(style.borders).toHaveLength(1); const border = style.borders[0]; expect(border.color.hex).toBe('#60ACFF'); expect(border.thickness).toBe(2.5); expect(style.opacity).toBe(0.4); }); it('dash类型的描边', () => { const attr = { stroke: '#60acff', strokeDasharray: '1px,1px', opacity: '.3', }; const style = svgson.parseNodeAttrToStyle(attr); expect(style.borders).toHaveLength(1); expect(style.sketchBorderOptions.dashPattern).toStrictEqual([1, 1]); }); }); describe('Fill填色', () => { it('带有填充色', () => { const attr = { fill: '#7f95ff', opacity: '0.1', }; const style = svgson.parseNodeAttrToStyle(attr); expect(style.fills).toHaveLength(1); expect(style.opacity).toBe(0.1); const fill = style.fills[0]; expect(fill.type).toBe(0); // 填色类型 expect(fill.color.hex).toBe('#7f95ff'.toUpperCase()); }); it('无填充色', () => { const attr = { fill: 'none' }; const style = svgson.parseNodeAttrToStyle(attr); expect(style.fills).toHaveLength(0); }); it('默认黑色', () => { const attr = {}; const style = svgson.parseNodeAttrToStyle(attr); expect(style.fills).toHaveLength(1); expect(style.opacity).toBe(1); const fill = style.fills[0]; expect(fill.type).toBe(0); // 填色类型 expect(fill.color.hex).toBe('#000000'); }); }); describe('渐变', () => { it('径向渐变', () => { const attr = { fill: 'url(#c)', }; const grad = Svgson.parseSvgDefs({ name: 'radialGradient', type: 'element', value: '', attributes: { id: 'c', cx: '50%', cy: '50%', r: '50%', fx: '50%', fy: '50%', // TODO 解析 gradientTransform gradientTransform: 'matrix(0 1 -.98305 0 .992 0)', }, children: [ { name: 'stop', type: 'element', value: '', attributes: { offset: '0%', stopColor: '#3187FF', }, children: [], }, { name: 'stop', type: 'element', value: '', attributes: { offset: '100%', stopColor: '#338FFF', stopOpacity: '0.3', }, children: [], }, ], }); svgson.defs.push(<Gradient>grad); const style = svgson.parseNodeAttrToStyle(attr); expect(style.fills).toHaveLength(1); const fill = style.fills[0]; expect(fill.type).toBe(1); // 填充类型是渐变 const { gradient } = fill; expect(gradient.type).toBe(1); // 渐变类型是径向渐变 expect(gradient.from).toStrictEqual({ x: 0.5, y: 0.5 }); expect(gradient.to).toStrictEqual({ x: 1, y: 0.5 }); // TODO 渐变的 Transform 和 ellipseLength 覆盖 // 渐变梯度 expect(gradient.stops).toHaveLength(2); const [s1, s2] = gradient.stops; expect(Math.abs(s1.offset!)).toBe(0); expect(s1.color.hex).toBe('#3187FF'); expect(s1.color.alpha).toBe(1); expect(s2.offset).toBe(1); expect(s2.color.hex).toBe('#338FFF'); expect(s2.color.alpha).toBe(0.3); // 渐变透明度 }); }); }); describe('applyTransformString', () => { it('空 transform,frame 不变', () => { const frame = new Frame(); expect(frame.x).toBe(0); expect(frame.y).toBe(0); expect(frame.rotation).toBe(0); svgson.applyTransformString(frame); expect(frame.x).toBe(0); expect(frame.y).toBe(0); expect(frame.rotation).toBe(0); }); it('错误的 transform ,frame 不变', () => { const frame = new Frame(); expect(frame.x).toBe(0); expect(frame.y).toBe(0); expect(frame.rotation).toBe(0); svgson.applyTransformString(frame, '123'); expect(frame.x).toBe(0); expect(frame.y).toBe(0); expect(frame.rotation).toBe(0); }); it('正确的 transform', () => { const frame = new Frame(); svgson.applyTransformString(frame, 'rotate(15 408.32 3453.665)'); expect(frame.x).toBe(907.787444013645); expect(frame.y).toBe(11.999788653103678); expect(frame.rotation).toBe(15); }); }); describe('测试用例', () => { it('子级继承父级 fill 属性', () => { const svg = ` <svg> <g fill="none" fill-rule="evenodd" > <g> <g> <circle cx="73" cy="73" r="73" stroke="#60ACFF" opacity=".2"/> </g> </g> </g> </svg> `; const result = new Svgson(svg, { width: 100, height: 100 }); expect(result.layers).toHaveLength(2); // 取到圆 const circle = result.layers[1].layers[0].layers[0].layers[0]; expect(circle.class).toBe('ellipse'); // 确保取到的是 ellipse expect(circle.style.fills).toHaveLength(0); // 没有填充 }); it('svg 循环嵌套', () => { const svg = `<svg><svg><g></g></svg></svg>`; const result = new Svgson(svg, { width: 100, height: 100 }); expect(result.layers).toHaveLength(2); }); }); });
the_stack
module WinJSTests { "use strict"; var COUNT = 6; var FlipView = <typeof WinJS.UI.PrivateFlipView>WinJS.UI.FlipView; function navigateAndSpliceTwiceInDataSource(element, flipView, rawData, complete) { var data = [ { title: "New Delhi", data1: "India" }, { title: "Redmond", data1: "America" } ]; var list = new WinJS.Binding.List(data); var tests = [ function () { var ds = list.dataSource; flipView.itemDataSource = ds; }, function () { flipView.next(); list.splice(2, 1); list.splice(1, 1); flipView._pageManager._notificationsEndedSignal.promise.then(function () { LiveUnit.Assert.areEqual("New DelhiIndia", flipView._pageManager._currentPage.element.textContent); complete(); }); } ]; runFlipViewTests(flipView, tests); } function insertJumpAndChangeInDataSource(element, flipView, rawData, complete) { var data = [ { title: "New Delhi", data1: "India" }, { title: "Redmond", data1: "America" }, { title: "Seattle", data1: "America" } ]; var list = new WinJS.Binding.List(data); var tests = [ function () { var ds = list.dataSource; flipView.itemDataSource = ds; }, function () { // Insert list.unshift({ title: "Bellevue", data1: "America" }); // Jump flipView.currentPage = 0; flipView._pageManager._notificationsEndedSignal.promise.then(function () { // Change list.setAt(0, { title: "Tampa", data1: "America" }); LiveUnit.Assert.areEqual("TampaAmerica", flipView._pageManager._currentPage.element.textContent); complete(); }); } ]; runFlipViewTests(flipView, tests); } function insertAndChangeInDatasource(element, flipView, rawData, complete) { var data = [ { title: "New Delhi", data1: "India" }, { title: "Redmond", data1: "America" } ]; var list = new WinJS.Binding.List(data); var tests = [ function () { var ds = list.dataSource; flipView.itemDataSource = ds; }, function () { list.push({ title: "Tampa", data1: "US" }); list.setAt(2, { title: "Boston", data1: "US" }); list.setAt(2, { title: "Seattle", data1: "US" }); flipView.currentPage = 2; }, function () { LiveUnit.Assert.areEqual("SeattleUS", flipView._pageManager._currentPage.element.textContent); complete(); } ]; runFlipViewTests(flipView, tests); } function shiftAndChangeInDatasource(element, flipView, rawData, complete) { var data = [ { title: "Tokio", data1: "Japan" }, { title: "Paris", data1: "France" } ]; var list = new WinJS.Binding.List(data); var tests = [ function () { var ds = list.dataSource; flipView.itemDataSource = ds; }, function () { list.shift(); list.setAt(0, { title: "Miami", data1: "US" }); list.setAt(0, { title: "San Jose", data1: "US" }); return true; }, function () { LiveUnit.Assert.areEqual("San JoseUS", flipView._pageManager._currentPage.element.textContent); complete(); } ]; runFlipViewTests(flipView, tests); } function verifyDisplayedItem(flipView, rawData) { LiveUnit.LoggingCore.logComment("Verifying displayed page is correct"); LiveUnit.Assert.isTrue(currentPageInView(flipView)); flipView.itemTemplate.verifyOutput(getDisplayedElement(flipView), rawData); } function verifyNoOldDataRemains(element, className) { LiveUnit.Assert.areEqual(0, element.querySelectorAll(className).length); } function datasourceTest(element, flipView, rawData, complete) { var otherSource = createArraySource(COUNT * 2, ["400px"], ["400px"], "newData"), otherRawData = otherSource.rawData, pageInvisible, pageVisible, oldCurrentPage; flipView.addEventListener("pagevisibilitychanged", function (e) { if (e.detail.visible) { pageVisible = e.target; } else { pageInvisible = e.target; } }, false); var tests = [ function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyDisplayedItem(flipView, rawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyDisplayedItem(flipView, rawData[1]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(2, flipView.currentPage); verifyDisplayedItem(flipView, rawData[2]); flipView.currentPage = 5; }, function () { LiveUnit.Assert.areEqual(5, flipView.currentPage); verifyDisplayedItem(flipView, rawData[5]); oldCurrentPage = getDisplayedElement(flipView); pageVisible = null; pageInvisible = null; flipView.itemDataSource = otherSource.dataSource; }, function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyDisplayedItem(flipView, otherRawData[0]); LiveUnit.Assert.areEqual(pageInvisible, oldCurrentPage); LiveUnit.Assert.areEqual(pageVisible, getDisplayedElement(flipView)); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyDisplayedItem(flipView, otherRawData[1]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(2, flipView.currentPage); verifyDisplayedItem(flipView, otherRawData[2]); flipView.currentPage = 11; }, function () { LiveUnit.Assert.areEqual(11, flipView.currentPage); verifyDisplayedItem(flipView, otherRawData[11]); LiveUnit.Assert.isFalse(flipView.next()); complete(); }, ]; runFlipViewTests(flipView, tests); } function rendererTest(element, flipView, rawData, complete) { var pageInvisible, pageVisible, oldCurrentPage; flipView.addEventListener("pagevisibilitychanged", function (e) { if (e.detail.visible) { pageVisible = e.target; } else { pageInvisible = e.target; } }, false); var tests = [ function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyDisplayedItem(flipView, rawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyDisplayedItem(flipView, rawData[1]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(2, flipView.currentPage); verifyDisplayedItem(flipView, rawData[2]); flipView.currentPage = 5; }, function () { LiveUnit.Assert.areEqual(5, flipView.currentPage); verifyDisplayedItem(flipView, rawData[5]); pageInvisible = null; pageVisible = null; oldCurrentPage = getDisplayedElement(flipView); flipView.itemTemplate = alternateBasicInstantRenderer; }, function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyDisplayedItem(flipView, rawData[0]); LiveUnit.Assert.areEqual(pageInvisible, oldCurrentPage); LiveUnit.Assert.areEqual(pageVisible, getDisplayedElement(flipView)); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyDisplayedItem(flipView, rawData[1]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(2, flipView.currentPage); verifyDisplayedItem(flipView, rawData[2]); flipView.currentPage = 5; }, function () { LiveUnit.Assert.areEqual(5, flipView.currentPage); verifyDisplayedItem(flipView, rawData[5]); LiveUnit.Assert.isFalse(flipView.next()); complete(); }, ]; runFlipViewTests(flipView, tests); } function changeDuringAnimationTest(element, flipView, rawData, complete) { var otherSource = createArraySource(COUNT * 2, ["400px"], ["400px"], "newData"), otherRawData = otherSource.rawData; var tests = [ function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyDisplayedItem(flipView, rawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { flipView.itemDataSource = otherSource.dataSource; }, function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyDisplayedItem(flipView, otherRawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyDisplayedItem(flipView, otherRawData[1]); flipView.currentPage = 5; }, function () { verifyNoOldDataRemains(element, rawData[0].className); LiveUnit.Assert.areEqual(5, flipView.currentPage); verifyDisplayedItem(flipView, otherRawData[5]); flipView.currentPage = 0; }, function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyDisplayedItem(flipView, otherRawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { flipView.itemTemplate = alternateBasicInstantRenderer; }, function () { LiveUnit.Assert.areEqual(0, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyNoOldDataRemains(element, otherRawData[0].className); verifyDisplayedItem(flipView, otherRawData[0]); LiveUnit.Assert.isTrue(flipView.next()); }, function () { LiveUnit.Assert.areEqual(1, flipView.currentPage); verifyNoOldDataRemains(element, rawData[0].className); verifyNoOldDataRemains(element, otherRawData[0].className); verifyDisplayedItem(flipView, otherRawData[1]); complete(); } ]; runFlipViewTests(flipView, tests); } function changeToNullDataSource(element, flipView, rawData, complete) { var tests = [ function () { var refreshHandler = flipView._refreshHandler; flipView._refreshHandler = function () { refreshHandler.call(flipView); flipView.count().done(function (count) { LiveUnit.Assert.areEqual(0, count); complete(); }); }; flipView.itemDataSource = null; } ]; runFlipViewTests(flipView, tests); } export class FlipViewDatasourceTests { setUp() { LiveUnit.LoggingCore.logComment("In setup"); var newNode = document.createElement("div"); newNode.id = "BasicFlipView"; newNode.style.width = "400px"; newNode.style.height = "400px"; document.body.appendChild(newNode); } tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); var element = document.getElementById("BasicFlipView"); if (element) { WinJS.Utilities.disposeSubTree(element); document.body.removeChild(element); } } testBatchNotificationMoveThenRemove = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); var currentCount = 1; for (var i = 0; i < 6; i++) { bl.push({ title: i }); currentCount++; } var fv = new WinJS.UI.FlipView(element, { itemDataSource: bl.dataSource, currentPage: 3, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; el.style.backgroundColor = "teal"; return el; }); } }); var dsChanged = false; fv.addEventListener("pagecompleted", function updateDS() { if (!dsChanged) { bl.dataSource.beginEdits(); // move index 4 to 1 bl.move(4, 1); //remove at 4 bl.splice(4, 1); bl.dataSource.endEdits(); dsChanged = true; } else { Helper.validateUnhandledErrors(); validateInternalBuffers(fv); WinJS.Utilities.disposeSubTree(element); document.body.removeChild(element); complete(); } }); }; testReleasedItemAfterInsertAtIndexOne = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); var currentCount = 1; for (var i = 0; i < 6; i++) { bl.push({ title: i }); currentCount++; } var fv = new FlipView(element, { itemDataSource: bl.dataSource, currentPage: 0, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; el.style.backgroundColor = "teal"; return el; }); } }); fv.addEventListener("pagecompleted", function updateDS() { bl.splice(1, 0, { title: "new" }); fv._pageManager._notificationsEndedSignal.promise.then(function () { Helper.validateUnhandledErrors(); validateInternalBuffers(fv); WinJS.Utilities.disposeSubTree(element); document.body.removeChild(element); complete(); }); }); }; testBatchOfRandomChanges = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); for (var i = 0; i < 20; i++) { bl.push({ title: String.fromCharCode(97 + i) }); } var fv = new FlipView(element, { itemDataSource: bl.dataSource, currentPage: 4, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; return el; }); } }); fv.addEventListener("pagecompleted", function () { bl.dataSource.beginEdits(); //add item at index 3 bl.splice(3, 0, { title: "new1" }); //remove at 5 bl.splice(5, 1); // move index 4 to 1 bl.move(4, 1); //remove at 4 bl.splice(4, 1); //add item at index 3 bl.splice(3, 0, { title: "new2" }); bl.dataSource.endEdits(); fv._pageManager._notificationsEndedSignal.promise.then(function () { Helper.validateUnhandledErrors(); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.element.textContent, "f"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.element.textContent, "g"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.next.element.textContent, "h"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.element.textContent, "c"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.prev.element.textContent, "new2"); document.body.removeChild(element); complete(); }); }); }; testBatchOfMoveThenDeleteAtSameIndex = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); for (var i = 0; i < 20; i++) { bl.push({ title: String.fromCharCode(97 + i) }); } var fv = new FlipView(element, { itemDataSource: bl.dataSource, currentPage: 2, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; return el; }); } }); fv.addEventListener("pagecompleted", function () { bl.dataSource.beginEdits(); // move index 4 to 1 bl.move(4, 1); //remove at 4 bl.splice(4, 1); bl.dataSource.endEdits(); fv._pageManager._notificationsEndedSignal.promise.then(function () { Helper.validateUnhandledErrors(); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.element.textContent, "c"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.element.textContent, "f"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.next.element.textContent, "g"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.element.textContent, "b"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.prev.element.textContent, "e"); document.body.removeChild(element); complete(); }); }); }; testUpdateCurrentElementThenBatchOfRandomChanges = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); for (var i = 0; i < 20; i++) { bl.push({ title: String.fromCharCode(97 + i) }); } var fv = new FlipView(element, { itemDataSource: bl.dataSource, currentPage: 1, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; return el; }); } }); fv.addEventListener("pagecompleted", function () { bl.setAt(1, { title: "changed" }); bl.dataSource.beginEdits(); //add item at index 3 bl.splice(3, 0, { title: "new 1" }); //remove at 5 bl.splice(5, 1); // move index 4 to 1 bl.move(4, 1); //remove at 4 bl.splice(4, 1); //add item at index 3 bl.splice(3, 0, { title: "new2" }); bl.dataSource.endEdits(); fv._pageManager._notificationsEndedSignal.promise.then(function () { Helper.validateUnhandledErrors(); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.element.textContent, "changed"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.element.textContent, "new2"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.next.element.textContent, "c"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.element.textContent, "d"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.prev.element.textContent, "a"); document.body.removeChild(element); complete(); }); }); }; testChangesMovingCurrentViewportThenDeleteItem = function (complete) { Helper.initUnhandledErrors(); var element = document.createElement("div"); document.body.appendChild(element); var bl = new WinJS.Binding.List(); for (var i = 0; i < 20; i++) { bl.push({ title: String.fromCharCode(97 + i) }); } var fv = new FlipView(element, { itemDataSource: bl.dataSource, currentPage: 1, itemTemplate: function (itemPromise) { return itemPromise.then(function (value) { var el = document.createElement("div"); el.textContent = value.data.title; el.style.height = el.style.width = "100px"; return el; }); } }); fv.addEventListener("pagecompleted", function () { bl.dataSource.beginEdits(); // move index 3 to 1 bl.move(3, 1); //remove at 3 bl.splice(3, 1); bl.dataSource.endEdits(); //remove at 1 bl.splice(1, 1); fv._pageManager._notificationsEndedSignal.promise.then(function () { Helper.validateUnhandledErrors(); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.element.textContent, "b"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.element.textContent, "e"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.next.next.element.textContent, "f"); LiveUnit.Assert.areEqual(fv._pageManager._currentPage.prev.element.textContent, "a"); LiveUnit.Assert.isTrue(!fv._pageManager._currentPage.prev.prev.element); document.body.removeChild(element); complete(); }); }); }; } function generate(name, testFunction) { function generateTest(orientation) { FlipViewDatasourceTests.prototype[name + "_" + orientation] = function (complete) { var element = document.getElementById("BasicFlipView"), testData = createArraySource(COUNT, ["400px"], ["400px"]), rawData = testData.rawData, flipView = new WinJS.UI.FlipView(element, { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation }); setupQuickAnimations(flipView); testFunction(element, flipView, rawData, complete); }; } generateTest("horizontal"); generateTest( "vertical"); } generate("testFlipViewDatasourceProperty", datasourceTest); generate("testFlipViewRendererProperty", rendererTest); generate("testFlipViewDSAndRendererDuringAnimation", changeDuringAnimationTest); generate("testFlipViewChangeToNullDataSource", changeToNullDataSource); generate("testFlipViewInsertAndChangeInDataSource", insertAndChangeInDatasource); generate("testFlipViewShiftAndChangeInDataSource", shiftAndChangeInDatasource); generate("testFlipViewNavigateAndSpliceTwiceInDataSource", navigateAndSpliceTwiceInDataSource); generate("testFlipViewInsertJumpAndChangeInDataSource", insertJumpAndChangeInDataSource); } LiveUnit.registerTestClass("WinJSTests.FlipViewDatasourceTests");
the_stack
import { LoanMasterNodeRegTestContainer } from './loan_container' import { Testing } from '@defichain/jellyfish-testing' import BigNumber from 'bignumber.js' import { VaultActive, VaultState } from '../../../src/category/loan' describe('Loan getVault', () => { const container = new LoanMasterNodeRegTestContainer() const testing = Testing.create(container) let collateralAddress: string let oracleId: string beforeAll(async () => { await testing.container.start() await testing.container.waitForWalletCoinbaseMaturity() collateralAddress = await testing.generateAddress() await testing.token.dfi({ address: collateralAddress, amount: 30000 }) await testing.token.create({ symbol: 'BTC', collateralAddress }) await testing.generate(1) await testing.token.mint({ symbol: 'BTC', amount: 20000 }) await testing.generate(1) // loan scheme await testing.container.call('createloanscheme', [100, 1, 'default']) await testing.generate(1) // price oracle const addr = await testing.generateAddress() const priceFeeds = [ { token: 'DFI', currency: 'USD' }, { token: 'BTC', currency: 'USD' }, { token: 'TSLA', currency: 'USD' } ] oracleId = await testing.rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 }) await testing.generate(1) const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '1@DFI', currency: 'USD' }] }) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '10000@BTC', currency: 'USD' }] }) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) await testing.generate(1) // collateral tokens await testing.rpc.loan.setCollateralToken({ token: 'DFI', factor: new BigNumber(1), fixedIntervalPriceId: 'DFI/USD' }) await testing.rpc.loan.setCollateralToken({ token: 'BTC', factor: new BigNumber(0.5), fixedIntervalPriceId: 'BTC/USD' }) await testing.generate(1) // loan token await testing.rpc.loan.setLoanToken({ symbol: 'TSLA', fixedIntervalPriceId: 'TSLA/USD' }) await testing.generate(1) }) afterAll(async () => { await testing.container.stop() }) it('should getVault', async () => { const ownerAddress = await testing.generateAddress() const vaultId = await testing.rpc.container.call('createvault', [ownerAddress, 'default']) await testing.container.generate(1) const data = await testing.rpc.loan.getVault(vaultId) expect(data).toStrictEqual({ vaultId: vaultId, loanSchemeId: 'default', // Get default loan scheme ownerAddress: ownerAddress, state: VaultState.ACTIVE, collateralAmounts: [], loanAmounts: [], interestAmounts: [], collateralValue: expect.any(BigNumber), loanValue: expect.any(BigNumber), interestValue: expect.any(BigNumber), collateralRatio: expect.any(Number), informativeRatio: expect.any(BigNumber) }) }) it('should getVault with deposited collateral details', async () => { const ownerAddress = await testing.generateAddress() const vaultId = await testing.rpc.container.call('createvault', [ownerAddress, 'default']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '10000@DFI']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '1@BTC']) await testing.generate(1) const data = await testing.rpc.loan.getVault(vaultId) expect(data).toStrictEqual({ vaultId: vaultId, loanSchemeId: 'default', // Get default loan scheme ownerAddress: ownerAddress, state: VaultState.ACTIVE, collateralAmounts: ['10000.00000000@DFI', '1.00000000@BTC'], loanAmounts: [], interestAmounts: [], // (10000 DFI * DFIUSD Price * DFI collaterization factor 1) + (1BTC * BTCUSD Price * BTC collaterization factor 0.5) collateralValue: new BigNumber(10000 * 1 * 1).plus(new BigNumber(1 * 10000 * 0.5)), loanValue: new BigNumber(0), interestValue: new BigNumber(0), collateralRatio: -1, informativeRatio: new BigNumber(-1) }) }) it('should getVault with loan details', async () => { const ownerAddress = await testing.generateAddress() const vaultId = await testing.rpc.container.call('createvault', [ownerAddress, 'default']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '10000@DFI']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '1@BTC']) await testing.generate(1) // take loan await testing.container.call('takeloan', [{ vaultId: vaultId, amounts: '30@TSLA' }]) await testing.generate(1) // interest info. const interestInfo: any = await testing.rpc.call('getinterest', ['default', 'TSLA'], 'bignumber') const data = await testing.rpc.loan.getVault(vaultId) as VaultActive const informativeRatio: BigNumber = data.collateralValue.dividedBy(data.loanValue).multipliedBy(100) expect(data).toStrictEqual({ vaultId: vaultId, loanSchemeId: 'default', // Get default loan scheme ownerAddress: ownerAddress, state: VaultState.ACTIVE, collateralAmounts: ['10000.00000000@DFI', '1.00000000@BTC'], // 30 TSLA + total interest loanAmounts: [new BigNumber(30).plus(interestInfo[0].totalInterest).toFixed(8) + '@TSLA'], // 30.00000570@TSLA interestAmounts: ['0.00000571@TSLA'], // (10000 DFI * DFIUSD Price * DFI collaterization factor 1) + (1BTC * BTCUSD Price * BTC collaterization factor 0.5) collateralValue: new BigNumber(10000 * 1 * 1).plus(new BigNumber(1 * 10000 * 0.5)), // (30 TSLA + total interest) * TSLAUSD Price loanValue: new BigNumber(30).plus(interestInfo[0].totalInterest).multipliedBy(2), interestValue: new BigNumber(0.00001142), // lround ((collateral value / loan value) * 100) collateralRatio: Math.ceil(informativeRatio.toNumber()), // 25000 informativeRatio: new BigNumber(informativeRatio.toFixed(8, BigNumber.ROUND_DOWN)) // 24999.995241667572335939 -> 24999.99524166 }) }) it('should getVault with liquidated vault', async () => { const ownerAddress = await testing.generateAddress() const vaultId = await testing.rpc.container.call('createvault', [ownerAddress, 'default']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '10000@DFI']) await testing.generate(1) await testing.container.call('deposittovault', [vaultId, collateralAddress, '1@BTC']) await testing.generate(1) // take loan await testing.container.call('takeloan', [{ vaultId: vaultId, amounts: '30@TSLA' }]) await testing.generate(1) // check vault not under liquidation. const data = await testing.rpc.loan.getVault(vaultId) expect(data.state).toStrictEqual(VaultState.ACTIVE) // make vault enter under liquidation state by a price hike of the loan token const timestamp = Math.floor(new Date().getTime() / 1000) await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '1000@TSLA', currency: 'USD' }] }) await testing.generate(12) // Wait for 12 blocks which are equivalent to 2 hours (1 block = 10 minutes) in order to liquidate the vault // get auction details await testing.rpc.account.sendTokensToAddress({}, { [collateralAddress]: ['40@TSLA'] }) await testing.generate(1) const txid = await testing.container.call('placeauctionbid', [vaultId, 0, collateralAddress, '40@TSLA']) expect(typeof txid).toStrictEqual('string') expect(txid.length).toStrictEqual(64) await testing.generate(1) const vaultDataAfterPriceHike = await testing.rpc.loan.getVault(vaultId) expect(vaultDataAfterPriceHike).toStrictEqual({ vaultId: vaultId, loanSchemeId: 'default', // Get default loan scheme ownerAddress: ownerAddress, state: VaultState.IN_LIQUIDATION, liquidationHeight: 168, liquidationPenalty: 5, batchCount: 2, batches: [ { collaterals: [ '6666.66660000@DFI', '0.66666666@BTC' ], index: 0, loan: '20.00004547@TSLA', highestBid: { amount: '40.00000000@TSLA', owner: collateralAddress } }, { collaterals: [ '3333.33340000@DFI', '0.33333334@BTC' ], index: 1, loan: '10.00002305@TSLA' } ] }) // set the price oracle back to original price await testing.rpc.oracle.setOracleData(oracleId, timestamp, { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) }) it('should not getVault if vault id is invalid', async () => { { // Pass non existing hex id const promise = testing.rpc.loan.getVault('2cca2e3be0504af2daac12255cb5a691447e0aa3c9ca9120fb634a96010d2b4f') await expect(promise).rejects.toThrow('RpcApiError: \'Vault <2cca2e3be0504af2daac12255cb5a691447e0aa3c9ca9120fb634a96010d2b4f> not found\', code: -20, method: getvault') } { // Pass hex id with invalid length const promise = testing.rpc.loan.getVault(Buffer.from('INVALID_VAULT_ID').toString('hex')) await expect(promise).rejects.toThrow('RpcApiError: \'vaultId must be of length 64 (not 32, for \'494e56414c49445f5641554c545f4944\')\', code: -8, method: getvault') } { // Pass non hex id const promise = testing.rpc.loan.getVault('x'.repeat(64)) await expect(promise).rejects.toThrow('RpcApiError: \'vaultId must be hexadecimal string (not \'' + 'x'.repeat(64) + '\')\', code: -8, method: getvault') } }) })
the_stack
import { AsyncSeriesWaterfallHook } from '@umijs/deps/compiled/tapable'; import { BabelRegister, lodash, NodeEnv } from '@umijs/utils'; import assert from 'assert'; import { EventEmitter } from 'events'; import { existsSync } from 'fs'; import { join } from 'path'; import Config from '../Config/Config'; import { getUserConfigWithKey } from '../Config/utils/configUtils'; import Logger from '../Logger/Logger'; import { ApplyPluginsType, ConfigChangeType, EnableBy, PluginType, ServiceStage, } from './enums'; import getPaths from './getPaths'; import PluginAPI from './PluginAPI'; import { ICommand, IHook, IPackage, IPlugin, IPreset } from './types'; import isPromise from './utils/isPromise'; import loadDotEnv from './utils/loadDotEnv'; import { pathToObj, resolvePlugins, resolvePresets } from './utils/pluginUtils'; const logger = new Logger('umi:core:Service'); export interface IServiceOpts { cwd: string; pkg?: IPackage; presets?: string[]; plugins?: string[]; configFiles?: string[]; env?: NodeEnv; } interface IConfig { presets?: string[]; plugins?: string[]; [key: string]: any; } // TODO // 1. duplicated key export default class Service extends EventEmitter { cwd: string; pkg: IPackage; skipPluginIds: Set<string> = new Set<string>(); // lifecycle stage stage: ServiceStage = ServiceStage.uninitialized; // registered commands commands: { [name: string]: ICommand | string; } = {}; // including presets and plugins plugins: { [id: string]: IPlugin; } = {}; // plugin methods pluginMethods: { [name: string]: Function; } = {}; // initial presets and plugins from arguments, config, process.env, and package.json initialPresets: IPreset[]; initialPlugins: IPlugin[]; // presets and plugins for registering _extraPresets: IPreset[] = []; _extraPlugins: IPlugin[] = []; // user config userConfig: IConfig; configInstance: Config; config: IConfig | null = null; // babel register babelRegister: BabelRegister; // hooks hooksByPluginId: { [id: string]: IHook[]; } = {}; hooks: { [key: string]: IHook[]; } = {}; // paths paths: { cwd?: string; absNodeModulesPath?: string; absSrcPath?: string; absPagesPath?: string; absOutputPath?: string; absTmpPath?: string; } = {}; env: string | undefined; ApplyPluginsType = ApplyPluginsType; EnableBy = EnableBy; ConfigChangeType = ConfigChangeType; ServiceStage = ServiceStage; args: any; constructor(opts: IServiceOpts) { super(); logger.debug('opts:'); logger.debug(opts); this.cwd = opts.cwd || process.cwd(); // repoDir should be the root dir of repo this.pkg = opts.pkg || this.resolvePackage(); this.env = opts.env || process.env.NODE_ENV; assert(existsSync(this.cwd), `cwd ${this.cwd} does not exist.`); // register babel before config parsing this.babelRegister = new BabelRegister(); // load .env or .local.env logger.debug('load env'); this.loadEnv(); // get user config without validation logger.debug('get user config'); const configFiles = opts.configFiles; this.configInstance = new Config({ cwd: this.cwd, service: this, localConfig: this.env === 'development', configFiles: Array.isArray(configFiles) && !!configFiles[0] ? configFiles : undefined, }); this.userConfig = this.configInstance.getUserConfig(); logger.debug('userConfig:'); logger.debug(this.userConfig); // get paths this.paths = getPaths({ cwd: this.cwd, config: this.userConfig!, env: this.env, }); logger.debug('paths:'); logger.debug(this.paths); // setup initial presets and plugins const baseOpts = { pkg: this.pkg, cwd: this.cwd, }; this.initialPresets = resolvePresets({ ...baseOpts, presets: opts.presets || [], userConfigPresets: this.userConfig.presets || [], }); this.initialPlugins = resolvePlugins({ ...baseOpts, plugins: opts.plugins || [], userConfigPlugins: this.userConfig.plugins || [], }); this.babelRegister.setOnlyMap({ key: 'initialPlugins', value: lodash.uniq([ ...this.initialPresets.map(({ path }) => path), ...this.initialPlugins.map(({ path }) => path), ]), }); logger.debug('initial presets:'); logger.debug(this.initialPresets); logger.debug('initial plugins:'); logger.debug(this.initialPlugins); } setStage(stage: ServiceStage) { this.stage = stage; } resolvePackage() { try { return require(join(this.cwd, 'package.json')); } catch (e) { return {}; } } loadEnv() { const basePath = join(this.cwd, '.env'); const localPath = `${basePath}.local`; loadDotEnv(localPath); loadDotEnv(basePath); } async init() { this.setStage(ServiceStage.init); // we should have the final hooksByPluginId which is added with api.register() await this.initPresetsAndPlugins(); // collect false configs, then add to this.skipPluginIds // skipPluginIds include two parts: // 1. api.skipPlugins() // 2. user config with the `false` value // Object.keys(this.hooksByPluginId).forEach(pluginId => { // const { key } = this.plugins[pluginId]; // if (this.getPluginOptsWithKey(key) === false) { // this.skipPluginIds.add(pluginId); // } // }); // delete hooks from this.hooksByPluginId with this.skipPluginIds // for (const pluginId of this.skipPluginIds) { // if (this.hooksByPluginId[pluginId]) delete this.hooksByPluginId[pluginId]; // delete this.plugins[pluginId]; // } // hooksByPluginId -> hooks // hooks is mapped with hook key, prepared for applyPlugins() this.setStage(ServiceStage.initHooks); Object.keys(this.hooksByPluginId).forEach((id) => { const hooks = this.hooksByPluginId[id]; hooks.forEach((hook) => { const { key } = hook; hook.pluginId = id; this.hooks[key] = (this.hooks[key] || []).concat(hook); }); }); // plugin is totally ready this.setStage(ServiceStage.pluginReady); await this.applyPlugins({ key: 'onPluginReady', type: ApplyPluginsType.event, }); // get config, including: // 1. merge default config // 2. validate this.setStage(ServiceStage.getConfig); const defaultConfig = await this.applyPlugins({ key: 'modifyDefaultConfig', type: this.ApplyPluginsType.modify, initialValue: await this.configInstance.getDefaultConfig(), }); this.config = await this.applyPlugins({ key: 'modifyConfig', type: this.ApplyPluginsType.modify, initialValue: this.configInstance.getConfig({ defaultConfig, }) as any, }); // merge paths to keep the this.paths ref this.setStage(ServiceStage.getPaths); // config.outputPath may be modified by plugins if (this.config!.outputPath) { this.paths.absOutputPath = join(this.cwd, this.config!.outputPath); } const paths = (await this.applyPlugins({ key: 'modifyPaths', type: ApplyPluginsType.modify, initialValue: this.paths, })) as object; Object.keys(paths).forEach((key) => { this.paths[key] = paths[key]; }); } async initPresetsAndPlugins() { this.setStage(ServiceStage.initPresets); this._extraPlugins = []; while (this.initialPresets.length) { await this.initPreset(this.initialPresets.shift()!); } this.setStage(ServiceStage.initPlugins); this._extraPlugins.push(...this.initialPlugins); while (this._extraPlugins.length) { await this.initPlugin(this._extraPlugins.shift()!); } } getPluginAPI(opts: any) { const pluginAPI = new PluginAPI(opts); // register built-in methods [ 'onPluginReady', 'modifyPaths', 'onStart', 'modifyDefaultConfig', 'modifyConfig', ].forEach((name) => { pluginAPI.registerMethod({ name, exitsError: false }); }); return new Proxy(pluginAPI, { get: (target, prop: string) => { // 由于 pluginMethods 需要在 register 阶段可用 // 必须通过 proxy 的方式动态获取最新,以实现边注册边使用的效果 if (this.pluginMethods[prop]) return this.pluginMethods[prop]; if ( [ 'applyPlugins', 'ApplyPluginsType', 'EnableBy', 'ConfigChangeType', 'babelRegister', 'stage', 'ServiceStage', 'paths', 'cwd', 'pkg', 'userConfig', 'config', 'env', 'args', 'hasPlugins', 'hasPresets', ].includes(prop) ) { return typeof this[prop] === 'function' ? this[prop].bind(this) : this[prop]; } return target[prop]; }, }); } async applyAPI(opts: { apply: Function; api: PluginAPI }) { let ret = opts.apply()(opts.api); if (isPromise(ret)) { ret = await ret; } return ret || {}; } async initPreset(preset: IPreset) { const { id, key, apply } = preset; preset.isPreset = true; const api = this.getPluginAPI({ id, key, service: this }); // register before apply this.registerPlugin(preset); // TODO: ...defaultConfigs 考虑要不要支持,可能这个需求可以通过其他渠道实现 const { presets, plugins, ...defaultConfigs } = await this.applyAPI({ api, apply, }); // register extra presets and plugins if (presets) { assert( Array.isArray(presets), `presets returned from preset ${id} must be Array.`, ); // 插到最前面,下个 while 循环优先执行 this._extraPresets.splice( 0, 0, ...presets.map((path: string) => { return pathToObj({ type: PluginType.preset, path, cwd: this.cwd, }); }), ); } // 深度优先 const extraPresets = lodash.clone(this._extraPresets); this._extraPresets = []; while (extraPresets.length) { await this.initPreset(extraPresets.shift()!); } if (plugins) { assert( Array.isArray(plugins), `plugins returned from preset ${id} must be Array.`, ); this._extraPlugins.push( ...plugins.map((path: string) => { return pathToObj({ type: PluginType.plugin, path, cwd: this.cwd, }); }), ); } } async initPlugin(plugin: IPlugin) { const { id, key, apply } = plugin; const api = this.getPluginAPI({ id, key, service: this }); // register before apply this.registerPlugin(plugin); await this.applyAPI({ api, apply }); } getPluginOptsWithKey(key: string) { return getUserConfigWithKey({ key, userConfig: this.userConfig, }); } registerPlugin(plugin: IPlugin) { // 考虑要不要去掉这里的校验逻辑 // 理论上不会走到这里,因为在 describe 的时候已经做了冲突校验 if (this.plugins[plugin.id]) { const name = plugin.isPreset ? 'preset' : 'plugin'; throw new Error(`\ ${name} ${plugin.id} is already registered by ${this.plugins[plugin.id].path}, \ ${name} from ${plugin.path} register failed.`); } this.plugins[plugin.id] = plugin; } isPluginEnable(pluginId: string) { // api.skipPlugins() 的插件 if (this.skipPluginIds.has(pluginId)) return false; const { key, enableBy } = this.plugins[pluginId]; // 手动设置为 false if (this.userConfig[key] === false) return false; // 配置开启 if (enableBy === this.EnableBy.config && !(key in this.userConfig)) { return false; } // 函数自定义开启 if (typeof enableBy === 'function') { return enableBy(); } // 注册开启 return true; } hasPlugins(pluginIds: string[]) { return pluginIds.every((pluginId) => { const plugin = this.plugins[pluginId]; return plugin && !plugin.isPreset && this.isPluginEnable(pluginId); }); } hasPresets(presetIds: string[]) { return presetIds.every((presetId) => { const preset = this.plugins[presetId]; return preset && preset.isPreset && this.isPluginEnable(presetId); }); } async applyPlugins(opts: { key: string; type: ApplyPluginsType; initialValue?: any; args?: any; }) { const hooks = this.hooks[opts.key] || []; switch (opts.type) { case ApplyPluginsType.add: if ('initialValue' in opts) { assert( Array.isArray(opts.initialValue), `applyPlugins failed, opts.initialValue must be Array if opts.type is add.`, ); } const tAdd = new AsyncSeriesWaterfallHook(['memo']); for (const hook of hooks) { if (!this.isPluginEnable(hook.pluginId!)) { continue; } tAdd.tapPromise( { name: hook.pluginId!, stage: hook.stage || 0, // @ts-ignore before: hook.before, }, async (memo: any[]) => { const items = await hook.fn(opts.args); return memo.concat(items); }, ); } return await tAdd.promise(opts.initialValue || []); case ApplyPluginsType.modify: const tModify = new AsyncSeriesWaterfallHook(['memo']); for (const hook of hooks) { if (!this.isPluginEnable(hook.pluginId!)) { continue; } tModify.tapPromise( { name: hook.pluginId!, stage: hook.stage || 0, // @ts-ignore before: hook.before, }, async (memo: any) => { return await hook.fn(memo, opts.args); }, ); } return await tModify.promise(opts.initialValue); case ApplyPluginsType.event: const tEvent = new AsyncSeriesWaterfallHook(['_']); for (const hook of hooks) { if (!this.isPluginEnable(hook.pluginId!)) { continue; } tEvent.tapPromise( { name: hook.pluginId!, stage: hook.stage || 0, // @ts-ignore before: hook.before, }, async () => { await hook.fn(opts.args); }, ); } return await tEvent.promise(); default: throw new Error( `applyPlugin failed, type is not defined or is not matched, got ${opts.type}.`, ); } } async run({ name, args = {} }: { name: string; args?: any }) { args._ = args._ || []; // shift the command itself if (args._[0] === name) args._.shift(); this.args = args; await this.init(); logger.debug('plugins:'); logger.debug(this.plugins); this.setStage(ServiceStage.run); await this.applyPlugins({ key: 'onStart', type: ApplyPluginsType.event, args: { name, args, }, }); return this.runCommand({ name, args }); } async runCommand({ name, args = {} }: { name: string; args?: any }) { assert(this.stage >= ServiceStage.init, `service is not initialized.`); args._ = args._ || []; // shift the command itself if (args._[0] === name) args._.shift(); const command = typeof this.commands[name] === 'string' ? this.commands[this.commands[name] as string] : this.commands[name]; assert(command, `run command failed, command ${name} does not exists.`); const { fn } = command as ICommand; return fn({ args }); } }
the_stack
import { Component, OnInit, OnDestroy, ViewChild, trigger, state, style, transition, animate } from '@angular/core'; import { environment } from './../../../../../../environments/environment'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import * as _ from 'lodash'; import * as frLocale from 'date-fns/locale/en'; import {WorkflowService} from '../../../../../core/services/workflow.service'; import * as moment from 'moment'; import { UtilsService } from '../../../../../shared/services/utils.service'; import { LoggerService } from '../../../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../../../shared/services/error-handling.service'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/pairwise'; import { RouterUtilityService } from '../../../../../shared/services/router-utility.service'; import { AdminService } from '../../../../services/all-admin.service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { SelectComponent } from 'ng2-select'; import { UploadFileService } from '../../../../services/upload-file-service'; import { DatepickerOptions } from 'ng2-datepicker'; @Component({ selector: 'app-admin-create-sticky-exceptions', templateUrl: './create-sticky-exceptions.component.html', styleUrls: ['./create-sticky-exceptions.component.css'], animations: [ trigger('slideInOut', [ state('in', style({ transform: 'translate3d(0, 0, 0)' })), state('out', style({ transform: 'translate3d(100%, 0, 0)' })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]), trigger('fadeInOut', [ state('open', style({ 'z-index': 2, opacity: 1 })), state('closed', style({ 'z-index': -1, opacity: 0 })), transition('open <=> closed', animate('500ms')), ]) ], providers: [ LoggerService, ErrorHandlingService, UploadFileService, AdminService ] }) export class CreateStickyExceptionsComponent implements OnInit, OnDestroy { @ViewChild('targetTypeRuleSelect') targetTypeRuleSelectComponent: SelectComponent; pageTitle: String = ''; breadcrumbArray: any = ['Admin', 'Sticky Exceptions']; breadcrumbLinks: any = ['policies', 'sticky-exceptions']; breadcrumbPresent: any; outerArr: any = []; filters: any = []; date = new Date(); dateToday = this.date.getFullYear() + '-' + (this.date.getMonth() + 1) + '-' + this.date.getDate(); exceptionDetailsForm: any = { name: '', reason: '', expiry: this.dateToday, assetGroup: [] } isExceptionNameValid: any = -1; allAssetGroupNames: Array<string>; selectedAssetGroup: string; dataForm: FormGroup; user: FormGroup; assetLoaderTitle: string = ''; assetLoader: boolean = false; assetLoaderFailure: boolean = false; attributeName: any = []; attributeValue: string = ''; selectedRules: any = []; allOptionalRuleParams: any = []; isRuleInvokeFailed: boolean = false; isRuleInvokeSuccess: boolean = false; ruleContentLoader: boolean = true; ruleLoader: boolean = false; invocationId: String = ''; paginatorSize: number = 25; isLastPage: boolean; isFirstPage: boolean; totalPages: number; pageNumber: number = 0; showLoader: boolean = true; errorMessage: any; searchTerm: String = ''; hideContent: boolean = false; pageContent: any = [ { title: 'Enter Exception Details', hide: false }, { title: 'Exempt Target Types', hide: true } ]; options: DatepickerOptions = { minYear: this.date.getFullYear(), maxYear: 2030, displayFormat: 'DD/MM/YYYY', barTitleFormat: 'DD/MM/YYYY', firstCalendarDay: 0, locale: frLocale }; isCreate: boolean = false; successTitle: String = ''; failedTitle: string = ''; successSubTitle: String = ''; isAssetGroupExceptionCreationUpdationFailed: boolean = false; isAssetGroupExceptionCreationUpdationSuccess: boolean = false; loadingContent: string = ''; assetGroupExceptionLoader: boolean = false; highlightName: string = ''; availChoosedItems: any = {}; availChoosedSelectedItems = {}; availChoosedItemsCount = 0; selectChoosedItems: any = {}; selectChoosedSelectedItems = {}; selectChoosedItemsCount = 0; availableItems: any = []; selectedItems: any = []; availableItemsBackUp: any = []; selectedItemsBackUp: any = []; availableItemsCopy: any = []; selectedItemsCopy: any = []; searchSelectedDomainTerms: any = ''; searchAvailableDomainTerms = ''; // Target Details // availTdChoosedItems: any = {}; availTdChoosedSelectedItems = {}; availTdChoosedItemsCount = 0; selectTdChoosedItems: any = {}; selectTdChoosedSelectedItems = {}; selectTdChoosedItemsCount = 0; availableTdItems: any = []; selectedTdItems: any = []; availableTdItemsBackUp: any = []; selectedTdItemsBackUp: any = []; availableTdItemsCopy: any = []; selectedTdItemsCopy: any = []; searchSelectedTargetTerms: any = ''; searchAvailableTargetTerms = ''; stepIndex: number = 0; stepTitle: any = this.pageContent[this.stepIndex].title; allAttributeDetails: any = []; allAttributeDetailsCopy: any = []; filterText: any = {}; errorValue: number = 0; urlID: string = ''; exceptionName: string = ''; FullQueryParams: any; queryParamsWithoutFilter: any; urlToRedirect: any = ''; mandatory: any; public labels: any; private previousUrl: any = ''; private pageLevel = 0; public backButtonRequired; private routeSubscription: Subscription; private getKeywords: Subscription; private previousUrlSubscription: Subscription; private downloadSubscription: Subscription; constructor( private router: Router, private activatedRoute: ActivatedRoute, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private workflowService: WorkflowService, private routerUtilityService: RouterUtilityService, private adminService: AdminService ) { this.routerParam(); this.updateComponent(); } ngOnInit() { this.urlToRedirect = this.router.routerState.snapshot.url; this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently( this.pageLevel ); this.expiryDate = moment(new Date()).format('DD/MM/YYYY'); this.user = new FormGroup({ name: new FormControl(moment('2018-07-14', 'YYYY-MM-DD').toDate(), [Validators.required, Validators.minLength(1)]) }); } state: string = 'closed'; menuState: string = 'out'; closeAttributeConfigure() { this.state = 'closed'; this.menuState = 'out'; this.searchAttribute(); } selectedIndex: number = -1; selectedAllRules: Array<string> = []; openAttributeConfigure(attributeDetail, index) { this.attributeValue = ''; this.attributeName = []; this.state = 'open'; this.menuState = 'in'; this.selectedAllRules = attributeDetail.allRules; this.selectedRules = attributeDetail.rules; this.selectedIndex = index; attributeDetail.rules; if(attributeDetail.allRules.length === 0) { this.targetTypeRuleSelectComponent.placeholder = 'No Rules Available'; } else { this.targetTypeRuleSelectComponent.items = attributeDetail.allRules; this.targetTypeRuleSelectComponent.placeholder = 'Select Rule Name'; } } addAttributes(attributeName, attributeValue) { let ruleDetails = _.find(this.allAttributeDetails[this.selectedIndex].allRules, { id: attributeName[0].id }); this.allAttributeDetails[this.selectedIndex].rules.push(ruleDetails); let itemIndex = this.allAttributeDetails[this.selectedIndex].allRules.indexOf(ruleDetails); if (itemIndex !== -1) { this.allAttributeDetails[this.selectedIndex].allRules.splice(itemIndex, 1); this.selectedAllRules = this.allAttributeDetails[this.selectedIndex].allRules; this.targetTypeRuleSelectComponent.items = this.selectedAllRules; } this.attributeValue = ''; this.attributeName = []; if(this.allAttributeDetails[this.selectedIndex].allRules.length === 0) { this.targetTypeRuleSelectComponent.placeholder = 'No Rules Available'; } else { this.targetTypeRuleSelectComponent.placeholder = 'Select Rule Name'; } } deleteAttributes(attributeName, itemIndex) { let ruleDetails = this.allAttributeDetails[this.selectedIndex].rules[itemIndex]; this.allAttributeDetails[this.selectedIndex].rules.splice(itemIndex, 1); if (itemIndex !== -1) { this.allAttributeDetails[this.selectedIndex].allRules.push(ruleDetails); this.selectedAllRules = this.allAttributeDetails[this.selectedIndex].allRules; this.targetTypeRuleSelectComponent.items = this.selectedAllRules; } if(this.allAttributeDetails[this.selectedIndex].allRules.length === 0) { this.targetTypeRuleSelectComponent.placeholder = 'No Rules Available'; } else { this.targetTypeRuleSelectComponent.placeholder = 'Select Rule Name'; } } nextPage() { try { if (!this.isLastPage) { this.pageNumber++; this.showLoader = true; } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } prevPage() { try { if (!this.isFirstPage) { this.pageNumber--; this.showLoader = true; } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } exceptionNames: any = []; isExceptionNameAvailable(exceptionNameKeyword) { if (exceptionNameKeyword.trim().length == 0) { this.isExceptionNameValid = -1; } else { let isKeywordExits = this.exceptionNames.findIndex(item => exceptionNameKeyword.trim().toLowerCase() === item.trim().toLowerCase()); if (isKeywordExits === -1) { this.isExceptionNameValid = 1; } else { this.isExceptionNameValid = 0; } } } getAllExceptionNames() { const url = environment.getAllStickyExceptionNames.url; const method = environment.getAllStickyExceptionNames.method; this.adminService.executeHttpAction(url, method, {}, {}).subscribe(reponse => { this.pageContent[0].hide = false; this.exceptionNames = reponse[0]; this.assetLoader = false; }, error => { this.assetLoaderFailure = true; this.allAssetGroupNames = []; this.errorMessage = 'apiResponseError'; this.assetLoader = false; this.showLoader = false; }) } getAllAssetGroupNames() { this.assetLoader = true; this.pageContent[0].hide = true; this.assetLoaderFailure = false; var url = environment.assetGroupNames.url; var method = environment.assetGroupNames.method; this.adminService.executeHttpAction(url, method, {}, {}).subscribe(reponse => { this.allAssetGroupNames = reponse[0]; this.getAllExceptionNames(); }, error => { this.assetLoaderFailure = true; this.allAssetGroupNames = []; this.errorMessage = 'apiResponseError'; this.assetLoader = false; this.showLoader = false; }); } stickyExceptionDetails: any; getAllStickyExceptionDetails(exceptionName) { this.assetLoaderFailure = false; this.assetLoader = true; this.pageContent[0].hide = true; this.assetLoaderTitle = this.exceptionName; var url = environment.getAllStickyExceptionDetails.url; var method = environment.getAllStickyExceptionDetails.method; this.adminService.executeHttpAction(url, method, {}, {exceptionName: exceptionName, dataSource: 'aws'}).subscribe(reponse => { this.assetLoader = false; this.pageContent[0].hide = false; this.stickyExceptionDetails = reponse[0]; this.exceptionDetailsForm = { name: reponse[0].exceptionName, reason: reponse[0].exceptionReason, expiry: moment(reponse[0].expiryDate).format('YYYY-MM-DD') , assetGroup: [{text: reponse[0].groupName, id: reponse[0].groupName}] } this.selectedAssetGroup = reponse[0].groupName; }, error => { this.assetLoaderFailure = true; this.allAssetGroupNames = []; this.errorMessage = 'apiResponseError'; this.assetLoader = false; this.showLoader = false; }); } private collectTargetTypes() { this.assetLoaderFailure = false; this.assetLoader = true; this.assetLoaderTitle = 'Target Types'; this.pageContent[0].hide = true; let url = environment.getTargetTypesByAssetGroupName.url; let method = environment.getTargetTypesByAssetGroupName.method; let assetGroupName = ''; if (this.exceptionDetailsForm.assetGroup.length > 0) { assetGroupName = this.exceptionDetailsForm.assetGroup[0].text; } this.adminService.executeHttpAction(url, method, {}, { assetGroupName: assetGroupName }).subscribe(reponse => { this.assetLoader = false; this.showLoader = false; if (reponse.length > 0) { reponse[0].sort(function(a, b){ return b.rules.length - a.rules.length; }); reponse[0] = _.orderBy(reponse[0], ['added'], ['desc']); this.allAttributeDetails = reponse[0]; this.allAttributeDetailsCopy = reponse[0]; this.goToNextStep(); } }, error => { this.assetLoader = false; this.assetLoaderFailure = true; this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; }); } nextStep() { if (this.stepIndex + 1 === 1) { if(this.isCreate) { this.collectTargetTypes(); } else { let selectedAssetGroup = this.exceptionDetailsForm.assetGroup[0].text; if(this.stickyExceptionDetails.groupName === selectedAssetGroup) { this.allAttributeDetails = this.stickyExceptionDetails.targetTypes; this.allAttributeDetailsCopy = _.cloneDeep(this.allAttributeDetails); this.goToNextStep(); } else { this.collectTargetTypes(); } } this.searchAttribute(); } else { this.goToNextStep(); } } goToNextStep() { this.pageContent[this.stepIndex].hide = true; this.stepIndex++; this.stepTitle = this.pageContent[this.stepIndex].title; this.pageContent[this.stepIndex].hide = false; } prevStep() { this.pageContent[this.stepIndex].hide = true; this.stepIndex--; this.stepTitle = this.pageContent[this.stepIndex].title; this.pageContent[this.stepIndex].hide = false; } expiryDate: any; getDateData(date: any): any { this.expiryDate = moment(date).format('DD/MM/YYYY'); } closeAssetErrorMessage() { this.assetLoaderFailure = false; this.assetLoader = false; this.pageContent[this.stepIndex].hide = false; } navigateToCreateAssetGroup() { try { this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root); this.router.navigate(['../create-asset-groups'], { relativeTo: this.activatedRoute, queryParamsHandling: 'merge', queryParams: { } }); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } createException(exceptionFormDetails) { let exceptionDetails = this.marshallingCreateExceptionData(exceptionFormDetails); this.loadingContent = 'creation'; this.successTitle = 'Exception Created'; this.highlightName = exceptionFormDetails.name; this.hideContent = true; this.assetGroupExceptionLoader = true; this.isAssetGroupExceptionCreationUpdationFailed = false; this.isAssetGroupExceptionCreationUpdationSuccess = false; //this.selectedAssetGroupExceptionName = assetGroupExceptionDetails.assetGroupExceptionName; //this.highlightName = assetGroupExceptionDetails.assetGroupExceptionName; let url = environment.configureStickyException.url; let method = environment.configureStickyException.method; this.adminService.executeHttpAction(url, method, exceptionDetails, {}).subscribe(reponse => { this.successTitle = 'Exception Created'; this.isAssetGroupExceptionCreationUpdationSuccess = true; this.assetGroupExceptionLoader = false; /*this.assetGroupExceptions = { assetGroupExceptionName: '', description: '', writePermission: false };*/ }, error => { this.failedTitle = 'Creation Failed'; this.assetGroupExceptionLoader = false; this.isAssetGroupExceptionCreationUpdationFailed = true; }) } deleteException(exceptionDetails) { this.loadingContent = 'deletion'; this.hideContent = true; this.highlightName = ''; this.assetGroupExceptionLoader = true; this.isAssetGroupExceptionCreationUpdationFailed = false; this.isAssetGroupExceptionCreationUpdationSuccess = false; //this.selectedAssetGroupExceptionName = assetGroupExceptionDetails.assetGroupExceptionName; //this.highlightName = assetGroupExceptionDetails.assetGroupExceptionName; let url = environment.deleteStickyException.url; let method = environment.deleteStickyException.method; this.adminService.executeHttpAction(url, method, exceptionDetails, {}).subscribe(reponse => { this.successTitle = 'Exception Deleted'; this.isAssetGroupExceptionCreationUpdationSuccess = true; this.assetGroupExceptionLoader = false; /*this.assetGroupExceptions = { assetGroupExceptionName: '', description: '', writePermission: false };*/ }, error => { this.failedTitle = 'Deletion Failed'; this.assetGroupExceptionLoader = false; this.isAssetGroupExceptionCreationUpdationFailed = true; }) } updateException(exceptionFormDetails) { let exceptionDetails = this.marshallingCreateExceptionData(exceptionFormDetails); this.loadingContent = 'updation'; this.successTitle = 'Exception Updated'; this.highlightName = exceptionFormDetails.name; this.hideContent = true; this.assetGroupExceptionLoader = true; this.isAssetGroupExceptionCreationUpdationFailed = false; this.isAssetGroupExceptionCreationUpdationSuccess = false; //this.selectedAssetGroupExceptionName = assetGroupExceptionDetails.assetGroupExceptionName; //this.highlightName = assetGroupExceptionDetails.assetGroupExceptionName; let url = environment.configureStickyException.url; let method = environment.configureStickyException.method; this.adminService.executeHttpAction(url, method, exceptionDetails, {}).subscribe(reponse => { this.successTitle = 'Exception Updated'; this.isAssetGroupExceptionCreationUpdationSuccess = true; this.assetGroupExceptionLoader = false; /*this.assetGroupExceptions = { assetGroupExceptionName: '', description: '', writePermission: false };*/ }, error => { this.failedTitle = 'Updation Failed'; this.assetGroupExceptionLoader = false; this.isAssetGroupExceptionCreationUpdationFailed = true; }) } marshallingCreateExceptionData(exceptionFormDetails) { let exceptionDetails = { exceptionName: exceptionFormDetails.name, exceptionReason: exceptionFormDetails.reason, expiryDate: this.expiryDate, assetGroup: exceptionFormDetails.assetGroup[0].text, dataSource: 'aws', targetTypes: this.allAttributeDetails } return exceptionDetails; } closeErrorMessage() { this.isRuleInvokeFailed = false; this.hideContent = false; } searchAttribute() { let term = this.searchTerm; this.allAttributeDetails = this.allAttributeDetailsCopy.filter(function (tag) { return tag.targetName.indexOf(term) >= 0; }); this.allAttributeDetails.sort(function(a, b){ return b.rules.length - a.rules.length; }); this.allAttributeDetails = _.orderBy(this.allAttributeDetails, ['added'], ['desc']); } getData() { //this.getAllPolicyIds(); this.allAttributeDetails = []; this.allAttributeDetailsCopy = []; } /* * This function gets the urlparameter and queryObj *based on that different apis are being hit with different queryparams */ routerParam() { try { // this.filterText saves the queryparam let currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root); if (currentQueryParams) { this.FullQueryParams = currentQueryParams; this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams)); this.exceptionName = this.queryParamsWithoutFilter.exceptionName; delete this.queryParamsWithoutFilter['filter']; if (this.exceptionName) { this.assetLoaderTitle = this.exceptionName; this.pageTitle = 'Edit Sticky Exceptions'; this.breadcrumbPresent = 'Edit Sticky Exceptions'; this.isCreate = false; this.getAllStickyExceptionDetails(this.exceptionName); } else { this.assetLoaderTitle = 'Asset Groups'; this.pageTitle = 'Create Sticky Exceptions'; this.breadcrumbPresent = 'Create Sticky Exceptions'; this.isCreate = true; this.getAllAssetGroupNames(); } /** * The below code is added to get URLparameter and queryparameter * when the page loads ,only then this function runs and hits the api with the * filterText obj processed through processFilterObj function */ this.filterText = this.utils.processFilterObj( this.FullQueryParams ); this.urlID = this.FullQueryParams.TypeAsset; //check for mandatory filters. if (this.FullQueryParams.mandatory) { this.mandatory = this.FullQueryParams.mandatory; } } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.showLoader = true; this.errorValue = 0; this.getData(); } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } ngOnDestroy() { try { if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.previousUrlSubscription) { this.previousUrlSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
import { Loki } from "../../src/loki"; import { MemoryStorage } from "../../../memory-storage/src/memory_storage"; import { Collection } from "../../src/collection"; import { Doc } from "../../../common/types"; import { LokiOperatorPackageMap } from "../../src/operator_packages"; describe("dynamicviews", () => { interface User { name: string; owner?: string; maker?: string; age?: number; lang?: string; } let testRecords: User[]; let db: Loki; let users: Collection<User>; let jonas: Doc<User>; beforeEach(() => { testRecords = [ {name: "mjolnir", owner: "thor", maker: "dwarves"}, {name: "gungnir", owner: "odin", maker: "elves"}, {name: "tyrfing", owner: "Svafrlami", maker: "dwarves"}, {name: "draupnir", owner: "odin", maker: "elves"} ]; db = new Loki("test.json"); users = db.addCollection<User>("user"); users.insert({ name: "dave", age: 25, lang: "English" }); users.insert({ name: "joe", age: 39, lang: "Italian" }); jonas = users.insert({ name: "jonas", age: 30, lang: "Swedish" }); }); function docCompare(a: Doc<User>, b: Doc<User>) { if (a.$loki < b.$loki) return -1; if (a.$loki > b.$loki) return 1; return 0; } describe("test empty filter across changes", () => { it("works", () => { const db = new Loki("dvtest"); const items = db.addCollection<User>("users"); items.insert(testRecords); const dv = items.addDynamicView("view"); // with no filter, results should be all documents let results = dv.data(); expect(results.length).toBe(4); // find and update a document which will notify view to re-evaluate const gungnir = items.findOne({"name": "gungnir"}); expect(gungnir.owner).toBe("odin"); gungnir.maker = "dvalin"; items.update(gungnir); results = dv.data(); expect(results.length).toBe(4); }); }); describe("dynamic view rematerialize works as expected", () => { it("works", () => { const db = new Loki("dvtest"); const items = db.addCollection<User>("users"); items.insert(testRecords); const dv = items.addDynamicView("view"); dv.applyFind({"owner": "odin"}); dv.applyWhere((obj: User) => obj.maker === "elves"); expect(dv.data().length).toEqual(2); expect(dv["_filterPipeline"].length).toEqual(2); dv["_rematerialize"]({removeWhereFilters: true}); expect(dv.data().length).toEqual(2); expect(dv["_filterPipeline"].length).toEqual(1); }); }); describe("dynamic view toJSON does not circularly reference", () => { it("works", () => { const db = new Loki("dvtest"); const items = db.addCollection<User>("users"); items.insert(testRecords); const dv = items.addDynamicView("view"); const obj = dv.toJSON(); expect(obj["_collection"]).toEqual(undefined); }); }); describe("dynamic view removeFilters works as expected", () => { it("works", () => { const db = new Loki("dvtest"); const items = db.addCollection<User>("users"); items.insert(testRecords); const dv = items.addDynamicView("ownr"); dv.applyFind({"owner": "odin"}); dv.applyWhere((obj: User) => obj.maker === "elves"); expect(dv["_filterPipeline"].length).toEqual(2); expect(dv.data().length).toEqual(2); dv.removeFilters(); expect(dv["_filterPipeline"].length).toEqual(0); expect(dv.count()).toEqual(4); }); }); describe("removeDynamicView works correctly", () => { it("works", () => { const db = new Loki("dvtest"); const items = db.addCollection<User>("users"); items.insert(testRecords); const dv = items.addDynamicView("ownr", {persistent: true}); dv.applyFind({"owner": "odin"}); dv.applyWhere((obj: User) => obj.maker === "elves"); expect(items["_dynamicViews"].length).toEqual(1); items.removeDynamicView("ownr"); expect(items["_dynamicViews"].length).toEqual(0); }); }); describe("stepEvaluateDocument", () => { it("works", () => { const view = users.addDynamicView("test"); const query = { "age": { "$gt": 24 } }; view.applyFind(query); // churn evaluateDocuments() to make sure it works right jonas.age = 23; users.update(jonas); // evaluate documents expect(view.data().length).toEqual(users.count() - 1); jonas.age = 30; users.update(jonas); expect(view.data().length).toEqual(users.count()); jonas.age = 23; users.update(jonas); expect(view.data().length).toEqual(users.count() - 1); jonas.age = 30; users.update(jonas); expect(view.data().length).toEqual(users.count()); // assert set equality of docArrays irrelevant of sort/sequence const result1 = users.find(query).sort(docCompare); const result2 = view.data().sort(docCompare); result1.forEach((obj: Doc<User>) => { delete obj.meta; }); result2.forEach((obj: Doc<User>) => { delete obj.meta; }); expect(result1).toEqual(result2, "Result data Equality"); expect(view["_resultSet"]).toEqual(view["_resultSet"].copy(), "View data equality"); expect(view["_resultSet"] === view["_resultSet"].copy()).toBeFalsy("View data copy strict equality"); return view; }); }); describe("stepDynamicViewPersistence", () => { it("works 1", () => { const query = { "age": { "$gt": 24 } }; // set up a persistent dynamic view with sort const pview = users.addDynamicView("test2", { persistent: true }); pview.applyFind(query); pview.applySimpleSort("age"); // the dynamic view depends on an internal ResultSet // the persistent dynamic view also depends on an internal resultdata data array // filteredrows should be applied immediately to ResultSet will be lazily built into resultdata later when data() is called expect(pview["_resultSet"]._filteredRows.length).toEqual(3, "dynamic view initialization 1"); expect(pview["_resultData"].length).toEqual(0, "dynamic view initialization 2"); // compare how many documents are in results before adding new ones const pviewResultsetLenBefore = pview["_resultSet"]._filteredRows.length; users.insert({ name: "abc", age: 21, lang: "English" }); users.insert({ name: "def", age: 25, lang: "English" }); // now see how many are in (without rebuilding persistent view) const pviewResultsetLenAfter = pview["_resultSet"]._filteredRows.length; // only one document should have been added to ResultSet (1 was filtered out) expect(pviewResultsetLenBefore + 1).toEqual(pviewResultsetLenAfter, "dv ResultSet is valid"); // Test sorting and lazy build of resultdata // retain copy of internal ResultSet's filteredrows before lazy sort const frcopy = pview["_resultSet"]._filteredRows.slice(); pview.data(); // now make a copy of internal result's filteredrows after lazy sort const frcopy2 = pview["_resultSet"]._filteredRows.slice(); // verify filteredrows logically matches resultdata (irrelevant of sort) expect(frcopy2.length).not.toBe(0); for (let idxFR = 0; idxFR < frcopy2.length; idxFR++) { expect(pview["_resultData"][idxFR]).not.toBe(undefined); expect(pview["_resultData"][idxFR]).toEqual(pview["_collection"]._data[frcopy2[idxFR]], "dynamic view ResultSet/resultdata consistency"); } // now verify they are not exactly equal (verify sort moved stuff) expect(frcopy).not.toEqual(frcopy2, "dynamic view sort"); }); it("works 2", () => { interface CR { index: string; a: number; } const test = db.addCollection<CR>("nodupes", { rangedIndexes: { index: {} } }); const item = test.insert({ index: "key", a: 1 }); let results = test.find({ index: "key" }); expect(results.length).toEqual(1, "one result exists"); expect(results[0].a).toEqual(1, "the correct result is returned"); item.a = 2; test.update(item); results = test.find({ index: "key" }); expect(results.length).toEqual(1, "one result exists"); expect(results[0].a).toEqual(2, "the correct result is returned"); }); it("works 3", function testEmptyTableWithIndex() { const itc = db.addCollection<any>("test", { rangedIndexes: { testindex: {} } }); const resultsNoIndex = itc.find({ "testid": 2 }); expect(resultsNoIndex.length).toEqual(0); const resultsWithIndex = itc.find({ "testindex": 4 }); //it("no results found", () => { expect(resultsWithIndex.length).toEqual(0); //}); }); it("works 4", (done) => { // mock persistence by using memory storage const mem = new MemoryStorage(); const db = new Loki("testCollections"); db.initializePersistence({adapter: mem}) .then(() => { expect(db.filename).toEqual("testCollections"); const t = db.addCollection<any>("test1", { transactional: true }); db.addCollection("test2"); // Throw error on wrong remove. expect(() => t.remove("foo")).toThrowErrorOfType("Error"); // Throw error on non-synced doc expect(() => t.remove({ name: "joe" })).toThrowErrorOfType("Error"); expect(db.listCollections().length).toEqual(2); t.clear(); const users = [{ name: "joe" }, { name: "dave" }]; t.insert(users); expect(2).toEqual(t.count()); t.remove(users); expect(0).toEqual(t.count()); class TestError implements Error { public name = "TestError"; public message = "TestErrorMessage"; } db["_autosaveEnable"](); db.on("close", () => { throw new TestError(); }); db.close().then(() => done.fail, done); }); }); }); it("applySortCriteria", () => { const db = new Loki("dvtest.db"); const coll = db.addCollection<User>("any"); coll.insert([{ name: "mjolnir", owner: "odin", maker: "dwarves", }, { name: "tyrfing", owner: "thor", maker: "dwarves", }, { name: "gungnir", owner: "odin", maker: "elves", }, { name: "draupnir", owner: "thor", maker: "elves", }]); const dv = coll.addDynamicView("test"); let result = dv.applySortCriteria(["owner", "maker"]).data(); expect(result).toEqual(dv.applySortCriteria([["owner", false], ["maker", false]]).data()); expect(result.length).toBe(4); expect(result[0].name).toBe("mjolnir"); expect(result[1].name).toBe("gungnir"); expect(result[2].name).toBe("tyrfing"); expect(result[3].name).toBe("draupnir"); result = dv.applySortCriteria([["owner", false], ["maker", true]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("gungnir"); expect(result[1].name).toBe("mjolnir"); expect(result[2].name).toBe("draupnir"); expect(result[3].name).toBe("tyrfing"); result = dv.applySortCriteria([["owner", true], ["maker", false]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("tyrfing"); expect(result[1].name).toBe("draupnir"); expect(result[2].name).toBe("mjolnir"); expect(result[3].name).toBe("gungnir"); result = dv.applySortCriteria([["owner", true], ["maker", true]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("draupnir"); expect(result[1].name).toBe("tyrfing"); expect(result[2].name).toBe("gungnir"); expect(result[3].name).toBe("mjolnir"); result = dv.applySortCriteria(["maker", "owner"]).data(); expect(result).toEqual(dv.applySortCriteria([["maker", false], ["owner", false]]).data()); expect(result.length).toBe(4); expect(result[0].name).toBe("mjolnir"); expect(result[1].name).toBe("tyrfing"); expect(result[2].name).toBe("gungnir"); expect(result[3].name).toBe("draupnir"); result = dv.applySortCriteria([["maker", false], ["owner", true]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("tyrfing"); expect(result[1].name).toBe("mjolnir"); expect(result[2].name).toBe("draupnir"); expect(result[3].name).toBe("gungnir"); result = dv.applySortCriteria([["maker", true], ["owner", false]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("gungnir"); expect(result[1].name).toBe("draupnir"); expect(result[2].name).toBe("mjolnir"); expect(result[3].name).toBe("tyrfing"); result = dv.applySortCriteria([["maker", true], ["owner", true]]).data(); expect(result.length).toBe(4); expect(result[0].name).toBe("draupnir"); expect(result[1].name).toBe("gungnir"); expect(result[2].name).toBe("tyrfing"); expect(result[3].name).toBe("mjolnir"); }); describe("dynamic view simplesort options work correctly", () => { it("works", function () { const db = new Loki("dvtest.db"); let coll = db.addCollection<{ a: number, b: number }>("colltest", { rangedIndexes: { a: {}, // uses default 'js' comparator b: {} // uses default 'js' comparator } }); // add basic dv with filter on a and basic simplesort on b let dv = coll.addDynamicView("dvtest"); dv.applyFind({a: {$lte: 20}}); dv.applySimpleSort("b"); // data only needs to be inserted once since we are leaving collection intact while // building up and tearing down dynamic views within it coll.insert([{a: 1, b: 11}, {a: 2, b: 9}, {a: 8, b: 3}, {a: 6, b: 7}, {a: 2, b: 14}, {a: 22, b: 1}]); // test whether results are valid let results = dv.data(); expect(results.length).toBe(5); for (let idx = 0; idx < results.length - 1; idx++) { expect(LokiOperatorPackageMap["js"].$lte(results[idx]["b"], results[idx + 1]["b"])); } // remove dynamic view coll.removeDynamicView("dvtest"); }); }); });
the_stack
import { mdiAlertCircle, mdiCircle, mdiCircleOutline, mdiProgressClock, mdiProgressWrench, mdiRecordCircleOutline, } from "@mdi/js"; import { css, CSSResultGroup, html, LitElement, PropertyValues, TemplateResult, } from "lit"; import { customElement, property } from "lit/decorators"; import { ifDefined } from "lit/directives/if-defined"; import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time"; import { relativeTime } from "../../common/datetime/relative_time"; import { fireEvent } from "../../common/dom/fire_event"; import { toggleAttribute } from "../../common/dom/toggle_attribute"; import { LogbookEntry } from "../../data/logbook"; import { ChooseAction, ChooseActionChoice, getActionType, } from "../../data/script"; import { describeAction } from "../../data/script_i18n"; import { AutomationTraceExtended, ChooseActionTraceStep, getDataFromPath, isTriggerPath, TriggerTraceStep, } from "../../data/trace"; import { HomeAssistant } from "../../types"; import "./ha-timeline"; import type { HaTimeline } from "./ha-timeline"; const LOGBOOK_ENTRIES_BEFORE_FOLD = 2; /* eslint max-classes-per-file: "off" */ // Report time entry when more than this time has passed const SIGNIFICANT_TIME_CHANGE = 1000; // 1 seconds const isSignificantTimeChange = (a: Date, b: Date) => Math.abs(b.getTime() - a.getTime()) > SIGNIFICANT_TIME_CHANGE; class RenderedTimeTracker { private lastReportedTime: Date; constructor( private hass: HomeAssistant, private entries: TemplateResult[], trace: AutomationTraceExtended ) { this.lastReportedTime = new Date(trace.timestamp.start); } setLastReportedTime(date: Date) { this.lastReportedTime = date; } renderTime(from: Date, to: Date): void { this.entries.push(html` <ha-timeline label> ${relativeTime(from, this.hass.locale, to, false)} later </ha-timeline> `); this.lastReportedTime = to; } maybeRenderTime(timestamp: Date): boolean { if (!isSignificantTimeChange(timestamp, this.lastReportedTime)) { this.lastReportedTime = timestamp; return false; } this.renderTime(this.lastReportedTime, timestamp); return true; } } class LogbookRenderer { private curIndex: number; private pendingItems: Array<[Date, LogbookEntry]> = []; constructor( private entries: TemplateResult[], private timeTracker: RenderedTimeTracker, private logbookEntries: LogbookEntry[] ) { // Skip the "automation got triggered item" this.curIndex = logbookEntries.length > 0 && logbookEntries[0].domain === "automation" ? 1 : 0; } get curItem() { return this.logbookEntries[this.curIndex]; } get hasNext() { return this.curIndex !== this.logbookEntries.length; } maybeRenderItem() { const logbookEntry = this.curItem; this.curIndex++; const entryDate = new Date(logbookEntry.when); if (this.pendingItems.length === 0) { this.pendingItems.push([entryDate, logbookEntry]); return; } const previousEntryDate = this.pendingItems[this.pendingItems.length - 1][0]; // If logbook entry is too long after the last one, // add a time passed label if (isSignificantTimeChange(previousEntryDate, entryDate)) { this._renderLogbookEntries(); this.timeTracker.renderTime(previousEntryDate, entryDate); } this.pendingItems.push([entryDate, logbookEntry]); } flush() { if (this.pendingItems.length > 0) { this._renderLogbookEntries(); } } private _renderLogbookEntries() { this.timeTracker.maybeRenderTime(this.pendingItems[0][0]); const parts: TemplateResult[] = []; let i; for ( i = 0; i < Math.min(this.pendingItems.length, LOGBOOK_ENTRIES_BEFORE_FOLD); i++ ) { parts.push(this._renderLogbookEntryHelper(this.pendingItems[i][1])); } let moreItems: TemplateResult[] | undefined; // If we didn't render all items, push rest into `moreItems` if (i < this.pendingItems.length) { moreItems = []; for (; i < this.pendingItems.length; i++) { moreItems.push(this._renderLogbookEntryHelper(this.pendingItems[i][1])); } } this.entries.push(html` <ha-timeline .icon=${mdiCircleOutline} .moreItems=${moreItems}> ${parts} </ha-timeline> `); // Clear rendered items. this.timeTracker.setLastReportedTime( this.pendingItems[this.pendingItems.length - 1][0] ); this.pendingItems = []; } private _renderLogbookEntryHelper(entry: LogbookEntry) { return html`${entry.name} (${entry.entity_id}) ${entry.message || `turned ${entry.state}`}<br />`; } } class ActionRenderer { private curIndex = 0; private keys: string[]; constructor( private hass: HomeAssistant, private entries: TemplateResult[], private trace: AutomationTraceExtended, private logbookRenderer: LogbookRenderer, private timeTracker: RenderedTimeTracker ) { this.keys = Object.keys(trace.trace); } get curItem() { return this._getItem(this.curIndex); } get hasNext() { return this.curIndex !== this.keys.length; } renderItem() { this.curIndex = this._renderItem(this.curIndex); } private _getItem(index: number) { return this.trace.trace[this.keys[index]]; } private _renderItem( index: number, actionType?: ReturnType<typeof getActionType> ): number { const value = this._getItem(index); if (isTriggerPath(value[0].path)) { return this._handleTrigger(index, value[0] as TriggerTraceStep); } const timestamp = new Date(value[0].timestamp); // Render all logbook items that are in front of this item. while ( this.logbookRenderer.hasNext && new Date(this.logbookRenderer.curItem.when) < timestamp ) { this.logbookRenderer.maybeRenderItem(); } this.logbookRenderer.flush(); this.timeTracker.maybeRenderTime(timestamp); const path = value[0].path; let data; try { data = getDataFromPath(this.trace.config, path); } catch (err: any) { this._renderEntry( path, `Unable to extract path ${path}. Download trace and report as bug` ); return index + 1; } const parts = path.split("/"); const isTopLevel = parts.length === 2; if (!isTopLevel && !actionType) { this._renderEntry(path, path.replace(/\//g, " ")); return index + 1; } if (!actionType) { actionType = getActionType(data); } if (actionType === "choose") { return this._handleChoose(index); } this._renderEntry(path, describeAction(this.hass, data, actionType)); let i = index + 1; for (; i < this.keys.length; i++) { if (this.keys[i].split("/").length === parts.length) { break; } } return i; } private _handleTrigger(index: number, triggerStep: TriggerTraceStep): number { this._renderEntry( triggerStep.path, `Triggered ${ triggerStep.path === "trigger" ? "manually" : `by the ${this.trace.trigger}` } at ${formatDateTimeWithSeconds( new Date(triggerStep.timestamp), this.hass.locale )}`, mdiCircle ); return index + 1; } private _handleChoose(index: number): number { // startLevel: choose root config // +1: 'default // +2: executed sequence // +1: 'choose' // +2: current choice // +3: 'conditions' // +4: evaluated condition // +3: 'sequence' // +4: executed sequence const choosePath = this.keys[index]; const startLevel = choosePath.split("/").length; const chooseTrace = this._getItem(index)[0] as ChooseActionTraceStep; const defaultExecuted = chooseTrace.result?.choice === "default"; const chooseConfig = this._getDataFromPath( this.keys[index] ) as ChooseAction; const name = chooseConfig.alias || "Choose"; if (defaultExecuted) { this._renderEntry(choosePath, `${name}: Default action executed`); } else if (chooseTrace.result) { const choiceNumeric = chooseTrace.result.choice !== "default" ? chooseTrace.result.choice + 1 : undefined; const choiceConfig = this._getDataFromPath( `${this.keys[index]}/choose/${chooseTrace.result.choice}` ) as ChooseActionChoice | undefined; const choiceName = choiceConfig ? `${choiceConfig.alias || `Option ${choiceNumeric}`} executed` : `Error: ${chooseTrace.error}`; this._renderEntry(choosePath, `${name}: ${choiceName}`); } else { this._renderEntry(choosePath, `${name}: No action taken`); } let i; // Skip over conditions for (i = index + 1; i < this.keys.length; i++) { const parts = this.keys[i].split("/"); // We're done if no more sequence in current level if (parts.length <= startLevel) { return i; } // We're going to skip all conditions if ( (defaultExecuted && parts[startLevel + 1] === "default") || (!defaultExecuted && parts[startLevel + 3] === "sequence") ) { break; } } // Render choice while (i < this.keys.length) { const path = this.keys[i]; const parts = path.split("/"); // We're done if no more sequence in current level if (parts.length <= startLevel) { return i; } // We know it's an action sequence, so force the type like that // for rendering. i = this._renderItem(i, getActionType(this._getDataFromPath(path))); } return i; } private _renderEntry( path: string, description: string, icon = mdiRecordCircleOutline ) { this.entries.push(html` <ha-timeline .icon=${icon} data-path=${path}> ${description} </ha-timeline> `); } private _getDataFromPath(path: string) { return getDataFromPath(this.trace.config, path); } } @customElement("hat-trace-timeline") export class HaAutomationTracer extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public trace?: AutomationTraceExtended; @property({ attribute: false }) public logbookEntries?: LogbookEntry[]; @property({ attribute: false }) public selectedPath?: string; @property({ type: Boolean }) public allowPick = false; protected render(): TemplateResult { if (!this.trace) { return html``; } const entries: TemplateResult[] = []; const timeTracker = new RenderedTimeTracker(this.hass, entries, this.trace); const logbookRenderer = new LogbookRenderer( entries, timeTracker, this.logbookEntries || [] ); const actionRenderer = new ActionRenderer( this.hass, entries, this.trace, logbookRenderer, timeTracker ); while (actionRenderer.hasNext) { actionRenderer.renderItem(); } while (logbookRenderer.hasNext) { logbookRenderer.maybeRenderItem(); } logbookRenderer.flush(); // Render footer const renderFinishedAt = () => formatDateTimeWithSeconds( new Date(this.trace!.timestamp.finish!), this.hass.locale ); const renderRuntime = () => `(runtime: ${( (new Date(this.trace!.timestamp.finish!).getTime() - new Date(this.trace!.timestamp.start).getTime()) / 1000 ).toFixed(2)} seconds)`; let entry: { description: TemplateResult | string; icon: string; className?: string; }; if (this.trace.state === "running") { entry = { description: "Still running", icon: mdiProgressClock, }; } else if (this.trace.state === "debugged") { entry = { description: "Debugged", icon: mdiProgressWrench, }; } else if (this.trace.script_execution === "finished") { entry = { description: `Finished at ${renderFinishedAt()} ${renderRuntime()}`, icon: mdiCircle, }; } else if (this.trace.script_execution === "aborted") { entry = { description: `Aborted at ${renderFinishedAt()} ${renderRuntime()}`, icon: mdiAlertCircle, }; } else if (this.trace.script_execution === "cancelled") { entry = { description: `Cancelled at ${renderFinishedAt()} ${renderRuntime()}`, icon: mdiAlertCircle, }; } else { let reason: string; let isError = false; let extra: TemplateResult | undefined; switch (this.trace.script_execution) { case "failed_conditions": reason = "a condition failed"; break; case "failed_single": reason = "only a single execution is allowed"; break; case "failed_max_runs": reason = "maximum number of parallel runs reached"; break; case "error": reason = "an error was encountered"; isError = true; extra = html`<br /><br />${this.trace.error!}`; break; default: reason = `of unknown reason "${this.trace.script_execution}"`; isError = true; } entry = { description: html`Stopped because ${reason} at ${renderFinishedAt()} ${renderRuntime()}${extra || ""}`, icon: mdiAlertCircle, className: isError ? "error" : undefined, }; } entries.push(html` <ha-timeline lastItem .icon=${entry.icon} class=${ifDefined(entry.className)} > ${entry.description} </ha-timeline> `); return html`${entries}`; } protected updated(props: PropertyValues) { super.updated(props); // Pick first path when we load a new trace. if ( this.allowPick && props.has("trace") && this.trace && this.selectedPath && !(this.selectedPath in this.trace.trace) ) { const element = this.shadowRoot!.querySelector<HaTimeline>( "ha-timeline[data-path]" ); if (element) { fireEvent(this, "value-changed", { value: element.dataset.path }); this.selectedPath = element.dataset.path; } } if (props.has("trace") || props.has("selectedPath")) { this.shadowRoot!.querySelectorAll<HaTimeline>( "ha-timeline[data-path]" ).forEach((el) => { toggleAttribute(el, "selected", this.selectedPath === el.dataset.path); if (!this.allowPick || el.tabIndex === 0) { return; } el.tabIndex = 0; const selectEl = () => { this.selectedPath = el.dataset.path; fireEvent(this, "value-changed", { value: el.dataset.path }); }; el.addEventListener("click", selectEl); el.addEventListener("keydown", (ev: KeyboardEvent) => { if (ev.key === "Enter" || ev.key === " ") { selectEl(); } }); el.addEventListener("mouseover", () => { el.raised = true; }); el.addEventListener("mouseout", () => { el.raised = false; }); }); } } static get styles(): CSSResultGroup { return [ css` ha-timeline[lastItem].condition { --timeline-ball-color: var(--error-color); } ha-timeline[data-path] { cursor: pointer; } ha-timeline[selected] { --timeline-ball-color: var(--primary-color); } ha-timeline:focus { outline: none; --timeline-ball-color: var(--accent-color); } .error { --timeline-ball-color: var(--error-color); color: var(--error-color); } `, ]; } } declare global { interface HTMLElementTagNameMap { "hat-trace-timeline": HaAutomationTracer; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages an App Service Certificate Order. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleCertificateOrder = new azure.appservice.CertificateOrder("exampleCertificateOrder", { * resourceGroupName: exampleResourceGroup.name, * location: "global", * distinguishedName: "CN=example.com", * productType: "Standard", * }); * ``` * * ## Import * * App Service Certificate Orders can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:appservice/certificateOrder:CertificateOrder example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.CertificateRegistration/certificateOrders/certificateorder1 * ``` */ export class CertificateOrder extends pulumi.CustomResource { /** * Get an existing CertificateOrder resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: CertificateOrderState, opts?: pulumi.CustomResourceOptions): CertificateOrder { return new CertificateOrder(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:appservice/certificateOrder:CertificateOrder'; /** * Returns true if the given object is an instance of CertificateOrder. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is CertificateOrder { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === CertificateOrder.__pulumiType; } /** * Reasons why App Service Certificate is not renewable at the current moment. */ public /*out*/ readonly appServiceCertificateNotRenewableReasons!: pulumi.Output<string[]>; /** * true if the certificate should be automatically renewed when it expires; otherwise, false. Defaults to true. */ public readonly autoRenew!: pulumi.Output<boolean | undefined>; /** * State of the Key Vault secret. A `certificates` block as defined below. */ public /*out*/ readonly certificates!: pulumi.Output<outputs.appservice.CertificateOrderCertificate[]>; /** * Last CSR that was created for this order. */ public readonly csr!: pulumi.Output<string>; /** * The Distinguished Name for the App Service Certificate Order. */ public readonly distinguishedName!: pulumi.Output<string>; /** * Domain verification token. */ public /*out*/ readonly domainVerificationToken!: pulumi.Output<string>; /** * Certificate expiration time. */ public /*out*/ readonly expirationTime!: pulumi.Output<string>; /** * Certificate thumbprint intermediate certificate. */ public /*out*/ readonly intermediateThumbprint!: pulumi.Output<string>; /** * Whether the private key is external or not. */ public /*out*/ readonly isPrivateKeyExternal!: pulumi.Output<boolean>; /** * Certificate key size. Defaults to 2048. */ public readonly keySize!: pulumi.Output<number | undefined>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. Currently the only valid value is `global`. */ public readonly location!: pulumi.Output<string>; /** * Specifies the name of the certificate. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * Certificate product type, such as `Standard` or `WildCard`. */ public readonly productType!: pulumi.Output<string | undefined>; /** * The name of the resource group in which to create the certificate. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * Certificate thumbprint for root certificate. */ public /*out*/ readonly rootThumbprint!: pulumi.Output<string>; /** * Certificate thumbprint for signed certificate. */ public /*out*/ readonly signedCertificateThumbprint!: pulumi.Output<string>; /** * Current order status. */ public /*out*/ readonly status!: pulumi.Output<string>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Duration in years (must be between `1` and `3`). Defaults to `1`. */ public readonly validityInYears!: pulumi.Output<number | undefined>; /** * Create a CertificateOrder resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: CertificateOrderArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: CertificateOrderArgs | CertificateOrderState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as CertificateOrderState | undefined; inputs["appServiceCertificateNotRenewableReasons"] = state ? state.appServiceCertificateNotRenewableReasons : undefined; inputs["autoRenew"] = state ? state.autoRenew : undefined; inputs["certificates"] = state ? state.certificates : undefined; inputs["csr"] = state ? state.csr : undefined; inputs["distinguishedName"] = state ? state.distinguishedName : undefined; inputs["domainVerificationToken"] = state ? state.domainVerificationToken : undefined; inputs["expirationTime"] = state ? state.expirationTime : undefined; inputs["intermediateThumbprint"] = state ? state.intermediateThumbprint : undefined; inputs["isPrivateKeyExternal"] = state ? state.isPrivateKeyExternal : undefined; inputs["keySize"] = state ? state.keySize : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["productType"] = state ? state.productType : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["rootThumbprint"] = state ? state.rootThumbprint : undefined; inputs["signedCertificateThumbprint"] = state ? state.signedCertificateThumbprint : undefined; inputs["status"] = state ? state.status : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["validityInYears"] = state ? state.validityInYears : undefined; } else { const args = argsOrState as CertificateOrderArgs | undefined; if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["autoRenew"] = args ? args.autoRenew : undefined; inputs["csr"] = args ? args.csr : undefined; inputs["distinguishedName"] = args ? args.distinguishedName : undefined; inputs["keySize"] = args ? args.keySize : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["productType"] = args ? args.productType : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["validityInYears"] = args ? args.validityInYears : undefined; inputs["appServiceCertificateNotRenewableReasons"] = undefined /*out*/; inputs["certificates"] = undefined /*out*/; inputs["domainVerificationToken"] = undefined /*out*/; inputs["expirationTime"] = undefined /*out*/; inputs["intermediateThumbprint"] = undefined /*out*/; inputs["isPrivateKeyExternal"] = undefined /*out*/; inputs["rootThumbprint"] = undefined /*out*/; inputs["signedCertificateThumbprint"] = undefined /*out*/; inputs["status"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(CertificateOrder.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering CertificateOrder resources. */ export interface CertificateOrderState { /** * Reasons why App Service Certificate is not renewable at the current moment. */ appServiceCertificateNotRenewableReasons?: pulumi.Input<pulumi.Input<string>[]>; /** * true if the certificate should be automatically renewed when it expires; otherwise, false. Defaults to true. */ autoRenew?: pulumi.Input<boolean>; /** * State of the Key Vault secret. A `certificates` block as defined below. */ certificates?: pulumi.Input<pulumi.Input<inputs.appservice.CertificateOrderCertificate>[]>; /** * Last CSR that was created for this order. */ csr?: pulumi.Input<string>; /** * The Distinguished Name for the App Service Certificate Order. */ distinguishedName?: pulumi.Input<string>; /** * Domain verification token. */ domainVerificationToken?: pulumi.Input<string>; /** * Certificate expiration time. */ expirationTime?: pulumi.Input<string>; /** * Certificate thumbprint intermediate certificate. */ intermediateThumbprint?: pulumi.Input<string>; /** * Whether the private key is external or not. */ isPrivateKeyExternal?: pulumi.Input<boolean>; /** * Certificate key size. Defaults to 2048. */ keySize?: pulumi.Input<number>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. Currently the only valid value is `global`. */ location?: pulumi.Input<string>; /** * Specifies the name of the certificate. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Certificate product type, such as `Standard` or `WildCard`. */ productType?: pulumi.Input<string>; /** * The name of the resource group in which to create the certificate. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * Certificate thumbprint for root certificate. */ rootThumbprint?: pulumi.Input<string>; /** * Certificate thumbprint for signed certificate. */ signedCertificateThumbprint?: pulumi.Input<string>; /** * Current order status. */ status?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Duration in years (must be between `1` and `3`). Defaults to `1`. */ validityInYears?: pulumi.Input<number>; } /** * The set of arguments for constructing a CertificateOrder resource. */ export interface CertificateOrderArgs { /** * true if the certificate should be automatically renewed when it expires; otherwise, false. Defaults to true. */ autoRenew?: pulumi.Input<boolean>; /** * Last CSR that was created for this order. */ csr?: pulumi.Input<string>; /** * The Distinguished Name for the App Service Certificate Order. */ distinguishedName?: pulumi.Input<string>; /** * Certificate key size. Defaults to 2048. */ keySize?: pulumi.Input<number>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. Currently the only valid value is `global`. */ location?: pulumi.Input<string>; /** * Specifies the name of the certificate. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Certificate product type, such as `Standard` or `WildCard`. */ productType?: pulumi.Input<string>; /** * The name of the resource group in which to create the certificate. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Duration in years (must be between `1` and `3`). Defaults to `1`. */ validityInYears?: pulumi.Input<number>; }
the_stack
import { task } from 'hardhat/config'; import dotenv from 'dotenv'; import readline from 'readline'; import { BigNumber } from 'ethers'; import { DRE } from '../../helpers/misc-utils'; import { getMnemonicSigner } from '../../helpers/wallet-helpers'; import ContractAddresses from '../../contractAddresses.json'; import AaveGovernanceV2Abi from '../../abis/AaveGovernanceV2.json'; import { initPolygonMarketUpdateContract, initPolygonBridgeExecutor, listenForActionsQueued, getMumbaiBlocktime, getActionsExecutionTime, getActionsSetId, listenForUpdateExecuted, getActionsSetById, } from '../../helpers/polygon-helpers'; dotenv.config({ path: '../../.env' }); task('simulate-mumbai-governance', 'Create Proposal').setAction(async (_, localBRE) => { await localBRE.run('set-DRE'); const { ethers } = DRE; const { provider, BigNumber } = ethers; const overrides = { gasLimit: 2000000, gasPrice: 951 * 1000 * 1000 * 1000, }; let proposal; let vote; let queuedProposal; let executionLog; let aaveWhaleSigner = getMnemonicSigner(1); aaveWhaleSigner = aaveWhaleSigner.connect(provider); const aaveWhaleAddress = await aaveWhaleSigner.getAddress(); console.log(`Aave Whale: ${aaveWhaleAddress}\n\n`); const govContract = new DRE.ethers.Contract( ContractAddresses.governance, AaveGovernanceV2Abi, aaveWhaleSigner ); const polygonMarketUpdate = await initPolygonMarketUpdateContract(); await listenForUpdateExecuted(polygonMarketUpdate); const polygonBridgeExecutor = await initPolygonBridgeExecutor(); await listenForActionsQueued(polygonBridgeExecutor); /* * Create Proposal * Encode params for AavePolygonGov Receiver to call PolygonMarketUpdate Contract * Encode Aave GovV2 Proposal Params */ const dummyUint = 389; const dummyString = 'this is a test'; const targets: string[] = []; const values: BigNumber[] = []; const signatures: string[] = []; const calldatas: string[] = []; const withDelegatecalls: boolean[] = []; // push the first transaction fields into action arrays const encodedNumber = ethers.utils.defaultAbiCoder.encode(['uint256'], [dummyUint]); targets.push(ContractAddresses.marketUpdate); values.push(BigNumber.from(0)); signatures.push('execute(uint256)'); calldatas.push(encodedNumber); withDelegatecalls.push(false); // push the second transaction fields into action arrays const encodedBytes = ethers.utils.defaultAbiCoder.encode( ['bytes32'], [ethers.utils.formatBytes32String(dummyString)] ); targets.push(ContractAddresses.marketUpdate); values.push(BigNumber.from(0)); signatures.push('executeWithDelegate(bytes32)'); calldatas.push(encodedBytes); withDelegatecalls.push(true); // encode actions for BridgeExecutor const encodedActions = ethers.utils.defaultAbiCoder.encode( ['address[]', 'uint256[]', 'string[]', 'bytes[]', 'bool[]'], [targets, values, signatures, calldatas, withDelegatecalls] ); // encode data for FxRoot const encodedRootCalldata = ethers.utils.defaultAbiCoder.encode( ['address', 'bytes'], [ContractAddresses.polygonBridgeExecutor, encodedActions] ); let proposalTransaction; let proposalReceipt; try { proposalTransaction = await govContract.create( ContractAddresses.executor, [ContractAddresses.fxRoot], [BigNumber.from(0)], ['sendMessageToChild(address,bytes)'], [encodedRootCalldata], [0], '0xf7a1f565fcd7684fba6fea5d77c5e699653e21cb6ae25fbf8c5dbc8d694c7949', { gasLimit: 2000000, gasPrice: 951 * 1000 * 1000 * 1000, nonce: 224, } ); proposalReceipt = await proposalTransaction.wait(); } catch (e) { console.log(`Error in Proposal Creation Transaction`); console.log(e); process.exit(1); } try { const proposalLog = govContract.interface.parseLog(proposalReceipt.logs[0]); proposal = govContract.interface.decodeEventLog( proposalLog.eventFragment, proposalReceipt.logs[0].data ); } catch (e) { console.log(`Error in Proposal Creation Log Parsing`); console.log(e); process.exit(1); } console.log(`Proposal Created (id): ${proposal.id}\n`); const status = await govContract.getProposalState(proposal.id, { gasLimit: 5000000 }); let currentBlockNumber = await DRE.ethers.provider.getBlockNumber(); console.log(`Proposal ${proposal.id} Status: ${status}`); // Await Start Vote console.log(`Waiting for vote to start...\n`); process.stdout.write(`Vote Starting Block Number: ${proposal.startBlock}\n`); const startBlockPlusOne = proposal.startBlock.add(BigNumber.from(1)); while (currentBlockNumber <= startBlockPlusOne) { if (DRE.network.name === 'tenderly') { await aaveWhaleSigner.sendTransaction({ to: aaveWhaleAddress, value: 0, gasLimit: 100000, }); } if (DRE.network.name === 'goerli') { await sleep(15000); } readline.cursorTo(process.stdout, 0); process.stdout.write(`Current Block Number: ${currentBlockNumber}`); currentBlockNumber = await DRE.ethers.provider.getBlockNumber(); } console.log(`\n\nChecking Status...`); const updatedStatus = await govContract.getProposalState(proposal.id, { gasLimit: 5000000 }); console.log(`Proposal ${proposal.id} Status: ${updatedStatus}`); // Vote console.log(``); console.log(`Submiting Vote...`); let voteTransaction; let voteReceipt; try { voteTransaction = await govContract.submitVote(proposal.id, 1, overrides); voteReceipt = await voteTransaction.wait(); } catch (e) { console.log(`Error in vote Transaction`); console.log(e); process.exit(1); } try { const voteLog = govContract.interface.parseLog(voteReceipt.logs[0]); vote = govContract.interface.decodeEventLog(voteLog.eventFragment, voteReceipt.logs[0].data); console.log( `${voteReceipt.from} voted ${vote.support ? 'YES' : 'NO'} with ${vote.votingPower}` ); } catch (e) { console.log(`Error parsing vote logs`); console.log(e); process.exit(1); } // Await End Vote console.log(`\nWaiting for vote to end...\n`); process.stdout.write(`Vote Ending Block Number: ${proposal.endBlock}\n`); while ((await DRE.ethers.provider.getBlockNumber()) <= proposal.endBlock) { if (DRE.network.name === 'tenderly') { await aaveWhaleSigner.sendTransaction({ to: aaveWhaleAddress, value: 0, gasLimit: 100000, }); } if (DRE.network.name === 'goerli') { await sleep(15000); } readline.cursorTo(process.stdout, 0); process.stdout.write(`Current Block Number: ${currentBlockNumber}`); currentBlockNumber = await DRE.ethers.provider.getBlockNumber(); } // Queue console.log('\n\nQueuing Proposal...'); let queueTransaction; let queueReceipt; try { queueTransaction = await govContract.queue(proposal.id, overrides); queueReceipt = await queueTransaction.wait(); } catch (e) { console.log(`Error Queueing Proposal`); console.log(e.reason); console.log(e); } try { const queuedLog = govContract.interface.parseLog(queueReceipt.logs[1]); queuedProposal = govContract.interface.decodeEventLog( queuedLog.eventFragment, queueReceipt.logs[1].data ); console.log(`Proposal ${queuedProposal.id} queued.`); } catch (e) { console.log(`Error Parsing Queue Log`); console.log(e.reason); console.log(e); process.exit(1); } // Await Execution (Aave-Gov) console.log(`\nWaiting for Execution Time... (~15 second sleeps)\n`); let currentBlock = await DRE.ethers.provider.getBlockNumber(); let blockTimestamp = (await DRE.ethers.provider.getBlock(currentBlock)).timestamp; process.stdout.write(`Execution Time: ${queuedProposal.executionTime}\n`); process.stdout.write(`Current Time: ${blockTimestamp}`); while (blockTimestamp <= queuedProposal.executionTime) { if (DRE.network.name === 'tenderly') { await aaveWhaleSigner.sendTransaction({ to: aaveWhaleAddress, value: 0, gasLimit: 100000, }); await sleep(15000); } if (DRE.network.name === 'goerli') { await sleep(15000); } readline.cursorTo(process.stdout, 0); process.stdout.write(`Current Time: ${blockTimestamp}`); currentBlock = await DRE.ethers.provider.getBlockNumber(); blockTimestamp = (await DRE.ethers.provider.getBlock(currentBlock)).timestamp; } readline.cursorTo(process.stdout, 0); process.stdout.write(`Current Time: ${blockTimestamp}\n\n`); // Execute (Aave-Gov) console.log(``); console.log(`Executing Transaction...`); let executeTransaction; let executeReceipt; try { executeTransaction = await govContract.execute(proposal.id, overrides); executeReceipt = await executeTransaction.wait(); } catch (e) { console.log(`Error executing transaction`); console.log(e.reason); console.log(e); process.exit(1); } try { const rawExecutionLog = govContract.interface.parseLog(executeReceipt.logs[2]); executionLog = govContract.interface.decodeEventLog( rawExecutionLog.eventFragment, executeReceipt.logs[2].data ); console.log(`Proposal ${executionLog.id} executed`); console.log(``); } catch (e) { console.log(`Error Parsing Execution Log`); console.log(e); process.exit(1); } // Wait for polygon update console.log(`waiting for update event on Polygon...`); const start = Date.now(); while (polygonBridgeExecutor.listenerCount() > 0) { readline.cursorTo(process.stdout, 0); process.stdout.write(`Seconds Passed: ${Math.floor((Date.now() - start) / 1000)}`); await sleep(1000); } await sleep(5000); // Try immediate execution console.log(`Trying immediate execution -- should fail`); console.log(`Executing Transaction...`); let actionSetFailedTx; try { console.log(`actionSetId: ${getActionsSetId()} `); actionSetFailedTx = await polygonBridgeExecutor.execute(getActionsSetId(), { gasLimit: 200000, }); } catch (e) { console.log(`Immediate Execution Successfully Reverted`); console.log(`Transaction: ${actionSetFailedTx.hash}`); } // Wait for polygon execution time console.log(`\n\nWaiting for ActionsSet Execution Time`); let mumbaiBlocktime = await getMumbaiBlocktime(); const mumbaiExecutionTime = await getActionsExecutionTime(); console.log(`Blocktime: ${mumbaiBlocktime}`); console.log(`Execution Time: ${mumbaiExecutionTime}`); while (BigNumber.from(mumbaiBlocktime).lt(mumbaiExecutionTime)) { if (DRE.network.name === 'tenderly') { await aaveWhaleSigner.sendTransaction({ to: aaveWhaleAddress, value: 0, gasLimit: 100000, }); await sleep(15000); } if (DRE.network.name === 'goerli') { await sleep(5000); } readline.cursorTo(process.stdout, 0); process.stdout.write(`Current Time: ${mumbaiBlocktime}`); mumbaiBlocktime = await getMumbaiBlocktime(); } // Execute ActionsSet (Polygon) console.log(`\n\nExecute ActionsSet`); const initialCounter = await polygonMarketUpdate.getCounter(); const initialTestNumber = await polygonMarketUpdate.getTestInt(); let executeActionsSetTx; let executeActionsSetReceipt; try { executeActionsSetTx = await polygonBridgeExecutor.execute(getActionsSetId(), { gasLimit: 500000, }); executeActionsSetReceipt = await executeActionsSetTx.wait(); } catch (e) { console.log(`Error executing transaction`); console.log(e.reason); console.log(e); process.exit(1); } try { const rawExecutionLog = polygonBridgeExecutor.interface.parseLog( executeActionsSetReceipt.logs[2] ); executionLog = polygonBridgeExecutor.interface.decodeEventLog( rawExecutionLog.eventFragment, executeActionsSetReceipt.logs[2].data ); console.log(`Proposal ${executionLog.id} executed`); console.log(``); } catch (e) { console.log(`Error Parsing Execution Log`); console.log(e); process.exit(1); } // Confirm Polygon StateUpdate console.log(); console.log(`Initial Counter: ${initialCounter.toString()}`); console.log(`Initial Test Int: ${initialTestNumber.toString()}`); console.log(); console.log(`Current Counter: ${(await polygonMarketUpdate.getCounter()).toString()}`); console.log(`Current Test Int: ${(await polygonMarketUpdate.getTestInt()).toString()}`); }); const sleep = async (ms: number) => { return new Promise((resolve) => setTimeout(resolve, ms)); };
the_stack
module TDev { export module Revisions { export class SessionTests { constructor(public rt: Runtime) { } public runtest(which: string): void { if (typeof this[which] === "function") { this.print("running test \"" + which + "\""); this[which](); } else this.print("no such test: \"" + which + "\""); } private print(s: string) { this.rt.postBoxedText(s, ""); } public fail(msg: string) { this.print("FAILED: " + msg); } public assert(cond: boolean) { if (!cond) this.print("FAILED"); } // common private randomsuffix(): string { var d = new Date(); var ms = d.getMilliseconds(); return String.fromCharCode("a".charCodeAt(0) + ms % 26) + String.fromCharCode("a".charCodeAt(0) + Math.floor(ms / 26) % 26); } /* // collab tests public collabAdd() { var p = Promise.as(); p = p.then(() => this.print("initially----------------------------")); p = p.then(() => { this.print("list invitations for group:"); return TDev.Collab.getCollaborationsAsync("coepuxlg").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => { this.print("get collab for script:"); return TDev.Collab.getCollaborationAsync("bqsl", "c1809ad4-3dd0-4289-4642-cc8282c31f3f").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => this.print("put----------------------------")); p = p.then(() => { this.print("put collab for script:"); return TDev.Collab.startCollaborationAsync("c1809ad4-3dd0-4289-4642-cc8282c31f3f", "xxx", "coepuxlg").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => { this.print("list invitations for group:"); return TDev.Collab.getCollaborationsAsync("coepuxlg").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => { this.print("get collab for script:"); return TDev.Collab.getCollaborationAsync("bqsl", "c1809ad4-3dd0-4289-4642-cc8282c31f3f").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => this.print("clear----------------------------")); p = p.then(() => { this.print("put collab for script:"); return TDev.Collab.stopCollaborationAsync("c1809ad4-3dd0-4289-4642-cc8282c31f3f").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => { this.print("list invitations for group:"); return TDev.Collab.getCollaborationsAsync("coepuxlg").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); p = p.then(() => { this.print("get collab for script:"); return TDev.Collab.getCollaborationAsync("bqsl", "c1809ad4-3dd0-4289-4642-cc8282c31f3f").then( (inv) => this.print("ok: " + JSON.stringify(inv)), (e) => this.print("error: " + JSON.stringify(e))) }); } */ // session tests public refreshtoken(): void { Revisions.getRevisionServiceTokenAsync().then( (token:any) => { this.print("success:"); this.print("token=" + token); }, (e) => { this.fail("error: " + e); }); } public list(): void { var user = Cloud.getUserId(); this.print("issuing get request for sessions by user " + user + "..."); Revisions.queryMySessionsOnRevisionServerAsync(this.rt).then( (s) => { this.print("success:"); (<RT.CloudSession[]>s).forEach(si => { this.print(""); this.print("id=" + si._id); this.print("d=" + si._title); }); }, (e) => { this.fail("error: " + e); }); } public deletetests(): void { var user = Cloud.getUserId(); this.print("issuing get request for sessions by user " + user + "..."); Revisions.queryMySessionsOnRevisionServerAsync(this.rt).then( (s) => { this.print("success:"); (<RT.CloudSession[]>s).forEach(si => { if (si._title.indexOf("test session for") == 0) { this.print("deleting " + si._id); Revisions.deleteSessionAsync(this.rt.sessions.getCloudSessionDescriptor(s._id, s._title, s._permissions), this.rt).then( (ack) => { this.print("successfully deleted " + si._id); }, (err) => { this.fail("error deleting " + si._id + ": " + err); } ).done(); } }); }, (e) => { this.fail("error: " + e); }); } public connect1(): void { this.print("connecting..."); var sfx = this.randomsuffix(); var testname = "connectone" + sfx; var s = new TDev.Revisions.ClientSession(Cloud.getUserId() + "0" + testname, "a" + sfx, Cloud.getUserId()); s.connect(this.rt.sessions.url_ws(), Revisions.getRevisionServiceTokenAsync); this.print("create elt..."); var dcustomer = "customer()"; var alice = s.user_create_item(dcustomer, [], []); var items = s.user_get_items_in_domain(dcustomer); this.assert(items.length == 1); this.assert(items[0] === alice); this.print("issuing fence 1..."); s.user_issue_fence(() => { this.print("fence 1 completed."); var items = s.user_get_items_in_domain(dcustomer); this.assert(items.length == 1); this.assert(items[0] === alice); this.print("delete elt..."); s.user_delete_item(alice); var items = s.user_get_items_in_domain(dcustomer); this.assert(items.length == 0); this.print("issuing fence 2..."); s.user_issue_fence(() => { this.print("fence 2 completed."); var items = s.user_get_items_in_domain(dcustomer); this.assert(items.length == 0); this.print("DATA:"); var lines = s.user_dump_stable_data(b => this.assert(b)); lines.forEach((l) => this.print(l)); this.print("test completed."); }, true); }, true); } public connect2(): void { this.print("connecting..."); var testname = Cloud.getUserId() + "0" + "connecttwo" + this.randomsuffix(); var s = new TDev.Revisions.ClientSession(testname, testname, Cloud.getUserId()); s.connect(this.rt.sessions.url_ws(), Revisions.getRevisionServiceTokenAsync); var st = s.user_get_value(s.user_get_lval("mystring,string[void[]]", [], [])); var db = s.user_get_value(s.user_get_lval("mydouble,double[void[]]", [], [])); this.assert(st === ""); this.assert(db === 0.0); this.print("writing data..."); s.user_modify_lval(s.user_get_lval("mystring,string[void[]]", [], []), ""); s.user_modify_lval(s.user_get_lval("mydouble,double[void[]]", [], []), 3.14); var st = s.user_get_value(s.user_get_lval("mystring,string[void[]]", [], [])); var db = s.user_get_value(s.user_get_lval("mydouble,double[void[]]", [], [])); this.assert(st === ""); this.assert(db === 3.14); this.print("yielding..."); s.user_yield(); // send off first chg to server s.user_modify_lval(s.user_get_lval("mystring,string[void[]]", [], []), "new"); s.user_modify_lval(s.user_get_lval("mydouble,double[void[]]", [], []), "A-3"); var st = s.user_get_value(s.user_get_lval("mystring,string[void[]]", [], [])); var db = s.user_get_value(s.user_get_lval("mydouble,double[void[]]", [], [])); this.assert(st === "new"); this.assert(db - 0.14 < 0.000000001); this.print("issuing fence 1..."); s.user_issue_fence(() => { this.print("fence 1 completed."); var st = s.user_get_value(s.user_get_lval("mystring,string[void[]]", [], [])); var db = s.user_get_value(s.user_get_lval("mydouble,double[void[]]", [], [])); this.assert(st === "new"); this.assert(db - 0.14 < 0.000000001); this.print("DATA:"); var lines = s.user_dump_stable_data(b => this.assert(b)); lines.forEach((l) => this.print(l)); this.print("test completed."); }, true); } public serverpersistence1(): void { this.print("connecting first session..."); var sfx = this.randomsuffix(); var testname = Cloud.getUserId() + "0serverpersistenceone" + sfx; var s = new TDev.Revisions.ClientSession(testname, "a", Cloud.getUserId()); s.connect(this.rt.sessions.url_ws(), Revisions.getRevisionServiceTokenAsync); this.print("data..."); var alice = s.user_create_item("customer()", [], []); var bob = s.user_create_item("customer()", [], []); var charlie = s.user_create_item("customer()", [], []); var delta = s.user_create_item("customer()", [], []); s.user_modify_lval(s.user_get_lval("name,string[customertable[customer()]]", [alice.uid], []), "Alice"); s.user_modify_lval(s.user_get_lval("name,string[customertable[customer()]]", [bob.uid], []), "Bob"); s.user_modify_lval(s.user_get_lval("name,string[customertable[customer()]]", [charlie.uid], []), "Charlie"); s.user_modify_lval(s.user_get_lval("name,string[customertable[customer()]]", [delta.uid], []), ""); var is = s.user_get_items_in_domain("customer()").map(e => e.target()).sort(); var ref = [alice.uid, bob.uid, charlie.uid, delta.uid].sort(); this.assert(is.length == ref.length); for (var i = 0; i < is.length; i++) this.assert(is[i] === ref[i]); var ks = s.user_get_entries_in_indexdomain("customertable[customer()]").map(e => e.target()).sort(); var ref = [s.user_get_entry("customertable[customer()]", [alice.uid], []), s.user_get_entry("customertable[customer()]", [bob.uid], []), s.user_get_entry("customertable[customer()]", [charlie.uid], [])].map(e => e.target()).sort(); this.assert(ks.length == ref.length); for (var i = 0; i < ks.length; i++) this.assert(ks[i] === ref[i]); this.print("saving..."); s.user_issue_fence(() => { this.print("save completed."); this.print("connecting second session..."); s = new TDev.Revisions.ClientSession(testname, "b", Cloud.getUserId()); s.connect(this.rt.sessions.url_ws(), Revisions.getRevisionServiceTokenAsync); this.print("loading..."); s.user_issue_fence(() => { this.print("load completed."); this.print("checking data..."); var is = s.user_get_items_in_domain("customer()"); this.assert(is.length == 4); var es = s.user_get_entries_in_indexdomain("customertable[customer()]"); this.assert(es.length == 3); this.print("DATA:"); var lines = s.user_dump_stable_data(b => this.assert(b)); var ref = ["new|customer()|1.1", "new|customer()|1.2", "new|customer()|1.3", "new|customer()|1.4", "mod|name,string[customertable[customer()]]|1.1|+Alice", "mod|name,string[customertable[customer()]]|1.2|+Bob", "mod|name,string[customertable[customer()]]|1.3|+Charlie"]; this.assert(lines.length == ref.length); for (var i = 0; i < lines.length; i++) { this.assert(lines[i] === ref[i]); this.print(lines[i]); } this.print("test completed."); }, true); },true); } } } }
the_stack
import { createBehavior, isSignal, createSetupBehavior, stopped, createTimeout, createSystem, ActorRef, } from '../src'; import { ActorSignalType, Logger, BehaviorReducer } from '../src/types'; describe('ActorSystem', () => { it('simple test', done => { const rootBehavior = createBehavior<any, boolean>((_, msg) => { if (isSignal(msg)) return false; expect(msg).toEqual({ type: 'hey' }); return true; }, false); const system = createSystem(rootBehavior, 'hello'); system.subscribe(state => { if (state) { done(); } }); system.send({ type: 'hey' }); }); it('First example', done => { interface Greet { type: 'greet'; whom: string; replyTo: ActorRef<Greeted>; } interface Greeted { type: 'greeted'; whom: string; from: ActorRef<Greet>; } interface SayHello { type: 'sayHello'; name: string; } const HelloWorld = createBehavior<Greet>((_, message, ctx) => { if (isSignal(message)) return _; ctx.log(`Hello ${message.whom}!`); message.replyTo.send({ type: 'greeted', whom: message.whom, from: ctx.self, }); return _; }, undefined); const HelloWorldBot = (max: number) => { const bot = (greetingCounter: number, max: number) => { return createBehavior<Greeted>( (state, message, ctx) => { if (isSignal(message)) return state; const n = state.n + 1; ctx.log(`Greeting ${n} for ${message.whom}`); if (n === max) { return state; // do nothing } else { message.from.send({ type: 'greet', whom: message.whom, replyTo: ctx.self, }); return { n, max }; } }, { n: greetingCounter, max } ); }; return bot(0, max); }; const HelloWorldMain = createSetupBehavior< SayHello, { greeter: ActorRef<Greet> | undefined } >( (_, ctx) => { return { greeter: ctx.spawn(HelloWorld, 'greeter') }; }, ({ greeter }, message, ctx) => { if (message.type === 'sayHello') { const replyTo = ctx.spawn(HelloWorldBot(3), message.name); greeter?.send({ type: 'greet', whom: message.name, replyTo, }); } return { greeter }; }, { greeter: undefined, } ); const system = createSystem(HelloWorldMain, 'hello'); system.send({ type: 'sayHello', name: 'World' }); system.send({ type: 'sayHello', name: 'Akka' }); setTimeout(() => { done(); }, 1000); }); it('more complex example', done => { interface GetSession { type: 'GetSession'; screenName: string; replyTo: ActorRef<SessionEvent>; } type RoomCommand = GetSession | PublishSessionMessage; interface SessionGranted { type: 'SessionGranted'; handle: ActorRef<PostMessage>; } interface SessionDenied { type: 'SessionDenied'; reason: string; } interface MessagePosted { type: 'MessagePosted'; screenName: string; message: string; } type SessionEvent = SessionGranted | SessionDenied | MessagePosted; interface PostMessage { type: 'PostMessage'; message: string; } interface NotifyClient { type: 'NotifyClient'; message: MessagePosted; } type SessionCommand = PostMessage | NotifyClient; interface PublishSessionMessage { type: 'PublishSessionMessage'; screenName: string; message: string; } const ChatRoom = () => chatRoom([]); const session = ( room: ActorRef<PublishSessionMessage>, screenName: string, client: ActorRef<SessionEvent> ) => { return createBehavior<SessionCommand>((_, message, _ctx) => { switch (message.type) { case 'PostMessage': room.send({ type: 'PublishSessionMessage', screenName, message: message.message, }); return undefined; case 'NotifyClient': client.send(message.message); return undefined; default: return undefined; } }, undefined); }; const chatRoom = (sessions: ActorRef<SessionCommand>[]) => { return createBehavior< RoomCommand, { sessions: ActorRef<SessionCommand>[] } >( (state, message, context) => { context.log(message); switch (message.type) { case 'GetSession': const ses = context.spawn( session( context.self as any, message.screenName, message.replyTo ), message.screenName ); message.replyTo.send({ type: 'SessionGranted', handle: ses as any, }); return { sessions: [ses, ...sessions] }; case 'PublishSessionMessage': const notification: NotifyClient = { type: 'NotifyClient', message: { type: 'MessagePosted', screenName: message.screenName, message: message.message, }, }; state.sessions.forEach(session => session.send(notification)); return state; default: return state; } }, { sessions } ); }; const Gabbler = () => { return createBehavior<SessionEvent>((_, message, context) => { context.log(message); switch (message.type) { case 'SessionGranted': message.handle.send({ type: 'PostMessage', message: 'Hello world!', }); return undefined; case 'MessagePosted': context.log( `message has been posted by '${message.screenName}': ${message.message}` ); done(); return undefined; // return BehaviorTag.Stopped; default: return undefined; } }, undefined); }; const Main = () => createSetupBehavior( (_, context) => { context.log('setting up'); const chatRoom = context.spawn(ChatRoom(), 'chatRoom'); const gabblerRef = context.spawn(Gabbler(), 'gabbler'); chatRoom.send({ type: 'GetSession', screenName: "ol' Gabbler", replyTo: gabblerRef, }); return undefined; }, s => s, undefined ); createSystem(Main(), 'Chat'); }); it('aggregation example', done => { interface OrchestratorState { entities: Map<string, ActorRef<EntityEvent>>; aggregations: { [entityId: string]: number | undefined; }; } type OrchestratorEvent = | { type: 'entity.add'; entityId: string; value: number; } | { type: 'entity.receive'; entity: ActorRef<EntityEvent>; count: number; } | { type: 'getAll'; }; type EntityEvent = | { type: 'add'; value: number; } | { type: 'get'; ref: ActorRef<OrchestratorEvent>; }; interface EntityState { count: number; } const entityReducer: BehaviorReducer<EntityState, EntityEvent> = ( state, event, ctx ) => { if (event.type === 'add') { ctx.log(`adding ${event.value} ${state.count}`); state.count += event.value; } if (event.type === 'get') { event.ref.send({ type: 'entity.receive', entity: ctx.self, count: state.count, }); } return state; }; const orchestratorReducer: BehaviorReducer< OrchestratorState, OrchestratorEvent > = (state, event, ctx) => { if (event.type === 'entity.add') { let entity = state.entities.get(event.entityId); if (!entity) { entity = ctx.spawn( createBehavior(entityReducer, { count: 0 }), event.entityId ); state.entities.set(event.entityId, entity); } entity.send({ type: 'add', value: event.value }); } if (event.type === 'getAll') { Array.from(state.entities.entries()).forEach(([entityId, entity]) => { state.aggregations[entityId] = undefined; entity.send({ type: 'get', ref: ctx.self }); }); } if (event.type === 'entity.receive') { state.aggregations[event.entity.name] = event.count; if ( Object.values(state.aggregations).every(value => value !== undefined) ) { ctx.log(state.aggregations); done(); } } return state; }; const system = createSystem( createBehavior(orchestratorReducer, { entities: new Map(), aggregations: {}, }), 'orchestrator' ); system.send({ type: 'entity.add', entityId: 'foo', value: 3, }); system.send({ type: 'entity.add', entityId: 'foo', value: 3, }); system.send({ type: 'entity.add', entityId: 'foo', value: 2, }); system.send({ type: 'entity.add', entityId: 'bar', value: 3, }); system.send({ type: 'entity.add', entityId: 'bar', value: 3, }); system.send({ type: 'entity.add', entityId: 'bar', value: 2, }); system.send({ type: 'entity.add', entityId: 'foo', value: 1, }); system.send({ type: 'getAll', }); }); it('guardian actor should receive messages sent to system', done => { const HelloWorldMain = createBehavior<{ type: 'hello' }>((_, event) => { if (event.type === 'hello') { done(); } }, undefined); const system = createSystem(HelloWorldMain, 'hello'); system.send({ type: 'hello' }); }); it('stopping actors', done => { // https://doc.akka.io/docs/akka/2.6.5/typed/actor-lifecycle.html#stopping-actors const stoppedActors: any[] = []; interface SpawnJob { type: 'SpawnJob'; name: string; } interface GracefulShutdown { type: 'GracefulShutdown'; } type Command = SpawnJob | GracefulShutdown; const Job = (name: string) => createBehavior<Command>((_, signal, ctx) => { ctx.log(signal); if (signal.type === ActorSignalType.PostStop) { ctx.log(`Worker ${name} stopped`); stoppedActors.push(name); } }, undefined); const MasterControlProgram = () => createBehavior<Command>((state, message, context) => { const cleanup = (log: Logger): void => { log(`Cleaning up!`); }; if (isSignal(message)) { if (message.type === ActorSignalType.PostStop) { context.log(`Master Control Program stopped`); cleanup(context.log); expect(stoppedActors).toEqual(['a', 'b']); done(); } return; } switch (message.type) { case 'SpawnJob': const { name: jobName } = message; context.log(`Spawning job ${jobName}!`); context.spawn(Job(jobName), jobName); return; case 'GracefulShutdown': context.log(`Initiating graceful shutdown...`); return stopped(state); } }, undefined); const system = createSystem(MasterControlProgram(), 'B7700'); system.send({ type: 'SpawnJob', name: 'a' }); system.send({ type: 'SpawnJob', name: 'b' }); setTimeout(() => { system.send({ type: 'GracefulShutdown' }); }, 100); }); it('watching actors', done => { interface SpawnJob { type: 'SpawnJob'; jobName: string; } const Job = (name: string) => createSetupBehavior<{ type: 'finished' }, undefined>( (_, ctx) => { ctx.spawn( createTimeout( ctx.self, ref => { ref.send({ type: 'finished' }); }, 100 ), 'timeout' ); ctx.log(`Hi I am job ${name}`); return undefined; }, (state, event) => { if (event.type === 'finished') { return stopped(state); } return state; }, undefined ); const MasterControlProgram = () => createBehavior<SpawnJob>((state, message, context) => { if (isSignal(message)) { switch (message.type) { case ActorSignalType.Terminated: context.log(`Job stopped: ${message.ref.name}`); expect(message.ref.name).toEqual('job1'); done(); return state; default: return state; } } switch (message.type) { case 'SpawnJob': context.log(`Spawning job ${message.jobName}!`); const job = context.spawn(Job(message.jobName), message.jobName); context.watch(job); return state; default: return state; } }, undefined); const sys = createSystem(MasterControlProgram(), 'master'); sys.send({ type: 'SpawnJob', jobName: 'job1', }); }, 1000); describe('interaction patterns', () => { it('fire and forget', done => { interface PrintMe { type: 'PrintMe'; message: string; } // const Printer = (): Behavior<PrintMe> => { // return receive((ctx, msg) => { // switch (msg.type) { // case 'PrintMe': // ctx.log(msg.message); // if (msg.message === 'not message 2') { // done(); // } // return BehaviorTag.Same; // } // }); // }; const Printer = () => createBehavior<PrintMe>((state, msg, ctx) => { switch (msg.type) { case 'PrintMe': ctx.log(msg.message); if (msg.message === 'not message 2') { done(); } return state; } }, undefined); const sys = createSystem(Printer(), 'fire-and-forget-sample'); sys.send({ type: 'PrintMe', message: 'message 1' }); sys.send({ type: 'PrintMe', message: 'not message 2' }); }); it('request-response', done => { interface ResponseMsg { type: 'Response'; result: string; } interface RequestMsg { type: 'Request'; query: string; replyTo: ActorRef<ResponseMsg | any>; } const CookieFabric = () => createBehavior<RequestMsg>((state, msg, ctx) => { switch (msg.type) { case 'Request': ctx.send(msg.replyTo, { type: 'Response', result: `Here are the cookies for [${msg.query}]!`, }); return state; default: return state; } }, undefined); const Requestor = () => createBehavior<ResponseMsg | { type: 'start' }>((state, msg, ctx) => { switch (msg.type) { case 'start': const cookieFabric = ctx.spawn(CookieFabric(), 'cookie-fabric'); ctx.send(cookieFabric, { type: 'Request', query: 'my query', replyTo: ctx.self, }); return state; case 'Response': ctx.log(`Got a response: ${msg.result}`); console.log(sys.logs); const participants: Set<ActorRef<any>> = new Set(); sys.logs.map(log => { if ('log' in log) { participants.add(log.ref); } else { participants.add(log.from); participants.add(log.to); } }); const parr = Array.from(participants); const seqDiagram = `sequenceDiagram\n` + parr .map((value, index) => { return ` participant ${index} as ${value.name}`; }) .join('\n') + '\n' + sys.logs .map(log => { if ('log' in log) { return ` Note right of ${parr.indexOf(log.ref)}: ${ log.log }`; } const from = parr.indexOf(log.from); const to = parr.indexOf(log.to); return ` ${from}->>${to}: '${JSON.stringify( log.message, (_key, value) => { if (value instanceof ActorRef) { return value.name; } return value; } )}'`; }) .join('\n'); console.log(seqDiagram); done(); return state; default: return state; } }, undefined); const sys = createSystem(Requestor(), 'test'); sys.send({ type: 'start' }); }); // it('request-response with ask between two actors', (done) => { // // object Hal { // // sealed trait Command // // case class OpenThePodBayDoorsPlease(replyTo: ActorRef[Response]) extends Command // // case class Response(message: String) // // def apply(): Receive[Hal.Command] = // // receiveMessage[Command] { // // case OpenThePodBayDoorsPlease(replyTo) => // // replyTo ! Response("I'm sorry, Dave. I'm afraid I can't do that.") // // same // // } // // } // interface HalResponse { // type: 'HalResponse'; // message: string; // } // interface OpenThePodBayDoorsPlease { // type: 'OpenThePodBayDoorsPlease'; // replyTo: ActorRef<HalResponse>; // } // const Hal = () => // receive<OpenThePodBayDoorsPlease>((ctx, msg) => { // switch (msg.type) { // case 'OpenThePodBayDoorsPlease': // msg.replyTo.send({ // type: 'HalResponse', // message: "I'm sorry, Dave. I'm afraid I can't do that.", // }); // return BehaviorTag.Same; // } // }); // }); }); });
the_stack
import { dispatch, store } from "./AppRedux"; import { AppState } from "./AppState"; import { Constants as C } from "./Constants"; import { ConfirmDlg } from "./dlg/ConfirmDlg"; import { SignupDlg } from "./dlg/SignupDlg"; import { UserIntf } from "./intf/UserIntf"; import * as J from "./JavaIntf"; import { PubSub } from "./PubSub"; import { Singletons } from "./Singletons"; let S: Singletons; PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => { S = s; }); export class User implements UserIntf { closeAccountResponse = (res: J.CloseAccountResponse): void => { /* Remove warning dialog to ask user about leaving the page */ window.onbeforeunload = null; /* reloads browser with the query parameters stripped off the path */ window.location.href = window.location.origin; } closeAccount = (): void => { let state = store.getState(); new ConfirmDlg("Are you sure you want to close your account?", "Close Account", () => { new ConfirmDlg("Your data will be deleted and can never be recovered. Are you sure?", "Last Chance... One more Click", () => { this.deleteAllUserLocalDbEntries(); S.util.ajax<J.CloseAccountRequest, J.CloseAccountResponse>("closeAccount", {}, this.closeAccountResponse); }, null, null, null, state ).open(); }, null, null, null, state ).open(); } /* * for testing purposes, I want to allow certain users additional privileges. A bit of a hack because it will go * into production, but on my own production these are my "testUserAccounts", so no real user will be able to * use these names */ isTestUserAccount = (state: AppState): boolean => { return state.userName.toLowerCase() === "adam" || // state.userName.toLowerCase() === "bob" || // state.userName.toLowerCase() === "cory" || // state.userName.toLowerCase() === "dan"; } openSignupPg = (state: AppState): void => { new SignupDlg(state).open(); } defaultHandleAnonUser = (state: AppState) => { // todo-1: new logic: always send anon users to fediverse view. // but we need to make this an admin-configurable behavior. // var tab = S.util.getParameterByName("tab"); // if (tab === "feed") { if (window.location.href.endsWith("/app")) { setTimeout(() => { S.quanta.showPublicFediverse(); }, 10); } else { S.quanta.loadAnonPageHome(null); } } refreshLogin = async (state: AppState): Promise<void> => { console.log("refreshLogin."); const loginState: string = await S.localDB.getVal(C.LOCALDB_LOGIN_STATE); /* if we have known state as logged out, then do nothing here */ if (loginState === "0") { // console.log("loginState known as logged out."); this.defaultHandleAnonUser(state); return; } const usr = await S.localDB.getVal(C.LOCALDB_LOGIN_USR); const pwd = await S.localDB.getVal(C.LOCALDB_LOGIN_PWD); const usingCredentials: boolean = usr && pwd; /* * empyt credentials causes server to try to log in with any active session credentials. */ const callUsr: string = usr || ""; const callPwd: string = pwd || ""; console.log("refreshLogin with name: " + callUsr); if (!callUsr) { this.defaultHandleAnonUser(state); } else { S.util.ajax<J.LoginRequest, J.LoginResponse>("login", { userName: callUsr, password: callPwd, tzOffset: new Date().getTimezoneOffset(), dst: S.util.daylightSavingsTime }, async (res: J.LoginResponse) => { S.quanta.authToken = res.authToken; // console.log("login: " + S.util.prettyPrint(res)); if (res && !res.success) { await S.user.deleteAllUserLocalDbEntries(); } if (usingCredentials) { // console.log("calling loginResponse()"); // Note: If user entered wrong case-sentitivity string on login dialog they can still login // but this res.userName however will have the correct name (case-sensitive) here now. this.loginResponse(res, res.userName, callPwd, false, state); } else { if (res.success) { S.quanta.setStateVarsUsingLoginResponse(res); } this.defaultHandleAnonUser(state); } }, async (error: string) => { await S.user.deleteAllUserLocalDbEntries(); S.quanta.loadAnonPageHome(null); }); } } logout = async (updateLocalDb: any, state: AppState): Promise<void> => { if (state.isAnonUser) { return; } /* Remove warning dialog to ask user about leaving the page */ window.onbeforeunload = null; if (updateLocalDb) { await S.localDB.setVal(C.LOCALDB_LOGIN_STATE, "0"); /* Setting logged in state for non-user also */ await S.localDB.setVal(C.LOCALDB_LOGIN_STATE, "0", "anon"); } S.quanta.loggingOut = true; S.util.ajax<J.LogoutRequest, J.LogoutResponse>("logout", {}, this.logoutResponse, this.logoutResponse); } logoutResponse = (): void => { S.push.close(); S.quanta.authToken = null; S.quanta.userName = null; window.location.href = window.location.origin; // + "/app"; } deleteAllUserLocalDbEntries = (): Promise<any> => { return Promise.all([ // S.localDB.setVal(C.LOCALDB_LOGIN_USR, null), S.localDB.setVal(C.LOCALDB_LOGIN_PWD, null), S.localDB.setVal(C.LOCALDB_LOGIN_STATE, null) ]); } loginResponse = async (res: J.LoginResponse, usr: string, pwd: string, calledFromLoginDlg: boolean, state: AppState): Promise<void> => { if (S.util.checkSuccess("Login", res)) { if (usr !== J.PrincipalName.ANON) { S.localDB.userName = usr; if (usr) { await S.localDB.setVal(C.LOCALDB_LOGIN_USR, usr); // set this user for the 'anon' case also meaning it'll be default when user it not logged in await S.localDB.setVal(C.LOCALDB_LOGIN_USR, usr, "anon"); } if (pwd) { await S.localDB.setVal(C.LOCALDB_LOGIN_PWD, pwd); // set this pwd for the 'anon' case also meaning it'll be default when user it not logged in await S.localDB.setVal(C.LOCALDB_LOGIN_PWD, pwd, "anon"); } await S.localDB.setVal(C.LOCALDB_LOGIN_STATE, "1"); await S.localDB.setVal(C.LOCALDB_LOGIN_STATE, "1", "anon"); S.quanta.userName = usr; console.log("Logged in as: " + usr); this.queryUserProfile(res.rootNode); this.checkMessages(); setTimeout(() => { S.quanta.loadBookmarks(); S.push.init(); }, 1000); } S.quanta.setStateVarsUsingLoginResponse(res); // we just processed a dispatch so we need to get the current state now. state = store.getState(); /* set ID to be the page we want to show user right after login */ let id: string = null; let childId: string = null; let renderLeafIfParent = true; if (res.homeNodeOverride) { id = res.homeNodeOverride; // console.log("homeNodeOverride=" + id); if (id && id.startsWith("~")) { renderLeafIfParent = false; } } // else { const lastNode = await S.localDB.getVal(C.LOCALDB_LAST_PARENT_NODEID); if (lastNode) { id = lastNode; // console.log("Node selected from local storage: id=" + id); childId = await S.localDB.getVal(C.LOCALDB_LAST_CHILD_NODEID); } else { // todo-2: note... this path is now untested due to recent refactoring. id = state.homeNodeId; // console.log("Node selected from homeNodeId: id=" + id); } } // console.log("Window: " + window.location.href); if (window.location.href.endsWith("/app") && usr === J.PrincipalName.ANON) { // console.log("login is refreshingTree with ID=" + id); // var tab = S.util.getParameterByName("tab"); // if (tab === "feed") { setTimeout(() => { // todo-1: new logic, always send anon users to fediverse view S.quanta.showPublicFediverse(); }, 10); // } } else { // console.log("loginResponse final refresh id chosen: " + id); S.view.refreshTree(id, true, renderLeafIfParent, childId, false, true, true, state); } } else { console.log("LocalDb login failed."); // if we tried a login and it wasn't from a login dialog then just blow away the login state // so that any kind of page refresh is guaranteed to just show login dialog and not try to login await this.deleteAllUserLocalDbEntries(); // location.reload(); if (!calledFromLoginDlg) { S.nav.login(state); } } } checkMessages = (): Promise<void> => { return new Promise<void>((resolve, reject) => { S.util.ajax<J.CheckMessagesRequest, J.CheckMessagesResponse>("checkMessages", { }, (res: J.CheckMessagesResponse): void => { // console.log("Response: " + S.util.prettyPrint(res)); if (res) { dispatch("Action_SetNewMessageCount", (s: AppState): AppState => { s.newMessageCount = res.numNew; return s; }); } resolve(); }, () => resolve()); }); } queryUserProfile = (userId: string): Promise<void> => { return new Promise<void>((resolve, reject) => { S.util.ajax<J.GetUserProfileRequest, J.GetUserProfileResponse>("getUserProfile", { userId }, (res: J.GetUserProfileResponse): void => { // console.log("queryUserProfile Response: " + S.util.prettyPrint(res)); if (res && res.userProfile) { dispatch("Action_SetUserProfile", (s: AppState): AppState => { s.userProfile = res.userProfile; return s; }); } resolve(); }, () => resolve()); }); } }
the_stack
* @title: 3D Physics benchmark * @description: * This sample is a benchmark for rigid body physics simulation with randomly generated boxes, spheres, cones, * cylinders, capsules and convex hulls. * The rigid bodies fall into a procedurally generated triangle mesh bowl that can be animated. * The sample also shows the time spent on the different physics simulation phases. * Disabling the debug rendering will show its impact on the framerate, the physics simulation will continue but * without any graphics update. */ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/floor.js") }}*/ /*{{ javascript("jslib/geometry.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/light.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/vmath.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/resourceloader.js") }}*/ /*{{ javascript("jslib/scenedebugging.js") }}*/ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/physicsmanager.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/vertexbuffermanager.js") }}*/ /*{{ javascript("jslib/indexbuffermanager.js") }}*/ /*{{ javascript("jslib/mouseforces.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*{{ javascript("scripts/sceneloader.js") }}*/ /*global TurbulenzEngine: true */ /*global RequestHandler: false */ /*global SceneLoader: false */ /*global SceneNode: false */ /*global TurbulenzServices: false */ /*global ShaderManager: false */ /*global Scene: false */ /*global Camera: false */ /*global CameraController: false */ /*global Floor: false */ /*global MouseForces: false */ /*global PhysicsManager: false */ /*global HTMLControls: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; TurbulenzEngine.onerror = errorCallback; var warningCallback = function warningCallback(msg) { window.alert(msg); }; TurbulenzEngine.onwarning = warningCallback; var mathDeviceParameters = { }; var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters); var graphicsDeviceParameters = { }; var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters); var physicsDeviceParameters = { }; var physicsDevice = TurbulenzEngine.createPhysicsDevice(physicsDeviceParameters); var dynamicsWorldParameters = { variableTimeSteps : true, maxSubSteps : 2 }; var dynamicsWorld = physicsDevice.createDynamicsWorld(dynamicsWorldParameters); var inputDeviceParameters = { }; var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters); var requestHandlerParameters = { }; var requestHandler = RequestHandler.create(requestHandlerParameters); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var physicsManager = PhysicsManager.create(mathDevice, physicsDevice, dynamicsWorld); var debugMode = true; // Renderer and assets for the scene. var scene = Scene.create(mathDevice); var sceneLoader = SceneLoader.create(); // Setup world space var clearColor = mathDevice.v4Build(0.95, 0.95, 1.0, 1.0); var loadingClearColor = mathDevice.v4Build(0.8, 0.8, 0.8, 1.0); var worldUp = mathDevice.v3BuildYAxis(); // Setup a camera to view a close-up object var camera = Camera.create(mathDevice); camera.nearPlane = 0.05; var cameraDefaultPos = mathDevice.v3Build(0, 8.0, 18.1); var cameraDefaultLook = mathDevice.v3Build(0, -(camera.farPlane / 4), -camera.farPlane); // The objects needed to draw the crosshair var technique2d; var shader2d; var techniqueParameters2d; var chSemantics = graphicsDevice.createSemantics(['POSITION']); var chFormats = [graphicsDevice.VERTEXFORMAT_FLOAT3]; // Setup world floor var floor = Floor.create(graphicsDevice, mathDevice); var cameraController = CameraController.create(graphicsDevice, inputDevice, camera); // Mouse forces var dragMin = mathDevice.v3Build(-50, -50, -50); var dragMax = mathDevice.v3Build(50, 50, 50); var mouseForces = MouseForces.create(graphicsDevice, inputDevice, mathDevice, physicsDevice, dragMin, dragMax); mouseForces.clamp = 400; // Control codes var keyCodes = inputDevice.keyCodes; var mouseCodes = inputDevice.mouseCodes; // Dynamic physics objects var physicsObjects = []; var bowlObject; // Configuration of demo. // Bowl radius and height var bowlRadius = 9; var bowlHeight = 5; // Number of radial points, and planes in bowl. var radialN = 30; var depthN = 10; // Control approximate size of objects var objectSize = 0.5; // Radius to place objects at in spiral // y-displacement between each object. // And start y position. var genRadius = bowlRadius - 4; var genDeltaY = 1; var genStartY = 50; var genStartSpeed = 60; // Number of objects var genCount = 100; // Determine a suitable angular displacement between each object. var genTheta = Math.asin(0.5 * Math.sqrt(100 * objectSize * objectSize + genDeltaY * genDeltaY) / genRadius); // Whether bowl is animated. var animateBowl = false; var animateBowlTime = 0; var prevAnimationTime = 0; var animatedBowlAxis = mathDevice.v3Build(0, 0, 1); var animatedBowlTransform = mathDevice.m43BuildIdentity(); function reset() { // Reset camera camera.lookAt(cameraDefaultLook, worldUp, cameraDefaultPos); camera.updateViewMatrix(); // Reset physics object positions to new random values. // We keep the physics objects that already exist to simplify things. var n; var maxN = physicsObjects.length; for (n = 0; n < maxN; n += 1) { var body = physicsObjects[n]; dynamicsWorld.removeRigidBody(body); var position = mathDevice.m43BuildTranslation(genRadius * Math.cos(n * genTheta), genStartY + (genDeltaY * n) * 3, genRadius * Math.sin(n * genTheta)); body.transform = position; body.linearVelocity = mathDevice.v3Build(0, -genStartSpeed, 0); body.angularVelocity = mathDevice.v3BuildZero(); body.active = true; dynamicsWorld.addRigidBody(body); } } var onMouseDown = function (button) { if (mouseCodes.BUTTON_0 === button || mouseCodes.BUTTON_1 === button) { mouseForces.onmousedown(); } }; var onMouseUp = function (button) { if (mouseCodes.BUTTON_0 === button || mouseCodes.BUTTON_1 === button) { mouseForces.onmouseup(); } }; var onKeyUp = function physicsOnkeyupFn(keynum) { if (keynum === keyCodes.R) // 'r' key { reset(); } else { cameraController.onkeyup(keynum); } }; // Add event listeners inputDevice.addEventListener("keyup", onKeyUp); inputDevice.addEventListener("mousedown", onMouseDown); inputDevice.addEventListener("mouseup", onMouseUp); // Controls var htmlControls = HTMLControls.create(); htmlControls.addCheckboxControl({ id: "checkbox01", value: "debugMode", isSelected: debugMode, fn: function () { debugMode = !debugMode; return debugMode; } }); htmlControls.addCheckboxControl({ id: "checkbox02", value: "animate", isSelected: animateBowl, fn: function () { animateBowl = !animateBowl; prevAnimationTime = TurbulenzEngine.time; return animateBowl; } }); htmlControls.register(); function drawCrosshair() { if (!mouseForces.pickedBody) { graphicsDevice.setTechnique(technique2d); var screenWidth = graphicsDevice.width; var screenHeight = graphicsDevice.height; techniqueParameters2d.clipSpace = mathDevice.v4Build(2.0 / screenWidth, -2.0 / screenHeight, -1.0, 1.0, techniqueParameters2d.clipSpace); graphicsDevice.setTechniqueParameters(techniqueParameters2d); var writer = graphicsDevice.beginDraw( graphicsDevice.PRIMITIVE_LINES, 4, chFormats, chSemantics); if (writer) { var halfWidth = screenWidth * 0.5; var halfHeight = screenHeight * 0.5; writer(halfWidth - 10, halfHeight); writer(halfWidth + 10, halfHeight); writer(halfWidth, halfHeight - 10); writer(halfWidth, halfHeight + 10); graphicsDevice.endDraw(writer); } } } var nextUpdate = 0; var fpsElement = document.getElementById("fpscounter"); var lastFPS = ""; var discreteElement = document.getElementById("discrete"); var preComputationsElement = document.getElementById("precomputations"); var physicsIterationsElement = document.getElementById("physicsiterations"); var continuousElement = document.getElementById("continuous"); var lastDiscreteText = ""; var lastPreComputationsText = ""; var lastPhysicsIterationsText = ""; var lastContinuousText = ""; var discreteVal = -1; var preComputationsVal = -1; var physicsIterationsVal = -1; var continuousVal = -1; var displayPerformance = function displayPerformanceFn() { if (TurbulenzEngine.canvas) { var data = dynamicsWorld.performanceData; var preval = data.sleepComputation + data.prestepContacts + data.prestepConstraints + data.integrateVelocities + data.warmstartContacts + data.warmstartConstraints; var contval = data.integratePositions + data.continuous; if (discreteVal === -1) { discreteVal = data.discrete; preComputationsVal = preval; physicsIterationsVal = data.physicsIterations; continuousVal = contval; } else { discreteVal = (0.95 * discreteVal) + (0.05 * data.discrete); preComputationsVal = (0.95 * preComputationsVal) + (0.05 * preval); physicsIterationsVal = (0.95 * physicsIterationsVal) + (0.05 * data.physicsIterations); continuousVal = (0.95 * continuousVal) + (0.05 * contval); } } var currentTime = TurbulenzEngine.time; if (nextUpdate < currentTime) { nextUpdate = (currentTime + 0.1); // No fpsElement if we are running in standalone or // directly via the .tzjs if (fpsElement) { var fpsText = (graphicsDevice.fps).toFixed(2); if (lastFPS !== fpsText) { lastFPS = fpsText; fpsElement.innerHTML = fpsText + " fps"; } } if (TurbulenzEngine.canvas) { var discreteText = (1e3 * discreteVal).toFixed(2); var preComputationsText = (1e3 * preComputationsVal).toFixed(2); var physicsIterationsText = (1e3 * physicsIterationsVal).toFixed(2); var continuousText = (1e3 * continuousVal).toFixed(2); if (discreteElement && lastDiscreteText !== discreteText) { lastDiscreteText = discreteText; discreteElement.innerHTML = discreteText + " ms"; } if (preComputationsElement && lastPreComputationsText !== preComputationsText) { lastPreComputationsText = preComputationsText; preComputationsElement.innerHTML = preComputationsText + " ms"; } if (physicsIterationsElement && lastPhysicsIterationsText !== physicsIterationsText) { lastPhysicsIterationsText = physicsIterationsText; physicsIterationsElement.innerHTML = physicsIterationsText + " ms"; } if (continuousElement && lastContinuousText !== continuousText) { lastContinuousText = continuousText; continuousElement.innerHTML = continuousText + " ms"; } discreteVal = -1; preComputationsVal = -1; physicsIterationsVal = -1; continuousVal = -1; } } }; // Functions to generate a physics object of a particular type. var factories = [ // Create a random box primitive function boxFactoryFn() { var width = objectSize + (Math.random() * objectSize); var height = objectSize + (Math.random() * objectSize); var depth = objectSize + (Math.random() * objectSize); return physicsDevice.createBoxShape({ halfExtents : mathDevice.v3Build(width, height, depth), margin : 0.001 }); }, // Create a random convex hull primitive function convexHullFactoryFn() { var radius0 = (objectSize + (Math.random() * objectSize)) * 2.0; var radius1 = (objectSize + (Math.random() * objectSize)) * 2.0; var radius2 = (objectSize + (Math.random() * objectSize)) * 2.0; var numPoints = Math.floor(5 + Math.random() * 30); var positionsData = []; var i; for (i = 0; i < (numPoints * 3); i += 3) { var azimuth = Math.random() * Math.PI * 2; var elevation = (Math.random() - 0.5) * Math.PI; positionsData[i] = Math.sin(azimuth) * Math.cos(elevation) * radius0; positionsData[i + 1] = Math.cos(azimuth) * radius2; positionsData[i + 2] = Math.sin(azimuth) * Math.sin(elevation) * radius1; } return physicsDevice.createConvexHullShape({ points : positionsData, margin : 0.001 }); }, // Create a random sphere primitive function sphereFactoryFn() { return physicsDevice.createSphereShape({ radius : (objectSize + (Math.random() * objectSize)) * 1.5, margin : 0.0 }); }, // Create a random capsule primitive function capsuleFactoryFn() { return physicsDevice.createCapsuleShape({ radius : (objectSize + (Math.random() * objectSize)), height : (objectSize + (Math.random() * objectSize)) * 2, margin : 0.001 }); }, // Create a random cylinder primitive function cylinderFactoryFn() { var radius = (objectSize + (Math.random() * objectSize)); var height = (objectSize + (Math.random() * objectSize)); return physicsDevice.createCylinderShape({ halfExtents : mathDevice.v3Build(radius, height, radius), margin : 0.001 }); }, // Create a random cone primitive function coneFactoryFn() { return physicsDevice.createConeShape({ radius : (objectSize + (Math.random() * objectSize)) * 1.5, height : (objectSize + (Math.random() * objectSize)) * 3, margin : 0.001 }); } ]; var skipFrame = true; var deferredObjectCreation = function deferredObjectCreationFn() { var i = physicsObjects.length; var shape = factories[Math.floor(factories.length * Math.random())](); var position = mathDevice.m43BuildTranslation(genRadius * Math.cos(i * genTheta), genStartY + (genDeltaY * i), genRadius * Math.sin(i * genTheta)); var sceneNode = SceneNode.create({ name: "Phys" + i, local: position, dynamic: true, disabled: false }); var rigidBody = physicsDevice.createRigidBody({ shape: shape, mass: 10.0, inertia: mathDevice.v3ScalarMul(shape.inertia, 10.0), transform: position, friction: 0.8, restitution: 0.2, angularDamping: 0.4, linearVelocity : mathDevice.v3Build(0, -genStartSpeed, 0) }); scene.addRootNode(sceneNode); physicsManager.addNode(sceneNode, rigidBody); physicsObjects.push(rigidBody); }; var renderFrame = function renderFrameFn() { // Update input and camera inputDevice.update(); if (mouseForces.pickedBody) { // If we're dragging a body don't apply the movement to the camera cameraController.pitch = 0; cameraController.turn = 0; cameraController.step = 0; } cameraController.update(); var deviceWidth = graphicsDevice.width; var deviceHeight = graphicsDevice.height; var aspectRatio = (deviceWidth / deviceHeight); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); // Generate new physics objects. // // To deal with JIT slow-down on start up in canvas, we continously add new objects // every other frame to prevent massive initial slow down. if (physicsObjects.length !== genCount && !skipFrame) { deferredObjectCreation(); } skipFrame = !skipFrame; if (animateBowl) { animateBowlTime += (TurbulenzEngine.time - prevAnimationTime); prevAnimationTime = TurbulenzEngine.time; mathDevice.m43FromAxisRotation(animatedBowlAxis, 0.5 * Math.sin(animateBowlTime), animatedBowlTransform); animatedBowlTransform[10] = Math.abs(7 * 0.5 * Math.sin(Math.sin(animateBowlTime))); bowlObject.transform = animatedBowlTransform; } // Update the physics mouseForces.update(dynamicsWorld, camera, 0.1); dynamicsWorld.update(); physicsManager.update(); scene.update(); scene.updateVisibleNodes(camera); if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor, 1.0, 0); floor.render(graphicsDevice, camera); if (debugMode) { scene.drawPhysicsGeometry(graphicsDevice, shaderManager, camera, physicsManager); } drawCrosshair(); graphicsDevice.endFrame(); } displayPerformance(); }; var intervalID; var loadingCompleted = false; var loadingLoop = function loadingLoopFn() { if (graphicsDevice.beginFrame()) { graphicsDevice.clear(loadingClearColor); graphicsDevice.endFrame(); } if (loadingCompleted) { TurbulenzEngine.clearInterval(intervalID); camera.lookAt(cameraDefaultLook, worldUp, cameraDefaultPos); camera.updateViewMatrix(); shader2d = shaderManager.get("shaders/generic2D.cgfx"); technique2d = shader2d.getTechnique("constantColor2D"); techniqueParameters2d = graphicsDevice.createTechniqueParameters({ clipSpace : mathDevice.v4BuildOne(), constantColor : mathDevice.v4Build(0, 0, 0, 1) }); intervalID = TurbulenzEngine.setInterval(renderFrame, 1000 / 60); } }; intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10); // Change the clear color before we start loading assets loadingLoop(); var postLoad = function postLoadFn() { // Floor is represented by a plane shape var floorShape = physicsDevice.createPlaneShape({ normal : mathDevice.v3Build(0, 1, 0), distance : 0, margin : 0.001 }); var floorObject = physicsDevice.createCollisionObject({ shape : floorShape, transform : mathDevice.m43BuildIdentity(), friction : 0.8, restitution : 0.1, group: physicsDevice.FILTER_STATIC, mask: physicsDevice.FILTER_ALL }); // Adds the floor collision object to the world dynamicsWorld.addCollisionObject(floorObject); // Bowl is represented by a triangle mesh shape. // We create the triangle mesh simply and manually. var positionsData = []; var indicesData = []; // Compute bowl vertices. var i, j, offset; for (i = 0; i < depthN; i += 1) { var elevation = (Math.PI * 0.75) * ((i + 1) / (depthN + 2)); for (j = 0; j < radialN; j += 1) { var azimuth = (Math.PI * 2) * (j / radialN); offset = ((i * radialN) + j) * 3; positionsData[offset] = Math.sin(elevation) * Math.cos(azimuth) * bowlRadius; positionsData[offset + 1] = (1 - Math.cos(elevation)) * bowlHeight; positionsData[offset + 2] = Math.sin(elevation) * Math.sin(azimuth) * bowlRadius; } } offset = (depthN * radialN) * 3; positionsData[offset] = 0; positionsData[offset + 1] = 0; positionsData[offset + 2] = 0; // Compute bowl triangle indices for (i = 0; i < (depthN - 1); i += 1) { for (j = 0; j < radialN; j += 1) { offset = ((i * radialN) + j) * 3 * 2; indicesData[offset] = (i * radialN) + j; indicesData[offset + 1] = (i * radialN) + ((j + 1) % radialN); indicesData[offset + 2] = ((i + 1) * radialN) + j; indicesData[offset + 3] = ((i + 1) * radialN) + j; indicesData[offset + 4] = (i * radialN) + ((j + 1) % radialN); indicesData[offset + 5] = ((i + 1) * radialN) + ((j + 1) % radialN); } } for (i = 0; i < radialN; i += 1) { offset = (((depthN - 1) * radialN) * 3 * 2) + (i * 3); indicesData[offset] = i; indicesData[offset + 1] = (depthN * radialN); indicesData[offset + 2] = ((i + 1) % radialN); } // Create triangle array for bowl var bowlTriangleArray = physicsDevice.createTriangleArray({ vertices : positionsData, indices : indicesData }); // Create bowl physics shape and object. var bowlShape = physicsDevice.createTriangleMeshShape({ triangleArray : bowlTriangleArray, margin : 0.001 }); bowlObject = physicsDevice.createCollisionObject({ shape : bowlShape, transform : mathDevice.m43BuildIdentity(), friction : 0.8, restitution : 0.1, group: physicsDevice.FILTER_STATIC, mask: physicsDevice.FILTER_ALL, kinematic : true }); // Create SceneNode for bowl, and add to scene. var bowlSceneNode = SceneNode.create({ name: "Bowl", local: bowlObject.transform, dynamic: true, disabled: false }); scene.addRootNode(bowlSceneNode); physicsManager.addNode(bowlSceneNode, bowlObject, null, bowlTriangleArray); }; var numShadersToLoad = 2; var shadersLoaded = function shadersLoadedFn(/* shader */) { numShadersToLoad -= 1; if (0 === numShadersToLoad) { postLoad(); loadingCompleted = true; } }; var loadAssets = function loadAssetsFn() { shaderManager.load("shaders/debug.cgfx", shadersLoaded); shaderManager.load("shaders/generic2D.cgfx", shadersLoaded); }; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); loadAssets(); }; var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); }; var gameSessionFailed = function gameSessionFailedFn(reason) { gameSessionCreated(null); }; var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated, gameSessionFailed); // Create a scene destroy callback to run when the window is closed function destroyScene() { gameSession.destroy(); TurbulenzEngine.clearInterval(intervalID); clearColor = null; if (physicsManager) { physicsManager.clear(); physicsManager = null; } if (scene) { scene.destroy(); scene = null; } requestHandler = null; camera = null; techniqueParameters2d = null; technique2d = null; shader2d = null; chSemantics = null; chFormats = null; if (shaderManager) { shaderManager.destroy(); shaderManager = null; } TurbulenzEngine.flush(); graphicsDevice = null; mathDevice = null; physicsDevice = null; dynamicsWorld = null; mouseCodes = null; keyCodes = null; inputDevice = null; cameraController = null; floor = null; } TurbulenzEngine.onunload = destroyScene; };
the_stack
import { ChangeDetectorRef, Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, NgModule, OnDestroy, OnInit, Optional, Output, Inject } from '@angular/core'; import { IgxNavigationService, IToggleView } from '../../core/navigation'; import { IgxOverlayService } from '../../services/overlay/overlay'; import { AbsoluteScrollStrategy, ConnectedPositioningStrategy, IPositionStrategy, OverlayEventArgs, OverlaySettings } from '../../services/public_api'; import { filter, first, takeUntil } from 'rxjs/operators'; import { Subscription, Subject, MonoTypeOperatorFunction } from 'rxjs'; import { OverlayClosingEventArgs } from '../../services/overlay/utilities'; import { CancelableBrowserEventArgs, IBaseEventArgs } from '../../core/utils'; export interface ToggleViewEventArgs extends IBaseEventArgs { /** Id of the toggle view */ id: string; event?: Event; } export interface ToggleViewCancelableEventArgs extends ToggleViewEventArgs, CancelableBrowserEventArgs { } @Directive({ exportAs: 'toggle', selector: '[igxToggle]' }) export class IgxToggleDirective implements IToggleView, OnInit, OnDestroy { /** * Emits an event after the toggle container is opened. * * ```typescript * onToggleOpened(event) { * alert("Toggle opened!"); * } * ``` * * ```html * <div * igxToggle * (onOpened)='onToggleOpened($event)'> * </div> * ``` */ @Output() public opened = new EventEmitter<ToggleViewEventArgs>(); /** * Emits an event before the toggle container is opened. * * ```typescript * onToggleOpening(event) { * alert("Toggle opening!"); * } * ``` * * ```html * <div * igxToggle * (onOpening)='onToggleOpening($event)'> * </div> * ``` */ @Output() public opening = new EventEmitter<ToggleViewCancelableEventArgs>(); /** * Emits an event after the toggle container is closed. * * ```typescript * onToggleClosed(event) { * alert("Toggle closed!"); * } * ``` * * ```html * <div * igxToggle * (onClosed)='onToggleClosed($event)'> * </div> * ``` */ @Output() public closed = new EventEmitter<ToggleViewEventArgs>(); /** * Emits an event before the toggle container is closed. * * ```typescript * onToggleClosing(event) { * alert("Toggle closing!"); * } * ``` * * ```html * <div * igxToggle * (closing)='onToggleClosing($event)'> * </div> * ``` */ @Output() public closing = new EventEmitter<ToggleViewCancelableEventArgs>(); /** * Emits an event after the toggle element is appended to the overlay container. * * ```typescript * onAppended() { * alert("Content appended!"); * } * ``` * * ```html * <div * igxToggle * (onAppended)='onToggleAppended()'> * </div> * ``` */ @Output() public appended = new EventEmitter<ToggleViewEventArgs>(); /** * @hidden */ public get collapsed(): boolean { return this._collapsed; } /** * Identifier which is registered into `IgxNavigationService` * * ```typescript * let myToggleId = this.toggle.id; * ``` */ @Input() public id: string; /** * @hidden */ public get element(): HTMLElement { return this.elementRef.nativeElement; } /** * @hidden */ @HostBinding('class.igx-toggle--hidden') @HostBinding('attr.aria-hidden') public get hiddenClass() { return this.collapsed; } /** * @hidden */ @HostBinding('class.igx-toggle') public get defaultClass() { return !this.collapsed; } protected _overlayId: string; private _collapsed = true; private destroy$ = new Subject<boolean>(); private _overlaySubFilter: [MonoTypeOperatorFunction<OverlayEventArgs>, MonoTypeOperatorFunction<OverlayEventArgs>] = [ filter(x => x.id === this._overlayId), takeUntil(this.destroy$) ]; private _overlayOpenedSub: Subscription; private _overlayClosingSub: Subscription; private _overlayClosedSub: Subscription; private _overlayContentAppendedSub: Subscription; /** * @hidden */ constructor( private elementRef: ElementRef, private cdr: ChangeDetectorRef, @Inject(IgxOverlayService) protected overlayService: IgxOverlayService, @Optional() private navigationService: IgxNavigationService) { } /** * Opens the toggle. * * ```typescript * this.myToggle.open(); * ``` */ public open(overlaySettings?: OverlaySettings) { // if there is open animation do nothing // if toggle is not collapsed and there is no close animation do nothing const info = this.overlayService.getOverlayById(this._overlayId); const openAnimationStarted = info?.openAnimationPlayer?.hasStarted() ?? false; const closeAnimationStarted = info?.closeAnimationPlayer?.hasStarted() ?? false; if (openAnimationStarted || !(this._collapsed || closeAnimationStarted)) { return; } this._collapsed = false; this.cdr.detectChanges(); if (!info) { this.unsubscribe(); this.subscribe(); this._overlayId = this.overlayService.attach(this.elementRef, overlaySettings); } const args: ToggleViewCancelableEventArgs = { cancel: false, owner: this, id: this._overlayId }; this.opening.emit(args); if (args.cancel) { this.unsubscribe(); this.overlayService.detach(this._overlayId); this._collapsed = true; this.cdr.detectChanges(); return; } this.overlayService.show(this._overlayId, overlaySettings); } /** * Closes the toggle. * * ```typescript * this.myToggle.close(); * ``` */ public close() { // if toggle is collapsed do nothing // if there is close animation do nothing, toggle will close anyway const info = this.overlayService.getOverlayById(this._overlayId); const closeAnimationStarted = info?.closeAnimationPlayer?.hasStarted() || false; if (this._collapsed || closeAnimationStarted) { return; } this.overlayService.hide(this._overlayId); } /** * Opens or closes the toggle, depending on its current state. * * ```typescript * this.myToggle.toggle(); * ``` */ public toggle(overlaySettings?: OverlaySettings) { // if toggle is collapsed call open // if there is running close animation call open if (this.collapsed || this.isClosing) { this.open(overlaySettings); } else { this.close(); } } /** @hidden @internal */ public get isClosing() { const info = this.overlayService.getOverlayById(this._overlayId); return info ? info.closeAnimationPlayer?.hasStarted() : false; } /** * Returns the id of the overlay the content is rendered in. * ```typescript * this.myToggle.overlayId; * ``` */ public get overlayId() { return this._overlayId; } /** * Repositions the toggle. * ```typescript * this.myToggle.reposition(); * ``` */ public reposition() { this.overlayService.reposition(this._overlayId); } /** * Offsets the content along the corresponding axis by the provided amount */ public setOffset(deltaX: number, deltaY: number) { this.overlayService.setOffset(this._overlayId, deltaX, deltaY); } /** * @hidden */ public ngOnInit() { if (this.navigationService && this.id) { this.navigationService.add(this.id, this); } } /** * @hidden */ public ngOnDestroy() { if (this.navigationService && this.id) { this.navigationService.remove(this.id); } if (!this.collapsed && this._overlayId) { this.overlayService.detach(this._overlayId); } this.unsubscribe(); this.destroy$.next(true); this.destroy$.complete(); } private overlayClosed = (e) => { this._collapsed = true; this.cdr.detectChanges(); this.unsubscribe(); this.overlayService.detach(this.overlayId); const args: ToggleViewEventArgs = { owner: this, id: this._overlayId, event: e.event }; delete this._overlayId; this.closed.emit(args); this.cdr.markForCheck(); }; private subscribe() { this._overlayContentAppendedSub = this.overlayService .contentAppended .pipe(first(), takeUntil(this.destroy$)) .subscribe(() => { const args: ToggleViewEventArgs = { owner: this, id: this._overlayId }; this.appended.emit(args); }); this._overlayOpenedSub = this.overlayService .opened .pipe(...this._overlaySubFilter) .subscribe(() => { const args: ToggleViewEventArgs = { owner: this, id: this._overlayId }; this.opened.emit(args); }); this._overlayClosingSub = this.overlayService .closing .pipe(...this._overlaySubFilter) .subscribe((e: OverlayClosingEventArgs) => { const args: ToggleViewCancelableEventArgs = { cancel: false, event: e.event, owner: this, id: this._overlayId }; this.closing.emit(args); e.cancel = args.cancel; // in case event is not canceled this will close the toggle and we need to unsubscribe. // Otherwise if for some reason, e.g. close on outside click, close() gets called before // onClosed was fired we will end with calling onClosing more than once if (!e.cancel) { this.clearSubscription(this._overlayClosingSub); } }); this._overlayClosedSub = this.overlayService .closed .pipe(...this._overlaySubFilter) .subscribe(this.overlayClosed); } private unsubscribe() { this.clearSubscription(this._overlayOpenedSub); this.clearSubscription(this._overlayClosingSub); this.clearSubscription(this._overlayClosedSub); this.clearSubscription(this._overlayContentAppendedSub); } private clearSubscription(subscription: Subscription) { if (subscription && !subscription.closed) { subscription.unsubscribe(); } } } @Directive({ exportAs: 'toggle-action', selector: '[igxToggleAction]' }) export class IgxToggleActionDirective implements OnInit { /** * Provide settings that control the toggle overlay positioning, interaction and scroll behavior. * ```typescript * const settings: OverlaySettings = { * closeOnOutsideClick: false, * modal: false * } * ``` * --- * ```html * <!--set--> * <div igxToggleAction [overlaySettings]="settings"></div> * ``` */ @Input() public overlaySettings: OverlaySettings; /** * Determines where the toggle element overlay should be attached. * * ```html * <!--set--> * <div igxToggleAction [igxToggleOutlet]="outlet"></div> * ``` * Where `outlet` in an instance of `IgxOverlayOutletDirective` or an `ElementRef` */ @Input('igxToggleOutlet') public outlet: IgxOverlayOutletDirective | ElementRef; /** * @hidden */ @Input('igxToggleAction') public set target(target: any) { if (target !== null && target !== '') { this._target = target; } } /** * @hidden */ public get target(): any { if (typeof this._target === 'string') { return this.navigationService.get(this._target); } return this._target; } protected _overlayDefaults: OverlaySettings; protected _target: IToggleView | string; constructor(private element: ElementRef, @Optional() private navigationService: IgxNavigationService) { } /** * @hidden */ @HostListener('click') public onClick() { if (this.outlet) { this._overlayDefaults.outlet = this.outlet; } const clonedSettings = Object.assign({}, this._overlayDefaults, this.overlaySettings); this.updateOverlaySettings(clonedSettings); this.target.toggle(clonedSettings); } /** * @hidden */ public ngOnInit() { const targetElement = this.element.nativeElement; this._overlayDefaults = { target: targetElement, positionStrategy: new ConnectedPositioningStrategy(), scrollStrategy: new AbsoluteScrollStrategy(), closeOnOutsideClick: true, modal: false, excludeFromOutsideClick: [targetElement as HTMLElement] }; } /** * Updates provided overlay settings * * @param settings settings to update * @returns returns updated copy of provided overlay settings */ protected updateOverlaySettings(settings: OverlaySettings): OverlaySettings { if (settings && settings.positionStrategy) { const positionStrategyClone: IPositionStrategy = settings.positionStrategy.clone(); settings.target = this.element.nativeElement; settings.positionStrategy = positionStrategyClone; } return settings; } } /** * Mark an element as an igxOverlay outlet container. * Directive instance is exported as `overlay-outlet` to be assigned to templates variables: * ```html * <div igxOverlayOutlet #outlet="overlay-outlet"></div> * ``` */ @Directive({ exportAs: 'overlay-outlet', selector: '[igxOverlayOutlet]' }) export class IgxOverlayOutletDirective { constructor(public element: ElementRef<HTMLElement>) { } /** @hidden */ public get nativeElement() { return this.element.nativeElement; } } /** * @hidden */ @NgModule({ declarations: [IgxToggleDirective, IgxToggleActionDirective, IgxOverlayOutletDirective], exports: [IgxToggleDirective, IgxToggleActionDirective, IgxOverlayOutletDirective], providers: [IgxNavigationService] }) export class IgxToggleModule { }
the_stack
import React, {Component, Fragment} from 'react'; import {Picker} from 'emoji-mart'; import styles from './style.module.scss'; import {ReactComponent as CheckmarkIcon} from 'assets/images/icons/checkmark.svg'; import {ReactComponent as CloseIcon} from 'assets/images/icons/close.svg'; import {ReactComponent as SmileyIcon} from 'assets/images/icons/smiley.svg'; class InputComponent extends Component<InputProps, IState> { public static defaultProps = { height: 48, fontClass: 'font-l', label: '', autoFocus: false, hideLabel: false, showCounter: true, }; inputRef: React.RefObject<HTMLInputElement>; node: HTMLDivElement; constructor(props) { super(props); this.state = { validationResult: undefined, wasBlurred: false, isShowingEmojiDrawer: false, }; this.inputRef = React.createRef(); } componentDidMount = () => { const {inputRef, value} = this.props; if (value) { this.validateInput((inputRef || this.inputRef).current); } }; componentDidUpdate = prevProps => { const inputRef = this.props.inputRef || this.inputRef; if ((inputRef.current && !prevProps.showErrors && this.props.showErrors) || this.props.value !== prevProps.value) { this.validateInput(inputRef.current); } }; translateResult = (type, validity) => { if (validity.valueMissing) { return 'This field cannot be empty.'; } else if (type === 'url' && validity.typeMismatch) { return 'The URL is invalid'; } else { return validity.valid; } }; checkWithHTML5Validation = inputElement => { if (inputElement === null || !this.hasValidations()) { return; } inputElement.checkValidity(); this.setState({validationResult: inputElement.validity.valid}); if (inputElement.type === 'email') { if (!inputElement.validity.valid) { this.setState({ validationResult: 'This doesn’t look like an email address.', }); } else { this.setState({validationResult: true}); } } else { this.setState({ validationResult: this.translateResult(inputElement.type, inputElement.validity), }); } }; hasValidations = () => { return ( this.props.type === 'url' || this.props.type === 'email' || this.props.required || this.props.minLength || this.props.maxLength || this.props.validation ); }; checkWithValidationFunction = inputElement => { const {validation} = this.props; const validationResult = validation(inputElement.value); this.setState({validationResult: validationResult}); if (validationResult === true) { inputElement.setCustomValidity(''); } else { inputElement.setCustomValidity(validationResult); } }; checkWithURLValidation = inputElement => { this.checkWithHTML5Validation(inputElement); if (!this.props.required && inputElement.value.length == 0) { inputElement.setCustomValidity(''); return; } if (!inputElement.value.match(/.*\w\.\w.*/)) { this.setState({ validationResult: 'The URL is invalid', }); inputElement.setCustomValidity('The URL is invalid'); } else { inputElement.setCustomValidity(''); } }; validateInput = inputElement => { const {validation, type} = this.props; if (validation) { this.checkWithValidationFunction(inputElement); } else if (type === 'url') { this.checkWithURLValidation(inputElement); } else { this.checkWithHTML5Validation(inputElement); } }; onChange = event => { const {onChange} = this.props; this.validateInput(event.target); if (onChange) { onChange(event); } }; onBlur = event => { const {onBlur} = this.props; this.setState({wasBlurred: true}); this.validateInput(event.target); if (onBlur) { onBlur(event); } }; getCurrentValidationState = () => { if (this.state.validationResult === true) { return 'inputValid'; } else if (this.state.validationResult === undefined) { return null; } if (!this.state.wasBlurred && !this.props.showErrors) { return null; } return 'inputInvalid'; }; classForState = () => { switch (this.getCurrentValidationState()) { case 'inputInvalid': return styles.inputInvalid; case 'inputValid': return styles.inputValid; default: return ''; } }; iconForState = () => { if (this.state.validationResult === true) { return ( <div className={styles.icon}> <CheckmarkIcon aria-hidden="true" /> </div> ); } else if (this.state.validationResult === undefined) { return null; } if (!this.state.wasBlurred && !this.props.showErrors) { return null; } return ( <div className={styles.closeIcon}> <CloseIcon aria-hidden="true" /> </div> ); }; addListeners = () => { document.addEventListener('keydown', this.handleEmojiKeyEvent); document.addEventListener('click', this.handleEmojiOutsideClick); }; removeListeners = () => { document.removeEventListener('keydown', this.handleEmojiKeyEvent); document.removeEventListener('click', this.handleEmojiOutsideClick); }; handleEmojiDrawer = () => { if (!this.state.isShowingEmojiDrawer) { this.addListeners(); } else { this.removeListeners(); this.inputRef.current && this.inputRef.current.focus(); } this.setState({isShowingEmojiDrawer: !this.state.isShowingEmojiDrawer}); }; handleEmojiKeyEvent = e => { if (e.key === 'Escape') { this.handleEmojiDrawer(); } }; handleEmojiOutsideClick = e => { if (this.node && this.node.contains(e.target)) { return; } this.handleEmojiDrawer(); }; addEmoji = emoji => { let message = emoji.native; const inputRef = this.props.inputRef || this.inputRef; if (this.props.value) { message = this.props.value + ' ' + message; } inputRef.current.value = message; this.onChange({target: inputRef.current}); this.handleEmojiDrawer(); }; emojiDrawer = () => { return ( <div ref={node => { this.node = node; }} className={styles.emojiDrawer}> <Picker showPreview={false} onSelect={this.addEmoji} title="Emoji" style={{right: '28px', position: 'absolute', bottom: '-84px'}} /> </div> ); }; render() { const { id, label, hideLabel, name, value, checked, placeholder, hint, height, type, inputRef, inputmode, minLength, maxLength, showErrors, children, fontClass, inputComponent, autoFocus, required, autoComplete, disabled, onKeyDown, pattern, showCounter, onFocus, dataCy, } = this.props; const {validationResult, wasBlurred} = this.state; const labelClass = `${this.classForState()} ${styles.label}`; const inputClass = `${styles[fontClass]} ${styles.inputInner} `; return ( <label className={labelClass}> <div className={styles.inputTitleRow}> {!hideLabel && ( <div className={styles.inputTitle}> {children ? ( children(this.iconForState()) ) : ( <Fragment> {label} {this.iconForState()} </Fragment> )} </div> )} {this.props.maxLength > 0 && this.props.showCounter ? ( <div className={styles.inputMaxLength}> <span className={value.length > this.props.maxLength ? styles.inputMaxLengthError : ''}> {Math.max(0, this.props.maxLength - value.length)} </span> </div> ) : ( '' )} </div> {inputComponent ? ( inputComponent({ id: id, inputRef: inputRef || this.inputRef, placeholder: placeholder, onChange: this.onChange, onBlur: this.onBlur, onKeyDown: onKeyDown, type: type, value: value, checked: checked, autoFocus: autoFocus, name: name, minLength: minLength, maxLength: maxLength, required: required, fontClass: fontClass, pattern: pattern, currentValidationState: this.getCurrentValidationState(), showCounter: showCounter, }) ) : ( <div className={styles.input}> <input id={id} ref={inputRef || this.inputRef} className={inputClass} checked={checked} placeholder={placeholder} onChange={this.onChange} onKeyDown={onKeyDown} onFocus={onFocus} onBlur={this.onBlur} style={{ height: `${height}px`, }} type={type} value={value} autoFocus={autoFocus} name={name} minLength={minLength} maxLength={maxLength} required={required} autoComplete={autoComplete} disabled={disabled} pattern={pattern} inputMode={inputmode} data-cy={dataCy} /> {this.props.emoji ? ( <div className={styles.emojiWrapper}> {this.state.isShowingEmojiDrawer && this.emojiDrawer()} <button type="button" onClick={this.handleEmojiDrawer} disabled={this.props.maxLength - value.length <= 0} className={`${styles.emojiIcon} ${this.state.isShowingEmojiDrawer && styles.emojiIconActive}`}> <SmileyIcon title="Emoji" className={styles.smileyIcon} /> </button> </div> ) : null} </div> )} <div className={styles.inputHint}> {typeof validationResult === 'string' && (wasBlurred || showErrors) ? validationResult : hint} </div> </label> ); } } export interface InputProps { id?: string; /** The label above the input field */ label?: string; /** Want to hide the label completely? */ hideLabel?: boolean; /** An addional hint below the input field */ hint?: string; value?: string; checked?: boolean; name?: string; placeholder?: string; /** * validation function. Should return true if valid, * undefined if neutral and a string explaining * what is wrong otherwise **/ validation?: any; type?: string; autoFocus?: boolean; onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void; onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void; onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void; onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void; inputRef?: React.RefObject<HTMLInputElement>; /** Minimum length for validation */ minLength?: number; maxLength?: number; /** true if this is a required input, defaults to false */ required?: boolean; /** If we wish to disable the input field for further input or validation related issues */ disabled?: boolean; pattern?: string; /** * usually the field only shows the error after a blur event, * but if you want to show errors on all fields after a submit button * was pressed, simply set this state to true and the error is shown. */ showErrors?: boolean; height?: number; // Since tuning font size is not the most common operation, this should suffice for now fontClass?: 'font-base' | 'font-s' | 'font-m' | 'font-l' | 'font-xl' | 'font-xxl'; /** * If you want to modify the label, you can add a function here. It will * receive the icon as the first value of the function */ children?: any; /** * You can replace the input tag with a custom rendered version with this function. See * `Textarea` for an implementation example. */ inputComponent?: any; // If you want to enable browser suggestions on the input autoComplete?: string; // set this to true if you want to have an emoji button emoji?: boolean; // set this to true if you want to display the length counter showCounter?: boolean; // html5 input mode inputmode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search'; // a handle for Cypress dataCy?: string; } interface IState { validationResult: string | boolean; wasBlurred: boolean; isShowingEmojiDrawer: boolean; } export const Input = InputComponent;
the_stack
import React from 'react' import useInterval from 'use-interval' import camelCase from 'camelcase' import * as Figma from 'figma-js' import { cosmiconfig } from 'cosmiconfig' import fs from 'fs' import path from 'path' import util from 'util' import rimraf from 'rimraf' import prettier from 'prettier' import { Text, Box, Color, render } from 'ink' import { StyleFill } from './StyleFill' import { StyleText } from './StyleText' import { Frame } from './Frame' import { ErrorBox } from './Error' import { getStylesFromFile, FigmintFillStyleType, FigmintTypeStyleType, FigmintExportType, downloadImage, PartialFigmintExportType, FigmintGradient, BaseTypeStyleType, BaseEffectStyleType, } from './utils' import { exportFormatOptions } from 'figma-js' // export our types for clients to use export * from './utils/types' // clear the console process.stdout.write('\x1Bc') // Local Types type DownloadListType = { [formatScale: string]: PartialFigmintExportType[] } type FinalExportsType = { [page: string]: { [fileName: string]: { svg?: PartialFigmintExportType pdf?: PartialFigmintExportType png?: { [scale: number]: PartialFigmintExportType } jpg?: { [scale: number]: PartialFigmintExportType } } } } // Components const Header = ({ text }: { text: string }) => ( <Color gray> <Box marginBottom={1}> <Text bold>{text}:</Text> </Box> </Color> ) const Output = () => { // 📝 State // -------- // Config const [file, setFile] = React.useState('') const [output, setOutput] = React.useState('figmaStyles') const [typescript, setTypescript] = React.useState(false) // Data from Figma const [fileName, setFileName] = React.useState('') const [fills, setFills] = React.useState<FigmintFillStyleType[]>([]) const [typography, setTypography] = React.useState<FigmintTypeStyleType[]>([]) const [exports, setExports] = React.useState<FigmintExportType>() // Internal State const [loading, setLoading] = React.useState(true) const [hasConfig, setHasConfig] = React.useState(false) const [watching] = React.useState(process.argv.slice(2)[0] === 'watch') const [client, setClient] = React.useState<Figma.ClientInterface>() // Function to get an image URL from figma given some params const fetchAndAddImageUrls = React.useCallback( async (downloadLists: DownloadListType, finalExports: FinalExportsType) => { if (client && file) { const baseDirectory = path.join(output, 'exports') // Clear out the output dir if it already exists if (fs.existsSync(baseDirectory)) { rimraf.sync(baseDirectory) } fs.mkdirSync(baseDirectory, { recursive: true }) await Promise.all( Object.keys(downloadLists).map(async (format) => { if (downloadLists[format].length > 0) { let imageResponse // first we get the image urls from figma based on format and scale if (format === 'svg' || format === 'pdf') { imageResponse = await client.fileImages(file, { format, ids: downloadLists[format].map((image) => image.id), }) } else { imageResponse = await client.fileImages(file, { format: downloadLists[format][0].format, scale: downloadLists[format][0].scale, ids: downloadLists[format].map((image) => image.id), }) } // next we use these urls to download the images and add the url and file info to our exports object Object.entries(imageResponse.data.images).forEach(([id, url]) => { const image = downloadLists[format].find( (image) => image.id === id, ) if (image) { // store images based on the page const outDirectory = path.join( baseDirectory, camelCase(image.page), ) // image file name based on format and scale const outFile = `${image.name}${ image.scale > 1 ? `@${image.scale}x` : '' }.${image.format}` const outUrl = path.join(outDirectory, outFile) // make sure the directory for this image exists directory exists if (!fs.existsSync(outDirectory)) { fs.mkdirSync(outDirectory, { recursive: true }) } downloadImage(url, outUrl) if (image.format === 'png' || image.format === 'jpg') { finalExports[image.page][image.name][image.format]![ image.scale ] = { ...finalExports[image.page][image.name][image.format]![ image.scale ], url: outUrl, directory: outDirectory, file: outFile, } } else { finalExports[image.page][image.name][image.format] = { ...finalExports[image.page][image.name][image.format]!, url: outUrl, directory: outDirectory, file: outFile, } } } }) } }), ) return finalExports } throw new Error('client and file needed to run this function') }, [client, file, output], ) // 📡 Function to connect to Figma and get the data we need // -------------------------------------------------------- const fetchData = React.useCallback(async () => { if (client && file) { const [fileResponse, imageFillsResponse] = await Promise.all([ client.file(file), client.fileImageFills(file), ]) setFileName(fileResponse.data.name) // Make sure the output directory exists if (!fs.existsSync(output)) { fs.mkdirSync(output, { recursive: true }) } // combine the style meta data with the actual style info const { styles, exports } = await getStylesFromFile( fileResponse.data, imageFillsResponse.data, output, ) // 🖼 time to get export images! const finalExports: FinalExportsType = {} const downloadLists: DownloadListType = {} // first we look at all the various exports found in the file. // We need to note the scale and format so we can ask for images // of the right type and format from the figma API. Object.entries(exports).forEach(([id, info]) => { info.exportInfo.forEach((image) => { const name = info.name const group = info.folder const page = info.page const format = image.format.toLowerCase() as exportFormatOptions const scale = image.constraint.type === 'SCALE' ? image.constraint.value : 1 const imageDetails = { id, format, page, group, name, scale, } if (!(page in finalExports)) { finalExports[page] = {} } if (!(name in finalExports[page])) { finalExports[page][name] = {} } // vector images don't have a scale if (format === 'svg' || format === 'pdf') { finalExports[page][name][format] = imageDetails if (!(format in downloadLists)) { downloadLists[format] = [] } downloadLists[format].push(imageDetails) } else if (format === 'png' || format === 'jpg') { if (!(format in finalExports[page][name])) { finalExports[page][name][format] = {} } finalExports[page][name][format]![scale] = imageDetails const formatScale = format + `@${scale}x` if (!(formatScale in downloadLists)) { downloadLists[formatScale] = [] } downloadLists[formatScale].push(imageDetails) } }) }) // Once we know everything we need about our exports we fetch the image URL's from figma // we group these by file type to reduce the number of requests. styles.exports = (await fetchAndAddImageUrls( downloadLists, finalExports, )) as FigmintExportType // write out our file let colors = {} as { [colorName: string]: string } let gradients = {} as { [gradientName: string]: FigmintGradient } let imageFills = {} as { [imageFillName: string]: string } let textStyles = {} as { [name: string]: BaseTypeStyleType } let effectStyles = {} as { [name: string]: BaseEffectStyleType } styles.fillStyles.forEach((fill) => { fill.styles.forEach((style) => { switch (style.type) { case 'SOLID': colors[camelCase(fill.name)] = style.color break case 'GRADIENT_LINEAR': case 'GRADIENT_RADIAL': case 'GRADIENT_ANGULAR': case 'GRADIENT_DIAMOND': gradients[camelCase(fill.name)] = style break case 'IMAGE': imageFills[camelCase(fill.name)] = style.fileName } }) }) styles.textStyles.forEach((text) => { textStyles[camelCase(text.name)] = text.styles }) styles.effectStyles.forEach((effect) => { effectStyles[camelCase(effect.name)] = effect.styles }) const options = await prettier.resolveConfig(output) fs.writeFileSync( path.join(output, `index.${typescript ? 'ts' : 'js'}`), prettier.format( ` const styles = { colors: ${util.inspect(colors, { depth: Infinity, compact: false, maxArrayLength: null, })}, gradients: ${util.inspect(gradients, { depth: Infinity, compact: false, maxArrayLength: null, })}, imageFills: ${util.inspect(imageFills, { depth: Infinity, compact: false, maxArrayLength: null, })}, textStyles: ${util.inspect(textStyles, { depth: Infinity, compact: false, maxArrayLength: null, })}, effectStyles: ${util.inspect(effectStyles, { depth: Infinity, compact: false, maxArrayLength: null, })}, raw: ${util.inspect(styles, { depth: Infinity, compact: false, maxArrayLength: null, })}, }${typescript ? ' as const' : ''} ${ typescript ? ` export type ColorValues = keyof typeof styles.colors export type GradientValues = keyof typeof styles.gradients export type TextValues = keyof typeof styles.textStyles export type EffectValues = keyof typeof styles.effectStyles ` : '' } export default styles`, { ...options, parser: typescript ? 'typescript' : 'babel' }, ), ) setLoading(false) // set our local state setFills(styles.fillStyles) setTypography(styles.textStyles) setExports(styles.exports) } }, [client, fetchAndAddImageUrls, file, output, typescript]) // ⚓️ Hooks! // --------- // 🛠 Initial Setup React.useEffect(() => { const processConfig = async () => { const explorer = cosmiconfig('figmint') const configResult = await explorer.search() if (configResult) { setHasConfig(true) if ('file' in configResult.config) { setFile(configResult.config.file) } if ('output' in configResult.config) { setOutput(configResult.config.output) } if ('typescript' in configResult.config) { setTypescript(configResult.config.typescript) } if (configResult.config.token) { setClient( Figma.Client({ personalAccessToken: configResult.config.token, }), ) } } } processConfig() }, []) // 🐶 Initial data fetch React.useEffect(() => { const fetch = async () => { fetchData() } fetch() }, [client, fetchData]) // 👀 if we're watching, keep fetching useInterval(fetchData, watching ? 1000 : null) // ⚠️ Error Handling // ----------------- if (!hasConfig) { return ( <Frame> <ErrorBox> Figmint requires a config. (https://github.com/tiltshift/figmint#config) </ErrorBox> </Frame> ) } if (!client) { return ( <Frame> <ErrorBox> Figma Token is required. (https://github.com/tiltshift/figmint#token) </ErrorBox> </Frame> ) } if (!file) { return ( <Frame> <ErrorBox> Figma File is required. (https://github.com/tiltshift/figmint#file) </ErrorBox> </Frame> ) } // 🍃 The App // ---------- return ( <Frame loading={loading} watching={watching} fileName={fileName}> <Box flexDirection="row"> <Box flexDirection="column"> <Header text="Fill Styles" /> {fills.map((fill) => ( <StyleFill key={fill.key} fill={fill} /> ))} </Box> <Box flexDirection="column"> <Header text="Text Styles" /> {typography.map((text) => ( <StyleText key={text.key} text={text} /> ))} </Box> {exports && ( <Box flexDirection="column"> <Header text="Exports" /> <Box textWrap="wrap"> <Text> Exports are working, but we don't display anything here yet... </Text> </Box> </Box> )} </Box> </Frame> ) } render(<Output />)
the_stack
import { dia } from 'jointjs'; import { ValidatorFn, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms' import { Flo } from './flo-common'; import { Subject, Observable } from 'rxjs' import {debounceTime, switchMap} from 'rxjs/operators'; export namespace Properties { export enum InputType { TEXT, NUMBER, SELECT, CHECKBOX, PASSWORD, EMAIL, URL, CODE } export interface Property { readonly id: string; readonly name: string; readonly type?: string; readonly description?: string; readonly defaultValue?: any; value?: any; readonly valueOptions?: any[] readonly [propName: string]: any; } export interface PropertyFilter { accept: (property: Property) => boolean; } export interface SelectOption { name: string; value: any; } export interface ErrorData { id: string; message: string; } export interface Validation { validator?: ValidatorFn|ValidatorFn[]|null, asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null, errorData?: Array<ErrorData>; } export interface ControlModel<T> { readonly type: InputType; readonly id: string; value: T; readonly defaultValue: T; readonly name?: string; readonly description?: string; readonly property: Property readonly validation?: Validation; } export interface CodeControlModel<T> extends ControlModel<T> { readonly language: string; } export class GenericControlModel<T> implements ControlModel<T> { constructor(private _property: Property, public type: InputType, public validation?: Validation) {} get id() { return this.property.id; } get name() { return this.property.name; } get description() { return this.property.description; } get defaultValue() { return this.property.defaultValue; } get value(): T { return this.getValue(); } set value(value: T) { this.setValue(value); } get property(): Property { return this._property; } protected setValue(value: T) { this.property.value = value; } protected getValue(): T { return this.property.value; } } export class CheckBoxControlModel extends GenericControlModel<boolean> { constructor(_property: Property, validation?: Validation) { super(_property, InputType.CHECKBOX, validation); } protected getValue() { const res = super.getValue(); const type = typeof res; switch (type) { case 'boolean': return res; case 'string': switch ((<any>res).trim().toLowerCase()) { case 'true': case '1': return true; case 'false': case '0': return false; default: return this.property.defaultValue } case 'number': const num = <any> res; if (num === 0) { return false; } else if (num === 1) { return true; } else { return this.property.defaultValue } } return this.property.defaultValue; } } export abstract class AbstractCodeControlModel extends GenericControlModel<string> implements CodeControlModel<string> { abstract language: string; constructor(_property: Property, private encode?: (s: string) => string, private decode?: (s: string) => string, validation?: Validation) { super(_property, InputType.CODE, validation); } set value(value: string) { if (value && this.encode) { super.setValue(this.encode(value)); } else { super.setValue(value); } } get value(): string { let dsl = super.getValue(); if (dsl && this.decode) { return this.decode(dsl); } else { return dsl; } } } export class GenericCodeControlModel extends AbstractCodeControlModel { constructor(_property: Property, public language: string, encode?: (s: string) => string, decode?: (s: string) => string, validation?: Validation) { super(_property, encode, decode, validation); } } export class CodeControlModelWithDynamicLanguageProperty extends AbstractCodeControlModel { private _langControlModel: Properties.ControlModel<any>; constructor(_property: Properties.Property, private _languagePropertyName: string, private _groupModel: Properties.PropertiesGroupModel, encode?: (s: string) => string, decode?: (s: string) => string, validation?: Validation) { super(_property, encode, decode, validation); } get language(): string { const value = this.languageControlModel.value; return value ? value : this.languageControlModel.defaultValue; } get languageControlModel(): Properties.ControlModel<any> { if (!this._langControlModel) { // Cast to Properties.ControlModel<any> from Properties.ControlModel<any> | undefined // Should not be undefined! this._langControlModel = <Properties.ControlModel<any>> this._groupModel.getControlsModels().find(c => c.id === this._languagePropertyName); } return this._langControlModel; } } export class GenericListControlModel extends GenericControlModel<string> { constructor(property: Property, validation?: Validation) { super(property, InputType.TEXT, validation); } get value(): string { return this.property.value ? this.property.value.toString().trim().split(/\s*,\s*/).join(', ') : ''; } set value(value: string) { this.property.value = value && value.trim() ? value.split(/\s*,\s*/).join(',') : undefined; } } export class SelectControlModel extends GenericControlModel<any> { constructor(_property: Property, type: InputType, public options: Array<SelectOption>, validation?: Validation) { super(_property, type, validation); if (_property.defaultValue === undefined) { options.unshift({ name: 'SELECT', value: _property.defaultValue }) } } } export interface PropertiesSource { getProperties(): Promise<Property[]>; applyChanges(properties: Property[]): void; } export class DefaultCellPropertiesSource implements PropertiesSource { protected cell: dia.Cell; constructor(cell: dia.Cell) { this.cell = cell; } getProperties(): Promise<Array<Property>> { let metadata: Flo.ElementMetadata = this.cell.get('metadata'); return Promise.resolve(metadata.properties().then(propsMetadata => Array.from(propsMetadata.values()).map(m => this.createProperty(m)))); } protected createProperty(metadata: Flo.PropertyMetadata): Property { return { id: metadata.id, name: metadata.name, type: metadata.type, defaultValue: metadata.defaultValue, attr: `props/${metadata.name}`, value: this.cell.attr(`props/${metadata.name}`), description: metadata.description, valueOptions: metadata.options } } applyChanges(properties: Property[]) { this.cell.trigger('batch:start', { batchName: 'update properties' }); properties.forEach(property => { if ((typeof property.value === 'boolean' && !property.defaultValue && !property.value) || (property.value === property.defaultValue || property.value === '' || property.value === undefined || property.value === null)) { let currentValue = this.cell.attr(property.attr); if (currentValue !== undefined && currentValue !== null) { // Remove attr doesn't fire appropriate event. Set default value first as a workaround to schedule DSL resync // this.cell.attr(property.attr, property.defaultValue === undefined ? null : property.defaultValue); this.cell.attr(property.attr, null); this.cell.removeAttr(property.attr); } } else { this.cell.attr(property.attr, property.value); } }); this.cell.trigger('batch:stop', { batchName: 'update properties' }); } } export class PropertiesGroupModel { protected propertiesSource: PropertiesSource; protected controlModels: Array<ControlModel<any>>; protected loading = true; protected _loadedSubject: Subject<boolean>; constructor(propertiesSource: PropertiesSource) { this.propertiesSource = propertiesSource; } load() { this.loading = true; this._loadedSubject = new Subject<boolean>(); this.propertiesSource.getProperties().then(properties => { this.controlModels = properties.map(p => this.createControlModel(p)); this.loading = false; this._loadedSubject.next(true); this._loadedSubject.complete(); }); } get isLoading(): boolean { return this.loading; } get loadedSubject() { return this._loadedSubject; } getControlsModels() { return this.controlModels; } protected createControlModel(property: Property): ControlModel<any> { return new GenericControlModel(property, InputType.TEXT); } public applyChanges(): void { if (this.loading) { return; } let properties = this.controlModels.map(cm => cm.property); this.propertiesSource.applyChanges(properties); } } const UNIQUE_RESOURCE_ERROR = {uniqueResource: true}; export namespace Validators { export function uniqueResource(service: (value: any) => Observable<boolean>, debounceDuration: number): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors> => { return new Observable<ValidationErrors>(obs => { if (control.valueChanges) { return control.valueChanges.pipe( debounceTime(debounceDuration), switchMap(() => service(control.value)), ).subscribe((res) => { if (res) { obs.next(undefined); } else { obs.next(UNIQUE_RESOURCE_ERROR); } obs.complete(); }, () => { obs.next(UNIQUE_RESOURCE_ERROR); obs.complete(); }); } else { service(control.value).subscribe((res) => { if (res) { obs.next(undefined); } else { obs.next(UNIQUE_RESOURCE_ERROR); } obs.complete(); }, () => { obs.next(UNIQUE_RESOURCE_ERROR); obs.complete(); }) } }); } } export function noneOf(excluded: Array<any>): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { return excluded.find(e => e === control.value) ? {'noneOf': {value: control.value}} : {}; }; } } }
the_stack
import bigInt from "big-integer"; import type { AuthKey } from "../crypto/AuthKey"; import { helpers } from "../"; import { Api } from "../tl"; import { sha256, toSignedLittleBuffer } from "../Helpers"; import { GZIPPacked, TLMessage } from "../tl/core"; import { BinaryReader } from "../extensions"; import type { BinaryWriter } from "../extensions"; import { IGE } from "../crypto/IGE"; import { InvalidBufferError, SecurityError } from "../errors"; export class MTProtoState { private readonly authKey?: AuthKey; private _log: any; timeOffset: number; salt: bigInt.BigInteger; private id: bigInt.BigInteger; _sequence: number; private _lastMsgId: bigInt.BigInteger; /** * `telethon.network.mtprotosender.MTProtoSender` needs to hold a state in order to be able to encrypt and decrypt incoming/outgoing messages, as well as generating the message IDs. Instances of this class hold together all the required information. It doesn't make sense to use `telethon.sessions.abstract.Session` for the sender because the sender should *not* be concerned about storing this information to disk, as one may create as many senders as they desire to any other data center, or some CDN. Using the same session for all these is not a good idea as each need their own authkey, and the concept of "copying" sessions with the unnecessary entities or updates state for these connections doesn't make sense. While it would be possible to have a `MTProtoPlainState` that does no encryption so that it was usable through the `MTProtoLayer` and thus avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more focused to efficiency and this state is also more advanced (since it supports gzipping and invoking after other message IDs). There are too many methods that would be needed to make it convenient to use for the authentication process, at which point the `MTProtoPlainSender` is better * @param authKey * @param loggers */ constructor(authKey?: AuthKey, loggers?: any) { this.authKey = authKey; this._log = loggers; this.timeOffset = 0; this.salt = bigInt.zero; this._sequence = 0; this.id = this._lastMsgId = bigInt.zero; this.reset(); } /** * Resets the state */ reset() { // Session IDs can be random on every connection this.id = helpers.generateRandomLong(true); this._sequence = 0; this._lastMsgId = bigInt.zero; } /** * Updates the message ID to a new one, * used when the time offset changed. * @param message */ updateMessageId(message: any) { message.msgId = this._getNewMsgId(); } /** * Calculate the key based on Telegram guidelines, specifying whether it's the client or not * @param authKey * @param msgKey * @param client * @returns {{iv: Buffer, key: Buffer}} */ async _calcKey(authKey: Buffer, msgKey: Buffer, client: boolean) { const x = client ? 0 : 8; const [sha256a, sha256b] = await Promise.all([ sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])), sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])), ]); const key = Buffer.concat([ sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32), ]); const iv = Buffer.concat([ sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32), ]); return { key, iv }; } /** * Writes a message containing the given data into buffer. * Returns the message id. * @param buffer * @param data * @param contentRelated * @param afterId */ async writeDataAsMessage( buffer: BinaryWriter, data: Buffer, contentRelated: boolean, afterId?: bigInt.BigInteger ) { const msgId = this._getNewMsgId(); const seqNo = this._getSeqNo(contentRelated); let body; if (!afterId) { body = await GZIPPacked.gzipIfSmaller(contentRelated, data); } else { body = await GZIPPacked.gzipIfSmaller( contentRelated, new Api.InvokeAfterMsg({ msgId: afterId, query: { getBytes() { return data; }, }, }).getBytes() ); } const s = Buffer.alloc(4); s.writeInt32LE(seqNo, 0); const b = Buffer.alloc(4); b.writeInt32LE(body.length, 0); const m = toSignedLittleBuffer(msgId, 8); buffer.write(Buffer.concat([m, s, b])); buffer.write(body); return msgId; } /** * Encrypts the given message data using the current authorization key * following MTProto 2.0 guidelines core.telegram.org/mtproto/description. * @param data */ async encryptMessageData(data: Buffer) { if (!this.authKey) { throw new Error("Auth key unset"); } await this.authKey.waitForKey(); const authKey = this.authKey.getKey(); if (!authKey) { throw new Error("Auth key unset"); } if (!this.salt || !this.id || !authKey || !this.authKey.keyId) { throw new Error("Unset params"); } const s = toSignedLittleBuffer(this.salt, 8); const i = toSignedLittleBuffer(this.id, 8); data = Buffer.concat([Buffer.concat([s, i]), data]); const padding = helpers.generateRandomBytes( helpers.mod(-(data.length + 12), 16) + 12 ); // Being substr(what, offset, length); x = 0 for client // "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)" const msgKeyLarge = await sha256( Buffer.concat([authKey.slice(88, 88 + 32), data, padding]) ); // "msg_key = substr (msg_key_large, 8, 16)" const msgKey = msgKeyLarge.slice(8, 24); const { iv, key } = await this._calcKey(authKey, msgKey, true); const keyId = helpers.readBufferFromBigInt(this.authKey.keyId, 8); return Buffer.concat([ keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding])), ]); } /** * Inverse of `encrypt_message_data` for incoming server messages. * @param body */ async decryptMessageData(body: Buffer) { if (!this.authKey) { throw new Error("Auth key unset"); } if (body.length < 8) { throw new InvalidBufferError(body); } // TODO Check salt,sessionId, and sequenceNumber const keyId = helpers.readBigIntFromBuffer(body.slice(0, 8)); if (!this.authKey.keyId || keyId.neq(this.authKey.keyId)) { throw new SecurityError("Server replied with an invalid auth key"); } const authKey = this.authKey.getKey(); if (!authKey) { throw new SecurityError("Unset AuthKey"); } const msgKey = body.slice(8, 24); const { iv, key } = await this._calcKey(authKey, msgKey, false); body = new IGE(key, iv).decryptIge(body.slice(24)); // https://core.telegram.org/mtproto/security_guidelines // Sections "checking sha256 hash" and "message length" const ourKey = await sha256( Buffer.concat([authKey.slice(96, 96 + 32), body]) ); if (!msgKey.equals(ourKey.slice(8, 24))) { throw new SecurityError( "Received msg_key doesn't match with expected one" ); } const reader = new BinaryReader(body); reader.readLong(); // removeSalt const serverId = reader.readLong(); if (serverId !== this.id) { // throw new SecurityError('Server replied with a wrong session ID'); } const remoteMsgId = reader.readLong(); const remoteSequence = reader.readInt(); reader.readInt(); // msgLen for the inner object, padding ignored // We could read msg_len bytes and use those in a new reader to read // the next TLObject without including the padding, but since the // reader isn't used for anything else after this, it's unnecessary. const obj = reader.tgReadObject(); return new TLMessage(remoteMsgId, remoteSequence, obj); } /** * Generates a new unique message ID based on the current * time (in ms) since epoch, applying a known time offset. * @private */ _getNewMsgId() { const now = new Date().getTime() / 1000 + this.timeOffset; const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9); let newMsgId = bigInt(Math.floor(now)) .shiftLeft(bigInt(32)) .or(bigInt(nanoseconds).shiftLeft(bigInt(2))); if (this._lastMsgId.greaterOrEquals(newMsgId)) { newMsgId = this._lastMsgId.add(bigInt(4)); } this._lastMsgId = newMsgId; return newMsgId; } /** * Updates the time offset to the correct * one given a known valid message ID. * @param correctMsgId {BigInteger} */ updateTimeOffset(correctMsgId: bigInt.BigInteger) { const bad = this._getNewMsgId(); const old = this.timeOffset; const now = Math.floor(new Date().getTime() / 1000); const correct = correctMsgId.shiftRight(BigInt(32)).toJSNumber(); this.timeOffset = correct - now; if (this.timeOffset !== old) { this._lastMsgId = bigInt.zero; this._log.debug( `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})` ); } return this.timeOffset; } /** * Generates the next sequence number depending on whether * it should be for a content-related query or not. * @param contentRelated * @private */ _getSeqNo(contentRelated: boolean) { if (contentRelated) { const result = this._sequence * 2 + 1; this._sequence += 1; return result; } else { return this._sequence * 2; } } }
the_stack
import {PolyScene} from '../scene/PolyScene'; import {CoreGraphNode} from '../../core/graph/CoreGraphNode'; import {UIData} from './utils/UIData'; import {FlagsController, FlagsControllerD} from './utils/FlagsController'; import {StatesController} from './utils/StatesController'; import {HierarchyParentController} from './utils/hierarchy/ParentController'; import {HierarchyChildrenController} from './utils/hierarchy/ChildrenController'; import {LifeCycleController} from './utils/LifeCycleController'; import {TypedContainerController} from './utils/ContainerController'; import {NodeCookController, OnCookCompleteHook} from './utils/CookController'; import {NameController} from './utils/NameController'; import {NodeSerializer, NodeSerializerData} from './utils/Serializer'; import {ParamsController} from './utils/params/ParamsController'; import {ParamConstructorMap} from '../params/types/ParamConstructorMap'; import {ParamInitValuesTypeMap} from '../params/types/ParamInitValuesTypeMap'; import {NodeParamsConfig} from './utils/params/ParamsConfig'; import {ParamsValueAccessor, ParamsValueAccessorType} from './utils/params/ParamsValueAccessor'; // import {ProcessingContext} from './utils/ProcessingContext'; import {IOController, ParamsInitData} from './utils/io/IOController'; import {NodeEvent} from '../poly/NodeEvent'; import {NodeContext} from '../poly/NodeContext'; import {ParamsAccessorType, ParamsAccessor} from './utils/params/ParamsAccessor'; export interface NodeDeletedEmitData { parent_id: CoreGraphNodeId; } export interface NodeCreatedEmitData { child_node_json: NodeSerializerData; } type EmitDataByNodeEventMapGeneric = {[key in NodeEvent]: any}; export interface EmitDataByNodeEventMap extends EmitDataByNodeEventMapGeneric { [NodeEvent.CREATED]: NodeCreatedEmitData; [NodeEvent.DELETED]: NodeDeletedEmitData; [NodeEvent.ERROR_UPDATED]: undefined; } export interface IntegrationData { name: string; data: PolyDictionary<string>; } // import {ContainerMap, ContainerType} from '../containers/utils/ContainerMap'; import {ContainableMap} from '../containers/utils/ContainableMap'; import {ParamOptions} from '../params/utils/OptionsController'; import {ParamType} from '../poly/ParamType'; import {DisplayNodeController} from './utils/DisplayNodeController'; import {NodeTypeMap} from '../containers/utils/ContainerMap'; import {ParamInitValueSerialized} from '../params/types/ParamInitValueSerialized'; import {ModuleName} from '../poly/registers/modules/Common'; import {BasePersistedConfig} from './utils/PersistedConfig'; import {AssemblerName} from '../poly/registers/assemblers/_BaseRegister'; import {PolyNodeController} from './utils/poly/PolyNodeController'; import {CoreGraphNodeId} from '../../core/graph/CoreGraph'; import {PolyDictionary} from '../../types/GlobalTypes'; /** * TypedNode is the base class that all nodes inherit from. This inherits from [CoreGraphNode](/docs/api/CoreGraphNode). * */ export class TypedNode<NC extends NodeContext, K extends NodeParamsConfig> extends CoreGraphNode { containerController: TypedContainerController<NC> = new TypedContainerController<NC>(this); private _parent_controller: HierarchyParentController | undefined; private _ui_data: UIData | undefined; private _states: StatesController<NC> | undefined; private _lifecycle: LifeCycleController | undefined; private _serializer: NodeSerializer | undefined; private _cook_controller: NodeCookController<NC> | undefined; public readonly flags: FlagsController | undefined; public readonly displayNodeController: DisplayNodeController | undefined; public readonly persisted_config: BasePersistedConfig | undefined; private _params_controller: ParamsController | undefined; readonly paramsConfig: K | undefined; readonly pv: ParamsValueAccessorType<K> = (<unknown>new ParamsValueAccessor<K>()) as ParamsValueAccessorType<K>; // readonly pv: ParamsValueAccessor<K> = new ParamsValueAccessor<K>(this); readonly p: ParamsAccessorType<K> = (<unknown>new ParamsAccessor<K>()) as ParamsAccessorType<K>; copy_param_values(node: TypedNode<NC, K>) { const non_spare = this.params.non_spare; for (let param of non_spare) { const other_param = node.params.get(param.name()); if (other_param) { param.copy_value(other_param); } } } private _name_controller: NameController | undefined; get parentController(): HierarchyParentController { return (this._parent_controller = this._parent_controller || new HierarchyParentController(this)); } static displayedInputNames(): string[] { return []; } private _children_controller: HierarchyChildrenController | undefined; protected _children_controller_context: NodeContext | undefined; get childrenControllerContext() { return this._children_controller_context; } private _create_children_controller(): HierarchyChildrenController | undefined { if (this._children_controller_context) { return new HierarchyChildrenController(this, this._children_controller_context); } } get childrenController(): HierarchyChildrenController | undefined { return (this._children_controller = this._children_controller || this._create_children_controller()); } childrenAllowed(): boolean { return this._children_controller_context != null; } get uiData(): UIData { return (this._ui_data = this._ui_data || new UIData(this)); } get states(): StatesController<NC> { return (this._states = this._states || new StatesController(this)); } get lifecycle(): LifeCycleController { return (this._lifecycle = this._lifecycle || new LifeCycleController(this)); } get serializer(): NodeSerializer { return (this._serializer = this._serializer || new NodeSerializer(this)); } get cookController(): NodeCookController<NC> { return (this._cook_controller = this._cook_controller || new NodeCookController(this)); } protected _io: IOController<NC> | undefined; get io(): IOController<NC> { return (this._io = this._io || new IOController(this)); } get nameController(): NameController { return (this._name_controller = this._name_controller || new NameController(this)); } /** * sets the name of a node. Note that if a sibbling node already has that name, it will be updated to be unique. * */ setName(name: string) { this.nameController.setName(name); } _set_core_name(name: string) { this._name = name; } get params(): ParamsController { return (this._params_controller = this._params_controller || new ParamsController(this)); } // get processing_context(): ProcessingContext { // return (this._processing_context = this._processing_context || new ProcessingContext(this)); // } constructor(scene: PolyScene, name: string = 'BaseNode', public params_init_value_overrides?: ParamsInitData) { super(scene, name); } private _initialized: boolean = false; public initialize_base_and_node() { if (!this._initialized) { this._initialized = true; this.displayNodeController?.initializeNode(); this.initializeBaseNode(); // for base classes of Sop, Obj... this.initializeNode(); // for Derivated node clases, like BoxSop, TransformSop... if (this.polyNodeController) { this.polyNodeController.initializeNode(); } } else { console.warn('node already initialized'); } } protected initializeBaseNode() {} protected initializeNode() {} static type(): string { throw 'type to be overriden'; } /** * returns the type of the node. * */ type() { const c = this.constructor as typeof BaseNodeClass; return c.type(); } static context(): NodeContext { console.error('node has no node_context', this); throw 'context requires override'; } /** * returns the context. * */ context(): NodeContext { const c = this.constructor as typeof BaseNodeClass; return c.context(); } static require_webgl2(): boolean { return false; } require_webgl2(): boolean { const c = this.constructor as typeof BaseNodeClass; return c.require_webgl2(); } setParent(parent: BaseNodeType | null) { this.parentController.setParent(parent); } /** * returns the parent. * */ parent() { return this.parentController.parent(); } root() { return this._scene.root(); } /** * returns the path. * */ path(relative_to_parent?: BaseNodeType): string { return this.parentController.path(relative_to_parent); } // params createParams() {} addParam<T extends ParamType>( type: T, name: string, default_value: ParamInitValuesTypeMap[T], options?: ParamOptions ): ParamConstructorMap[T] | undefined { return this._params_controller?.addParam(type, name, default_value, options); } paramDefaultValue(name: string): ParamInitValueSerialized { return null; } // cook cook(input_contents: any[]): any { return null; } /** * registers a callback that will be run every time the node finishes cooking. * */ onCookEnd(callbackName: string, callback: OnCookCompleteHook) { this.cookController.registerOnCookEnd(callbackName, callback); } /** * returns a promise that will be resolved when the node finishes cooking. * */ async compute() { if (this.isDirty() || this.flags?.bypass?.active()) { return await this.containerController.compute(); } else { return this.containerController.container(); } } _setContainer(content: ContainableMap[NC], message: string | null = null) { // TODO: typescript: why is this a type of never this.containerController.container().set_content(content as never); //, this.self.cook_eval_key()); if (content != null) { if (!(content as any).name) { (content as any).name = this.path(); } if (!(content as any).node) { (content as any).node = this; } } this.cookController.endCook(message); } /** * create a node. * */ createNode(nodeClass: any, params_init_value_overrides?: ParamsInitData) { return this.childrenController?.createNode(nodeClass, params_init_value_overrides); } create_operation_container( type: string, operation_container_name: string, params_init_value_overrides?: ParamsInitData ) { return this.childrenController?.create_operation_container( type, operation_container_name, params_init_value_overrides ); } /** * removes a child node * */ removeNode(node: BaseNodeType) { this.childrenController?.removeNode(node); } dispose() { super.dispose(); this.setParent(null); this.io.inputs.dispose(); this.lifecycle.dispose(); this.displayNodeController?.dispose(); this.nameController.dispose(); this.childrenController?.dispose(); this.params.dispose(); } /** * returns the list of children * */ children() { return this.childrenController?.children() || []; } /** * returns a child node * */ node(path: string) { return this.parentController?.findNode(path) || null; } /** * returns a sibbling node * */ nodeSibbling(name: string): NodeTypeMap[NC] | null { const parent = this.parent(); if (parent) { const node = parent.childrenController?.child_by_name(name); if (node) { return node as NodeTypeMap[NC]; } } return null; } /** * returns the children matching the type * */ nodesByType(type: string) { return this.childrenController?.nodesByType(type) || []; } /** * sets a node as input * */ setInput( input_index_or_name: number | string, node: NodeTypeMap[NC] | null, output_index_or_name: number | string = 0 ) { this.io.inputs.setInput(input_index_or_name, node, output_index_or_name); } // emit emit(event_name: NodeEvent.CREATED, data: EmitDataByNodeEventMap[NodeEvent.CREATED]): void; emit(event_name: NodeEvent.DELETED, data: EmitDataByNodeEventMap[NodeEvent.DELETED]): void; emit(event_name: NodeEvent.NAME_UPDATED): void; emit(event_name: NodeEvent.OVERRIDE_CLONABLE_STATE_UPDATE): void; emit(event_name: NodeEvent.NAMED_INPUTS_UPDATED): void; emit(event_name: NodeEvent.NAMED_OUTPUTS_UPDATED): void; emit(event_name: NodeEvent.INPUTS_UPDATED): void; emit(event_name: NodeEvent.PARAMS_UPDATED): void; emit(event_name: NodeEvent.UI_DATA_POSITION_UPDATED): void; emit(event_name: NodeEvent.UI_DATA_COMMENT_UPDATED): void; emit(event_name: NodeEvent.ERROR_UPDATED): void; emit(event_name: NodeEvent.FLAG_BYPASS_UPDATED): void; emit(event_name: NodeEvent.FLAG_DISPLAY_UPDATED): void; emit(event_name: NodeEvent.FLAG_OPTIMIZE_UPDATED): void; emit(event_name: NodeEvent.SELECTION_UPDATED): void; emit(event_name: NodeEvent, data: object | null = null): void { this.scene().dispatchController.dispatch(this, event_name, data); } // serializer toJSON(include_param_components: boolean = false) { return this.serializer.toJSON(include_param_components); } // modules public async requiredModules(): Promise<ModuleName[] | void> {} public usedAssembler(): AssemblerName | void {} public integrationData(): IntegrationData | void {} // poly nodes public readonly polyNodeController: PolyNodeController | undefined; } export type BaseNodeType = TypedNode<any, any>; export class BaseNodeClass extends TypedNode<any, any> {} export class BaseNodeClassWithDisplayFlag extends TypedNode<any, any> { public readonly flags: FlagsControllerD = new FlagsControllerD(this); }
the_stack
import { Component, OnInit } from "@angular/core"; import { IdprestapiService } from "../idprestapi.service"; import { IdpdataService } from "../idpdata.service"; import { Router } from "@angular/router"; import { ViewChild } from "@angular/core"; import { IdpService } from "../idp-service.service"; import { IDPEncryption } from "../idpencryption.service"; import { constants } from "os"; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service'; @Component({ selector: "app-test-info", templateUrl: "./test-info.component.html", styleUrls: ["./test-info.component.css"] }) export class TestInfoComponent implements OnInit { @ViewChild("modalforRedirect") modalforRedirect; @ViewChild("modalforDelTestStep") modalforDelTestStep; confirmAlert; @ViewChild("modalforAlertDataMiss") modalforAlertDataMiss; @ViewChild("modalformandatoryFieldsAlert") modalformandatoryFieldsAlert; @ViewChild("modalforMandatorySAPStepswithJira") modalforMandatorySAPStepswithJira; @ViewChild("modalForConfirmSubmission") modalForConfirmSubmission; @ViewChild("modalforDelAntProperties") modalforDelAntProperties; @ViewChild("modalforDotNet") dotNetButton; @ViewChild("mandatorySCMAlert") mandatorySCMAlert; redirectModalRef: BsModalRef; dataMissingModalRef: BsModalRef; delTestStepModalRef: BsModalRef; mandatoryFieldsModalRef: BsModalRef; confirmSubmissionModalRef: BsModalRef; deleteAntPropModalRef: BsModalRef; mandatorySCMModalRef: BsModalRef; mandatorySAPStepsModalRef: BsModalRef; /*constructor start*/ constructor( public IdpdataService: IdpdataService, private IdpService: IdpService, private IdprestapiService: IdprestapiService, private router: Router, private idpencryption: IDPEncryption, private modalService:BsModalService ) { if (this.formStatusObject.operation === "copy" || this.formStatusObject.operation === "edit") { this.checkCheckBox(); } } /*constructor end*/ buildInfo: any = this.IdpdataService.data.buildInfo; testInfo: any = this.IdpdataService.data.testInfo; tempObjecttest: any = this.IdpdataService.data.checkboxStatus.testInfo; formStatusObject = this.IdpdataService.data.formStatus; env: any = []; applicationDetails: any = this.IdpdataService.application; // keys for Test Tool Option testCategory: any = []; listToFillFields: any = []; testTypeName: any = []; testframeworkList: any = [{ "name": "JUnit", "value": "jUnit" }, { "name": "TestNG", "value": "testNG" }]; caDevTestType: any = [{ "name": "Suite", "value": "suite" }, { "name": "Test Case", "value": "testCase" }]; testbrowserList: any = [{ "name": "Google Chrome", "value": "chrome" }, { "name": "Internet Explorer", "value": "ie" }, { "name": "Firefox", "value": "firefox" }]; msBuildVersion: any = [{ "name": "Default", "value": "(Default)" }, { "name": "15.0", "value": "MSBUILD_15" }, { "name": "14.0", "value": "MSBUILD_14" }, { "name": "12.0", "value": "MSBUILD_12" }, { "name": "4.0", "value": "MSBUILD_4" }]; // keys for Run Script Option shellScript: any = []; batchScript: any = []; antScript: any = []; iTafBrowserList: any = [{ "name": "Chrome", "value": "Chrome" }, { "name": "Mozilla", "value": "Mozilla" }, { "name": "Internet Explorer", "value": "Internet Explorer" },{ "name": "Sauce Labs Desktop Browser", "value": "Sauce Labs Desktop Browser" }, { "name": "Chrome Mobile (android)", "value": "Chrome Mobile (android)" }, { "name": "Safari Mobile (iOS)", "value": "Safari Mobile (iOS)" }, { "name": "Native App (android)", "value": "Native App (android)" }, { "name": "Sauce Labs Mobile Browser (android)", "value": "Sauce Labs Mobile Browser (android)" }, { "name": "Sauce Labs Mobile Browser (iOS)", "value": "Sauce Labs Mobile Browser (iOS)" }, { "name": "Sauce Labs Native App (android)", "value": "Sauce Labs Native App (android)" }, { "name": "Sauce Labs Native App (iOS)", "value": "Sauce Labs Native App (iOS)" }] testScriptList: any = [{ "name": "ANT Script", "value": "ant" }, { "name": "Shell Script", "value": "shellScript" }, { "name": "Batch Script", "value": "batchScript" }, { "name": "Powershell Script", "value": "powerShell" }, { "name": "SSH Execution", "value": "sshExecution" }]; scriptReportType: any = [{ "name": "Single View", "value": "singleView" }, { "name": "Serenity", "value": "serenity" }, { "name": "Others", "value": "others" }]; // keys for Iterating through Test Steps index: any; outerIndex: any; innerIndex: any; object: any; loader: any = "off"; message: any; errorMessage: any; msg: any; loc: any; indexI: any = -1; indexJ: any = -1; TriggerAlert(msg,loc) { this.redirectModalRef = this.modalService.show(this.modalforRedirect); this.redirectModalRef.content = {msg,loc}; } redirectToSync(modalRef) { modalRef.hide(); if (modalRef.content.loc) { this.router.navigate([modalRef.content.loc]); } } /* Checks for duplication of test Step name */ checkStepName(i, j) { console.log(this.testInfo); console.log(this.testInfo.testEnv[i].testSteps[j].stepName); for (let x = 0; x < this.testInfo.testEnv.length; x++) { if (this.testInfo.testEnv[x] !== undefined && this.testInfo.testEnv[x].testSteps !== undefined) { for (let y = 0; y < this.testInfo.testEnv[x].testSteps.length; y++) { if (this.tempObjecttest.testEnv[i].testSteps[j] === undefined) { this.tempObjecttest.testEnv[i].testSteps[j] = {}; } if (j !== y && this.testInfo.testEnv[x].testSteps[y].stepName !== undefined && this.testInfo.testEnv[i].testSteps[j].stepName !== undefined && this.testInfo.testEnv[x].testSteps[y].stepName === this.testInfo.testEnv[i].testSteps[j].stepName) { this.tempObjecttest.testEnv[i].testSteps[j].msgStep = "Step Name must be unique."; break; } else { this.tempObjecttest.testEnv[i].testSteps[j].msgStep = ""; } } } } } /* Addition of test step*/ addTestStep(index) { if (this.testInfo.testEnv[index].testSteps === undefined) { this.testInfo.testEnv[index].testSteps = []; } if (this.tempObjecttest.testEnv === undefined) { this.tempObjecttest.testEnv = []; } if (this.tempObjecttest.testEnv[index] === undefined) { this.tempObjecttest.testEnv[index] = {}; } if (this.tempObjecttest.testEnv[index].testSteps === undefined) { this.tempObjecttest.testEnv[index].testSteps = []; } this.testInfo.testEnv[index].testSteps.push({ "test": { "testCategory": "", "testTypeName": "", "frameWork": "", "browserName": "", "version": "" }, "runScript": { "scriptType": "", "reportType": "" } }); this.tempObjecttest.testEnv[index].testSteps.push({ "test": { "testCategory": "", "testTypeName": "", "frameWork": "", "browserName": "", "version": "" }, "runScript": { "scriptType": "", "reportType": "" } }); } removeTestStep(outerIndex, innerIndex) { this.delTestStepModalRef = this.modalService.show(this.modalforDelTestStep); this.delTestStepModalRef.content = {innerIndex,outerIndex} } confirmDeleteTestStep(modalRef) { this.testInfo.testEnv[modalRef.content.outerIndex].testSteps.splice(modalRef.content.innerIndex, 1); this.tempObjecttest.testEnv[modalRef.content.outerIndex].testSteps.splice(modalRef.content.innerIndex, 1); modalRef.hide(); } checkCategory(outerIndex, innerIndex, category) { this.innerIndex = innerIndex; this.outerIndex = outerIndex; /* Functional Testing Options */ if (category === "functional") { if (this.buildInfo.buildtool === 'iOS(Swift)') { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [ { 'name': 'Monkey Talk IOS', 'value': 'monkeyTalk' }, { "name": "iTAF", "value": "iTAF" }, { "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, {'name':'SAHI','value':'sahi'}, {'name':'HP UFT','value':'hpUft'}, { "name": "Cucumber", "value": "cucumber" } // {'name':'HP UFT','value':'hpUft'} ]; } else if (this.buildInfo.buildtool === 'oracleEBS') { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [ { 'name': 'OATS', 'value': 'oats' }, { "name": "iTAF", "value": "iTAF" }, { "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, {'name':'SAHI','value':'sahi'}, {'name':'HP UFT','value':'hpUft'}, { "name": "Cucumber", "value": "cucumber" } // {'name':'HP UFT','value':'hpUft'} ]; } else if (this.buildInfo.buildtool === 'tibco') { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [ { "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, //{ 'name': 'Soap UI', 'value': 'soapUI' }, {'name':'SAHI','value':'sahi'}, {'name':'HP UFT','value':'hpUft'}, { "name": "Cucumber", "value": "cucumber" } // {'name':'HP UFT','value':'hpUft'} ]; } else if (this.buildInfo.buildtool === "msBuild") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [ // { "name": "SAHI", "value": "sahi" }, { "name": "HP UFT", "value": "hpUft" } { "name": "SAHI", "value": "sahi" }, { "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, ]; } else if (this.buildInfo.buildtool === "maven") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, // { "name": "RFT", "value": "rft" }, { "name": "RFT", "value": "rft" }, // {"name": "Microsoft Test Manager", "value": "mtm"}, { "name": "SAHI", "value": "sahi" }]; // {"name": "HP UFT", "value": "hpUft"}, // {"name": "HP ALM", "value": "hpAlm"}]; } else if (this.buildInfo.buildtool === "dotNetCsharp") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, { "name": "iTAF", "value": "iTAF" }, { "name": "RFT", "value": "rft" }, { "name": "Protractor", "value": "protractor" }, { "name": "Cucumber", "value": "cucumber" }, { "name": "SAHI", "value": "sahi" }]; // {"name": "HP UFT", "value": "hpUft"}, {"name": "HP ALM", "value": "hpAlm"}]; } else if (this.buildInfo.buildtool === "angular") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }]; } else if (this.buildInfo.buildtool === "nodeJs") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, { "name": "SAHI", "value": "sahi" } // { "name": "HP UFT", "value": "hpUft" }, ]; } else if (this.buildInfo.buildtool === "ant") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, { "name": "SAHI", "value": "sahi" }]; // {"name": "Microsoft Test Manager", "value": "mtm"}]; // {"name": "HP UFT", "value": "hpUft"}, // {"name": "HP ALM", "value": "hpAlm"}]; } else if (this.buildInfo.buildtool === "gradle") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Monkey Talk", "value": "androidmonkeyTalk" }, { "name": "iTAF", "value": "iTAF" }, {'name':'Protractor','value':'protractor'}, { "name": "Cucumber", "value": "cucumber" }, { "name": "RFT", "value": "rft" }, {'name':'Protractor','value':'protractor'} ]; } else if (this.buildInfo.buildtool === 'maximo') { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [ { "name": "Selenium", "value": "selenium" }, { "name": "Cucumber", "value": "cucumber" }, { "name": "RFT", "value": "rft" }, { "name": "iTAF", "value": "iTAF" }, // { 'name': 'Soap UI', 'value': 'soapUI' }, {'name':'SAHI','value':'sahi'} // {'name':'HP UFT','value':'hpUft'} ]; } else { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Selenium", "value": "selenium" }, { "name": "RFT", "value": "rft" }, { "name": "SAHI", "value": "sahi" }]; } if (this.IdpdataService.isSAPApplication) { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "eCATT", "value": "eCATT" }, { "name": "HP UFT", "value": "hpUft" }, { "name": "Cucumber", "value": "cucumber" }]; } this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName.push( {'name':'HP UFT','value':'hpUft'}) } if (category === "performance") { if (this.buildInfo.buildtool === "ant" || this.buildInfo.buildtool === "maven" || this.buildInfo.buildtool === "msBuild" || this.buildInfo.buildtool === "nodeJs") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "JMeter", "value": "jMeter" }]; } else if (this.IdpdataService.isSAPApplication) { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "RPT", "value": "rpt" }]; } else if (this.buildInfo.buildtool === "SAPNonCharm") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "RPT", "value": "rpt" }]; } else this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "JMeter", "value": "jMeter" }, { "name": "RPT", "value": "rpt" }]; } if (category === "security") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "IBM AppScan Enterprise", "value": "appscan" }]; } if (category === "service") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = []; if (this.buildInfo.buildtool === "msBuild") { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Soap UI", "value": "soapUI" }]; } else { this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].testTypeName = [{ "name": "Soap UI", "value": "soapUI" }, { 'name': 'Parasoft SOA', 'value': 'parasoftsoa' }]; } } } changeRunScript(outerIndex, innerIndex) { this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.pathOfFile = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.targets = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.host = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.userName = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.password = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.script = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.pathToFiles = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.destinationDir = ""; this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].transferFilesFlag = "off"; this.tempObjecttest.testEnv[outerIndex].testSteps[innerIndex].runScript.flattenFilePath = "off"; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.flattenFilePath = "off"; } cleartransferFilesFlag(outerIndex, innerIndex) { this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.pathToFiles = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.destinationDir = ""; this.testInfo.testEnv[outerIndex].testSteps[innerIndex].runScript.flattenFilePath = "off"; } /* resets Data by default empty values * on resetting */ resetData() { const x = confirm("Are you sure to Reset ?"); if (x) { const val = this.testInfo.testEnv; this.testInfo = { "testEnv": [] }; for (let i = 0; i < val.length; i++) { this.testInfo.testEnv.push({ "envName": val[i].envName, "envFlag": "off", }); } this.IdpdataService.data.testInfo = this.testInfo; this.IdpdataService.data.checkboxStatus.testInfo = {}; this.tempObjecttest = this.IdpdataService.data.checkboxStatus.testInfo; } } /* Validation of Test page * for test steps selected */ validatePage() { let f = true; for (let i = 0; i < this.testInfo.testEnv.length; i++) { if (this.testInfo.testEnv[i].envFlag === "on" && (this.testInfo.testEnv[i].testSteps === undefined || (this.testInfo.testEnv[i].testSteps !== undefined && this.testInfo.testEnv[i].testSteps.length === 0))) { f = false; break; } else if (this.testInfo.testEnv[i].envFlag === "on" && this.testInfo.testEnv[i].testSteps !== undefined && this.testInfo.testEnv[i].testSteps.length !== 0) { for (let j = 0; j < this.testInfo.testEnv[i].testSteps.length; j++) { if ((this.tempObjecttest.testEnv[i].testSteps[j].runScriptFlag === undefined || this.tempObjecttest.testEnv[i].testSteps[j].runScriptFlag === "off") && (this.tempObjecttest.testEnv[i].testSteps[j].testToolFlag === undefined || this.tempObjecttest.testEnv[i].testSteps[j].testToolFlag === "off")) { f = false; break; } } } else if (this.testInfo.testEnv[i].envFlag === "off") { continue; } else { continue; } } if (f === true) { console.log(f); return true; } else { console.log(f); return false; } } setClouddata(appName, pipelineName, data) { let cloudDeploymentCount = 0; const cloudData = { "appName": appName, "pipelineName": pipelineName, "env": [] }; for (let i = 0; i < data.length; i++) { cloudData.env.push({ "name": data[i].envName, "step": [] }); if (data[i].deploySteps !== undefined) { for (let j = 0; j < data[i].deploySteps.length; j++) { if (data[i].deploySteps[j].cloudDeploymentFlag !== undefined && data[i].deploySteps[j].cloudDeploymentFlag === "on") { const pipeline_new = appName + "_" + pipelineName + "_" + data[i].envName + "_step" + j; const pipeline_id = this.idpencryption.encryptAES(pipeline_new); let id_new = "cfe00b10-f0f3-41c0-8edb-"; id_new = id_new + pipeline_id.substr(pipeline_id.length - 8); data[i].deploySteps[j].cloudData.id = id_new; data[i].deploySteps[j].cloudData.application=appName; const pipelineJson = JSON.stringify(data[i].deploySteps[j].cloudData); const encryptedPipelineString = this.idpencryption.encryptAES(pipelineJson); cloudData.env[i].step.push({ "index": j + 1, "pipelineInfo": encryptedPipelineString }); cloudDeploymentCount++; } } } } return [cloudData, cloudDeploymentCount]; } submitData(modalRef) { this.loader = "on"; this.IdpdataService.freezeNavBars = true; this.IdpdataService.data.testInfo = this.testInfo; this.IdpdataService.data.masterJson["basicInfo"] = this.IdpdataService.data.basicInfo; this.IdpdataService.data.masterJson["buildInfo"] = this.IdpdataService.data.buildInfo; this.IdpdataService.data.masterJson["code"] = this.IdpdataService.data.code; this.IdpdataService.data.masterJson["deployInfo"] = this.IdpdataService.data.deployInfo; this.IdpdataService.data.masterJson["testInfo"] = this.IdpdataService.data.testInfo; this.IdpdataService.data.checkboxStatus.testInfo = this.tempObjecttest; const applicationName = this.IdpdataService.data.basicInfo.applicationName; const pipelineName = this.IdpdataService.data.basicInfo.pipelineName; var count=this.setClouddata(applicationName,pipelineName,this.IdpdataService.data.deployInfo.deployEnv); var cloudErrorMsg="failure"; if(count[1]>0){ var applicationData={"job":[{"type":"createApplication","application":{"cloudProviders":"","instancePort":80,"name":applicationName,"dataSources": { "enabled": [ "canaryConfigs" ], "disabled": [] },"email":"userName@domain.com"},"user":"[anonymous]"}],"application":applicationName,"description":"Create Application: applicationName"} this.IdprestapiService.createCloudApplication(applicationData) .then(response => { try { let resp = response.json(); let errorMsg = resp.errorMessage; console.log(resp); this.loader = 'off'; // this.IdpdataService.freezeNavBars=false; if (errorMsg === null && resp.status.toLowerCase() === 'success') { this.IdprestapiService.createCloudPipeline(count[0]) .then(response => { try { let resp = response.json(); let errorMsg = resp.errorMessage; console.log(resp); this.loader = 'off'; // this.IdpdataService.freezeNavBars=false; if (errorMsg === null && resp.status.toLowerCase() === 'success') { cloudErrorMsg="success"; } } catch (e) { alert('Failed while submiting the trigger job'); console.log(e); } //callPipeline(count[0]) }) console.log(this.formStatusObject.operation); } } catch (e) { alert('Failed while submiting the trigger job'); console.log(e); } }); } let data = this.idpencryption.doubleDecryptPassword(this.IdpdataService.data.masterJson); data = this.idpencryption.encryptAES(JSON.stringify(data)); this.IdprestapiService.submit(data) .then(response => { modalRef.hide(); try { const resp = response.json(); const errorMsg = resp.errorMessage; this.loader = "off"; if (errorMsg === null && resp.resource.toLowerCase() === "success") { this.message = "success"; if (this.formStatusObject.operation !== "edit") { const actiondata = { "applicationName": this.IdpdataService.data.masterJson.basicInfo.applicationName, "method": "create", "pipelineName": this.IdpdataService.data.masterJson.basicInfo.pipelineName, "userName": this.IdpdataService.idpUserName }; this.IdprestapiService.sendPipeMail(actiondata); } else { const actiondata = { "applicationName": this.IdpdataService.data.masterJson.basicInfo.applicationName, "method": "edit", "pipelineName": this.IdpdataService.data.masterJson.basicInfo.pipelineName, "userName": this.IdpdataService.idpUserName }; this.IdprestapiService.sendPipeMail(actiondata); } this.getAppDetails(); } else { this.IdpdataService.freezeNavBars = false; this.message = "error"; this.errorMessage = errorMsg; } } catch (e) { alert("Failed while submiting the trigger job"); console.log(e); } }); } go() { if (this.validatePage()) { if (this.IdpdataService.isSAPApplication && this.buildInfo.buildtool === "SapNonCharm" && this.IdpdataService.data.checkboxStatus.buildInfo.codeAnalysisCheck === "on" && this.IdpdataService.data.checkboxStatus.buildInfo.SAPCodeInspectorCheck !== "on") { this.IdpdataService.allFormStatus.buildInfo = false; } if (this.IdpdataService.allFormStatus.basicInfo && this.IdpdataService.allFormStatus.codeInfo && this.IdpdataService.allFormStatus.buildInfo && this.IdpdataService.allFormStatus.deployInfo && this.IdpdataService.allFormStatus.testInfo) { let scmCheckBreak = false; let operationCheckBreak = false; if (this.IdpdataService.isSAPApplication && this.buildInfo.buildtool === "SapNonCharm") { const testEnv = this.testInfo.testEnv; for (let i = 0; i < testEnv.length; i++) { if (testEnv[i].envFlag === "on") { const testStep = testEnv[i].testSteps; for (let j = 0; j < testStep.length; j++) { if (testStep[j].test !== undefined && (testStep[j].test.testTypeName === "rpt" || testStep[j].test.testTypeName === "hpUft")) { if (this.IdpdataService.SAPScmCheck === undefined || this.IdpdataService.SAPScmCheck === "off" || this.IdpdataService.SAPScmCheck === "") { scmCheckBreak = true; break; } } } } } if (this.IdpdataService.data.checkboxStatus.buildInfo.RaiseJiraBugonfailureCheck === "on" && this.IdpdataService.data.checkboxStatus.buildInfo.codeAnalysisCheck !== "on" && this.IdpdataService.data.checkboxStatus.buildInfo.castAnalysisCheck !== "on" && this.IdpdataService.data.buildInfo.modules[0].unitTesting !== "on") { operationCheckBreak = true; } } if (scmCheckBreak) { this.mandatorySCMModalRef = this.modalService.show(this.mandatorySCMAlert); } else if (operationCheckBreak) { this.mandatorySAPStepsModalRef = this.modalService.show(this.modalforMandatorySAPStepswithJira); } else { this.confirmSubmissionModalRef = this.modalService.show(this.modalForConfirmSubmission); } } else { let listToFillFields = []; if (!this.IdpdataService.allFormStatus.basicInfo && this.listToFillFields.indexOf("BasicInfo") === -1) { listToFillFields.push("BasicInfo"); } if (!this.IdpdataService.allFormStatus.codeInfo && this.listToFillFields.indexOf("CodeInfo") === -1) { listToFillFields.push("CodeInfo"); } if (!this.IdpdataService.allFormStatus.buildInfo && this.listToFillFields.indexOf("BuildInfo") === -1) { listToFillFields.push("BuildInfo"); } if (!this.IdpdataService.allFormStatus.deployInfo && this.listToFillFields.indexOf("DeployInfo") === -1) { listToFillFields.push("DeployInfo"); } if (!this.IdpdataService.allFormStatus.testInfo && this.listToFillFields.indexOf("TestInfo") === -1) { listToFillFields.push("TestInfo"); } this.mandatoryFieldsModalRef = this.modalService.show(this.modalformandatoryFieldsAlert); this.mandatoryFieldsModalRef.content = {listToFillFields}; } } else { this.dataMissingModalRef = this.modalService.show(this.modalforAlertDataMiss); } } ngOnInit() { if (this.IdpdataService.data.formStatus.basicInfo.appNameStatus === "0") { this.TriggerAlert("Application Name","/createConfig/basicInfo"); } else if (this.IdpdataService.data.formStatus.buildInfo.buildToolStatus === "0") { this.TriggerAlert("Technology Type","/createConfig/codeInfo"); } if (this.buildInfo.buildtool === "SapNonCharm") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }]; } else if (this.buildInfo.buildtool === "maven" || this.buildInfo.buildtool === "ant" || this.buildInfo.buildtool === "msBuild") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" },]; } else if (this.buildInfo.buildtool === "nodeJs") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" }]; } else if (this.buildInfo.buildtool === "angular") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" }]; }else if (this.buildInfo.buildtool === "mainframe") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" }]; } else if (this.buildInfo.buildtool === 'tibco') { this.testCategory = [ { "name": "Functional", "value": "functional" }, { 'name': 'Performance', 'value': 'performance' }, { 'name': 'Service', 'value': 'service' } ]; } else if (this.buildInfo.buildtool === 'maximo') { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Service", "value": "service" }]; } else if (this.buildInfo.buildtool === "php") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Security", "value": "security" }, { "name": "Service", "value": "service" }]; } else if (this.buildInfo.buildtool === "mssql") { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" }]; } else if (this.buildInfo.buildtool === 'tibco') { this.testCategory = [{ 'name': 'Performance', 'value': 'performance' }, { 'name': 'Service', 'value': 'service' }]; } else if (this.buildInfo.buildtool === "gradle") { this.testCategory = [{ "name": "Functional", "value": "functional" }]; } else { this.testCategory = [{ "name": "Functional", "value": "functional" }, { "name": "Performance", "value": "performance" }, { "name": "Service", "value": "service" }]; } window.scroll(0,0); } redirectToBasicInfo() { this.router.navigate(["/createConfig/basicInfo"]); } // Start Clear Functions for Checkboxes clearStep(index) { this.testInfo.testEnv[index].testSteps = []; if (this.tempObjecttest.testEnv !== undefined && this.tempObjecttest.testEnv[index] !== undefined) { this.tempObjecttest.testEnv[index].testSteps = []; } return "off"; } clearRunScript(innerIndex, outerIndex) { this.testInfo.testEnv[innerIndex].testSteps[outerIndex].runScript = { "scriptType": "", "reportType": "" }; this.tempObjecttest.testEnv[innerIndex].testSteps[outerIndex].runScript = { "scriptType": "", "reportType": "" }; return "off"; } clearTest(innerIndex, outerIndex) { this.testInfo.testEnv[innerIndex].testSteps[outerIndex].test = { "testCategory": "", "testTypeName": "", "frameWork": "", "browserName": "", "version": "" }; this.tempObjecttest.testEnv[innerIndex].testSteps[outerIndex].test = { "testCategory": "", "testTypeName": "", "frameWork": "", "browserName": "", "version": "" }; return "off"; } clearLibraryFlag(innerIndex, outerIndex) { this.testInfo.testEnv[innerIndex].testSteps[outerIndex].test.externalFilePath = ""; return "off"; } cleardataPool(innerIndex, outerIndex) { this.testInfo.testEnv[innerIndex].testSteps[outerIndex].test.iteration = ""; this.testInfo.testEnv[innerIndex].testSteps[outerIndex].test.fullIteration = ""; return "off"; } clearSharedProject(innerIndex, outerIndex) { this.testInfo.testEnv[innerIndex].testSteps[outerIndex].test.userName = ""; return "off"; } getAppDetails() { this.IdprestapiService.getApplicationDetails(this.IdpdataService.data.masterJson.basicInfo.applicationName) .then(response => { if (response) { const resp = response.json().resource; let parsed; try { parsed = JSON.parse(resp); if (parsed) { this.IdpdataService.application = parsed.appJson; this.redirectTo(); } } catch (e) { console.log(e); alert("Failed while getting the pipeline details"); this.redirectTo(); } } }); } redirectTo() { setTimeout(() => { this.router.navigate(["/createPipeline/success"]); }, 3000); } // End Clear Functions for Checkboxes // Start Check Checkbox function checkCheckBox() { if (this.tempObjecttest.testEnv === undefined) { this.tempObjecttest.testEnv = []; } for (let i = 0; i < this.testInfo.testEnv.length; i++) { const envFlag = "off"; if (this.tempObjecttest.testEnv[i] === undefined) { this.tempObjecttest.testEnv[i] = {}; } if (this.tempObjecttest.testEnv[i].testSteps === undefined) { this.tempObjecttest.testEnv[i].testSteps = []; } if (this.testInfo.testEnv[i].testSteps !== undefined) { if (this.testInfo.testEnv[i].testSteps.length !== 0) { this.testInfo.testEnv[i].envFlag = "on"; } for (let j = 0; j < this.testInfo.testEnv[i].testSteps.length; j++) { const runScriptFlag = "off"; const testToolFlag = "off"; if (this.testInfo.testEnv[i].testSteps[j].runScript !== "" && this.testInfo.testEnv[i].testSteps[j].runScript !== undefined) { if (this.testInfo.testEnv[i].testSteps[j].runScript.scriptType !== "" && this.testInfo.testEnv[i].testSteps[j].runScript.scriptType !== undefined) { if (this.tempObjecttest.testEnv[i].testSteps[j] === undefined) { this.tempObjecttest.testEnv[i].testSteps[j] = {}; } this.tempObjecttest.testEnv[i].testSteps[j].runScriptFlag = "on"; if (this.testInfo.testEnv[i].testSteps[j].runScript.scriptType === "ant") { if (this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr && this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr[0].antKey !== undefined && this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr[0].antValue !== undefined) { this.testInfo.testEnv[i].testSteps[j].runScript.antProperty1 = "on"; } if (this.testInfo.testEnv[i].testSteps[j].runScript.javaOptions !== undefined) { this.testInfo.testEnv[i].testSteps[j].runScript.antJavaOption1 = "on"; } } } } if (this.testInfo.testEnv[i].testSteps[j].test.testCategory !== "" && this.testInfo.testEnv[i].testSteps[j].test.testCategory !== undefined) { if (this.testInfo.testEnv[i].testSteps[j].test.testCategory !== "" && this.testInfo.testEnv[i].testSteps[j].test.testCategory !== undefined) { if (this.tempObjecttest.testEnv[i].testSteps[j] === undefined) { this.tempObjecttest.testEnv[i].testSteps[j] = {}; } this.tempObjecttest.testEnv[i].testSteps[j].testToolFlag = "on"; this.checkCategory(i, j, this.testInfo.testEnv[i].testSteps[j].test.testCategory); } } if (this.testInfo.testEnv[i].testSteps[j].runScript.pathToFiles !== "" && this.testInfo.testEnv[i].testSteps[j].runScript.pathToFiles !== undefined) { if (this.tempObjecttest.testEnv[i].testSteps[j].runScript === undefined) { this.tempObjecttest.testEnv[i].testSteps[j].runScript = {}; } this.tempObjecttest.testEnv[i].testSteps[j].transferFilesFlag = "on"; if (this.testInfo.testEnv[i].testSteps[j].runScript.flattenFilePath === "on") { this.tempObjecttest.testEnv[i].testSteps[j].runScript.flattenFilePath = "on"; } } this.IdpdataService.data.checkboxStatus.testInfo = this.tempObjecttest; } } else { continue; } } } clearTool(i, j) { this.testInfo.testEnv[i].testSteps[j].test.testTypeName = ""; this.clearAllValues(i, j); } clearAllValues(envIndex, index) { this.testInfo.testEnv[envIndex].testSteps[index].test.folderUrl = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.projectName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.frameWork = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.rootDir = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.testSuiteName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.externalFilePath = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.scriptPath = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.targets = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.timeout = 60; this.testInfo.testEnv[envIndex].testSteps[index].test.serverName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.userName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.password = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.domain = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.testCase = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.fullIiteration = "off"; this.testInfo.testEnv[envIndex].testSteps[index].test.iteration = 2; this.testInfo.testEnv[envIndex].testSteps[index].test.path = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.serverUrl = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.browserName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.testPlan = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.version = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.folderUrl = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.projectLocation = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.parameters = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.version = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.arg = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.serviceName = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.authenticationCode = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.sharedProject = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.ownerId = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.buildDefId = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.arg = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafUser = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafPassword = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafAgent = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafProject = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafBrowser = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafTestSuite = ""; this.testInfo.testEnv[envIndex].testSteps[index].test.iTafUrl = ""; } // End Check Checkbox function setFormStatus(data) { this.IdpdataService.allFormStatus.testInfo = data; } // Antproperties Srart here openAntPropertiesField(i, j) { this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr = []; this.addAntProperties(i, j); return "on"; } addAntProperties(i, j) { this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr.push({ }); } clearAntPropertisField(i, j) { this.testInfo.testEnv[i].testSteps[j].runScript.antPropertiesArr = []; return false; } deleteAntProp(index, i, j) { this.deleteAntPropModalRef = this.modalService.show(this.modalforDelAntProperties); this.deleteAntPropModalRef.content = {index:index,indexI:i,indexJ:j} } deleteAntPropConfirm(modalRef) { this.testInfo.testEnv[modalRef.content.indexI].testSteps[modalRef.content.indexJ].runScript.antPropertiesArr.splice(modalRef.content.index, 1); modalRef.hide(); } }
the_stack
* @module Rendering */ import { assert } from "@itwin/core-bentley"; import { Point3d, Range1d, Range2d, Vector3d } from "@itwin/core-geometry"; import { OctEncodedNormal, QParams2d, QParams3d, QPoint2d, QPoint3d, Quantization } from "@itwin/core-common"; import { RenderMemory } from "../../RenderMemory"; import { RealityMeshPrimitive, RealityMeshProps } from "./RealityMeshPrimitive"; export enum Child { Q00, Q01, Q10, Q11 } class UpsampleIndexMap extends Map<number, number> { private _next = 0; public indices = new Array<number>(); public addTriangle(indices: number[]) { for (const index of indices) { let mapIndex = this.get(index); if (undefined === mapIndex) this.set(index, mapIndex = this._next++); this.indices.push(mapIndex); } } } class ClipAxis { constructor(public vertical: boolean, public lessThan: boolean, public value: number) { } } const scratchQPoint3d = QPoint3d.fromScalars(0, 0, 0), scratchQPoint3d1 = QPoint3d.fromScalars(0, 0, 0); const scratchQPoint2d = new QPoint2d(), scratchQPoint2d1 = new QPoint2d(); /** These are currently retained on terrain leaf tiles for upsampling. * It may be worthwhile to pack the data into buffers... * @internal. */ export class TerrainMeshPrimitive extends RealityMeshPrimitive { private _currPointCount = 0; private _currIndexCount = 0; private constructor(props: RealityMeshProps, private _pointCapacity: number, private _indexCapacity: number) { super(props); } public get isCompleted() { return this._currIndexCount === this._indexCapacity && this._currPointCount === this._pointCapacity; } public get nextPointIndex() { return this._currPointCount; } public static create(props: TerrainMesh.Props) { let totalIndices = props.indexCount; let totalPoints = props.pointCount; if (props.wantSkirts) { totalIndices += 6 * (Math.max(0, props.northCount - 1) + Math.max(0, props.southCount - 1) + Math.max(0, props.eastCount - 1) + Math.max(0, props.westCount - 1)); totalPoints += (props.northCount + props.southCount + props.eastCount + props.westCount); } const realityMeshProps = { indices: new Uint16Array(totalIndices), pointQParams: props.pointQParams, points: new Uint16Array(3 * totalPoints), uvQParams: QParams2d.fromZeroToOne(), uvs: new Uint16Array(2 * totalPoints), normals: props.wantNormals ? new Uint16Array(totalPoints) : undefined, featureID: 0, }; return new TerrainMeshPrimitive(realityMeshProps, totalPoints, totalIndices); } public override collectStatistics(stats: RenderMemory.Statistics): void { stats.addTerrain(this.bytesUsed); } public addVertex(point: Point3d, uvParam: QPoint2d, normal?: number) { scratchQPoint3d.init(point, this.pointQParams); this.addQuantizedVertex(scratchQPoint3d, uvParam, normal); } public addQuantizedVertex(point: QPoint3d, uv: QPoint2d, normal?: number) { if (this._currPointCount >= this._pointCapacity) { assert(false, "terrain point capacity exceeded"); return; } let pointIndex = 3 * this._currPointCount; this.points[pointIndex++] = point.x; this.points[pointIndex++] = point.y; this.points[pointIndex++] = point.z; let paramIndex = 2 * this._currPointCount; this.uvs[paramIndex++] = uv.x; this.uvs[paramIndex++] = uv.y; if (normal && this.normals) this.normals[this._currPointCount] = normal; this._currPointCount++; } public addQuad(i0: number, i1: number, i2: number, i3: number) { this.addTriangle(i0, i1, i2); this.addTriangle(i1, i3, i2); } public addTriangle(i0: number, i1: number, i2: number) { if (this._currIndexCount + 3 > this._indexCapacity) { assert(false, "terrain index capacity exceeded"); return; } this.indices[this._currIndexCount++] = i0; this.indices[this._currIndexCount++] = i1; this.indices[this._currIndexCount++] = i2; } public addIndices(indices: number[]) { for (const index of indices) this.indices[this._currIndexCount++] = index; } private static _scratchZRange = Range1d.createNull(); private static _scratchTriangleRange = Range2d.createNull(); private static _scratchUVRange = Range2d.createNull(); private static _scratchUVQParams = QParams2d.fromZeroToOne(); public upsample(uvSampleRange: Range2d): { heightRange: Range1d, mesh: TerrainMeshPrimitive } { const indexMap = new UpsampleIndexMap(); const uvLow = QPoint2d.create(uvSampleRange.low, TerrainMeshPrimitive._scratchUVQParams); const uvHigh = QPoint2d.create(uvSampleRange.high, TerrainMeshPrimitive._scratchUVQParams); const uvRange = Range2d.createXYXY(uvLow.x, uvLow.y, uvHigh.x, uvHigh.y, TerrainMeshPrimitive._scratchUVRange); const clipAxes = new Array<ClipAxis>(); const addedPoints = new Array<QPoint3d>(), addedParams = new Array<QPoint2d>(), addedNormals = new Array<number>(); if (uvLow.x > 0) clipAxes.push(new ClipAxis(true, false, uvLow.x)); if (uvHigh.x < Quantization.rangeScale16) clipAxes.push(new ClipAxis(true, true, uvHigh.x)); if (uvLow.y > 0) clipAxes.push(new ClipAxis(false, false, uvLow.y)); if (uvHigh.y < Quantization.rangeScale16) clipAxes.push(new ClipAxis(false, true, uvHigh.y)); for (let i = 0; i < this.indices.length;) { const triangleIndices = [this.indices[i++], this.indices[i++], this.indices[i++]]; const triangleRange = Range2d.createNull(TerrainMeshPrimitive._scratchTriangleRange); for (const index of triangleIndices) { const paramIndex = 2 * index; triangleRange.extendXY(this.uvs[paramIndex], this.uvs[paramIndex + 1]); } if (uvRange.intersectsRange(triangleRange)) { if (uvRange.containsRange(triangleRange)) { indexMap.addTriangle(triangleIndices); } else { this.addClipped(triangleIndices, indexMap, clipAxes, 0, addedPoints, addedParams, addedNormals); } } } const parentPoints = this.points; const parentParams = this.uvs; const parentNormals = this.normals; const parentPointCount = this.points.length / 3; const zRange = Range1d.createNull(TerrainMeshPrimitive._scratchZRange); const mesh = TerrainMeshPrimitive.create({ pointQParams: this.pointQParams, pointCount: indexMap.size, indexCount: indexMap.indices.length, wantSkirts: false, northCount: 0, southCount: 0, eastCount: 0, westCount: 0, wantNormals: this.normals !== undefined }); for (const mapEntry of indexMap.entries()) { const parentIndex = mapEntry[0]; let normal: number | undefined; if (parentIndex < parentPointCount) { const pointIndex = 3 * parentIndex; scratchQPoint3d.setFromScalars(parentPoints[pointIndex], parentPoints[pointIndex + 1], parentPoints[pointIndex + 2]); const paramIndex = 2 * parentIndex; scratchQPoint2d.setFromScalars(parentParams[paramIndex], parentParams[paramIndex + 1]); if (parentNormals) normal = parentNormals[parentIndex]; } else { const addedIndex = parentIndex - parentPointCount; addedPoints[addedIndex].clone(scratchQPoint3d); addedParams[addedIndex].clone(scratchQPoint2d); if (addedNormals.length) normal = addedNormals[addedIndex]; } mesh.addQuantizedVertex(scratchQPoint3d, scratchQPoint2d, normal); zRange.extendX(scratchQPoint3d.z); } mesh.addIndices(indexMap.indices); assert(mesh.isCompleted); const qParams = this.pointQParams; const heightRange = Range1d.createXX(Quantization.unquantize(zRange.low, qParams.origin.z, qParams.scale.z), Quantization.unquantize(zRange.high, qParams.origin.z, qParams.scale.z)); return { heightRange, mesh }; } private addClipped(triangleIndices: number[], indexMap: UpsampleIndexMap, clipAxes: ClipAxis[], clipIndex: number, addedPoints: QPoint3d[], addedParams: QPoint2d[], addedNormals: number[]) { if (clipIndex === clipAxes.length) { indexMap.addTriangle(triangleIndices); return; } const inside = new Array<boolean>(3); const values = new Array<number>(3); const clipOutput = new Array<number>(); const clipAxis = clipAxes[clipIndex++]; const parentPoints = this.points; const parentParams = this.uvs; const parentNormals = this.normals; const clipValue = clipAxis.value; const parentPointCount = parentPoints.length / 3; const getPoint = (index: number, result: QPoint3d): QPoint3d => { if (index < parentPointCount) { const pointIndex = index * 3; result.setFromScalars(parentPoints[pointIndex], parentPoints[pointIndex + 1], parentPoints[pointIndex + 2]); } else { addedPoints[index - parentPointCount].clone(result); } return result; }; const getParam = (index: number, result: QPoint2d): QPoint2d => { if (index < parentPointCount) { const pointIndex = index * 2; result.setFromScalars(parentParams[pointIndex], parentParams[pointIndex + 1]); } else { addedParams[index - parentPointCount].clone(result); } return result; }; const getNormal = (index: number): number | undefined => { if (!parentNormals) return undefined; return (index < parentPointCount) ? parentNormals[index] : addedNormals[index - parentPointCount]; }; for (let i = 0; i < 3; i++) { const index = triangleIndices[i]; const thisParam = getParam(index, scratchQPoint2d); const thisValue = clipAxis.vertical ? thisParam.x : thisParam.y; values[i] = thisValue; inside[i] = clipAxis.lessThan ? (thisValue < clipValue) : (thisValue > clipValue); } for (let i = 0; i < 3; i++) { const index = triangleIndices[i]; const next = (i + 1) % 3; if (inside[i]) clipOutput.push(index); if (inside[i] !== inside[next]) { const nextIndex = triangleIndices[next]; const fraction = (clipValue - values[i]) / (values[next] - values[i]); clipOutput.push(parentPointCount + addedPoints.length); addedPoints.push(interpolateQPoint3d(getPoint(index, scratchQPoint3d), getPoint(nextIndex, scratchQPoint3d1), fraction)); addedParams.push(interpolateQPoint2d(getParam(index, scratchQPoint2d), getParam(nextIndex, scratchQPoint2d1), fraction)); if (parentNormals) addedNormals.push(interpolateOctEncodedNormal(getNormal(index)!, getNormal(nextIndex)!, fraction)); } } if (clipOutput.length > 2) { this.addClipped(clipOutput.slice(0, 3), indexMap, clipAxes, clipIndex, addedPoints, addedParams, addedNormals); if (clipOutput.length > 3) this.addClipped([clipOutput[0], clipOutput[2], clipOutput[3]], indexMap, clipAxes, clipIndex, addedPoints, addedParams, addedNormals); } } } function interpolate(value0: number, value1: number, fraction: number) { return value0 + (value1 - value0) * fraction; } function interpolateInt(value0: number, value1: number, fraction: number) { return Math.floor(.5 + interpolate(value0, value1, fraction)); } function interpolateQPoint3d(qPoint: QPoint3d, qNext: QPoint3d, fraction: number): QPoint3d { return QPoint3d.fromScalars(interpolateInt(qPoint.x, qNext.x, fraction), interpolateInt(qPoint.y, qNext.y, fraction), interpolateInt(qPoint.z, qNext.z, fraction)); } function interpolateQPoint2d(qPoint: QPoint2d, qNext: QPoint2d, fraction: number): QPoint2d { return QPoint2d.fromScalars(interpolateInt(qPoint.x, qNext.x, fraction), interpolateInt(qPoint.y, qNext.y, fraction)); } function interpolateOctEncodedNormal(normal0: number, normal1: number, fraction: number): number { const n0 = OctEncodedNormal.decodeValue(normal0); const n1 = OctEncodedNormal.decodeValue(normal1); if (undefined !== n0 && undefined !== n1) { const n = Vector3d.create(interpolate(n0.x, n1.x, fraction), interpolate(n0.y, n1.y, fraction), interpolate(n0.z, n1.z, fraction)); n.normalizeInPlace(); return OctEncodedNormal.encode(n); } else { return OctEncodedNormal.encode(Vector3d.create(0, 0, 1)); } } export namespace TerrainMesh { export interface Props { readonly wantNormals: boolean; readonly pointQParams: QParams3d; readonly pointCount: number; readonly indexCount: number; readonly wantSkirts: boolean; readonly eastCount: number; readonly westCount: number; readonly northCount: number; readonly southCount: number; } }
the_stack
import {Watcher, RawValue, RawEAV, RawEAVC, _isId, asJS} from "./watcher"; import {v4 as uuid} from "uuid"; import naturalSort = require("javascript-natural-sort"); export interface Map<V>{[key:string]: V} export interface Style extends Map<RawValue|undefined> {__size: number} export interface ElemInstance extends Element {__element?: RawValue, __styles?: RawValue[], __sort?: RawValue, style?: any, listeners?: {[event:string]: boolean}} export abstract class DOMWatcher<Instance extends ElemInstance> extends Watcher { styles:Map<Style|undefined> = Object.create(null); roots:Map<Instance|undefined> = Object.create(null); instances:Map<Instance|undefined> = Object.create(null); elementToInstances:Map<RawValue[]|undefined> = Object.create(null); styleToInstances:Map<RawValue[]|undefined> = Object.create(null); abstract tagPrefix:string; abstract createInstance(id:RawValue, element:RawValue, tagname:RawValue):Instance; abstract getInstance(id:RawValue):Instance|undefined; abstract createRoot(id:RawValue):Instance|undefined; abstract addAttribute(instance:Instance, attribute:RawValue, value:RawValue|boolean):void; abstract removeAttribute(instance:Instance, attribute:RawValue, value:RawValue|boolean):void; protected _dummy:HTMLElement; protected _sendEvent(eavs:(RawEAV|RawEAVC)[]) { this.program.inputEAVs(eavs); } getStyle(id:RawValue) { return this.styles[id] = this.styles[id] || {__size: 0}; } isInstance(elem?:any): elem is Instance { if(!elem || !(elem instanceof Element)) return false; let instance = elem as Instance; return instance && !!instance["__element"]; } addInstance(id:RawValue, element:RawValue, tagname:RawValue):Instance|undefined { let instance = this.instances[id] = this.createInstance(id, element, tagname); if(!this.elementToInstances[element]) this.elementToInstances[element] = []; this.elementToInstances[element]!.push(id); return instance; } clearInstance(id:RawValue) { let instance = this.instances[id]; if(instance && instance.parentElement) { instance.parentElement.removeChild(instance); } this.instances[id] = undefined; let instances = instance && this.elementToInstances[instance.__element!]; if(instances) instances.splice(instances.indexOf(id), 1); } getRoot(id:RawValue, tagname:RawValue = "div"):Instance|undefined { return this.roots[id] = this.roots[id]; } clearRoot(id:RawValue) { this.clearInstance(id); this.roots[id] = undefined; } insertChild(parent:Element|null, child:Instance, at = child.__sort) { child.__sort = at if(at !== undefined) child.setAttribute("sort", ""+at); if(!parent) return; let current; for(let curIx = 0; curIx < parent.childNodes.length; curIx++) { let cur = parent.childNodes[curIx] as Instance; if(cur === child) continue; if(cur.__sort !== undefined && at !== undefined && naturalSort(cur.__sort, at) > 0) { current = cur; break; } } if(current) { parent.insertBefore(child, current); } else { parent.appendChild(child); } } insertSortedChild(parent:Element|null, child:Instance, sort?:RawValue) { child.__sort = sort; if(sort !== undefined) child.setAttribute("sort", ""+sort); else child.removeAttribute("sort"); this.insertChild(parent, child); } insertAutoSortedChild(parent:Element|null, child:Instance, autoSort?:RawValue) { if(autoSort !== undefined) { child.setAttribute("auto-sort", ""+autoSort); if(!child.hasAttribute("sort")) { child.__sort = autoSort; this.insertChild(parent, child); } } else child.removeAttribute("auto-sort"); } // @NOTE: This requires styles to have disjoint attribute sets or it'll do bad things. // @NOTE: Styles may only have a single value for each attribute due to our inability // to express an ordering of non-record values. setStyleAttribute(styleId:RawValue, attribute:RawValue, value:RawValue, count:-1|1) { let style = this.getStyle(styleId); if(count === -1) { //if(!style[attribute]) throw new Error(`Cannot remove non-existent attribute '${attribute}'`); //if(style[attribute] !== value) throw new Error(`Cannot remove mismatched AV ${attribute}: ${value} (current: ${style[attribute]})`); style[attribute] = undefined; } else { if(style[attribute]) throw new Error(`Cannot add already present attribute '${attribute}'`); style[attribute] = value; } style.__size += count; // Update all existing instances with this style. let instances = this.styleToInstances[styleId]; if(instances) { for(let instanceId of instances) { let instance = this.getInstance(instanceId); if(!instance) { // We may have removed one instance of multiple subscribed to this style. continue; } instance.style[attribute as any] = style[attribute] as any; } } } addStyleInstance(styleId:RawValue, instanceId:RawValue) { let instance = this.getInstance(instanceId); if(!instance) throw new Error(`Orphaned instance '${instanceId}'`); let style = this.getStyle(styleId); // Instead of a style record, we may be dealing with a style string. if(style.__size === 0) { this._dummy.setAttribute("style", styleId as string); let props = this._dummy.style; // Yep, we're inline CSS. if(props.length) { this.styles[styleId] = style; for(let propIx = 0; propIx < props.length; propIx++) { let prop = props[propIx]; let value = props.getPropertyValue(prop); style[prop] = value; style.__size += 1; } } } for(let prop in style) { if(prop === "__size") continue; instance.style[prop as any] = style[prop] as string; } if(this.styleToInstances[styleId]) this.styleToInstances[styleId]!.push(instanceId); else this.styleToInstances[styleId] = [instanceId]; if(!instance.__styles) instance.__styles = []; if(instance.__styles.indexOf(styleId) === -1) instance.__styles.push(styleId); } removeStyleInstance(styleId:RawValue, instanceId:RawValue) { let instance = this.getInstance(instanceId); if(!instance) return; instance.removeAttribute("style"); let ix = instance.__styles!.indexOf(styleId); instance.__styles!.splice(ix, 1); for(let otherStyleId of instance.__styles!) { let style = this.getStyle(otherStyleId); for(let prop in style) { if(prop === "__size") continue; instance.style[prop as any] = style[prop] as string; } } } setup() { if(typeof document === "undefined") return; this._dummy = document.createElement("div"); this.program .constants({tagPrefix: this.tagPrefix}) .commit("Remove click events!", ({find}) => { let click = find("{{tagPrefix}}/event/click"); return [click.remove()]; }) .bind("Create instances for each root.", ({find, record, lib}) => { let elem = find("{{tagPrefix}}/root"); return [ record("{{tagPrefix}}/instance", {element: elem, tagname: elem.tagname}) ]; }) .bind("Create an instance for each child of a rooted parent.", ({find, record, lib}) => { let elem = find("{{tagPrefix}}/element"); let parentElem = find("{{tagPrefix}}/element", {children: elem}); let parent = find("{{tagPrefix}}/instance", {element: parentElem}); return [ record("{{tagPrefix}}/instance", {element: elem, tagname: elem.tagname, parent}) ]; }) .watch("Export all instances.", ({find, record}) => { let instance = find("{{tagPrefix}}/instance"); return [ record({tagname: instance.tagname, element: instance.element, instance}) ]; }) .asObjects<{tagname:string, element:string, instance:string}>((diff) => { for(let e of Object.keys(diff.removes)) { let {instance:instanceId} = diff.removes[e]; this.clearInstance(instanceId); } for(let e of Object.keys(diff.adds)) { let {instance:instanceId, tagname, element} = diff.adds[e]; this.addInstance(instanceId, element, tagname); } }) .watch("Export roots.", ({find, record}) => { let root = find("{{tagPrefix}}/root"); let instance = find("{{tagPrefix}}/instance", {element: root}); return [ record({instance}) ]; }) .asDiffs((diff) => { for(let [e, a, rootId] of diff.removes) { this.clearRoot(rootId); } for(let [e, a, rootId] of diff.adds) { this.roots[rootId] = this.createRoot(rootId); } }) .watch("Export instance parents.", ({find, record}) => { let instance = find("{{tagPrefix}}/instance"); return [ record({instance, parent: instance.parent}) ]; }) .asObjects<{instance:string, parent:string}>((diff) => { for(let e of Object.keys(diff.removes)) { let {instance:instanceId, parent:parentId} = diff.removes[e]; let instance = this.getInstance(instanceId); let parent = this.getInstance(parentId); if(!instance || !parent) continue; if(instance && instance.parentElement) { instance.parentElement.removeChild(instance); } } for(let e of Object.keys(diff.adds)) { let {instance:instanceId, parent:parentId} = diff.adds[e]; let instance = this.getInstance(instanceId); if(!instance) throw new Error(`Orphaned instance '${instanceId}'`); let parent = this.getInstance(parentId); if(!parent) throw new Error(`Missing parent instance '${parentId}', ${instanceId}`); this.insertChild(parent, instance); } }) .watch("Export element styles.", ({find, record, lib, lookup}) => { let elem = find("{{tagPrefix}}/element"); let style = elem.style; let {attribute, value} = lookup(style); return [ style.add(attribute, value) ]; }) .asDiffs((diff) => { let maybeGC = []; for(let [styleId, a, v] of diff.removes) { maybeGC.push(styleId); this.setStyleAttribute(styleId, a, v, -1); } for(let [styleId, a, v] of diff.adds) { this.setStyleAttribute(styleId, a, v, 1); } for(let styleId of maybeGC) { let style = this.getStyle(styleId); if(style.__size === 0) { this.styles[styleId] = undefined; } } }) .watch("Export element attributes.", ({find, record, lookup}) => { let instance = find("{{tagPrefix}}/instance"); let elem = instance.element; let {attribute, value} = lookup(elem); attribute != "class"; return [ instance.add(attribute, value) ]; }) .asDiffs((diff) => { for(let [e, a, v] of diff.removes) { let instance = this.getInstance(e); if(!instance) continue; else if(a === "tagname") continue; else if(a === "children") continue; else if(a === "tag") continue; else if(a === "sort") continue; // I guess..? else if(a === "eve-auto-index") continue; // I guess..? else if(a === "text") instance.textContent = null; else if(a === "style") this.removeStyleInstance(v, e); else this.removeAttribute(instance, a, asJS(v)!); } for(let [e, a, v] of diff.adds) { let instance = this.getInstance(e); if(!instance) throw new Error(`Orphaned instance '${e}'`); else if((a === "tagname")) continue; else if(a === "children") continue; else if(a === "tag") continue; else if(a === "sort") this.insertSortedChild(instance.parentElement, instance, v); else if(a === "eve-auto-index") this.insertAutoSortedChild(instance.parentElement, instance, v); else if(a === "text") instance.textContent = ""+v; else if(a === "style") this.addStyleInstance(v, e); else this.addAttribute(instance, a, asJS(v)!); } }) .watch("Export static classes.", ({find, not, lookup}) => { let instance = find("{{tagPrefix}}/instance"); let elem = instance.element; let klass = elem.class; not(() => lookup(klass)); return [instance.add("class", klass)]; }) .asDiffs((diff) => { for(let [e, a, v] of diff.removes) { let instance = this.getInstance(e); if(!instance) continue; for(let klass of (""+v).split(" ")) { if(!klass) continue; instance.classList.remove(klass); } } for(let [e, a, v] of diff.adds) { let instance = this.getInstance(e); if(!instance) throw new Error(`Orphaned instance '${e}'`); for(let klass of (""+v).split(" ")) { if(!klass) continue; instance.classList.add(klass); } } }) .bind("Elements with a dynamic class record apply classes for each true attribute.", ({find, lookup, record}) => { let element = find("{{tagPrefix}}/element"); let {attribute, value} = lookup(element.class); value == "true"; return [ element.add("class", attribute) ]; }); } }
the_stack
* @module PropertyGrid */ import { inPlaceSort } from "fast-sort"; import memoize from "micro-memoize"; import { PropertyRecord, PropertyValueFormat as UiPropertyValueFormat } from "@itwin/appui-abstract"; import { IPropertyDataProvider, PropertyCategory, PropertyData, PropertyDataChangeEvent } from "@itwin/components-react"; import { assert } from "@itwin/core-bentley"; import { IModelConnection } from "@itwin/core-frontend"; import { addFieldHierarchy, CategoryDescription, ContentFlags, DefaultContentDisplayTypes, Descriptor, DescriptorOverrides, Field, FieldHierarchy, InstanceKey, NestedContentValue, PropertyValueFormat as PresentationPropertyValueFormat, ProcessFieldHierarchiesProps, ProcessPrimitiveValueProps, RelationshipMeaning, Ruleset, StartArrayProps, StartCategoryProps, StartContentProps, StartStructProps, traverseContentItem, traverseFieldHierarchy, Value, ValuesMap, } from "@itwin/presentation-common"; import { FavoritePropertiesScope, Presentation } from "@itwin/presentation-frontend"; import { FieldHierarchyRecord, IPropertiesAppender, PropertyRecordsBuilder } from "../common/ContentBuilder"; import { CacheInvalidationProps, ContentDataProvider, IContentDataProvider } from "../common/ContentDataProvider"; import { DiagnosticsProps } from "../common/Diagnostics"; import { createLabelRecord, findField } from "../common/Utils"; import { FAVORITES_CATEGORY_NAME, getFavoritesCategory } from "../favorite-properties/DataProvider"; const labelsComparer = new Intl.Collator(undefined, { sensitivity: "base" }).compare; /** * Default presentation ruleset used by [[PresentationPropertyDataProvider]]. The ruleset just gets properties * of the selected elements. * * @public */ // eslint-disable-next-line @typescript-eslint/no-var-requires export const DEFAULT_PROPERTY_GRID_RULESET: Ruleset = require("./DefaultPropertyGridRules.json"); /** * Interface for presentation rules-driven property data provider. * @public */ export type IPresentationPropertyDataProvider = IPropertyDataProvider & IContentDataProvider; /** * Properties for creating a `LabelsProvider` instance. * @public */ export interface PresentationPropertyDataProviderProps extends DiagnosticsProps { /** IModelConnection to use for requesting property data. */ imodel: IModelConnection; /** * Id of the ruleset to use when requesting properties or a ruleset itself. If not * set, default presentation rules are used which return content for the selected elements. */ ruleset?: string | Ruleset; /** * Auto-update property data when ruleset, ruleset variables or data in the iModel changes. * @alpha */ enableContentAutoUpdate?: boolean; /** * If true, additional 'favorites' category is not created. * @alpha */ disableFavoritesCategory?: boolean; } /** * Presentation Rules-driven property data provider implementation. * @public */ export class PresentationPropertyDataProvider extends ContentDataProvider implements IPresentationPropertyDataProvider { public onDataChanged = new PropertyDataChangeEvent(); private _includeFieldsWithNoValues: boolean; private _includeFieldsWithCompositeValues: boolean; private _isNestedPropertyCategoryGroupingEnabled: boolean; private _onFavoritesChangedRemoveListener: () => void; private _shouldCreateFavoritesCategory: boolean; /** * Constructor */ constructor(props: PresentationPropertyDataProviderProps) { super({ imodel: props.imodel, ruleset: props.ruleset ? props.ruleset : DEFAULT_PROPERTY_GRID_RULESET, displayType: DefaultContentDisplayTypes.PropertyPane, enableContentAutoUpdate: props.enableContentAutoUpdate, ruleDiagnostics: props.ruleDiagnostics, devDiagnostics: props.devDiagnostics, }); this._includeFieldsWithNoValues = true; this._includeFieldsWithCompositeValues = true; this._isNestedPropertyCategoryGroupingEnabled = true; this._onFavoritesChangedRemoveListener = Presentation.favoriteProperties.onFavoritesChanged.addListener(() => this.invalidateCache({})); this._shouldCreateFavoritesCategory = !props.disableFavoritesCategory; } /** * Dispose the presentation property data provider. */ public override dispose() { super.dispose(); this._onFavoritesChangedRemoveListener(); } /** * Invalidates cached content and clears categorized data. */ protected override invalidateCache(props: CacheInvalidationProps): void { super.invalidateCache(props); if (this.getMemoizedData) { this.getMemoizedData.cache.keys.length = 0; this.getMemoizedData.cache.values.length = 0; } if (this.onDataChanged) this.onDataChanged.raiseEvent(); } /** * Provides content configuration for the property grid */ protected override async getDescriptorOverrides(): Promise<DescriptorOverrides> { return { ...(await super.getDescriptorOverrides()), contentFlags: ContentFlags.ShowLabels | ContentFlags.MergeResults, }; } /** * Hides the computed display label field from the list of properties */ protected isFieldHidden(field: Field) { return field.name === "/DisplayLabel/"; } /** * Should fields with no values be included in the property list. No value means: * - For *primitive* fields: null, undefined, "" (empty string) * - For *array* fields: [] (empty array) * - For *struct* fields: {} (object with no members) */ public get includeFieldsWithNoValues(): boolean { return this._includeFieldsWithNoValues; } public set includeFieldsWithNoValues(value: boolean) { if (this._includeFieldsWithNoValues === value) return; this._includeFieldsWithNoValues = value; this.invalidateCache({ content: true }); } /** * Should fields with composite values be included in the property list. * Fields with composite values: * - *array* fields. * - *struct* fields. */ public get includeFieldsWithCompositeValues(): boolean { return this._includeFieldsWithCompositeValues; } public set includeFieldsWithCompositeValues(value: boolean) { if (this._includeFieldsWithCompositeValues === value) return; this._includeFieldsWithCompositeValues = value; this.invalidateCache({ content: true }); } /** Is nested property categories enabled */ public get isNestedPropertyCategoryGroupingEnabled(): boolean { return this._isNestedPropertyCategoryGroupingEnabled; } public set isNestedPropertyCategoryGroupingEnabled(value: boolean) { if (this._isNestedPropertyCategoryGroupingEnabled === value) return; this._isNestedPropertyCategoryGroupingEnabled = value; this.invalidateCache({ content: true }); } /** Should the specified field be included in the favorites category. */ // eslint-disable-next-line @typescript-eslint/naming-convention protected isFieldFavorite = (field: Field): boolean => (this._shouldCreateFavoritesCategory && Presentation.favoriteProperties.has(field, this.imodel, FavoritePropertiesScope.IModel)); /** * Sorts the specified list of categories by priority. May be overriden * to supply a different sorting algorithm. */ protected sortCategories(categories: CategoryDescription[]): void { inPlaceSort(categories).by([ { desc: (c) => c.priority }, { asc: (c) => c.label, comparer: labelsComparer }, ]); } /** * Sorts the specified list of fields by priority. May be overriden * to supply a different sorting algorithm. */ // eslint-disable-next-line @typescript-eslint/naming-convention protected sortFields = (category: CategoryDescription, fields: Field[]) => { if (category.name === FAVORITES_CATEGORY_NAME) Presentation.favoriteProperties.sortFields(this.imodel, fields); else { inPlaceSort(fields).by([ { desc: (f) => f.priority }, { asc: (f) => f.label, comparer: labelsComparer }, ]); } }; /** * Returns property data. */ // eslint-disable-next-line @typescript-eslint/naming-convention protected getMemoizedData = memoize(async (): Promise<PropertyData> => { const content = await this.getContent(); if (!content || 0 === content.contentSet.length) return createDefaultPropertyData(); const contentItem = content.contentSet[0]; const callbacks: PropertyPaneCallbacks = { isFavorite: this.isFieldFavorite, isHidden: this.isFieldHidden, sortCategories: this.sortCategories, sortFields: this.sortFields, }; const builder = new PropertyDataBuilder({ includeWithNoValues: this.includeFieldsWithNoValues, includeWithCompositeValues: this.includeFieldsWithCompositeValues, wantNestedCategories: this._isNestedPropertyCategoryGroupingEnabled, callbacks, }); traverseContentItem(builder, content.descriptor, contentItem); return builder.getPropertyData(); }); /** * Returns property data. */ public async getData(): Promise<PropertyData> { return this.getMemoizedData(); } /** * Get keys of instances which were used to create given [[PropertyRecord]]. * @beta */ public async getPropertyRecordInstanceKeys(record: PropertyRecord): Promise<InstanceKey[]> { const content = await this.getContent(); if (!content || 0 === content.contentSet.length) return []; let recordField = findField(content.descriptor, record.property.name); if (!recordField) return []; const fieldsStack: Field[] = []; while (recordField.parent) { recordField = recordField.parent; fieldsStack.push(recordField); } fieldsStack.reverse(); let contentItems: Array<{ primaryKeys: InstanceKey[], values: ValuesMap }> = content.contentSet; fieldsStack.forEach((field) => { const nestedContent = contentItems.reduce((nc, curr) => { const currItemValue = curr.values[field.name]; assert(Value.isNestedContent(currItemValue)); nc.push(...currItemValue); return nc; }, new Array<NestedContentValue>()); contentItems = nestedContent.map((nc) => ({ primaryKeys: nc.primaryKeys, values: nc.values, })); }); return contentItems.reduce((keys, curr) => { keys.push(...curr.primaryKeys); return keys; }, new Array<InstanceKey>()); } } const createDefaultPropertyData = (): PropertyData => ({ label: PropertyRecord.fromString("", "label"), categories: [], records: {}, }); interface PropertyPaneCallbacks { isFavorite(field: Field): boolean; isHidden(field: Field): boolean; sortCategories(categories: CategoryDescription[]): void; sortFields: (category: CategoryDescription, fields: Field[]) => void; } interface PropertyDataBuilderProps { includeWithNoValues: boolean; includeWithCompositeValues: boolean; callbacks: PropertyPaneCallbacks; wantNestedCategories: boolean; } class PropertyDataBuilder extends PropertyRecordsBuilder { private _props: PropertyDataBuilderProps; private _result: PropertyData | undefined; private _categoriesCache: PropertyCategoriesCache; private _categorizedRecords = new Map<string, FieldHierarchyRecord[]>(); private _favoriteFieldHierarchies: FieldHierarchy[] = []; private _categoriesStack: CategoryDescription[] = []; constructor(props: PropertyDataBuilderProps) { super(); this._props = props; this._categoriesCache = new PropertyCategoriesCache(props.wantNestedCategories); } public getPropertyData(): PropertyData { assert(this._result !== undefined); return this._result; } protected createRootPropertiesAppender(): IPropertiesAppender { return { append: (record: FieldHierarchyRecord): void => { // Note: usually the last category on the stack should be what we want, but in some cases, // when record's parent is merged, we need another category. In any case it's always expected // to be on the stack. const category = this._categoriesStack.find((c) => c.name === record.fieldHierarchy.field.category.name); assert(category !== undefined); let records = this._categorizedRecords.get(category.name); if (!records) { records = []; this._categorizedRecords.set(category.name, records); } records.push(record); }, }; } public override startContent(props: StartContentProps): boolean { this._categoriesCache.initFromDescriptor(props.descriptor); return super.startContent(props); } public override finishItem(): void { assert(this._result === undefined); const categorizedRecords: { [categoryName: string]: PropertyRecord[] } = {}; this._categorizedRecords.forEach((recs, categoryName) => { destructureRecords(recs); // istanbul ignore else if (recs.length) { const sortedFields = recs.map((r) => r.fieldHierarchy.field); this._props.callbacks.sortFields(this._categoriesCache.getEntry(categoryName)!, sortedFields); categorizedRecords[categoryName] = sortedFields.map((field) => recs.find((r) => r.fieldHierarchy.field === field)!.record); } }); const item = this.currentPropertiesAppender.item; assert(item !== undefined); this._result = { label: createLabelRecord(item.label, "label"), description: item.classInfo ? item.classInfo.label : undefined, categories: this.createPropertyCategories() .filter(({ categoryHasParent }) => !categoryHasParent) .map(({ category }) => category), records: categorizedRecords, reusePropertyDataState: true, }; } private createPropertyCategories(): Array<{ category: PropertyCategory, source: CategoryDescription, categoryHasParent: boolean }> { // determine which categories are actually used const usedCategoryNames = new Set(); this._categorizedRecords.forEach((records, categoryName) => { // istanbul ignore if if (records.length === 0) return; let category = this._categoriesCache.getEntry(categoryName); while (category) { usedCategoryNames.add(category.name); if (!this._props.wantNestedCategories) break; category = category.parent ? this._categoriesCache.getEntry(category.parent.name) : undefined; } }); // set up categories hierarchy const categoriesHierarchy = new Map<CategoryDescription | undefined, CategoryDescription[]>(); this._categoriesCache.getEntries().forEach((category) => { if (!usedCategoryNames.has(category.name)) { // skip unused categories return; } const parentCategory = this._props.wantNestedCategories ? category.parent : undefined; let childCategories = categoriesHierarchy.get(parentCategory); if (!childCategories) { childCategories = []; categoriesHierarchy.set(parentCategory, childCategories); } childCategories.push(category); }); // sort categories const nestedSortCategory = (category: CategoryDescription | undefined) => { const childCategories = categoriesHierarchy.get(category); if (childCategories && childCategories.length > 1) this._props.callbacks.sortCategories(childCategories); if (childCategories) childCategories.forEach(nestedSortCategory); }; nestedSortCategory(undefined); // create a hierarchy of PropertyCategory const propertyCategories = new Array<{ category: PropertyCategory; source: CategoryDescription; categoryHasParent: boolean; }>(); const pushPropertyCategories = (parentDescr?: CategoryDescription) => { const childCategoryDescriptions = categoriesHierarchy.get(parentDescr); const childPropertyCategories = (childCategoryDescriptions ?? []).map((categoryDescr) => { const category: PropertyCategory = { name: categoryDescr.name, label: categoryDescr.label, expand: categoryDescr.expand, }; if (categoryDescr.renderer) category.renderer = categoryDescr.renderer; return { category, source: categoryDescr, categoryHasParent: parentDescr !== undefined }; }); propertyCategories.push(...childPropertyCategories); for (const categoryInfo of childPropertyCategories) { const childCategories = pushPropertyCategories(categoryInfo.source); if (childCategories.length) categoryInfo.category.childCategories = childCategories; } return childPropertyCategories.map((categoryInfo) => categoryInfo.category); }; pushPropertyCategories(undefined); return propertyCategories; } private buildFavoriteFieldAncestors(field: Field) { let parentField = field.parent; while (parentField) { parentField = parentField.clone(); parentField.nestedFields = [field]; parentField.category = this._categoriesCache.getFavoriteCategory(parentField.category); field = parentField; parentField = parentField.parent; } field.rebuildParentship(); } private createFavoriteFieldsHierarchy(hierarchy: FieldHierarchy): FieldHierarchy { const favoriteField = hierarchy.field.clone(); favoriteField.category = this._categoriesCache.getFavoriteCategory(hierarchy.field.category); this.buildFavoriteFieldAncestors(favoriteField); return { field: favoriteField, childFields: hierarchy.childFields.map((c) => this.createFavoriteFieldsHierarchy(c)), }; } private createFavoriteFieldsList(fieldHierarchies: FieldHierarchy[]): FieldHierarchy[] { const favorites: FieldHierarchy[] = []; fieldHierarchies.forEach((fh) => traverseFieldHierarchy(fh, (hierarchy) => { if (!this._props.callbacks.isFavorite(hierarchy.field)) return true; addFieldHierarchy(favorites, this.createFavoriteFieldsHierarchy(hierarchy)); return false; })); return favorites; } public override processFieldHierarchies(props: ProcessFieldHierarchiesProps): void { super.processFieldHierarchies(props); this._favoriteFieldHierarchies = this.createFavoriteFieldsList(props.hierarchies); props.hierarchies.push(...this._favoriteFieldHierarchies); } public override startCategory(props: StartCategoryProps): boolean { this._categoriesStack.push(props.category); return true; } public override finishCategory(): void { this._categoriesStack.pop(); } public override startStruct(props: StartStructProps): boolean { if (this.shouldSkipField(props.hierarchy.field, () => !Object.keys(props.rawValues).length)) return false; return super.startStruct(props); } public override startArray(props: StartArrayProps): boolean { if (this.shouldSkipField(props.hierarchy.field, () => !props.rawValues.length)) return false; return super.startArray(props); } public override processPrimitiveValue(props: ProcessPrimitiveValueProps): void { if (this.shouldSkipField(props.field, () => (null === props.rawValue || undefined === props.rawValue || "" === props.rawValue))) return; super.processPrimitiveValue(props); } private shouldSkipField(field: Field, isValueEmpty: () => boolean): boolean { const isFieldFavorite = this._favoriteFieldHierarchies.find((h) => h.field.name === field.name) !== undefined; // skip values of hidden fields if (!isFieldFavorite && this._props.callbacks.isHidden(field)) return true; // skip empty values if (!isFieldFavorite && !this._props.includeWithNoValues && isValueEmpty()) return true; if (field.type.valueFormat !== PresentationPropertyValueFormat.Primitive && !this._props.includeWithCompositeValues) { // skip composite fields if requested return true; } return false; } } class PropertyCategoriesCache { private _byName = new Map<string, CategoryDescription>(); constructor(private _enableCategoryNesting: boolean) { } public initFromDescriptor(descriptor: Descriptor) { this.initFromFields(descriptor.fields); } private initFromFields(fields: Field[]) { fields.forEach((field: Field) => { if (field.isNestedContentField()) { this.initFromFields(field.nestedFields); } else { this.cache(field.category); } }); // add parent categories that have no fields of their own [...this._byName.values()].forEach((entry) => { let curr: CategoryDescription | undefined = entry; while (curr) curr = curr.parent ? this.cache(curr.parent) : undefined; }); } private cache(category: CategoryDescription) { const entry = this._byName.get(category.name); if (entry) return entry; this._byName.set(category.name, category); return category; } public getEntry(descr: string) { return this._byName.get(descr); } public getEntries() { return [...this._byName.values()]; } public getFavoriteCategory(sourceCategory: CategoryDescription): CategoryDescription { if (!this._enableCategoryNesting) return this.getRootFavoritesCategory(); const fieldCategoryRenameStatus = this.getRenamedCategory(`${FAVORITES_CATEGORY_NAME}-${sourceCategory.name}`, sourceCategory); let curr = fieldCategoryRenameStatus; while (!curr.fromCache && curr.category.parent) { const parentCategoryRenameStatus = this.getRenamedCategory(`${FAVORITES_CATEGORY_NAME}-${curr.category.parent.name}`, curr.category.parent); curr.category.parent = parentCategoryRenameStatus.category; curr = parentCategoryRenameStatus; } if (!curr.fromCache) curr.category.parent = this.getRootFavoritesCategory(); return fieldCategoryRenameStatus.category; } private getCachedCategory(name: string, factory: () => CategoryDescription) { let cached = this._byName.get(name); if (cached) return { category: cached, fromCache: true }; cached = factory(); this._byName.set(name, cached); return { category: cached, fromCache: false }; } private getRootFavoritesCategory() { return this.getCachedCategory(FAVORITES_CATEGORY_NAME, getFavoritesCategory).category; } private getRenamedCategory(name: string, source: CategoryDescription) { return this.getCachedCategory(name, () => ({ ...source, name })); } } function shouldDestructureArrayField(field: Field) { // destructure arrays if they're based on nested content field or nested under a nested content field return field.isNestedContentField() || field.parent; } function shouldDestructureStructField(field: Field, totalRecordsCount: number | undefined) { // destructure structs if they're based on nested content and: // - if relationship meaning is 'same instance' - always destructure // - if relationship meaning is 'related instance' - only if it's the only record in the list return field.isNestedContentField() && (field.relationshipMeaning === RelationshipMeaning.SameInstance || totalRecordsCount === 1); } function destructureStructMember(member: FieldHierarchyRecord): Array<FieldHierarchyRecord> { // only destructure array member items if (member.record.value.valueFormat !== UiPropertyValueFormat.Array || !shouldDestructureArrayField(member.fieldHierarchy.field) || !shouldDestructureStructField(member.fieldHierarchy.field, undefined)) return [member]; // don't want to include struct arrays without items - just return empty array if (member.record.value.items.length === 0) return []; // the array should be of size 1 if (member.record.value.items.length > 1) return [member]; // the single item should be a struct const item = member.record.value.items[0]; assert(item.value.valueFormat === UiPropertyValueFormat.Struct); // if all above checks pass, destructure the struct item const recs = [{ ...member, record: item }]; destructureRecords(recs); return recs; } function destructureStructArrayItems(items: PropertyRecord[], fieldHierarchy: FieldHierarchy) { const destructuredFields: FieldHierarchy[] = []; fieldHierarchy.childFields.forEach((nestedFieldHierarchy) => { let didDestructure = false; items.forEach((item) => { assert(item.value.valueFormat === UiPropertyValueFormat.Struct); if (item.value.members[nestedFieldHierarchy.field.name] === undefined) { // the member may not exist at all if we decided to skip it beforehand return; } // destructure a single struct array item member const destructuredMembers = destructureStructMember({ fieldHierarchy: nestedFieldHierarchy, record: item.value.members[nestedFieldHierarchy.field.name], }); // remove the old member and insert all destructured new members delete item.value.members[nestedFieldHierarchy.field.name]; destructuredMembers.forEach((destructuredMember) => { assert(item.value.valueFormat === UiPropertyValueFormat.Struct); item.value.members[destructuredMember.fieldHierarchy.field.name] = destructuredMember.record; }); // store new members. all items are expected to have the same members, so only need to do this once if (!didDestructure) { destructuredMembers.forEach((destructuredMember) => destructuredFields.push(destructuredMember.fieldHierarchy)); didDestructure = true; } }); }); // if we got a chance to destructure at least one item, replace old members with new ones // in the field hierarchy that we got // istanbul ignore else if (items.length > 0) fieldHierarchy.childFields = destructuredFields; } function destructureRecords(records: FieldHierarchyRecord[]) { let i = 0; while (i < records.length) { const entry = records[i]; if (entry.record.value.valueFormat === UiPropertyValueFormat.Array && shouldDestructureArrayField(entry.fieldHierarchy.field)) { if (shouldDestructureStructField(entry.fieldHierarchy.field, 1)) { // destructure individual array items destructureStructArrayItems(entry.record.value.items, entry.fieldHierarchy); } // destructure 0 or 1 sized arrays by removing the array record and putting its first item in its place (if any) if (entry.record.value.items.length <= 1) { records.splice(i, 1); // istanbul ignore else if (entry.record.value.items.length > 0) { const item = entry.record.value.items[0]; records.splice(i, 0, { ...entry, fieldHierarchy: entry.fieldHierarchy, record: item }); } continue; } } if (entry.record.value.valueFormat === UiPropertyValueFormat.Struct && shouldDestructureStructField(entry.fieldHierarchy.field, records.length)) { // destructure structs by replacing them with their member records const members = entry.fieldHierarchy.childFields.reduce((list, nestedFieldHierarchy) => { assert(entry.record.value.valueFormat === UiPropertyValueFormat.Struct); assert(entry.record.value.members[nestedFieldHierarchy.field.name] !== undefined); const member = { fieldHierarchy: nestedFieldHierarchy, field: nestedFieldHierarchy.field, record: entry.record.value.members[nestedFieldHierarchy.field.name], }; list.push(...destructureStructMember(member)); return list; }, new Array<FieldHierarchyRecord>()); records.splice(i, 1, ...members); continue; } ++i; } // lastly, when there's only one record in the list and it's an array that we want destructured, set the `hideCompositePropertyLabel` // attribute so only the items are rendered if (records.length === 1 && records[0].record.value.valueFormat === UiPropertyValueFormat.Array && shouldDestructureArrayField(records[0].fieldHierarchy.field)) { records[0].record.property.hideCompositePropertyLabel = true; } }
the_stack
import { PersistentModel, StoryboardFilePath } from '../../store/editor-state' import { objectMap } from '../../../../core/shared/object-utils' import { ProjectFile, isParseSuccess, SceneMetadata, TextFile, isTextFile, textFile, textFileContents, unparsed, RevisionsState, isParsedTextFile, } from '../../../../core/shared/project-file-types' import { isRight, right } from '../../../../core/shared/either' import { BakedInStoryboardVariableName, convertScenesToUtopiaCanvasComponent, } from '../../../../core/model/scene-utils' import { addFileToProjectContents, contentsToTree, getContentsTreeFileFromString, projectContentFile, ProjectContentFile, ProjectContentsTree, removeFromProjectContents, transformContentsTree, walkContentsTree, } from '../../../assets' import { isUtopiaJSXComponent } from '../../../../core/shared/element-template' export const CURRENT_PROJECT_VERSION = 7 export function applyMigrations( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: typeof CURRENT_PROJECT_VERSION } { const version1 = migrateFromVersion0(persistentModel) const version2 = migrateFromVersion1(version1) const version3 = migrateFromVersion2(version2) const version4 = migrateFromVersion3(version3) const version5 = migrateFromVersion4(version4) const version6 = migrateFromVersion5(version5) const version7 = migrateFromVersion6(version6) return version7 } function migrateFromVersion0( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 1 } & { openFiles: any; selectedFile: any } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 0) { return persistentModel as any } else { function updateOpenFilesEntry(openFile: string): any { return { type: 'OPEN_FILE_TAB', filename: openFile, } } const updatedOpenFiles = (persistentModel as any).openFiles.map((openFile: any) => updateOpenFilesEntry(openFile), ) let updatedSelectedFile: any | null = null const selectedFileAsString: string = (persistentModel as any).selectedFile as any if (selectedFileAsString != '') { updatedSelectedFile = updateOpenFilesEntry(selectedFileAsString) } return { ...persistentModel, openFiles: updatedOpenFiles, selectedFile: updatedSelectedFile, projectVersion: 1, } } } function migrateFromVersion1( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 2 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 1) { return persistentModel as any } else { const updatedFiles = objectMap((file: ProjectFile, fileName) => { if ( isTextFile(file) && isParseSuccess(file.fileContents as any) && isRight((file.fileContents as any).value.canvasMetadata) ) { const canvasMetadataParseSuccess = (file.fileContents as any).value.canvasMetadata.value // this old canvas metadata might store an array of `scenes: Array<SceneMetadata>`, whereas we expect a UtopiaJSXComponent here if ( (canvasMetadataParseSuccess as any).utopiaCanvasJSXComponent == null && (canvasMetadataParseSuccess as any)['scenes'] != null ) { const scenes = (canvasMetadataParseSuccess as any)['scenes'] as Array<SceneMetadata> const utopiaCanvasComponent = convertScenesToUtopiaCanvasComponent(scenes) const updatedCanvasMetadataParseSuccess: any = right({ utopiaCanvasJSXComponent: utopiaCanvasComponent, }) return { ...file, fileContents: { ...file.fileContents, value: { ...(file.fileContents as any).value, canvasMetadata: updatedCanvasMetadataParseSuccess, }, }, } as TextFile } else { return file } } else { return file } }, persistentModel.projectContents as any) return { ...persistentModel, projectContents: updatedFiles as any, projectVersion: 2, } } } function migrateFromVersion2( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 3 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 2) { return persistentModel as any } else { const updatedFiles = objectMap((file: ProjectFile, fileName) => { if (isTextFile(file) && isParseSuccess(file.fileContents as any)) { if ( isRight((file.fileContents as any).value.canvasMetadata) && // the parseSuccess contained a utopiaCanvasJSXComponent which we now merge to the array of topLevelElements ((file.fileContents as any).value.canvasMetadata.value as any).utopiaCanvasJSXComponent != null ) { const utopiaCanvasJSXComponent = ((file.fileContents as any).value.canvasMetadata .value as any).utopiaCanvasJSXComponent const updatedTopLevelElements = [ ...(file.fileContents as any).value.topLevelElements, utopiaCanvasJSXComponent, ] return { ...file, fileContents: { ...file.fileContents, value: { ...(file.fileContents as any).value, topLevelElements: updatedTopLevelElements, canvasMetadata: right({}), projectContainedOldSceneMetadata: true, }, }, } as TextFile } else { return { ...file, fileContents: { ...file.fileContents, value: { ...(file.fileContents as any).value, projectContainedOldSceneMetadata: true, }, }, } } } else { return file } }, persistentModel.projectContents as any) return { ...persistentModel, projectContents: updatedFiles as any, projectVersion: 3, } } } const PackageJsonUrl = '/package.json' function migrateFromVersion3( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 4 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 3) { return persistentModel as any } else { const packageJsonFile = (persistentModel.projectContents as any)[PackageJsonUrl] if (packageJsonFile != null && isTextFile(packageJsonFile)) { const parsedPackageJson = JSON.parse(packageJsonFile.fileContents as any) const updatedPackageJson = { ...parsedPackageJson, utopia: { ...parsedPackageJson.utopia, html: `public/${parsedPackageJson.utopia.html}`, js: `public/${parsedPackageJson.utopia.js}`, }, } const printedPackageJson = JSON.stringify(updatedPackageJson, null, 2) const updatedPackageJsonFile = { type: 'CODE_FILE', fileContents: printedPackageJson, lastSavedContents: null, } return { ...persistentModel, projectVersion: 4, projectContents: { ...persistentModel.projectContents, [PackageJsonUrl]: updatedPackageJsonFile as any, }, } } else { console.error('Error migrating project: package.json not found, skipping') return { ...persistentModel, projectVersion: 4 } } } } function migrateFromVersion4( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 5 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 4) { return persistentModel as any } else { return { ...persistentModel, projectVersion: 5, projectContents: contentsToTree(persistentModel.projectContents as any), } } } function migrateFromVersion5( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 6 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 5) { return persistentModel as any } else { return { ...persistentModel, projectVersion: 6, projectContents: transformContentsTree( persistentModel.projectContents, (tree: ProjectContentsTree) => { if (tree.type === 'PROJECT_CONTENT_FILE') { const file: ProjectContentFile['content'] = tree.content const fileType = file.type as string if (fileType === 'CODE_FILE') { const newFile = textFile( textFileContents((file as any).fileContents, unparsed, RevisionsState.CodeAhead), null, null, 0, ) return projectContentFile(tree.fullPath, newFile) } else if (fileType === 'UI_JS_FILE') { const code = (file as any).fileContents.value.code const lastRevisedTime = (file as any).lastRevisedTime const newFile = textFile( textFileContents(code, unparsed, RevisionsState.CodeAhead), null, null, lastRevisedTime, ) return projectContentFile(tree.fullPath, newFile) } else { return tree } } else { return tree } }, ), } } } function migrateFromVersion6( persistentModel: PersistentModel, ): PersistentModel & { projectVersion: 7 } { if (persistentModel.projectVersion != null && persistentModel.projectVersion !== 6) { return persistentModel as any } else { let storyboardTarget: string | null = null walkContentsTree(persistentModel.projectContents, (fullPath: string, file: ProjectFile) => { // Don't bother looking further if there's already something to work with. if (storyboardTarget == null) { if (isTextFile(file) && isParseSuccess(file.fileContents.parsed)) { for (const topLevelElement of file.fileContents.parsed.topLevelElements) { if ( isUtopiaJSXComponent(topLevelElement) && topLevelElement.name === BakedInStoryboardVariableName ) { storyboardTarget = fullPath } } } } }) let updatedProjectContents = persistentModel.projectContents if (storyboardTarget != null) { const file = getContentsTreeFileFromString(updatedProjectContents, storyboardTarget) if (file == null) { throw new Error(`Internal error in migration: Unable to find file ${storyboardTarget}.`) } else { // Move the file around. updatedProjectContents = removeFromProjectContents(updatedProjectContents, storyboardTarget) updatedProjectContents = addFileToProjectContents( updatedProjectContents, StoryboardFilePath, file, ) } } return { ...persistentModel, projectVersion: 7, projectContents: updatedProjectContents, } } }
the_stack
import * as React from 'react' import { shallow, mount } from 'enzyme' import { PrimaryButton, AlertModal, OutlineButton } from '@opentrons/components' import { Command } from '@opentrons/shared-data/protocol/types/schemaV5' import { LabwareDefinition2, MAGNETIC_MODULE_TYPE, } from '@opentrons/shared-data' import { fixtureP10Single, fixtureP300Single, } from '@opentrons/shared-data/pipette/fixtures/name' import fixture_tiprack_10_ul from '@opentrons/shared-data/labware/fixtures/2/fixture_tiprack_10_ul.json' import { FileSidebar, v4WarningContent, v5WarningContent } from '../FileSidebar' import { useBlockingHint } from '../../Hints/useBlockingHint' jest.mock('../../Hints/useBlockingHint') const mockUseBlockingHint = useBlockingHint as jest.MockedFunction< typeof useBlockingHint > describe('FileSidebar', () => { const pipetteLeftId = 'pipetteLeftId' const pipetteRightId = 'pipetteRightId' let props: React.ComponentProps<typeof FileSidebar> let commands: Command[] let modulesOnDeck: React.ComponentProps<typeof FileSidebar>['modulesOnDeck'] let pipettesOnDeck: React.ComponentProps<typeof FileSidebar>['pipettesOnDeck'] let savedStepForms: React.ComponentProps<typeof FileSidebar>['savedStepForms'] beforeEach(() => { props = { loadFile: jest.fn(), createNewFile: jest.fn(), canDownload: true, onDownload: jest.fn(), fileData: { labware: {}, labwareDefinitions: {}, metadata: {}, pipettes: {}, robot: { model: 'OT-2 Standard' }, schemaVersion: 3, commands: [], }, pipettesOnDeck: {}, modulesOnDeck: {}, savedStepForms: {}, schemaVersion: 3, } commands = [ { command: 'pickUpTip', params: { pipette: pipetteLeftId, labware: 'well', well: 'A1' }, }, ] pipettesOnDeck = { pipetteLeftId: { name: 'string' as any, id: pipetteLeftId, tiprackDefURI: 'test', tiprackLabwareDef: fixture_tiprack_10_ul as LabwareDefinition2, spec: fixtureP10Single, mount: 'left', }, pipetteRightId: { name: 'string' as any, id: pipetteRightId, tiprackDefURI: 'test', tiprackLabwareDef: fixture_tiprack_10_ul as LabwareDefinition2, spec: fixtureP300Single, mount: 'right', }, } modulesOnDeck = { magnet123: { type: MAGNETIC_MODULE_TYPE, } as any, } savedStepForms = { step123: { id: 'step123', pipette: pipetteLeftId, } as any, } }) afterEach(() => { jest.resetAllMocks() }) it('create new button creates new protocol', () => { const wrapper = shallow(<FileSidebar {...props} />) const createButton = wrapper.find(OutlineButton).at(0) createButton.simulate('click') expect(props.createNewFile).toHaveBeenCalled() }) it('import button imports saved protocol', () => { const event = { files: ['test.json'] } const wrapper = shallow(<FileSidebar {...props} />) const importButton = wrapper.find('[type="file"]') importButton.simulate('change', event) expect(props.loadFile).toHaveBeenCalledWith(event) }) it('export button is disabled when canDownload is false', () => { props.canDownload = false const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) expect(downloadButton.prop('disabled')).toEqual(true) }) it('export button exports protocol when no errors', () => { // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') expect(props.onDownload).toHaveBeenCalled() }) it('warning modal is shown when export is clicked with no command', () => { const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') const alertModal = wrapper.find(AlertModal) expect(alertModal).toHaveLength(1) expect(alertModal.prop('heading')).toEqual('Your protocol has no steps') const continueButton = alertModal.dive().find(OutlineButton).at(1) continueButton.simulate('click') expect(props.onDownload).toHaveBeenCalled() }) it('warning modal is shown when export is clicked with unused pipette', () => { // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands props.pipettesOnDeck = pipettesOnDeck props.savedStepForms = savedStepForms const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') const alertModal = wrapper.find(AlertModal) expect(alertModal).toHaveLength(1) expect(alertModal.prop('heading')).toEqual('Unused pipette') expect(alertModal.html()).toContain( pipettesOnDeck.pipetteRightId.spec.displayName ) expect(alertModal.html()).toContain(pipettesOnDeck.pipetteRightId.mount) expect(alertModal.html()).not.toContain( pipettesOnDeck.pipetteLeftId.spec.displayName ) const continueButton = alertModal.dive().find(OutlineButton).at(1) continueButton.simulate('click') expect(props.onDownload).toHaveBeenCalled() }) it('warning modal is shown when export is clicked with unused module', () => { props.modulesOnDeck = modulesOnDeck props.savedStepForms = savedStepForms // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') const alertModal = wrapper.find(AlertModal) expect(alertModal).toHaveLength(1) expect(alertModal.prop('heading')).toEqual('Unused module') expect(alertModal.html()).toContain('Magnetic module') const continueButton = alertModal.dive().find(OutlineButton).at(1) continueButton.simulate('click') expect(props.onDownload).toHaveBeenCalled() }) it('warning modal is shown when export is clicked with unused module and pipette', () => { props.modulesOnDeck = modulesOnDeck props.pipettesOnDeck = pipettesOnDeck props.savedStepForms = savedStepForms // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands const wrapper = shallow(<FileSidebar {...props} />) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') const alertModal = wrapper.find(AlertModal) expect(alertModal).toHaveLength(1) expect(alertModal.prop('heading')).toEqual('Unused pipette and module') expect(alertModal.html()).toContain( pipettesOnDeck.pipetteRightId.spec.displayName ) expect(alertModal.html()).toContain(pipettesOnDeck.pipetteRightId.mount) expect(alertModal.html()).toContain('Magnetic module') expect(alertModal.html()).not.toContain( pipettesOnDeck.pipetteLeftId.spec.displayName ) const continueButton = alertModal.dive().find(OutlineButton).at(1) continueButton.simulate('click') expect(props.onDownload).toHaveBeenCalled() }) it('blocking hint is shown when protocol is v4', () => { // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands props.pipettesOnDeck = { pipetteLeftId: { // @ts-expect-error(sa, 2021-6-22): not a valid pipette name name: 'string', id: pipetteLeftId, tiprackDefURI: 'test', tiprackLabwareDef: fixture_tiprack_10_ul as LabwareDefinition2, spec: fixtureP10Single, mount: 'left', }, } props.savedStepForms = savedStepForms const MockHintComponent = () => { return <div></div> } mockUseBlockingHint.mockReturnValue(<MockHintComponent />) const wrapper = mount(<FileSidebar {...props} schemaVersion={4} />) expect(wrapper.exists(MockHintComponent)).toEqual(true) // Before save button is clicked, enabled should be false expect(mockUseBlockingHint).toHaveBeenNthCalledWith(1, { enabled: false, hintKey: 'export_v4_protocol_3_18', content: v4WarningContent, handleCancel: expect.any(Function), handleContinue: expect.any(Function), }) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') // After save button is clicked, enabled should be true expect(mockUseBlockingHint).toHaveBeenLastCalledWith({ enabled: true, hintKey: 'export_v4_protocol_3_18', content: v4WarningContent, handleCancel: expect.any(Function), handleContinue: expect.any(Function), }) }) it('blocking hint is shown when protocol is v5', () => { // @ts-expect-error(sa, 2021-6-22): props.fileData might be null props.fileData.commands = commands props.savedStepForms = savedStepForms const MockHintComponent = () => { return <div></div> } mockUseBlockingHint.mockReturnValue(<MockHintComponent />) const wrapper = mount(<FileSidebar {...props} schemaVersion={5} />) expect(wrapper.exists(MockHintComponent)).toEqual(true) // Before save button is clicked, enabled should be false expect(mockUseBlockingHint).toHaveBeenNthCalledWith(1, { enabled: false, hintKey: 'export_v5_protocol_3_20', content: v5WarningContent, handleCancel: expect.any(Function), handleContinue: expect.any(Function), }) const downloadButton = wrapper.find(PrimaryButton).at(0) downloadButton.simulate('click') // After save button is clicked, enabled should be true expect(mockUseBlockingHint).toHaveBeenLastCalledWith({ enabled: true, hintKey: 'export_v5_protocol_3_20', content: v5WarningContent, handleCancel: expect.any(Function), handleContinue: expect.any(Function), }) }) })
the_stack
import { app, Menu, MenuItemConstructorOptions, shell, Notification, dialog, } from 'electron'; import {BrowserViewBind} from '../../Bind/BrowserViewBind'; import {MainWindow} from './MainWindow'; import {StreamIPC} from '../../../IPC/StreamIPC'; import {IssueIPC} from '../../../IPC/IssueIPC'; import {BrowserViewIPC} from '../../../IPC/BrowserViewIPC'; import {MainWindowIPC} from '../../../IPC/MainWindowIPC'; import {SQLiteBind} from '../../Bind/SQLiteBind'; import {UserPrefBind} from '../../Bind/UserPrefBind'; class _MainWindowMenu { private appMenu: Menu; private currentZoom: number = 1; async init() { if (!this.appMenu) this.buildMainMenu(); Menu.setApplicationMenu(this.appMenu); } enableShortcut(enable: boolean) { // devtoolが開いてるときは強制的にoffにする if (MainWindow.getWindow().webContents.isDevToolsOpened()) enable = false; setEnable(enable, this.appMenu) function setEnable(enable: boolean, menu: Menu) { for (const menuItem of menu.items) { // 1文字ショートカットのメニューのon/off if (menuItem.accelerator?.length === 1) menuItem.enabled = enable; // Spaceキーのon/off if (menuItem.accelerator === 'Space') menuItem.enabled = enable; // Shift + Jなどのメニューのon/off if (menuItem.accelerator?.includes('Shift+')) menuItem.enabled = enable; // 再帰 if (menuItem.submenu) setEnable(enable, menuItem.submenu); } } } private async quit() { app.exit(0); } private zoom(diffFactor: number, abs: boolean) { if (abs) { this.currentZoom = diffFactor; } else { this.currentZoom += diffFactor; } this.currentZoom = Math.max(this.currentZoom, 0.05); MainWindow.getWindow().webContents.setZoomFactor(this.currentZoom); BrowserViewBind.setZoomFactor(this.currentZoom); } private openPrefDir() { const eachPaths = UserPrefBind.getEachPaths(); shell.showItemInFolder(eachPaths.userPrefPath); } // @ts-ignore private deleteAllData() { const buttons = ['OK', 'Cancel']; const okId = buttons.findIndex(v => v === 'OK'); const cancelId = buttons.findIndex(v => v === 'Cancel'); const res = dialog.showMessageBoxSync(MainWindow.getWindow(), { type: 'warning', buttons, defaultId: cancelId, title: 'Delete All Data', message: 'Do you delete all data from Jasper?', cancelId, }); if (res === okId) { UserPrefBind.deleteAllData(); app.quit(); app.relaunch(); } } async vacuum() { const notification = new Notification({title: 'SQLite Vacuum', body: 'Running...'}); notification.show(); await StreamIPC.stopAllStreams(); await SQLiteBind.exec('vacuum'); await StreamIPC.restartAllStreams(); notification.close(); } private buildMainMenu() { const template: MenuItemConstructorOptions[] = [ { label: "Application", submenu: [ { label: "About Jasper", click: () => MainWindowIPC.showAbout() }, { label: "Update", click: () => shell.openExternal('https://jasperapp.io/release.html') }, { type: "separator" }, { label: "Preferences", accelerator: "CmdOrCtrl+,", click: () => MainWindowIPC.showPref() }, { type: "separator" }, { label: "Export Data", click: () => MainWindowIPC.showExportData()}, // { label: "Delete Data", click: () => this.deleteAllData()}, { type: "separator" }, { label: "Supporter", click: () => shell.openExternal('https://h13i32maru.jp/supporter/') }, // { type: "separator" }, // { label: 'Services', role: 'services' }, { type: "separator" }, { label: 'Hide Jasper', accelerator: 'CmdOrCtrl+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Option+CmdOrCtrl+H', role: 'hideOthers' }, { label: 'Show All', role: 'unhide' }, { type: "separator" }, { label: "Quit Jasper", accelerator: "CmdOrCtrl+Q", click: this.quit.bind(this)} ] }, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", role: "undo" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", role: "redo" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", role: "cut" }, { label: "Copy", accelerator: "CmdOrCtrl+C", role: "copy" }, { label: "Paste", accelerator: "CmdOrCtrl+V", role: "paste" }, { label: 'Paste and Match Style', accelerator: 'Shift+CmdOrCtrl+V', role: "pasteAndMatchStyle" }, { label: "Select All", accelerator: "CmdOrCtrl+A", role: "selectAll" } ] }, { label: 'View', submenu: [ {label: 'Jump Navigation', accelerator: 'CmdOrCtrl+K', click: () => MainWindowIPC.showJumpNavigation()}, {label: 'Recently Reads', accelerator: 'CmdOrCtrl+E', click: () => MainWindowIPC.showRecentlyReads()}, { type: "separator" }, { label: 'Single Pane', accelerator: 'CmdOrCtrl+1', click: () => MainWindowIPC.toggleLayout('one') }, { label: 'Two Pane', accelerator: 'CmdOrCtrl+2', click: () => MainWindowIPC.toggleLayout('two') }, { label: 'Three Pane', accelerator: 'CmdOrCtrl+3', click: () => MainWindowIPC.toggleLayout('three') }, { type: "separator" }, { label: 'Full Screen', role: 'togglefullscreen' } ] }, { label: 'Streams', submenu: [ {label: 'Toggle Notification', accelerator: 'CmdOrCtrl+I', click: () => MainWindowIPC.toggleNotification()}, { type: "separator" }, { label: 'Next Stream', accelerator: 'D', click: () => StreamIPC.selectNextStream()}, { label: 'Prev Stream', accelerator: 'F', click: () => StreamIPC.selectPrevStream()}, { type: "separator" }, // { label: 'LIBRARY', submenu: [ // { label: 'Inbox', accelerator: 'F1', click: () => StreamIPC.selectLibraryStreamInbox()}, // { label: 'Unread', accelerator: 'F2', click: () => StreamIPC.selectLibraryStreamUnread()}, // { label: 'Open', accelerator: 'F3', click: () => StreamIPC.selectLibraryStreamOpen()}, // { label: 'Bookmark', accelerator: 'F4', click: () => StreamIPC.selectLibraryStreamMark()}, // { label: 'Archived', accelerator: 'F5', click: () => StreamIPC.selectLibraryStreamArchived()} // ]}, // { label: 'SYSTEM', submenu: [ // { label: 'Me', accelerator: 'F6', click: () => StreamIPC.selectSystemStreamMe()}, // { label: 'Team', accelerator: 'F7', click: () => StreamIPC.selectSystemStreamTeam()}, // { label: 'Watching', accelerator: 'F8', click: () => StreamIPC.selectSystemStreamWatching()}, // { label: 'Subscription', accelerator: 'F9', click: () => StreamIPC.selectSystemStreamSubscription()} // ]}, { label: 'STREAMS', submenu: [ { label: '1st', accelerator: '1', click: () => StreamIPC.selectUserStream(0)}, { label: '2nd', accelerator: '2', click: () => StreamIPC.selectUserStream(1)}, { label: '3rd', accelerator: '3', click: () => StreamIPC.selectUserStream(2)}, { label: '4th', accelerator: '4', click: () => StreamIPC.selectUserStream(3)}, { label: '5th', accelerator: '5', click: () => StreamIPC.selectUserStream(4)}, ]}, ] }, { label: 'Issues', submenu: [ { label: 'Reload Issues', accelerator: '.', click: () => IssueIPC.reloadIssues()}, { type: 'separator' }, {label: 'Select Issue', submenu: [ { label: 'Next Issue', accelerator: 'J', click: (menuItem) => { // キーリピートをスロットリングする menuItem.enabled = false; IssueIPC.selectNextIssue(); setTimeout(() => menuItem.enabled = true, 100); }}, { label: 'Prev Issue', accelerator: 'K', click: (menuItem) => { menuItem.enabled = false; IssueIPC.selectPrevIssue() setTimeout(() => menuItem.enabled = true, 100); }}, { type: 'separator' }, { label: 'Next Unread Issue', accelerator: 'Shift+J', click: (menuItem) => { menuItem.enabled = false; IssueIPC.selectNextUnreadIssue() setTimeout(() => menuItem.enabled = true, 100); }}, { label: 'Prev Unread Issue', accelerator: 'Shift+K', click: (menuItem) => { menuItem.enabled = false; IssueIPC.selectPrevUnreadIssue() setTimeout(() => menuItem.enabled = true, 100); }}, ]}, { type: 'separator' }, { label: 'Issue State', submenu: [ { label: 'Toggle Read', accelerator: 'I', click: () => IssueIPC.toggleRead()}, { label: 'Toggle Bookmark', accelerator: 'B', click: () => IssueIPC.toggleMark()}, { label: 'Toggle Archive', accelerator: 'E', click: () => IssueIPC.toggleArchive()} ]}, { type: 'separator' }, {label: 'Filter Issue', submenu: [ { label: 'Filter Author', accelerator: 'A', click: () => IssueIPC.filterToggleAuthor()}, { label: 'Filter Assignee', accelerator: 'N', click: () => IssueIPC.filterToggleAssignee()}, { label: 'Filter Unread', accelerator: 'U', click: () => IssueIPC.filterToggleUnread()}, { label: 'Filter Open', accelerator: 'O', click: () => IssueIPC.filterToggleOpen()}, { label: 'Filter Bookmark', accelerator: 'M', click: () => IssueIPC.filterToggleMark()}, // { label: 'Filter Focus On', accelerator: '/', click: () => IssueIPC.focusFilter()}, // { label: 'Filter Clear', accelerator: 'C', click: () => IssueIPC.clearFilter()}, ]}, ] }, { label: 'Browser', submenu: [ { label: 'Reload', accelerator: 'CmdOrCtrl+R', click: () => BrowserViewBind.getWebContents().reload() }, { label: 'Back', accelerator: 'CmdOrCtrl+[', click: () => BrowserViewBind.getWebContents().goBack() }, { label: 'Forward', accelerator: 'CmdOrCtrl+]', click: () => BrowserViewBind.getWebContents().goForward() }, { type: 'separator' }, {label: 'Scroll', submenu: [ // note: spaceキーでのスクロールでsmoothするとちらつく(デフォルトの挙動とぶつかってる?) { label: 'Scroll Down', accelerator: 'Space', click: () => BrowserViewBind.scroll(60, 'auto')}, { label: 'Scroll Up', accelerator: 'Shift+Space', click: () => BrowserViewBind.scroll(-60, 'auto') }, { type: 'separator' }, { label: 'Scroll Long Down', accelerator: 'Alt+J', click: () => BrowserViewBind.scroll(600, 'smooth')}, { label: 'Scroll Long Up', accelerator: 'Alt+K', click: () => BrowserViewBind.scroll(-600, 'smooth') }, ]}, { type: 'separator' }, { label: 'Search Keyword', accelerator: 'CmdOrCtrl+F', click: () => BrowserViewIPC.startSearch() }, { type: 'separator' }, { label: 'Open Location', accelerator: 'CmdOrCtrl+L', click: () => BrowserViewIPC.focusURLInput() }, { label: 'Open with External', accelerator: 'CmdOrCtrl+O', click: () => BrowserViewIPC.openURLWithExternalBrowser() } ] }, { label: 'Window', role: 'window', submenu: [ {label: 'Zoom +', accelerator: 'CmdOrCtrl+Plus', click: this.zoom.bind(this, 0.05, false)}, {label: 'Zoom -', accelerator: 'CmdOrCtrl+-', click: this.zoom.bind(this, -0.05, false)}, {label: 'Zoom Reset', accelerator: 'CmdOrCtrl+0', click: this.zoom.bind(this, 1, true)}, {type: "separator"}, {label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize'}, {label: 'Bring All to Front', role: 'front'} ] }, { label: 'Help', role: 'help', submenu: [ {label: 'Handbook', click: () => shell.openExternal('https://docs.jasperapp.io/')}, {label: 'Feedback', click: ()=> shell.openExternal('https://github.com/jasperapp/jasper')} ] }, { label: 'Dev', submenu: [ {label: 'DevTools(Main)', click: () => MainWindow.getWindow().webContents.openDevTools({mode: 'detach'})}, {label: 'DevTools(BrowserView)', click: () => BrowserViewBind.getWebContents().openDevTools({mode: 'detach'})}, {type: 'separator' }, {label: 'Open Data Directory', click: () => this.openPrefDir()}, {type: 'separator' }, {label: 'SQLite Vacuum', click: this.vacuum.bind(this)}, // {type: 'separator' }, // {label: 'Restart Streams', accelerator: 'Alt+L', click: () => StreamIPC.restartAllStreams()}, // {label: 'Delete All Data', click: () => this.deleteAllData()}, ] } ]; this.appMenu = Menu.buildFromTemplate(template); } } export const MainWindowMenu = new _MainWindowMenu();
the_stack
import React, { ReactElement } from "react"; import { fireEvent, render } from "@testing-library/react"; import { RangeSlider, RangeSliderProps } from "../RangeSlider"; import { RangeSliderValue, SliderStepOptions } from "../types"; import { useRangeSlider } from "../useRangeSlider"; interface TestProps extends SliderStepOptions, Pick< RangeSliderProps, | "thumb1Props" | "thumb2Props" | "onBlur" | "onMouseDown" | "onTouchStart" | "vertical" | "disabled" | "getValueText" > { defaultValue?: RangeSliderValue; } function Test({ defaultValue, disabled, vertical, thumb1Props, thumb2Props, onBlur, onMouseDown, onTouchStart, getValueText, ...options }: TestProps): ReactElement { const [, controls] = useRangeSlider(defaultValue, options); return ( <RangeSlider {...controls} baseId="slider" label="Price" disabled={disabled} vertical={vertical} thumb1Props={thumb1Props} thumb2Props={thumb2Props} onBlur={onBlur} onMouseDown={onMouseDown} onTouchStart={onTouchStart} getValueText={getValueText} /> ); } describe("RangeSlider", () => { it("should render correctly", () => { const { container, getByRole, rerender } = render(<Test />); expect(container).toMatchSnapshot(); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); slider1.focus(); expect(container).toMatchSnapshot(); slider1.blur(); slider2.focus(); expect(container).toMatchSnapshot(); slider2.blur(); expect(container).toMatchSnapshot(); rerender(<Test vertical />); expect(container).toMatchSnapshot(); slider1.focus(); expect(container).toMatchSnapshot(); slider1.blur(); slider2.focus(); expect(container).toMatchSnapshot(); slider2.blur(); expect(container).toMatchSnapshot(); rerender(<Test disabled />); expect(container).toMatchSnapshot(); rerender(<Test disabled vertical />); expect(container).toMatchSnapshot(); }); it("should call the prop events correctly", () => { const thumb1KeyDown = jest.fn(); const thumb2KeyDown = jest.fn(); const onBlur = jest.fn(); const onMouseDown = jest.fn(); const onTouchStart = jest.fn(); const { container, getByRole } = render( <Test thumb1Props={{ onKeyDown: thumb1KeyDown }} thumb2Props={{ onKeyDown: thumb2KeyDown }} onBlur={onBlur} onMouseDown={onMouseDown} onTouchStart={onTouchStart} /> ); const track = container.querySelector(".rmd-slider-track"); if (!track) { throw new Error(); } const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); fireEvent.keyDown(slider1); expect(thumb1KeyDown).toBeCalledTimes(1); fireEvent.keyDown(slider2); expect(thumb2KeyDown).toBeCalledTimes(1); fireEvent.mouseDown(slider1, { altKey: true }); expect(onMouseDown).toBeCalledTimes(1); fireEvent.touchStart(slider1); expect(onTouchStart).toBeCalledTimes(1); fireEvent.blur(track); expect(onBlur).toBeCalledTimes(1); }); it("should ensure the value stays within the range if it changes after initial render to prevent errors from being thrown", () => { const props = { min: 0, max: 5, step: 1, }; const { rerender, getByRole } = render(<Test {...props} />); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); expect(slider1).toHaveAttribute("aria-valuemin", "0"); expect(slider1).toHaveAttribute("aria-valuemax", "5"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuemin", "0"); expect(slider2).toHaveAttribute("aria-valuemax", "5"); expect(slider2).toHaveAttribute("aria-valuenow", "5"); rerender(<Test {...props} step={2} max={6} />); expect(slider1).toHaveAttribute("aria-valuemin", "0"); expect(slider1).toHaveAttribute("aria-valuemax", "6"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuemin", "0"); expect(slider2).toHaveAttribute("aria-valuemax", "6"); expect(slider2).toHaveAttribute("aria-valuenow", "6"); rerender(<Test {...props} step={3} max={6} />); expect(slider1).toHaveAttribute("aria-valuemin", "0"); expect(slider1).toHaveAttribute("aria-valuemax", "6"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuemin", "0"); expect(slider2).toHaveAttribute("aria-valuemax", "6"); expect(slider2).toHaveAttribute("aria-valuenow", "6"); rerender(<Test {...props} step={10} max={100} />); expect(slider1).toHaveAttribute("aria-valuemin", "0"); expect(slider1).toHaveAttribute("aria-valuemax", "100"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuemin", "0"); expect(slider2).toHaveAttribute("aria-valuemax", "100"); expect(slider2).toHaveAttribute("aria-valuenow", "10"); rerender(<Test {...props} step={1} min={50} max={100} />); expect(slider1).toHaveAttribute("aria-valuemin", "50"); expect(slider1).toHaveAttribute("aria-valuemax", "100"); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuemin", "50"); expect(slider2).toHaveAttribute("aria-valuemax", "100"); expect(slider2).toHaveAttribute("aria-valuenow", "50"); }); describe("keyboard behavior", () => { it("should update the value correctly with specific keyboard keys", () => { const { getByRole } = render(<Test />); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); slider1.focus(); fireEvent.keyDown(slider1, { key: "ArrowRight" }); expect(slider1).toHaveAttribute("aria-valuenow", "1"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "PageUp" }); expect(slider1).toHaveAttribute("aria-valuenow", "11"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "ArrowLeft" }); expect(slider1).toHaveAttribute("aria-valuenow", "10"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "ArrowLeft" }); expect(slider1).toHaveAttribute("aria-valuenow", "9"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "PageDown" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "End" }); expect(slider1).toHaveAttribute("aria-valuenow", "99"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "Home" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "ArrowUp" }); expect(slider1).toHaveAttribute("aria-valuenow", "1"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "ArrowDown" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.keyDown(slider1, { key: "Tab" }); slider2.focus(); fireEvent.keyDown(slider2, { key: "Home" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "1"); fireEvent.keyDown(slider2, { key: "PageUp" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "11"); fireEvent.keyDown(slider2, { key: "ArrowLeft" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "10"); fireEvent.keyDown(slider2, { key: "PageDown" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "1"); }); }); describe("drag behavior", () => { it("should work correctly for mouse events", () => { const { container, getByRole } = render(<Test />); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); jest.spyOn(slider1, "getBoundingClientRect").mockImplementation(() => ({ x: 0, y: 0, height: 20, width: 48, top: 0, right: 48, left: 0, bottom: 1000, toJSON: () => "", })); jest.spyOn(slider2, "getBoundingClientRect").mockImplementation(() => ({ x: 952, y: 0, height: 20, width: 48, top: 0, right: 1000, left: 952, bottom: 1000, toJSON: () => "", })); const track = container.querySelector<HTMLSpanElement>(".rmd-slider-track"); if (!track) { throw new Error(); } jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({ x: 0, y: 0, height: 20, width: 1000, top: 0, right: 1000, left: 0, bottom: 20, toJSON: () => "", })); fireEvent.mouseDown(track, { clientX: 200, clientY: 0 }); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "20"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.mouseMove(window, { clientX: 500, clientY: 20 }); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.mouseUp(window); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.mouseMove(window, { clientX: 200, clientY: 10 }); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); }); it("should work correctly for touch events", () => { const { container, getByRole } = render(<Test />); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); jest.spyOn(slider1, "getBoundingClientRect").mockImplementation(() => ({ x: 0, y: 0, height: 20, width: 48, top: 0, right: 48, left: 0, bottom: 1000, toJSON: () => "", })); jest.spyOn(slider2, "getBoundingClientRect").mockImplementation(() => ({ x: 952, y: 0, height: 20, width: 48, top: 0, right: 1000, left: 952, bottom: 1000, toJSON: () => "", })); const track = container.querySelector<HTMLSpanElement>(".rmd-slider-track"); if (!track) { throw new Error(); } jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({ x: 0, y: 0, height: 20, width: 1000, top: 0, right: 1000, left: 0, bottom: 20, toJSON: () => "", })); fireEvent.touchStart(track, { changedTouches: [{ clientX: 200, clientY: 0 }], }); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "20"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.touchMove(window, { changedTouches: [{ clientX: 500, clientY: 20 }], }); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.touchEnd(window); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); fireEvent.mouseMove(window, { clientX: 200, clientY: 10 }); expect(slider1).toHaveAttribute("aria-valuenow", "50"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); }); it("should handle vertical drag events correctly as well", () => { const { container, getByRole } = render(<Test vertical />); const slider1 = getByRole("slider", { name: "Min" }); const slider2 = getByRole("slider", { name: "Max" }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "100"); jest.spyOn(slider1, "getBoundingClientRect").mockImplementation(() => ({ x: 10, y: 1000, height: 48, width: 20, top: 1000, right: 20, left: 0, bottom: 1000, toJSON: () => "", })); jest.spyOn(slider2, "getBoundingClientRect").mockImplementation(() => ({ x: 10, y: 0, height: 48, width: 20, top: 0, right: 20, left: 0, bottom: 952, toJSON: () => "", })); const track = container.querySelector<HTMLSpanElement>(".rmd-slider-track"); if (!track) { throw new Error(); } jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({ x: 0, y: 0, height: 1000, width: 20, top: 0, right: 20, left: 0, bottom: 1000, toJSON: () => "", })); fireEvent.mouseDown(track, { clientX: 0, clientY: 200 }); expect(container).toMatchSnapshot(); // slider 2 gets updated instead for this flow since the clientY is closer to slider2 expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "80"); fireEvent.mouseMove(window, { clientX: 20, clientY: 500 }); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "50"); fireEvent.mouseUp(window); expect(container).toMatchSnapshot(); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "50"); fireEvent.mouseMove(window, { clientX: 10, clientY: 200 }); expect(slider1).toHaveAttribute("aria-valuenow", "0"); expect(slider2).toHaveAttribute("aria-valuenow", "50"); }); }); describe("update behavior", () => { it('should only update value value on blur or dragend when the updateOn is set to "blur"', () => { const onChange = jest.fn(); function Test({ blur }: { blur: boolean }): ReactElement { const [value, controls] = useRangeSlider([0, 50], { onChange, updateOn: blur ? "blur" : "change", }); return ( <> <span data-testid="value1">{value[0]}</span> <span data-testid="value2">{value[1]}</span> <RangeSlider {...controls} baseId="slider" label="Slider" /> </> ); } const { getByRole, getByTestId, rerender } = render( <Test blur={false} /> ); const value1 = getByTestId("value1"); const value2 = getByTestId("value2"); const slider1 = getByRole("slider", { name: "Min" }); expect(value1.textContent).toBe("0"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); slider1.focus(); fireEvent.keyDown(slider1, { key: "ArrowRight" }); expect(onChange).not.toBeCalled(); expect(value1.textContent).toBe("1"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "1"); fireEvent.keyDown(slider1, { key: "ArrowRight" }); expect(onChange).not.toBeCalled(); expect(value1.textContent).toBe("2"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "2"); slider1.blur(); // it's pretty much useless to use `onChange` with updateOn === "change" expect(onChange).not.toBeCalled(); rerender(<Test blur />); expect(onChange).not.toBeCalled(); expect(value1.textContent).toBe("2"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "2"); fireEvent.keyDown(slider1, { key: "ArrowRight" }); expect(onChange).not.toBeCalled(); expect(value1.textContent).toBe("2"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "3"); fireEvent.keyDown(slider1, { key: "Home" }); expect(onChange).not.toBeCalled(); expect(value1.textContent).toBe("2"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); fireEvent.blur(slider1); expect(onChange).toBeCalledWith([0, 50]); expect(value1.textContent).toBe("0"); expect(value2.textContent).toBe("50"); expect(slider1).toHaveAttribute("aria-valuenow", "0"); slider1.focus(); fireEvent.keyDown(slider1, { key: "ArrowRight" }); fireEvent.keyDown(slider1, { key: "ArrowLeft" }); slider1.blur(); // should not be called again if value hasn't changed expect(onChange).toBeCalledTimes(1); }); }); });
the_stack
import { ServiceType } from "@protobuf-ts/runtime-rpc"; import type { BinaryWriteOptions } from "@protobuf-ts/runtime"; import type { IBinaryWriter } from "@protobuf-ts/runtime"; import { WireType } from "@protobuf-ts/runtime"; import type { BinaryReadOptions } from "@protobuf-ts/runtime"; import type { IBinaryReader } from "@protobuf-ts/runtime"; import { UnknownFieldHandler } from "@protobuf-ts/runtime"; import type { PartialMessage } from "@protobuf-ts/runtime"; import { reflectionMergePartial } from "@protobuf-ts/runtime"; import { MESSAGE_TYPE } from "@protobuf-ts/runtime"; import { MessageType } from "@protobuf-ts/runtime"; /** * ExistsRequest request to determine if debug info exists for a given build_id * * @generated from protobuf message parca.debuginfo.v1alpha1.ExistsRequest */ export interface ExistsRequest { /** * build_id is a unique identifier for the debug data * * @generated from protobuf field: string build_id = 1; */ buildId: string; /** * hash is the hash of the debug information file * * @generated from protobuf field: string hash = 2; */ hash: string; } /** * ExistsResponse returns whether the given build_id has debug info * * @generated from protobuf message parca.debuginfo.v1alpha1.ExistsResponse */ export interface ExistsResponse { /** * exists indicates if there is debug data present for the given build_id * * @generated from protobuf field: bool exists = 1; */ exists: boolean; } /** * UploadRequest upload debug info * * @generated from protobuf message parca.debuginfo.v1alpha1.UploadRequest */ export interface UploadRequest { /** * @generated from protobuf oneof: data */ data: { oneofKind: "info"; /** * info is the metadata for the debug info * * @generated from protobuf field: parca.debuginfo.v1alpha1.UploadInfo info = 1; */ info: UploadInfo; } | { oneofKind: "chunkData"; /** * chunk_data is the raw bytes of the debug info * * @generated from protobuf field: bytes chunk_data = 2; */ chunkData: Uint8Array; } | { oneofKind: undefined; }; } /** * UploadInfo contains the build_id and other metadata for the debug data * * @generated from protobuf message parca.debuginfo.v1alpha1.UploadInfo */ export interface UploadInfo { /** * build_id is a unique identifier for the debug data * * @generated from protobuf field: string build_id = 1; */ buildId: string; /** * hash is the hash of the debug information file * * @generated from protobuf field: string hash = 2; */ hash: string; } /** * UploadResponse returns the build_id and the size of the uploaded debug info * * @generated from protobuf message parca.debuginfo.v1alpha1.UploadResponse */ export interface UploadResponse { /** * build_id is a unique identifier for the debug data * * @generated from protobuf field: string build_id = 1; */ buildId: string; /** * size is the number of bytes of the debug info * * @generated from protobuf field: uint64 size = 2; */ size: string; } // @generated message type with reflection information, may provide speed optimized methods class ExistsRequest$Type extends MessageType<ExistsRequest> { constructor() { super("parca.debuginfo.v1alpha1.ExistsRequest", [ { no: 1, name: "build_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "hash", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<ExistsRequest>): ExistsRequest { const message = { buildId: "", hash: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ExistsRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ExistsRequest): ExistsRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string build_id */ 1: message.buildId = reader.string(); break; case /* string hash */ 2: message.hash = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ExistsRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string build_id = 1; */ if (message.buildId !== "") writer.tag(1, WireType.LengthDelimited).string(message.buildId); /* string hash = 2; */ if (message.hash !== "") writer.tag(2, WireType.LengthDelimited).string(message.hash); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.debuginfo.v1alpha1.ExistsRequest */ export const ExistsRequest = new ExistsRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class ExistsResponse$Type extends MessageType<ExistsResponse> { constructor() { super("parca.debuginfo.v1alpha1.ExistsResponse", [ { no: 1, name: "exists", kind: "scalar", T: 8 /*ScalarType.BOOL*/ } ]); } create(value?: PartialMessage<ExistsResponse>): ExistsResponse { const message = { exists: false }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<ExistsResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ExistsResponse): ExistsResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* bool exists */ 1: message.exists = reader.bool(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: ExistsResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* bool exists = 1; */ if (message.exists !== false) writer.tag(1, WireType.Varint).bool(message.exists); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.debuginfo.v1alpha1.ExistsResponse */ export const ExistsResponse = new ExistsResponse$Type(); // @generated message type with reflection information, may provide speed optimized methods class UploadRequest$Type extends MessageType<UploadRequest> { constructor() { super("parca.debuginfo.v1alpha1.UploadRequest", [ { no: 1, name: "info", kind: "message", oneof: "data", T: () => UploadInfo }, { no: 2, name: "chunk_data", kind: "scalar", oneof: "data", T: 12 /*ScalarType.BYTES*/ } ]); } create(value?: PartialMessage<UploadRequest>): UploadRequest { const message = { data: { oneofKind: undefined } }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<UploadRequest>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UploadRequest): UploadRequest { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* parca.debuginfo.v1alpha1.UploadInfo info */ 1: message.data = { oneofKind: "info", info: UploadInfo.internalBinaryRead(reader, reader.uint32(), options, (message.data as any).info) }; break; case /* bytes chunk_data */ 2: message.data = { oneofKind: "chunkData", chunkData: reader.bytes() }; break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: UploadRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* parca.debuginfo.v1alpha1.UploadInfo info = 1; */ if (message.data.oneofKind === "info") UploadInfo.internalBinaryWrite(message.data.info, writer.tag(1, WireType.LengthDelimited).fork(), options).join(); /* bytes chunk_data = 2; */ if (message.data.oneofKind === "chunkData") writer.tag(2, WireType.LengthDelimited).bytes(message.data.chunkData); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.debuginfo.v1alpha1.UploadRequest */ export const UploadRequest = new UploadRequest$Type(); // @generated message type with reflection information, may provide speed optimized methods class UploadInfo$Type extends MessageType<UploadInfo> { constructor() { super("parca.debuginfo.v1alpha1.UploadInfo", [ { no: 1, name: "build_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "hash", kind: "scalar", T: 9 /*ScalarType.STRING*/ } ]); } create(value?: PartialMessage<UploadInfo>): UploadInfo { const message = { buildId: "", hash: "" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<UploadInfo>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UploadInfo): UploadInfo { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string build_id */ 1: message.buildId = reader.string(); break; case /* string hash */ 2: message.hash = reader.string(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: UploadInfo, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string build_id = 1; */ if (message.buildId !== "") writer.tag(1, WireType.LengthDelimited).string(message.buildId); /* string hash = 2; */ if (message.hash !== "") writer.tag(2, WireType.LengthDelimited).string(message.hash); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.debuginfo.v1alpha1.UploadInfo */ export const UploadInfo = new UploadInfo$Type(); // @generated message type with reflection information, may provide speed optimized methods class UploadResponse$Type extends MessageType<UploadResponse> { constructor() { super("parca.debuginfo.v1alpha1.UploadResponse", [ { no: 1, name: "build_id", kind: "scalar", T: 9 /*ScalarType.STRING*/ }, { no: 2, name: "size", kind: "scalar", T: 4 /*ScalarType.UINT64*/ } ]); } create(value?: PartialMessage<UploadResponse>): UploadResponse { const message = { buildId: "", size: "0" }; globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); if (value !== undefined) reflectionMergePartial<UploadResponse>(this, message, value); return message; } internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UploadResponse): UploadResponse { let message = target ?? this.create(), end = reader.pos + length; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case /* string build_id */ 1: message.buildId = reader.string(); break; case /* uint64 size */ 2: message.size = reader.uint64().toString(); break; default: let u = options.readUnknownField; if (u === "throw") throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); } } return message; } internalBinaryWrite(message: UploadResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { /* string build_id = 1; */ if (message.buildId !== "") writer.tag(1, WireType.LengthDelimited).string(message.buildId); /* uint64 size = 2; */ if (message.size !== "0") writer.tag(2, WireType.Varint).uint64(message.size); let u = options.writeUnknownFields; if (u !== false) (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); return writer; } } /** * @generated MessageType for protobuf message parca.debuginfo.v1alpha1.UploadResponse */ export const UploadResponse = new UploadResponse$Type(); /** * @generated ServiceType for protobuf service parca.debuginfo.v1alpha1.DebugInfoService */ export const DebugInfoService = new ServiceType("parca.debuginfo.v1alpha1.DebugInfoService", [ { name: "Exists", options: {}, I: ExistsRequest, O: ExistsResponse }, { name: "Upload", clientStreaming: true, options: {}, I: UploadRequest, O: UploadResponse } ]);
the_stack
// Helper for defining opaque types like crypto_secretstream_xchacha20poly1305_state. declare const brand: unique symbol; interface Opaque<T> { readonly [brand]: T; } // Separate the tag constants that crypto_secretstream_xchacha20poly1305_* functions // take so that we can use them to limit the input values for those functions. interface CryptoSecretStreamTagConstants { CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH: 0; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PULL: 1; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY: 2; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL: 3; } type CryptoSecretStreamTagValues = CryptoSecretStreamTagConstants[keyof CryptoSecretStreamTagConstants]; interface Constants extends CryptoSecretStreamTagConstants { LIBRARY_VERSION_MAJOR: number; LIBRARY_VERSION_MINOR: number; VERSION_STRING: string; BASE64_VARIANT_ORIGINAL: number; BASE64_VARIANT_ORIGINAL_NO_PADDING: number; BASE64_VARIANT_URLSAFE: number; BASE64_VARIANT_URLSAFE_NO_PADDING: number; CRYPTO_AEAD_AES256GCM_KEYBYTES: number; CRYPTO_AEAD_AES256GCM_NSECBYTES: number; CRYPTO_AEAD_AES256GCM_NPUBBYTES: number; CRYPTO_AEAD_AES256GCM_ABYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_ABYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES: number; CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES: number; CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES: number; CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES: number; CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES: number; CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES: number; CRYPTO_AUTH_BYTES: number; CRYPTO_AUTH_KEYBYTES: number; CRYPTO_BOX_SEALBYTES: number; CRYPTO_BOX_SECRETKEYBYTES: number; CRYPTO_BOX_PUBLICKEYBYTES: number; CRYPTO_BOX_KEYPAIRBYTES: number; CRYPTO_BOX_MACBYTES: number; CRYPTO_BOX_NONCEBYTES: number; CRYPTO_BOX_SEEDBYTES: number; CRYPTO_KDF_BYTES_MIN: number; CRYPTO_KDF_BYTES_MAX: number; CRYPTO_KDF_CONTEXTBYTES: number; CRYPTO_KDF_KEYBYTES: number; CRYPTO_KX_BYTES: number; CRYPTO_KX_PRIMITIVE: string; CRYPTO_KX_SEEDBYTES: number; CRYPTO_KX_KEYPAIRBYTES: number; CRYPTO_KX_PUBLICKEYBYTES: number; CRYPTO_KX_SECRETKEYBYTES: number; CRYPTO_KX_SESSIONKEYBYTES: number; CRYPTO_GENERICHASH_BYTES: number; CRYPTO_GENERICHASH_BYTES_MIN: number; CRYPTO_GENERICHASH_BYTES_MAX: number; CRYPTO_GENERICHASH_KEYBYTES: number; CRYPTO_GENERICHASH_KEYBYTES_MIN: number; CRYPTO_GENERICHASH_KEYBYTES_MAX: number; CRYPTO_PWHASH_SALTBYTES: number; CRYPTO_PWHASH_STRPREFIX: string; CRYPTO_PWHASH_ALG_ARGON2I13: number; CRYPTO_PWHASH_ALG_ARGON2ID13: number; CRYPTO_PWHASH_ALG_DEFAULT: number; CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE: number; CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE: number; CRYPTO_PWHASH_OPSLIMIT_MODERATE: number; CRYPTO_PWHASH_MEMLIMIT_MODERATE: number; CRYPTO_PWHASH_OPSLIMIT_SENSITIVE: number; CRYPTO_PWHASH_MEMLIMIT_SENSITIVE: number; CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES: number; CRYPTO_SCALARMULT_BYTES: number; CRYPTO_SCALARMULT_SCALARBYTES: number; CRYPTO_SHORTHASH_BYTES: number; CRYPTO_SHORTHASH_KEYBYTES: number; CRYPTO_SECRETBOX_KEYBYTES: number; CRYPTO_SECRETBOX_MACBYTES: number; CRYPTO_SECRETBOX_NONCEBYTES: number; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES: number; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES: number; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES: number; CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX: number; CRYPTO_SIGN_BYTES: number; CRYPTO_SIGN_SEEDBYTES: number; CRYPTO_SIGN_PUBLICKEYBYTES: number; CRYPTO_SIGN_SECRETKEYBYTES: number; CRYPTO_SIGN_KEYPAIRBYTES: number; CRYPTO_STREAM_KEYBYTES: number; CRYPTO_STREAM_NONCEBYTES: number; } declare namespace Module { export type crypto_secretstream_xchacha20poly1305_state = Opaque< "crypto_secretstream_xchacha20poly1305_state" >; export type crypto_generichash_state = Opaque<"crypto_generichash_state">; export type Backend = Opaque<"Backend">; export class CryptographyKey { // Deny types that would otherwise structurally match CryptographyKey. // See: https://michalzalecki.com/nominal-typing-in-typescript/ private readonly __nominal: void; constructor(buf: Buffer); static from(...args: Parameters<typeof Buffer.from>): CryptographyKey; isEd25519Key(): boolean; isX25519Key(): boolean; isPublicKey(): boolean; getLength(): number; getBuffer(): Buffer; toString(encoding?: string): string; slice(): Buffer; } export class Ed25519PublicKey extends CryptographyKey { readonly keyType: "ed25519"; readonly publicKey: true; static from(...args: Parameters<typeof Buffer.from>): Ed25519PublicKey; } export class Ed25519SecretKey extends CryptographyKey { readonly keyType: "ed25519"; readonly publicKey: false; static from(...args: Parameters<typeof Buffer.from>): Ed25519SecretKey; } export class X25519PublicKey extends CryptographyKey { readonly keyType: "x25519"; readonly publicKey: true; static from(...args: Parameters<typeof Buffer.from>): X25519PublicKey; } export class X25519SecretKey extends CryptographyKey { readonly keyType: "x25519"; readonly publicKey: false; static from(...args: Parameters<typeof Buffer.from>): X25519SecretKey; } export class SodiumError extends Error {} export function getBackendObject( type?: "SodiumNative" | "LibsodiumWrappers" ): Backend; // Mix in Constants.* to SodiumPlus instances. export interface SodiumPlus extends Constants {} export class SodiumPlus { readonly backend: Backend; constructor(backend: Backend); getBackendName(): string; isSodiumNative(): boolean; isLibsodiumWrappers(): boolean; static auto(): Promise<SodiumPlus>; ensureLoaded(): Promise<void>; crypto_aead_xchacha20poly1305_ietf_decrypt( ciphertext: string | Buffer, nonce: string | Buffer, key: CryptographyKey, assocData?: string | Buffer ): Promise<Buffer>; crypto_aead_xchacha20poly1305_ietf_encrypt( plaintext: string | Buffer, nonce: string | Buffer, key: CryptographyKey, assocData?: string | Buffer ): Promise<Buffer>; crypto_aead_xchacha20poly1305_ietf_keygen(): Promise<CryptographyKey>; crypto_auth( message: string | Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_auth_keygen(): Promise<CryptographyKey>; crypto_auth_verify( message: string | Buffer, key: CryptographyKey, mac: Buffer ): Promise<boolean>; crypto_box( plaintext: string | Buffer, nonce: Buffer, myPrivateKey: X25519SecretKey, theirPublicKey: X25519PublicKey ): Promise<Buffer>; crypto_box_open( ciphertext: Buffer, nonce: Buffer, myPrivateKey: X25519SecretKey, theirPublicKey: X25519PublicKey ): Promise<Buffer>; crypto_box_keypair(): Promise<CryptographyKey>; crypto_box_keypair_from_secretkey_and_secretkey( sKey: X25519SecretKey, pKey: X25519PublicKey ): Promise<CryptographyKey>; crypto_box_secretkey(keypair: CryptographyKey): Promise<X25519SecretKey>; crypto_box_publickey(keypair: CryptographyKey): Promise<X25519PublicKey>; crypto_box_publickey_from_secretkey( secretKey: X25519SecretKey ): Promise<X25519PublicKey>; crypto_box_seal( plaintext: string | Buffer, publicKey: X25519PublicKey ): Promise<Buffer>; crypto_box_seal_open( ciphertext: Buffer, publicKey: X25519PublicKey, secretKey: X25519SecretKey ): Promise<Buffer>; crypto_generichash( message: string | Buffer, key?: CryptographyKey | null, outputLength?: number ): Promise<Buffer>; crypto_generichash_init( key?: CryptographyKey | null, outputLength?: number ): Promise<crypto_generichash_state>; crypto_generichash_update( state: crypto_generichash_state, message: string | Buffer ): Promise<crypto_generichash_state>; crypto_generichash_final( state: crypto_generichash_state, outputLength?: number ): Promise<Buffer>; crypto_generichash_keygen(): Promise<CryptographyKey>; crypto_kdf_derive_from_key( length: number, subKeyId: number, context: string | Buffer, key: CryptographyKey ): Promise<CryptographyKey>; crypto_kdf_keygen(): Promise<CryptographyKey>; crypto_kx_keypair(): Promise<CryptographyKey>; crypto_kx_seed_keypair(seed: string | Buffer): Promise<CryptographyKey>; crypto_kx_client_session_keys( clientPublicKey: X25519PublicKey, clientSecretKey: X25519SecretKey, serverPublicKey: X25519PublicKey ): Promise<CryptographyKey[]>; crypto_kx_server_session_keys( serverPublicKey: X25519PublicKey, serverSecretKey: X25519SecretKey, clientPublicKey: X25519PublicKey ): Promise<CryptographyKey[]>; crypto_onetimeauth( message: string | Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_onetimeauth_verify( message: string | Buffer, key: CryptographyKey, tag: Buffer ): Promise<boolean>; crypto_onetimeauth_keygen(): Promise<CryptographyKey>; crypto_pwhash( length: number, password: string | Buffer, salt: Buffer, opslimit: number, memlimit: number, algorithm?: number | null ): Promise<CryptographyKey>; crypto_pwhash_str( password: string | Buffer, opslimit: number, memlimit: number ): Promise<string>; crypto_pwhash_str_verify( password: string | Buffer, hash: string | Buffer ): Promise<boolean>; crypto_pwhash_str_needs_rehash( hash: string | Buffer, opslimit: number, memlimit: number ): Promise<boolean>; crypto_scalarmult( secretKey: X25519SecretKey, publicKey: X25519PublicKey ): Promise<CryptographyKey>; crypto_scalarmult_base( secretKey: X25519SecretKey ): Promise<X25519PublicKey>; crypto_secretbox( plaintext: string | Buffer, nonce: Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_secretbox_open( ciphertext: Buffer, nonce: Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_secretbox_keygen(): Promise<CryptographyKey>; crypto_secretstream_xchacha20poly1305_init_push( key: CryptographyKey ): Promise<crypto_secretstream_xchacha20poly1305_state>; crypto_secretstream_xchacha20poly1305_init_pull( key: Buffer, header: CryptographyKey ): Promise<crypto_secretstream_xchacha20poly1305_state>; crypto_secretstream_xchacha20poly1305_push( state: crypto_secretstream_xchacha20poly1305_state, message: string | Buffer, ad?: string | Buffer, tag?: CryptoSecretStreamTagValues ): Promise<Buffer>; crypto_secretstream_xchacha20poly1305_pull( state: crypto_secretstream_xchacha20poly1305_state, ciphertext: Buffer, ad?: string | Buffer, tag?: CryptoSecretStreamTagValues ): Promise<Buffer>; crypto_secretstream_xchacha20poly1305_rekey( state: crypto_secretstream_xchacha20poly1305_state ): Promise<void>; crypto_secretstream_xchacha20poly1305_keygen(): Promise<CryptographyKey>; crypto_shorthash( message: string | Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_shorthash_keygen(): Promise<CryptographyKey>; crypto_sign( message: string | Buffer, secretKey: Ed25519SecretKey ): Promise<Buffer>; crypto_sign_open( message: string | Buffer, publicKey: Ed25519PublicKey ): Promise<Buffer>; crypto_sign_detached( message: string | Buffer, secretKey: Ed25519SecretKey ): Promise<Buffer>; crypto_sign_verify_detached( message: string | Buffer, publicKey: Ed25519PublicKey, signature: Buffer ): Promise<boolean>; crypto_sign_secretkey(keypair: CryptographyKey): Promise<Ed25519SecretKey>; crypto_sign_publickey(keypair: CryptographyKey): Promise<Ed25519PublicKey>; crypto_sign_seed_keypair(seed: Buffer): Promise<CryptographyKey>; crypto_sign_keypair(): Promise<CryptographyKey>; crypto_sign_ed25519_sk_to_curve25519( sk: Ed25519SecretKey ): Promise<X25519SecretKey>; crypto_sign_ed25519_pk_to_curve25519( pk: Ed25519PublicKey ): Promise<X25519PublicKey>; crypto_stream( length: number, nonce: Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_stream_xor( plaintext: string | Buffer, nonce: Buffer, key: CryptographyKey ): Promise<Buffer>; crypto_stream_keygen(): Promise<CryptographyKey>; randombytes_buf(num: number): Promise<Buffer>; randombytes_uniform(upperBound: number): Promise<number>; sodium_add(val: Buffer, addv: Buffer): Promise<Buffer>; sodium_bin2hex(encoded: Buffer): Promise<string>; sodium_compare(b1: Buffer, b2: Buffer): Promise<number>; sodium_hex2bin(encoded: Buffer|string): Promise<Buffer>; sodium_increment(buf: Buffer): Promise<Buffer>; sodium_is_zero(buf: Buffer, len: number): Promise<Buffer>; sodium_memcmp(b1: Buffer, b2: Buffer): Promise<boolean>; sodium_memzero(buf: Buffer): Promise<void>; sodium_pad(buf: string | Buffer, blockSize: number): Promise<Buffer>; sodium_unpad(buf: string | Buffer, blockSize: number): Promise<Buffer>; } export class SodiumUtil { static cloneBuffer(buf: Buffer): Promise<Buffer>; static populateConstants<T>(anyobject: T): T & Constants; static toBuffer( stringOrBuffer: string | Buffer | Uint8Array | Promise<Buffer> ): Promise<Buffer>; } export class SodiumPolyfill { static crypto_onetimeauth( message: string | Buffer, key: CryptographyKey ): Promise<Buffer>; static crypto_onetimeauth_verify( message: string | Buffer, key: CryptographyKey, tag: Buffer ): Promise<boolean>; static crypto_stream_xor( plaintext: string | Buffer, nonce: Buffer, key: CryptographyKey ): Promise<Buffer>; static crypto_pwhash_str_needs_rehash( hash: string | Buffer, opslimit: number, memlimit: number ): Promise<boolean>; } } export = Module;
the_stack
class Client { /** * Class: Client * * Bootstrapping mechanism for the mxGraph thin client. The production version * of this file contains all code required to run the mxGraph thin client, as * well as global constants to identify the browser and operating system in * use. You may have to load chrome://global/content/contentAreaUtils.js in * your page to disable certain security restrictions in Mozilla. * * Contains the current version of the mxGraph library. The strings that * communicate versions of mxGraph use the following format. * * versionMajor.versionMinor.buildNumber.revisionNumber * * Current version is 4.2.2. */ static VERSION = '4.2.2'; /** * Optional global config variable to specify the extension of resource files. * Default is true. NOTE: This is a global variable, not a variable of Client. * * ```javascript * <script type="text/javascript"> * let mxResourceExtension = '.txt'; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` */ static mxResourceExtension = '.txt'; static setResourceExtension = (value: string) => { Client.mxResourceExtension = value; // Removes dependency with mxResources. // Client.mxResourceExtension can be used instead. // mxResources.extension = value; }; /** * Optional global config variable to toggle loading of the two resource files * in {@link Graph} and <Editor>. Default is true. NOTE: This is a global variable, * not a variable of Client. If this is false, you can use <Client.loadResources> * with its callback to load the default bundles asynchronously. * * ```javascript * <script type="text/javascript"> * let mxLoadResources = false; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` */ static mxLoadResources = true; static setLoadResources = (value: boolean) => { Client.mxLoadResources = value; }; /** * Optional global config variable to force loading the JavaScript files in * development mode. Default is undefined. NOTE: This is a global variable, * not a variable of Client. * * ```javascript * <script type="text/javascript"> * let mxForceIncludes = false; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` */ static mxForceIncludes = false; static setForceIncludes = (value: boolean) => { Client.mxForceIncludes = value; }; /** * Optional global config variable to toggle loading of the CSS files when * the library is initialized. Default is true. NOTE: This is a global variable, * not a variable of Client. * * ```javascript * <script type="text/javascript"> * let mxLoadStylesheets = false; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` */ static mxLoadStylesheets = true; static setLoadStylesheets = (value: boolean) => { Client.mxLoadStylesheets = value; }; /** * Basepath for all URLs in the core without trailing slash. Default is '.'. * Set mxBasePath prior to loading the Client library as follows to override * this setting: * * ```javascript * <script type="text/javascript"> * mxBasePath = '/path/to/core/directory'; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` * * When using a relative path, the path is relative to the URL of the page that * contains the assignment. Trailing slashes are automatically removed. */ static basePath = '.'; static setBasePath = (value: string) => { if (typeof value !== 'undefined' && value.length > 0) { // Adds a trailing slash if required if (value.substring(value.length - 1) === '/') { value = value.substring(0, value.length - 1); } Client.basePath = value; } else { Client.basePath = '.'; } }; /** * Basepath for all images URLs in the core without trailing slash. Default is * <Client.basePath> + '/images'. Set mxImageBasePath prior to loading the * Client library as follows to override this setting: * * ```javascript * <script type="text/javascript"> * mxImageBasePath = '/path/to/image/directory'; * </script> * <script type="text/javascript" src="/path/to/core/directory/js/Client.js"></script> * ``` * * When using a relative path, the path is relative to the URL of the page that * contains the assignment. Trailing slashes are automatically removed. */ static imageBasePath = '.'; static setImageBasePath = (value: string) => { if (typeof value !== 'undefined' && value.length > 0) { // Adds a trailing slash if required if (value.substring(value.length - 1) === '/') { value = value.substring(0, value.length - 1); } Client.imageBasePath = value; } else { Client.imageBasePath = `${Client.basePath}/images`; } }; /** * Defines the language of the client, eg. en for english, de for german etc. * The special value 'none' will disable all built-in internationalization and * resource loading. See {@link Resources#getSpecialBundle} for handling identifiers * with and without a dash. * * Set mxLanguage prior to loading the Client library as follows to override * this setting: * * ```javascript * <script type="text/javascript"> * mxLanguage = 'en'; * </script> * <script type="text/javascript" src="js/Client.js"></script> * ``` * * If internationalization is disabled, then the following variables should be * overridden to reflect the current language of the system. These variables are * cleared when i18n is disabled. * <Editor.askZoomResource>, <Editor.lastSavedResource>, * <Editor.currentFileResource>, <Editor.propertiesResource>, * <Editor.tasksResource>, <Editor.helpResource>, <Editor.outlineResource>, * {@link ElbowEdgeHandler#doubleClickOrientationResource}, {@link Utils#errorResource}, * {@link Utils#closeResource}, {@link GraphSelectionModel#doneResource}, * {@link GraphSelectionModel#updatingSelectionResource}, {@link GraphView#doneResource}, * {@link GraphView#updatingDocumentResource}, {@link CellRenderer#collapseExpandResource}, * {@link Graph#containsValidationErrorsResource} and * {@link Graph#alreadyConnectedResource}. */ static language = typeof window !== 'undefined' ? navigator.language : 'en'; static setLanguage = (value: string | undefined | null) => { if (typeof value !== 'undefined' && value != null) { Client.language = value; } else { Client.language = navigator.language; } }; /** * Defines the default language which is used in the common resource files. Any * resources for this language will only load the common resource file, but not * the language-specific resource file. Default is 'en'. * * Set mxDefaultLanguage prior to loading the Client library as follows to override * this setting: * * ```javascript * <script type="text/javascript"> * mxDefaultLanguage = 'de'; * </script> * <script type="text/javascript" src="js/Client.js"></script> * ``` */ static defaultLanguage = 'en'; static setDefaultLanguage = (value: string | undefined | null) => { if (typeof value !== 'undefined' && value != null) { Client.defaultLanguage = value; } else { Client.defaultLanguage = 'en'; } }; /** * Defines the optional array of all supported language extensions. The default * language does not have to be part of this list. See * {@link Resources#isLanguageSupported}. * * ```javascript * <script type="text/javascript"> * mxLanguages = ['de', 'it', 'fr']; * </script> * <script type="text/javascript" src="js/Client.js"></script> * ``` * * This is used to avoid unnecessary requests to language files, ie. if a 404 * will be returned. */ static languages: string[] | null = null; static setLanguages = (value: string[] | null | undefined) => { if (typeof value !== 'undefined' && value != null) { Client.languages = value; } }; /** * True if the current browser is Microsoft Edge. */ static IS_EDGE = typeof window !== 'undefined' && navigator.userAgent != null && !!navigator.userAgent.match(/Edge\//); /** * True if the current browser is Netscape (including Firefox). */ static IS_NS = typeof window !== 'undefined' && navigator.userAgent != null && navigator.userAgent.indexOf('Mozilla/') >= 0 && navigator.userAgent.indexOf('MSIE') < 0 && navigator.userAgent.indexOf('Edge/') < 0; /** * True if the current browser is Safari. */ static IS_SF = typeof window !== 'undefined' && /Apple Computer, Inc/.test(navigator.vendor); /** * Returns true if the user agent contains Android. */ static IS_ANDROID = typeof window !== 'undefined' && navigator.appVersion.indexOf('Android') >= 0; /** * Returns true if the user agent is an iPad, iPhone or iPod. */ static IS_IOS = typeof window !== 'undefined' && /iP(hone|od|ad)/.test(navigator.platform); /** * True if the current browser is Google Chrome. */ static IS_GC = typeof window !== 'undefined' && /Google Inc/.test(navigator.vendor); /** * True if the this is running inside a Chrome App. */ static IS_CHROMEAPP = typeof window !== 'undefined' && // @ts-ignore window.chrome != null && // @ts-ignore chrome.app != null && // @ts-ignore chrome.app.runtime != null; /** * True if the current browser is Firefox. */ static IS_FF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; /** * True if -moz-transform is available as a CSS style. This is the case * for all Firefox-based browsers newer than or equal 3, such as Camino, * Iceweasel, Seamonkey and Iceape. */ static IS_MT = typeof window !== 'undefined' && ((navigator.userAgent.indexOf('Firefox/') >= 0 && navigator.userAgent.indexOf('Firefox/1.') < 0 && navigator.userAgent.indexOf('Firefox/2.') < 0) || (navigator.userAgent.indexOf('Iceweasel/') >= 0 && navigator.userAgent.indexOf('Iceweasel/1.') < 0 && navigator.userAgent.indexOf('Iceweasel/2.') < 0) || (navigator.userAgent.indexOf('SeaMonkey/') >= 0 && navigator.userAgent.indexOf('SeaMonkey/1.') < 0) || (navigator.userAgent.indexOf('Iceape/') >= 0 && navigator.userAgent.indexOf('Iceape/1.') < 0)); /** * True if the browser supports SVG. */ static IS_SVG = typeof window !== 'undefined' && navigator.appName.toUpperCase() !== 'MICROSOFT INTERNET EXPLORER'; /** * True if foreignObject support is not available. This is the case for * Opera, older SVG-based browsers and all versions of IE. */ static NO_FO = typeof window !== 'undefined' && (!document.createElementNS || document.createElementNS( 'http://www.w3.org/2000/svg', 'foreignObject' ).toString() !== '[object SVGForeignObjectElement]' || navigator.userAgent.indexOf('Opera/') >= 0); /** * True if the client is a Windows. */ static IS_WIN = typeof window !== 'undefined' && navigator.appVersion.indexOf('Win') > 0; /** * True if the client is a Mac. */ static IS_MAC = typeof window !== 'undefined' && navigator.appVersion.indexOf('Mac') > 0; /** * True if the client is a Chrome OS. */ static IS_CHROMEOS = typeof window !== 'undefined' && /\bCrOS\b/.test(navigator.appVersion); /** * True if this device supports touchstart/-move/-end events (Apple iOS, * Android, Chromebook and Chrome Browser on touch-enabled devices). */ static IS_TOUCH = typeof window !== 'undefined' && 'ontouchstart' in document.documentElement; /** * True if this device supports Microsoft pointer events (always false on Macs). */ static IS_POINTER = typeof window !== 'undefined' && window.PointerEvent != null && !(navigator.appVersion.indexOf('Mac') > 0); /** * True if the documents location does not start with http:// or https://. */ static IS_LOCAL = typeof window !== 'undefined' && document.location.href.indexOf('http://') < 0 && document.location.href.indexOf('https://') < 0; /** * Returns true if the current browser is supported, that is, if * <Client.IS_SVG> is true. * * Example: * * ```javascript * if (!Client.isBrowserSupported()) * { * mxUtils.error('Browser is not supported!', 200, false); * } * ``` */ static isBrowserSupported = () => { return Client.IS_SVG; }; /** * Adds a link node to the head of the document. Use this * to add a stylesheet to the page as follows: * * ```javascript * Client.link('stylesheet', filename); * ``` * * where filename is the (relative) URL of the stylesheet. The charset * is hardcoded to ISO-8859-1 and the type is text/css. * * @param rel String that represents the rel attribute of the link node. * @param href String that represents the href attribute of the link node. * @param doc Optional parent document of the link node. * @param id unique id for the link element to check if it already exists */ static link = ( rel: string, href: string, doc: Document | null=null, id: string | null=null ) => { doc = doc || document; // Workaround for Operation Aborted in IE6 if base tag is used in head const link = doc.createElement('link'); link.setAttribute('rel', rel); link.setAttribute('href', href); link.setAttribute('charset', 'UTF-8'); link.setAttribute('type', 'text/css'); if (id) { link.setAttribute('id', id); } const head = doc.getElementsByTagName('head')[0]; head.appendChild(link); }; }; export default Client;
the_stack
import Cell from '../cell/datatypes/Cell'; import CellArray from '../cell/datatypes/CellArray'; import Rectangle from '../geometry/Rectangle'; import mxClient from '../../mxClient'; import SelectionChange from './SelectionChange'; import UndoableEdit from '../model/UndoableEdit'; import EventObject from '../event/EventObject'; import InternalEvent from '../event/InternalEvent'; import Dictionary from '../../util/Dictionary'; import RootChange from '../model/RootChange'; import ChildChange from '../model/ChildChange'; import { Graph } from '../Graph'; import { mixInto } from '../../util/Utils'; declare module '../Graph' { interface Graph { cells: CellArray; doneResource: string; updatingSelectionResource: string; singleSelection: boolean; selectionModel: any | null; getDoneResource: () => string; getUpdatingSelectionResource: () => string; getSelectionModel: () => any; setSelectionModel: (selectionModel: any) => void; isSingleSelection: () => boolean; setSingleSelection: (singleSelection: boolean) => void; isSelected: (cell: Cell) => boolean; isEmpty: () => boolean; clear: () => void; setCell: (cell: Cell | null) => void; setCells: (cells: CellArray) => void; getFirstSelectableCell: (cells: CellArray) => Cell | null; addCellToSelection: (cell: Cell) => void; addCellsToSelection: (cells: CellArray) => void; removeCellFromSelection: (cell: Cell) => void; removeCellsFromSelection: (cells: CellArray) => void; changeSelection: (added: CellArray | null, removed: CellArray | null) => void; cellAdded: (cell: Cell) => void; cellRemoved: (cell: Cell) => void; isCellSelected: (cell: Cell) => boolean; isSelectionEmpty: () => boolean; clearSelection: () => void; getSelectionCount: () => number; getSelectionCell: () => Cell; getSelectionCells: () => CellArray; setSelectionCell: (cell: Cell | null) => void; setSelectionCells: (cells: CellArray) => void; addSelectionCell: (cell: Cell) => void; addSelectionCells: (cells: CellArray) => void; removeSelectionCell: (cell: Cell) => void; removeSelectionCells: (cells: CellArray) => void; selectRegion: (rect: Rectangle, evt: MouseEvent) => CellArray; selectNextCell: () => void; selectPreviousCell: () => void; selectParentCell: () => void; selectChildCell: () => void; selectCell: (isNext?: boolean, isParent?: boolean, isChild?: boolean) => void; selectAll: (parent?: Cell | null, descendants?: boolean) => void; selectVertices: (parent: Cell, selectGroups: boolean) => void; selectEdges: (parent: Cell) => void; selectCells: ( vertices: boolean, edges: boolean, parent: Cell, selectGroups?: boolean ) => void; selectCellForEvent: (cell: Cell, evt: MouseEvent) => void; selectCellsForEvent: (cells: CellArray, evt: MouseEvent) => void; isSiblingSelected: (cell: Cell) => boolean; getSelectionCellsForChanges: (changes: any[], ignoreFn: Function | null) => CellArray; updateSelection: () => void; } } type PartialGraph = Pick< Graph, | 'getModel' | 'getView' | 'isCellSelectable' | 'fireEvent' | 'getDefaultParent' | 'getCurrentRoot' | 'getCells' | 'isToggleEvent' >; type PartialCells = Pick< Graph, | 'cells' | 'doneResource' | 'updatingSelectionResource' | 'singleSelection' | 'selectionModel' | 'getDoneResource' | 'getUpdatingSelectionResource' | 'getSelectionModel' | 'setSelectionModel' | 'isSingleSelection' | 'setSingleSelection' | 'isSelected' | 'isEmpty' | 'clear' | 'setCell' | 'setCells' | 'getFirstSelectableCell' | 'addCellToSelection' | 'addCellsToSelection' | 'removeCellFromSelection' | 'removeCellsFromSelection' | 'changeSelection' | 'cellAdded' | 'cellRemoved' | 'isCellSelected' | 'isSelectionEmpty' | 'clearSelection' | 'getSelectionCount' | 'getSelectionCell' | 'getSelectionCells' | 'setSelectionCell' | 'setSelectionCells' | 'addSelectionCell' | 'addSelectionCells' | 'removeSelectionCell' | 'removeSelectionCells' | 'selectRegion' | 'selectNextCell' | 'selectPreviousCell' | 'selectParentCell' | 'selectChildCell' | 'selectCell' | 'selectAll' | 'selectVertices' | 'selectEdges' | 'selectCells' | 'selectCellForEvent' | 'selectCellsForEvent' | 'isSiblingSelected' | 'getSelectionCellsForChanges' | 'updateSelection' >; type PartialType = PartialGraph & PartialCells; // @ts-expect-error The properties of PartialGraph are defined elsewhere. const GraphSelectionMixin: PartialType = { cells: new CellArray(), /** * Specifies the resource key for the status message after a long operation. * If the resource for this key does not exist then the value is used as * the status message. Default is 'done'. */ doneResource: mxClient.language !== 'none' ? 'done' : '', /** * Specifies the resource key for the status message while the selection is * being updated. If the resource for this key does not exist then the * value is used as the status message. Default is 'updatingSelection'. */ updatingSelectionResource: mxClient.language !== 'none' ? 'updatingSelection' : '', /** * Specifies if only one selected item at a time is allowed. * Default is false. */ singleSelection: false, selectionModel: null, getDoneResource() { return this.doneResource; }, getUpdatingSelectionResource() { return this.updatingSelectionResource; }, /** * Returns the {@link mxGraphSelectionModel} that contains the selection. */ getSelectionModel() { return this.selectionModel; }, /** * Sets the {@link mxSelectionModel} that contains the selection. */ setSelectionModel(selectionModel) { this.selectionModel = selectionModel; }, /** * Returns {@link singleSelection} as a boolean. */ isSingleSelection() { return this.singleSelection; }, /** * Sets the {@link singleSelection} flag. * * @param {boolean} singleSelection Boolean that specifies the new value for * {@link singleSelection}. */ setSingleSelection(singleSelection) { this.singleSelection = singleSelection; }, /** * Returns true if the given {@link Cell} is selected. */ isSelected(cell) { return this.cells.indexOf(cell) >= 0; }, /** * Returns true if no cells are currently selected. */ isEmpty() { return this.cells.length === 0; }, /** * Clears the selection and fires a {@link change} event if the selection was not * empty. */ clear() { this.changeSelection(null, this.cells); }, /** * Selects the specified {@link Cell} using {@link setCells}. * * @param cell {@link mxCell} to be selected. */ setCell(cell) { this.setCells(cell ? new CellArray(cell) : new CellArray()); }, /** * Selects the given array of {@link Cell} and fires a {@link change} event. * * @param cells Array of {@link Cell} to be selected. */ setCells(cells) { if (this.singleSelection) { cells = new CellArray(<Cell>this.getFirstSelectableCell(cells)); } const tmp = new CellArray(); for (let i = 0; i < cells.length; i += 1) { if (this.isCellSelectable(cells[i])) { tmp.push(cells[i]); } } this.changeSelection(tmp, this.cells); }, /** * Returns the first selectable cell in the given array of cells. */ getFirstSelectableCell(cells) { for (let i = 0; i < cells.length; i += 1) { if (this.isCellSelectable(cells[i])) { return cells[i]; } } return null; }, /** * Adds the given {@link Cell} to the selection and fires a {@link select} event. * * @param cell {@link mxCell} to add to the selection. */ addCellToSelection(cell) { this.addCellsToSelection(new CellArray(cell)); }, /** * Adds the given array of {@link Cell} to the selection and fires a {@link select} * event. * * @param cells Array of {@link Cell} to add to the selection. */ addCellsToSelection(cells) { let remove = null; if (this.singleSelection) { remove = this.cells; const selectableCell = this.getFirstSelectableCell(cells); cells = selectableCell ? new CellArray(selectableCell) : new CellArray(); } const tmp = new CellArray(); for (let i = 0; i < cells.length; i += 1) { if (!this.isSelected(cells[i]) && this.isCellSelectable(cells[i])) { tmp.push(cells[i]); } } this.changeSelection(tmp, remove); }, /** * Removes the specified {@link Cell} from the selection and fires a {@link select} * event for the remaining cells. * * @param cell {@link mxCell} to remove from the selection. */ removeCellFromSelection(cell) { this.removeCellsFromSelection(new CellArray(cell)); }, /** * Removes the specified {@link Cell} from the selection and fires a {@link select} * event for the remaining cells. * * @param cells {@link mxCell}s to remove from the selection. */ removeCellsFromSelection(cells) { const tmp = new CellArray(); for (let i = 0; i < cells.length; i += 1) { if (this.isSelected(cells[i])) { tmp.push(cells[i]); } } this.changeSelection(null, tmp); }, /** * Adds/removes the specified arrays of {@link Cell} to/from the selection. * * @param added Array of {@link Cell} to add to the selection. * @param remove Array of {@link Cell} to remove from the selection. */ changeSelection(added = null, removed = null) { if ( (added && added.length > 0 && added[0]) || (removed && removed.length > 0 && removed[0]) ) { const change = new SelectionChange( this as Graph, added || new CellArray(), removed || new CellArray() ); change.execute(); const edit = new UndoableEdit(this as Graph, false); edit.add(change); this.fireEvent(new EventObject(InternalEvent.UNDO, 'edit', edit)); } }, /** * Inner callback to add the specified {@link Cell} to the selection. No event * is fired in this implementation. * * Paramters: * * @param cell {@link mxCell} to add to the selection. */ cellAdded(cell) { if (!this.isSelected(cell)) { this.cells.push(cell); } }, /** * Inner callback to remove the specified {@link Cell} from the selection. No * event is fired in this implementation. * * @param cell {@link mxCell} to remove from the selection. */ cellRemoved(cell) { const index = this.cells.indexOf(cell); if (index >= 0) { this.cells.splice(index, 1); } }, /***************************************************************************** * Selection *****************************************************************************/ /** * Returns true if the given cell is selected. * * @param cell {@link mxCell} for which the selection state should be returned. */ isCellSelected(cell) { return this.isSelected(cell); }, /** * Returns true if the selection is empty. */ isSelectionEmpty() { return this.isEmpty(); }, /** * Clears the selection using {@link mxGraphSelectionModel.clear}. */ clearSelection() { this.clear(); }, /** * Returns the number of selected cells. */ getSelectionCount() { return this.cells.length; }, /** * Returns the first cell from the array of selected {@link Cell}. */ getSelectionCell() { return this.cells[0]; }, /** * Returns the array of selected {@link Cell}. */ getSelectionCells() { return this.cells.slice(); }, /** * Sets the selection cell. * * @param cell {@link mxCell} to be selected. */ setSelectionCell(cell) { this.setCell(cell); }, /** * Sets the selection cell. * * @param cells Array of {@link Cell} to be selected. */ setSelectionCells(cells) { this.setCells(cells); }, /** * Adds the given cell to the selection. * * @param cell {@link mxCell} to be add to the selection. */ addSelectionCell(cell) { this.addCellToSelection(cell); }, /** * Adds the given cells to the selection. * * @param cells Array of {@link Cell} to be added to the selection. */ addSelectionCells(cells) { this.addCellsToSelection(cells); }, /** * Removes the given cell from the selection. * * @param cell {@link mxCell} to be removed from the selection. */ removeSelectionCell(cell) { this.removeCellFromSelection(cell); }, /** * Removes the given cells from the selection. * * @param cells Array of {@link Cell} to be removed from the selection. */ removeSelectionCells(cells) { this.removeCellsFromSelection(cells); }, /** * Selects and returns the cells inside the given rectangle for the * specified event. * * @param rect {@link mxRectangle} that represents the region to be selected. * @param evt Mouseevent that triggered the selection. */ // selectRegion(rect: mxRectangle, evt: Event): mxCellArray; selectRegion(rect, evt) { const cells = this.getCells(rect.x, rect.y, rect.width, rect.height); this.selectCellsForEvent(cells, evt); return cells; }, /** * Selects the next cell. */ selectNextCell() { this.selectCell(true); }, /** * Selects the previous cell. */ selectPreviousCell() { this.selectCell(); }, /** * Selects the parent cell. */ selectParentCell() { this.selectCell(false, true); }, /** * Selects the first child cell. */ selectChildCell() { this.selectCell(false, false, true); }, /** * Selects the next, parent, first child or previous cell, if all arguments * are false. * * @param isNext Boolean indicating if the next cell should be selected. * @param isParent Boolean indicating if the parent cell should be selected. * @param isChild Boolean indicating if the first child cell should be selected. */ selectCell(isNext = false, isParent = false, isChild = false) { const cell = this.cells.length > 0 ? this.cells[0] : null; if (this.cells.length > 1) { this.clear(); } const parent = cell ? (cell.getParent() as Cell) : this.getDefaultParent(); const childCount = parent.getChildCount(); if (!cell && childCount > 0) { const child = parent.getChildAt(0); this.setSelectionCell(child); } else if ( parent && (!cell || isParent) && this.getView().getState(parent) && parent.getGeometry() ) { if (this.getCurrentRoot() !== parent) { this.setSelectionCell(parent); } } else if (cell && isChild) { const tmp = cell.getChildCount(); if (tmp > 0) { const child = cell.getChildAt(0); this.setSelectionCell(child); } } else if (childCount > 0) { let i = parent.getIndex(cell); if (isNext) { i++; const child = parent.getChildAt(i % childCount); this.setSelectionCell(child); } else { i--; const index = i < 0 ? childCount - 1 : i; const child = parent.getChildAt(index); this.setSelectionCell(child); } } }, /** * Selects all children of the given parent cell or the children of the * default parent if no parent is specified. To select leaf vertices and/or * edges use {@link selectCells}. * * @param parent Optional {@link Cell} whose children should be selected. * Default is {@link defaultParent}. * @param descendants Optional boolean specifying whether all descendants should be * selected. Default is `false`. */ selectAll(parent, descendants = false) { parent = parent ?? this.getDefaultParent(); const cells = descendants ? parent.filterDescendants((cell: Cell) => { return cell !== parent && !!this.getView().getState(cell); }) : parent.getChildren(); this.setSelectionCells(cells); }, /** * Select all vertices inside the given parent or the default parent. */ selectVertices(parent, selectGroups = false) { this.selectCells(true, false, parent, selectGroups); }, /** * Select all vertices inside the given parent or the default parent. */ selectEdges(parent) { this.selectCells(false, true, parent); }, /** * Selects all vertices and/or edges depending on the given boolean * arguments recursively, starting at the given parent or the default * parent if no parent is specified. Use {@link selectAll} to select all cells. * For vertices, only cells with no children are selected. * * @param vertices Boolean indicating if vertices should be selected. * @param edges Boolean indicating if edges should be selected. * @param parent Optional {@link Cell} that acts as the root of the recursion. * Default is {@link defaultParent}. * @param selectGroups Optional boolean that specifies if groups should be * selected. Default is `false`. */ selectCells(vertices = false, edges = false, parent, selectGroups = false) { parent = parent ?? this.getDefaultParent(); const filter = (cell: Cell) => { const p = cell.getParent(); return ( !!this.getView().getState(cell) && (((selectGroups || cell.getChildCount() === 0) && cell.isVertex() && vertices && p && !p.isEdge()) || (cell.isEdge() && edges)) ); }; const cells = parent.filterDescendants(filter); this.setSelectionCells(cells); }, /** * Selects the given cell by either adding it to the selection or * replacing the selection depending on whether the given mouse event is a * toggle event. * * @param cell {@link mxCell} to be selected. * @param evt Optional mouseevent that triggered the selection. */ selectCellForEvent(cell, evt) { const isSelected = this.isCellSelected(cell); if (this.isToggleEvent(evt)) { if (isSelected) { this.removeSelectionCell(cell); } else { this.addSelectionCell(cell); } } else if (!isSelected || this.getSelectionCount() !== 1) { this.setSelectionCell(cell); } }, /** * Selects the given cells by either adding them to the selection or * replacing the selection depending on whether the given mouse event is a * toggle event. * * @param cells Array of {@link Cell} to be selected. * @param evt Optional mouseevent that triggered the selection. */ selectCellsForEvent(cells, evt) { if (this.isToggleEvent(evt)) { this.addSelectionCells(cells); } else { this.setSelectionCells(cells); } }, /** * Returns true if any sibling of the given cell is selected. */ isSiblingSelected(cell) { const parent = cell.getParent() as Cell; const childCount = parent.getChildCount(); for (let i = 0; i < childCount; i += 1) { const child = parent.getChildAt(i); if (cell !== child && this.isCellSelected(child)) { return true; } } return false; }, /***************************************************************************** * Selection state *****************************************************************************/ /** * Function: getSelectionCellsForChanges * * Returns the cells to be selected for the given array of changes. * * Parameters: * * ignoreFn - Optional function that takes a change and returns true if the * change should be ignored. * */ getSelectionCellsForChanges(changes, ignoreFn = null) { const dict = new Dictionary(); const cells: CellArray = new CellArray(); const addCell = (cell: Cell) => { if (!dict.get(cell) && this.getModel().contains(cell)) { if (cell.isEdge() || cell.isVertex()) { dict.put(cell, true); cells.push(cell); } else { const childCount = cell.getChildCount(); for (let i = 0; i < childCount; i += 1) { addCell(cell.getChildAt(i)); } } } }; for (let i = 0; i < changes.length; i += 1) { const change = changes[i]; if (change.constructor !== RootChange && (!ignoreFn || !ignoreFn(change))) { let cell = null; if (change instanceof ChildChange) { cell = change.child; } else if (change.cell && change.cell instanceof Cell) { cell = change.cell; } if (cell) { addCell(cell); } } } return cells; }, /** * Removes selection cells that are not in the model from the selection. */ updateSelection() { const cells = this.getSelectionCells(); const removed = new CellArray(); for (const cell of cells) { if (!this.getModel().contains(cell) || !cell.isVisible()) { removed.push(cell); } else { let par = cell.getParent(); while (par && par !== this.getView().currentRoot) { if (par.isCollapsed() || !par.isVisible()) { removed.push(cell); break; } par = par.getParent(); } } } this.removeSelectionCells(removed); }, }; mixInto(Graph)(GraphSelectionMixin);
the_stack
export namespace DynamsoftEnums { /** Barcode Format */ enum EnumBarcodeFormat { BF_ALL = -32505857, BF_AZTEC = 268435456, BF_CODABAR = 8, BF_CODE_39 = 1, BF_CODE_39_EXTENDED = 1024, BF_CODE_93 = 4, BF_CODE_128 = 2, BF_DATAMATRIX = 134217728, BF_EAN_8 = 64, BF_EAN_13 = 32, BF_GS1_COMPOSITE = -2147483648, BF_GS1_DATABAR = 260096, BF_GS1_DATABAR_EXPANDED = 32768, BF_GS1_DATABAR_EXPANDED_STACKED = 65536, BF_GS1_DATABAR_LIMITED = 131072, BF_GS1_DATABAR_OMNIDIRECTIONAL = 2048, BF_GS1_DATABAR_STACKED = 8192, BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL = 16384, BF_GS1_DATABAR_TRUNCATED = 4096, BF_INDUSTRIAL_25 = 512, BF_ITF = 16, BF_MAXICODE = 536870912, BF_MICRO_PDF417 = 524288, BF_MICRO_QR = 1073741824, BF_NULL = 0, BF_ONED = 2047, BF_PATCHCODE = 262144, BF_PDF417 = 33554432, BF_QR_CODE = 67108864, BF_UPC_A = 128, BF_UPC_E = 256 } /** Barcode Format 2 */ enum EnumBarcodeFormat_2 { BF2_AUSTRALIANPOST = 8388608, BF2_DOTCODE = 2, BF2_NONSTANDARD_BARCODE = 1, BF2_NULL = 0, BF2_PLANET = 4194304, BF2_POSTALCODE = 32505856, BF2_POSTNET = 2097152, BF2_RM4SCC = 16777216, BF2_USPSINTELLIGENTMAIL = 1048576 } /** Barcode Color Mode */ enum EnumBarcodeColourMode { BICM_DARK_LIGHT_MIXED = 16, BICM_DARK_ON_DARK = 4, BICM_DARK_ON_LIGHT = 1, BICM_DARK_ON_LIGHT_DARK_SURROUNDING = 32, BICM_LIGHT_ON_DARK = 2, BICM_LIGHT_ON, _LIGHT = 8, BICM_SKIP = 0, } /** Barcode Complement Mode */ enum EnumBarcodeComplementMode { BCM_AUTO = 1, BCM_GENERAL = 2, BCM_SKIP = 0 } /** OCR Languages */ enum EnumDWT_OCRLanguage { OCRL_ENG = "eng", OCRL_ARA = "ara", OCRL_CHI_SIM = "chi_sim", OCRL_CHI_TRA = "chi_tra", OCRL_HIN = "hin", OCRL_URD = "urd", OCRL_SPA = "spa", OCRL_FRA = "fra", OCRL_MSA = "msa", OCRL_IND = "ind", OCRL_RUS = "rus", OCRL_BEN = "ben", OCRL_POR = "por", OCRL_PAN = "pan", OCRL_DEU = "deu", OCRL_JPN = "jpn", OCRL_FAS = "fas", OCRL_SWA = "swa", OCRL_JAV = "jav", OCRL_TEL = "tel", OCRL_TUR = "tur", OCRL_KOR = "kor", OCRL_MAR = "mar", OCRL_TAM = "tam", OCRL_VIE = "vie", OCRL_ITA = "ita", OCRL_THA = "tha" } /** OCR PageSet Mode */ enum EnumDWT_OCRPageSetMode { OCRPSM_OSD_ONLY = 0, PSM_AUTO_OSD = 1, PSM_AUTO_ONLY = 2, PSM_AUTO = 3, PSM_SINGLE_COLUMN = 4, PSM_SINGLE_BLOCK_VERT_TEXT = 5, PSM_SINGLE_BLOCK = 6, PSM_SINGLE_LINE = 7, PSM_SINGLE_WORD = 8, PSM_CIRCLE_WORD = 9, PSM_SINGLE_CHAR = 10 } /** OCR Output Format */ enum EnumDWT_OCROutputFormat { OCROF_TEXT = 0, OCROF_PDFPLAINTEXT = 1, OCROF_PDFIMAGEOVERTEXT = 2, OCROF_PDFPLAINTEXT_PDFX = 3, OCROF_PDFIMAGEOVERTEXT_PDFX = 4 } /** OCR Download Type */ enum EnumDWT_OCRDownloadType { OCRDT_Dll = 0, OCRDT_LANGUAGE = 1 } /** OCRPro Reconnition module */ enum EnumDWT_OCRProRecognitionModule { OCRPM_AUTO = "AUTO", OCRPM_MOSTACCURATE = "MOSTACCURATE", OCRPM_BALANCED = "BALANCED", OCRPM_FASTEST = "FASTEST" } /** OCRPro Output Format */ enum EnumDWT_OCRProOutputFormat { OCRPFT_TXTS = "TXTS", OCRPFT_TXTCSV = "TXTCSV", OCRPFT_TXTF = "TXTF", OCRPFT_XML = "XML", OCRPFT_IOTPDF = "IOTPDF", OCRPFT_IOTPDF_MRC = "IOTPDF_MRC" } /** OCRPro PDF Version */ enum EnumDWT_OCRProPDFVersion { OCRPPDFV_0 = "1.0", OCRPPDFV_1 = "1.1", OCRPPDFV_2 = "1.2", OCRPPDFV_3 = "1.3", OCRPPDFV_4 = "1.4", OCRPPDFV_5 = "1.5", OCRPPDFV_6 = "1.6", OCRPPDFV_7 = "1.7" } /** OCRPro PDFA Version */ enum EnumDWT_OCRProPDFAVersion { OCRPPDFAV_1A = "pdf/a-1a", OCRPPDFAV_1B = "pdf/a-1b", OCRPPDFAV_2A = "pdf/a-2a", OCRPPDFAV_2B = "pdf/a-2b", OCRPPDFAV_2U = "pdf/a-2u", OCRPPDFAV_3A = "pdf/a-3a", OCRPPDFAV_3B = "pdf/a-3b", OCRPPDFAV_3U = "pdf/a-3u" } /** OCRPro Type */ enum EnumDWT_OCRProType { OCRDT_File = 0, OCRDT_Index = 1 } /** OCRPro Find Text Flags */ enum EnumDWT_OCRFindTextFlags { OCRFT_WHOLEWORD = 1, OCRFT_MATCHCASE = 2, OCRFT_FUZZYMATCH = 4 // OCRFT_BACKWARD= 8 } /** OCRPro Find Text Action */ enum EnumDWT_OCRFindTextAction { OCRFT_HIGHLIGHT = 0, OCRFT_STRIKEOUT = 1, OCRFT_MARKFORREDACT = 2 } enum EnumDWT_ConvertMode { CM_DEFAULT = 0, CM_RENDERALL = 1 } enum EnumErrorCode { DBR_1D_LICENSE_INVALID = -10017, DBR_AZTEC_LICENSE_INVALID = -10041, DBR_BARCODE_FORMAT_INVALID = -10009, DBR_BPP_NOT_SUPPORTED = -10007, DBR_CUSTOM_MODULESIZE_INVALID = -10025, DBR_CUSTOM_REGION_INVALID = -10010, DBR_CUSTOM_SIZE_INVALID = -10024, DBR_DATAMATRIX_LICENSE_INVALID = -10020, DBR_DIB_BUFFER_INVALID = -10018, DBR_DOMAIN_NOT_MATCHED = -10039, DBR_DOTCODE_LICENSE_INVALID = -10061, DBR_DPM_LICENSE_INVALID = -10048, DBR_FILETYPE_NOT_SUPPORTED = -10006, DBR_FILE_NOT_FOUND = -10005, DBR_FRAME_DECODING_THREAD_EXISTS = -10049, DBR_GET_MODE_ARGUMENT_ERROR = -10055, DBR_GS1_COMPOSITE_LICENSE_INVALID = -10059, DBR_GS1_DATABAR_LICENSE_INVALID = -10058, DBR_IMAGE_READ_FAILED = -10012, DBR_INDEX_INVALID = -10008, DBR_IRT_LICENSE_INVALID = -10056, DBR_JSON_KEY_INVALID = -10032, DBR_JSON_NAME_KEY_MISSING = -10034, DBR_JSON_NAME_REFERENCE_INVALID = -10037, DBR_JSON_NAME_VALUE_DUPLICATED = -10035, DBR_JSON_PARSE_FAILED = -10030, DBR_JSON_TYPE_INVALID = -10031, DBR_JSON_VALUE_INVALID = -10033, DBR_LICENSEKEY_NOT_MATCHED = -10043, DBR_LICENSE_CONTENT_INVALID = -10052, DBR_LICENSE_DEVICE_RUNS_OUT = -10054, DBR_LICENSE_DLL_MISSING = -10042, DBR_LICENSE_EXPIRED = -10004, DBR_LICENSE_INIT_FAILED = -10045, DBR_LICENSE_INVALID = -10003, DBR_LICENSE_KEY_INVALID = -10053, DBR_MAXICODE_LICENSE_INVALID = -10057, DBR_MAX_BARCODE_NUMBER_INVALID = -10011, DBR_NO_MEMORY = -10001, DBR_NULL_REFERENCE = -10002, DBR_PAGE_NUMBER_INVALID = -10023, DBR_PARAMETER_VALUE_INVALID = -10038, DBR_PATCHCODE_LICENSE_INVALID = -10046, DBR_PDF417_LICENSE_INVALID = -10019, DBR_PDF_DLL_MISSING = -10022, DBR_PDF_READ_FAILED = -10021, DBR_POSTALCODE_LICENSE_INVALID = -10047, DBR_QR_LICENSE_INVALID = -10016, DBR_RECOGNITION_TIMEOUT = -10026, DBR_REQUESTED_FAILED = -10044, DBR_RESERVEDINFO_NOT_MATCHED = -10040, DBR_SET_MODE_ARGUMENT_ERROR = -10051, DBR_STOP_DECODING_THREAD_FAILED = -10050, DBR_SUCCESS = 0, DBR_SYSTEM_EXCEPTION = 1, DBR_TEMPLATE_NAME_INVALID = -10036, DBR_TIFF_READ_FAILED = -10013, DBR_UNKNOWN = -10000 } /** Specifies the video rotate mode on a video capture device. */ enum EnumDWT_VideoRotateMode { /** Don't rotate */ VRM_NONE = 0, /** 90 deg Clockwise */ VRM_90_DEGREES_CLOCKWISE = 1, /** 180 deg Clockwise */ VRM_180_DEGREES_CLOCKWISE = 2, /** 270 deg Clockwise */ VRM_270_DEGREES_CLOCKWISE = 3, /** Flip */ VRM_FLIP_VERTICAL = 4, /** Mirror */ VRM_FLIP_HORIZONTAL = 5 } /** Specifies video properties on a video capture device. */ enum EnumDWT_VideoProperty { /** * Specifies the brightness, also called the black level. * For NTSC, the value is expressed in IRE units * 100. * For non-NTSC sources, the units are arbitrary, with zero * representing blanking and 10,000 representing pure white. * Values range from -10,000 to 10,000. */ VP_BRIGHTNESS = 0, /** Specifies the contrast, expressed as gain factor * 100. Values range from zero to 10,000. */ VP_CONTRAST = 1, /** Specifies the hue, in degrees * 100. Values range from -180,000 to 180,000 (-180 to +180 degrees). */ VP_HUE = 2, /** Specifies the saturation. Values range from 0 to 10,000. */ VP_SATURATION = 3, /** Specifies the sharpness. Values range from 0 to 100. */ VP_SHARPNESS = 4, /** Specifies the gamma, as gamma * 100. Values range from 1 to 500. */ VP_GAMMA = 5, /** Specifies the color enable setting. The possible values are 0 (off) and 1 (on). */ VP_COLORENABLE = 6, /** Specifies the white balance, as a color temperature in degrees Kelvin. The range of values depends on the device. */ VP_WHITEBALANCE = 7, /** Specifies the backlight compensation setting. Possible values are 0 (off) and 1 (on). */ VP_BACKLIGHTCOMPENSATION = 8, /** * Specifies the gain adjustment. Zero is normal. * Positive values are brighter and negative values are darker. * The range of values depends on the device. */ VP_GAIN = 9 } /** Specifies a setting on a camera. */ enum EnumDWT_CameraControlProperty { /** * Specifies the camera's pan setting, in degrees. * Values range from -180 to +180, with the default set to zero. * Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), * and negative values are counterclockwise from the origin. */ CCP_PAN = 0, /** * Specifies the camera's tilt setting, in degrees. Values range from -180 to +180, with the default set to zero. * Positive values point the imaging plane up, and negative values point the imaging plane down. */ CCP_TILT = 1, /** * Specifies the camera's roll setting, in degrees. Values range from -180 to +180, with the default set to zero. * Positive values cause a clockwise rotation of the camera along the image-viewing axis, and negative values cause a counterclockwise rotation of the camera. */ CCP_ROLL = 2, /** Specifies the camera's zoom setting, in millimeters. Values range from 10 to 600, and the default is specific to the device. */ CCP_ZOOM = 3, /** * Specifies the exposure setting, in log base 2 seconds. In other words, for values less than zero, the exposure time is 1/2^n seconds, * and for values zero or above, the exposure time is 2^n seconds. For example= * Value Seconds * -3 1/8 * -2 1/4 * -1 1/2 * 0 1 * 1 2 * 2 4 */ CCP_EXPOSURE = 4, /** Specifies the camera's iris setting, in units of fstop* 10. */ CCP_IRIS = 5, /** * Specifies the camera's focus setting, as the distance to the optimally focused target, in millimeters. * The range and default value are specific to the device. */ CCP_FOCUS = 6 } /** Border Styles */ enum EnumDWT_BorderStyle { /** No border. */ TWBS_NONE = 0, /** Flat border. */ TWBS_SINGLEFLAT = 1, /** 3D border. */ TWBS_SINGLE3D = 2 } /** Capabilities */ enum EnumDWT_Cap { /** Nothing. */ CAP_NONE = 0, /** The application is willing to accept this number of images. */ CAP_XFERCOUNT = 1, /** * Allows the application and Source to identify which compression schemes they have in * common for Buffered Memory and File transfers. * Note for File transfers= * Since only certain file formats support compression, this capability must be negotiated after * setting the desired file format with ICAP_IMAGEFILEFORMAT. */ ICAP_COMPRESSION = 256, /** The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.). */ ICAP_PIXELTYPE = 257, /** * Unless a quantity is dimensionless or uses a specified unit of measure, ICAP_UNITS determines * the unit of measure for all quantities. */ ICAP_UNITS = 258, /** Allows the application and Source to identify which transfer mechanisms the source supports. */ ICAP_XFERMECH = 259, /** The name or other identifying information about the Author of the image. It may include a copyright string. */ CAP_AUTHOR = 4096, /** A general note about the acquired image. */ CAP_CAPTION = 4097, /** * If TRUE, Source must acquire data from the document feeder acquire area and other feeder * capabilities can be used. If FALSE, Source must acquire data from the non-feeder acquire area * and no other feeder capabilities can be used. */ CAP_FEEDERENABLED = 4098, /** Reflect whether there are documents loaded in the Source's feeder. */ CAP_FEEDERLOADED = 4099, /** * The date and time the image was acquired. * Stored in the form "YYYY/MM/DD HH=mm=SS.sss" where YYYY is the year, MM is the * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, * and sss is the millisecond. */ CAP_TIMEDATE = 4100, /** * Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate * which capabilities the Source will allow to be set by the application. Some capabilities can only * be set if certain setup work has been done so the Source cannot globally answer which * capabilities are "set-able." */ CAP_SUPPORTEDCAPS = 4101, /** Allows the application and Source to negotiate capabilities to be used in States 5 and 6. */ CAP_EXTENDEDCAPS = 4102, /** * If TRUE, the Source will automatically feed the next page from the document feeder after the * number of frames negotiated for capture from each page are acquired. CAP_FEEDERENABLED * must be TRUE to use this capability. */ CAP_AUTOFEED = 4103, /** * If TRUE, the Source will eject the current page being acquired from and will leave the feeder * acquire area empty. * If CAP_AUTOFEED is TRUE, a fresh page will be advanced. * CAP_FEEDERENABLED must equal TRUE to use this capability. * This capability must have been negotiated as an extended capability to be used in States 5 and 6. */ CAP_CLEARPAGE = 4104, /** * If TRUE, the Source will eject the current page and advance the next page in the document feeder * into the feeder acquire area. * If CAP_AUTOFEED is TRUE, the same action just described will occur and CAP_AUTOFEED will * remain active. * CAP_FEEDERENABLED must equal TRUE to use this capability. * This capability must have been negotiated as an extended capability to be used in States 5 and 6. */ CAP_FEEDPAGE = 4105, /** * If TRUE, the Source will return the current page to the input side of the document feeder and * feed the last page from the output side of the feeder back into the acquisition area. * If CAP_AUTOFEED is TRUE, automatic feeding will continue after all negotiated frames from this * page are acquired. * CAP_FEEDERENABLED must equal TRUE to use this capability. * This capability must have been negotiated as an extended capability to be used in States 5 and 6. */ CAP_REWINDPAGE = 4106, /** * If TRUE, the Source will display a progress indicator during acquisition and transfer, regardless * of whether the Source's user interface is active. If FALSE, the progress indicator will be * suppressed if the Source's user interface is inactive. * The Source will continue to display device-specific instructions and error messages even with * the Source user interface and progress indicators turned off. */ CAP_INDICATORS = 4107, /** * Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate * which capabilities the Source will allow to be set by the application. Some capabilities can only * be set if certain setup work has been done so the Source cannot globally answer which * capabilities are "set-able." */ CAP_SUPPORTEDCAPSEXT = 4108, /** This capability determines whether the device has a paper sensor that can detect documents on the ADF or Flatbed. */ CAP_PAPERDETECTABLE = 4109, /** * If TRUE, indicates that this Source supports acquisition with the UI disabled; i.e., * TW_USERINTERFACE's ShowUI field can be set to FALSE. If FALSE, indicates that this Source * can only support acquisition with the UI enabled. */ CAP_UICONTROLLABLE = 4110, /** * If TRUE, the physical hardware (e.g., scanner, digital camera, image database, etc.) that * represents the image source is attached, powered on, and communicating. */ CAP_DEVICEONLINE = 4111, /** * This capability is intended to boost the performance of a Source. The fundamental assumption * behind AutoScan is that the device is able to capture the number of images indicated by the * value of CAP_XFERCOUNT without waiting for the Application to request the image transfers. * This is only possible if the device has internal buffers capable of caching the images it captures. * The default behavior is undefined, because some high volume devices are incapable of anything * but CAP_AUTOSCAN being equal to TRUE. However, if a Source supports FALSE, it should use it * as the mandatory default, since this best describes the behavior of pre-1.8 TWAIN Applications. */ CAP_AUTOSCAN = 4112, /** * Allows an application to request the delivery of thumbnail representations for the set of images * that are to be delivered. * Setting CAP_THUMBNAILSENABLED to TRUE turns on thumbnail mode. Images transferred * thereafter will be sent at thumbnail size (exact thumbnail size is determined by the Data Source). * Setting this capability to FALSE turns thumbnail mode off and returns full size images. */ CAP_THUMBNAILSENABLED = 4113, /** * This indicates whether the scanner supports duplex. If so, it further indicates whether one-path * or two-path duplex is supported. */ CAP_DUPLEX = 4114, /** * The user can set the duplex option to be TRUE or FALSE. If TRUE, the scanner scans both sides * of a paper; otherwise, the scanner will scan only one side of the image. */ CAP_DUPLEXENABLED = 4115, /** Allows an application to query a source to see if it implements the new user interface settings dialog. */ CAP_ENABLEDSUIONLY = 4116, CAP_CUSTOMDSDATA = 4117, /** * Allows the application to specify the starting endorser / imprinter number. All other endorser/ * imprinter properties should be handled through the data source's user interface. * The user can set the starting number for the endorser. */ CAP_ENDORSER = 4118, /** Turns specific audible alarms on and off. */ CAP_ALARMS = 4120, /** * The volume of a device's audible alarm. Note that this control affects the volume of all alarms; * no specific volume control for individual types of alarms is provided. */ CAP_ALARMVOLUME = 4121, /** * The number of images to automatically capture. This does not refer to the number of images to * be sent to the Application, use CAP_XFERCOUNT for that. */ CAP_AUTOMATICCAPTURE = 4122, /** * For automatic capture, this value selects the number of milliseconds before the first picture is to * be taken, or the first image is to be scanned. */ CAP_TIMEBEFOREFIRSTCAPTURE = 4123, /** For automatic capture, this value selects the milliseconds to wait between pictures taken, or images scanned. */ CAP_TIMEBETWEENCAPTURES = 4124, /** CapGet() reports the presence of data in the scanner's buffers. CapSet() with a value of TWCB_CLEAR immediately clears the buffers. */ CAP_CLEARBUFFERS = 4125, /** Describes the number of pages that the scanner can buffer when CAP_AUTOSCAN is enabled. */ CAP_MAXBATCHBUFFERS = 4126, /** * The date and time of the device's clock. * Managed in the form "YYYY/MM/DD HH=mm=SS=sss" where YYYY is the year, MM is the * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, * and sss is the millisecond. */ CAP_DEVICETIMEDATE = 4127, /** CapGet() reports the kinds of power available to the device. CapGetCurrent() reports the current power supply in use. */ CAP_POWERSUPPLY = 4128, /** This capability queries the Source for UI support for preview mode. If TRUE, the Source supports preview UI. */ CAP_CAMERAPREVIEWUI = 4129, /** * A string containing the serial number of the currently selected device in the Source. Multiple * devices may all report the same serial number. */ CAP_SERIALNUMBER = 4132, /** * CapGet() returns the current list of available printer devices, along with the one currently being used for negotiation. * CapSet() selects the current device for negotiation, and optionally constrains the list. * Top/Bottom refers to duplex devices, and indicates if the printer is writing on the top or the bottom of the sheet of paper. * Simplex devices use the top settings. Before/After indicates whether printing occurs before or after the sheet of paper has been scanned. */ CAP_PRINTER = 4134, /** Turns the current CAP_PRINTER device on or off. */ CAP_PRINTERENABLED = 4135, /** The User can set the starting number for the current CAP_PRINTER device. */ CAP_PRINTERINDEX = 4136, /** * Specifies the appropriate current CAP_PRINTER device mode. * Note= * O TWPM_SINGLESTRING specifies that the printed text will consist of a single string. * O TWPM _MULTISTRING specifies that the printed text will consist of an enumerated list of * strings to be printed in order. * O TWPM _COMPOUNDSTRING specifies that the printed string will consist of a compound of a * String followed by a value followed by a suffix string. */ CAP_PRINTERMODE = 4137, /** * Specifies the string(s) that are to be used in the string component when the current * CAP_PRINTER device is enabled. */ CAP_PRINTERSTRING = 4138, /** Specifies the string that shall be used as the current CAP_PRINTER device's suffix. */ CAP_PRINTERSUFFIX = 4139, /** * Allows Application and Source to identify which languages they have in common for the exchange of string data, * and to select the language of the internal UI. Since the TWLG_xxxx codes include language and country data, there is no separate * capability for selecting the country. */ CAP_LANGUAGE = 4140, /** * Helps the Application determine any special actions it may need to take when negotiating * frames with the Source. Allowed values are listed in <see cref="TWCapFeederAlignment"/>. * TWFA_NONE= The alignment is free-floating. Applications should assume * that the origin for frames is on the left. * TWFA_LEFT= The alignment is to the left. * TWFA_CENTER= The alignment is centered. This means that the paper will * be fed in the middle of the ICAP_PHYSICALWIDTH of the * device. If this is set, then the Application should calculate * any frames with a left offset of zero. * TWFA_RIGHT= The alignment is to the right. */ CAP_FEEDERALIGNMENT = 4141, /** * TWFO_FIRSTPAGEFIRST if the feeder starts with the top of the first page. * TWFO_LASTPAGEFIRST is the feeder starts with the top of the last page. */ CAP_FEEDERORDER = 4142, /** * Indicates whether the physical hardware (e.g. scanner, digital camera) is capable of acquiring * multiple images of the same page without changes to the physical registration of that page. */ CAP_REACQUIREALLOWED = 4144, /** The minutes of battery power remaining to the device. */ CAP_BATTERYMINUTES = 4146, /** When used with CapGet(), return the percentage of battery power level on camera. If -1 is returned, it indicates that the battery is not present. */ CAP_BATTERYPERCENTAGE = 4147, /** Added 1.91 */ CAP_CAMERASIDE = 4148, /** Added 1.91 */ CAP_SEGMENTED = 4149, /** Added 2.0 */ CAP_CAMERAENABLED = 4150, /** Added 2.0 */ CAP_CAMERAORDER = 4151, /** Added 2.0 */ CAP_MICRENABLED = 4152, /** Added 2.0 */ CAP_FEEDERPREP = 4153, /** Added 2.0 */ CAP_FEEDERPOCKET = 4154, /** Added 2.1 */ CAP_AUTOMATICSENSEMEDIUM = 4155, /** Added 2.1 */ CAP_CUSTOMINTERFACEGUID = 4156, /** TRUE enables and FALSE disables the Source's Auto-brightness function (if any). */ ICAP_AUTOBRIGHT = 4352, /** The brightness values available within the Source. */ ICAP_BRIGHTNESS = 4353, /** The contrast values available within the Source. */ ICAP_CONTRAST = 4355, /** Specifies the square-cell halftone (dithering) matrix the Source should use to halftone the image. */ ICAP_CUSTHALFTONE = 4356, /** Specifies the exposure time used to capture the image, in seconds. */ ICAP_EXPOSURETIME = 4357, /** * Describes the color characteristic of the subtractive filter applied to the image data. * Multiple filters may be applied to a single acquisition. */ ICAP_FILTER = 4358, /** Specifies whether or not the image was acquired using a flash. */ ICAP_FLASHUSED = 4359, /** Gamma correction value for the image data. */ ICAP_GAMMA = 4360, /** A list of names of the halftone patterns available within the Source. */ ICAP_HALFTONES = 4361, /** * Specifies which value in an image should be interpreted as the lightest "highlight." All values * "lighter" than this value will be clipped to this value. Whether lighter values are smaller or * larger can be determined by examining the Current value of ICAP_PIXELFLAVOR. */ ICAP_HIGHLIGHT = 4362, /** * Informs the application which file formats the Source can generate (CapGet()). Tells the Source which file formats the application can handle (CapSet()). * TWFF_TIFF Used for document * TWFF_PICT Native Macintosh * TWFF_BMP Native Microsoft * TWFF_XBM Used for document * TWFF_JFIF Wrapper for JPEG * TWFF_FPX FlashPix, used with digital * TWFF_TIFFMULTI Multi-page TIFF files * TWFF_PNG An image format standard intended for use on the web, replaces GIF * TWFF_SPIFF A standard from JPEG, intended to replace JFIF, also supports JBIG * TWFF_EXIF File format for use with digital cameras. */ ICAP_IMAGEFILEFORMAT = 4364, /** TRUE means the lamp is currently, or should be set to ON. Sources may not support CapSet() operations. */ ICAP_LAMPSTATE = 4365, /** Describes the general color characteristic of the light source used to acquire the image. */ ICAP_LIGHTSOURCE = 4366, /** * Defines which edge of the "paper" the image's "top" is aligned with. This information is used to adjust the frames to match the * scanning orientation of the paper. For instance, if an ICAP_SUPPORTEDSIZE of TWSS_ISOA4 has been negotiated, * and ICAP_ORIENTATION is set to TWOR_LANDSCAPE, then the Source must rotate the frame it downloads to the scanner to reflect the * orientation of the paper. Please note that setting ICAP_ORIENTATION does not affect the values reported by ICAP_FRAMES; * it just causes the Source to use them in a different way. The upper-left of the image is defined as the location where both the primary and * secondary scans originate. (The X axis is the primary scan direction and the Y axis is the secondary scan direction.) * For a flatbed scanner, the light bar moves in the secondary scan direction. For a handheld scanner, the scanner is drug in the * secondary scan direction. For a digital camera, the secondary direction is the vertical axis when the viewed image is considered upright. */ ICAP_ORIENTATION = 4368, /** The maximum physical width (X-axis) the Source can acquire (measured in units of ICAP_UNITS). */ ICAP_PHYSICALWIDTH = 4369, /** The maximum physical height (Y-axis) the Source can acquire (measured in units of ICAP_UNITS). */ ICAP_PHYSICALHEIGHT = 4370, /** * Specifies which value in an image should be interpreted as the darkest "shadow." All values * "darker" than this value will be clipped to this value. */ ICAP_SHADOW = 4371, /** The list of frames the Source will acquire on each page. */ ICAP_FRAMES = 4372, /** * The native optical resolution along the X-axis of the device being controlled by the Source. Most * devices will respond with a single value (TW_ONEVALUE). * This is NOT a list of all resolutions that can be generated by the device. Rather, this is the * resolution of the device's optics. Measured in units of pixels per unit as defined by * ICAP_UNITS (pixels per TWUN_PIXELS yields dimensionless data). */ ICAP_XNATIVERESOLUTION = 4374, /** * The native optical resolution along the Y-axis of the device being controlled by the Source. * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS * yields dimensionless data). */ ICAP_YNATIVERESOLUTION = 4375, /** * All the X-axis resolutions the Source can provide. * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS * yields dimensionless data). That is, when the units are TWUN_PIXELS, both * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources * like to report the actual number of pixels that the device reports, but that response is more * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. */ ICAP_XRESOLUTION = 4376, /** * All the Y-axis resolutions the Source can provide. * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS * yields dimensionless data). That is, when the units are TWUN_PIXELS, both * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources * like to report the actual number of pixels that the device reports, but that response is more * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. */ ICAP_YRESOLUTION = 4377, /** * The maximum number of frames the Source can provide or the application can accept per page. * This is a bounding capability only. It does not establish current or future behavior. */ ICAP_MAXFRAMES = 4378, /** This is used with buffered memory transfers. If TRUE, Source can provide application with tiled image data. */ ICAP_TILES = 4379, /** * Specifies how the bytes in an image are filled by the Source. TWBO_MSBFIRST indicates that the leftmost bit in the byte (usually bit 7) is * the byte's Most Significant Bit. */ ICAP_BITORDER = 4380, /** * Used for CCITT Group 3 2-dimensional compression. The 'K' factor indicates how often the * new compression baseline should be re-established. A value of 2 or 4 is common in facsimile * communication. A value of zero in this field will indicate an infinite K factor—the baseline is * only calculated at the beginning of the transfer. */ ICAP_CCITTKFACTOR = 4381, /** Describes whether the image was captured transmissively or reflectively. */ ICAP_LIGHTPATH = 4382, /** Sense of the pixel whose numeric value is zero (minimum data value). */ ICAP_PIXELFLAVOR = 4383, /** * Allows the application and Source to identify which color data formats are available. There are * two options, "planar" and "chunky." */ ICAP_PLANARCHUNKY = 4384, /** * How the Source can/should rotate the scanned image data prior to transfer. This doesn't use * ICAP_UNITS. It is always measured in degrees. Any applied value is additive with any * rotation specified in ICAP_ORIENTATION. */ ICAP_ROTATION = 4385, /** * For devices that support fixed frame sizes. * Defined sizes match typical page sizes. This specifies the size(s) the Source can/should use to acquire image data. */ ICAP_SUPPORTEDSIZES = 4386, /** * Specifies the dividing line between black and white. This is the value the Source will use to * threshold, if needed, when ICAP_PIXELTYPE=TWPT_BW. * The value is normalized so there are no units of measure associated with this ICAP. */ ICAP_THRESHOLD = 4387, /** * All the X-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. * Do not use values less than or equal to zero. */ ICAP_XSCALING = 4388, /** * All the Y-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. * There are no units inherent with this data as it is normalized to 1.0 being "unscaled." */ ICAP_YSCALING = 4389, /** Used for CCITT data compression only. Indicates the bit order representation of the stored compressed codes. */ ICAP_BITORDERCODES = 4390, /** * Used only for CCITT data compression. Specifies whether the compressed codes' pixel "sense" * will be inverted from the Current value of ICAP_PIXELFLAVOR prior to transfer. */ ICAP_PIXELFLAVORCODES = 4391, /** * Allows the application and Source to agree upon a common set of color descriptors that are * made available by the Source. This ICAP is only useful for JPEG-compressed buffered memory image transfers. */ ICAP_JPEGPIXELTYPE = 4392, /** Used only with CCITT data compression. Specifies the minimum number of words of compressed codes (compressed data) to be transmitted per line. */ ICAP_TIMEFILL = 4394, /** * Specifies the pixel bit depths for the Current value of ICAP_PIXELTYPE. For example, when * using ICAP_PIXELTYPE=TWPT_GRAY, this capability specifies whether this is 8-bit gray or 4-bit gray. * This depth applies to all the data channels (for instance, the R, G, and B channels will all have * this same bit depth for RGB data). */ ICAP_BITDEPTH = 4395, /** * Specifies the Reduction Method the Source should use to reduce the bit depth of the data. Most * commonly used with ICAP_PIXELTYPE=TWPT_BW to reduce gray data to black and white. */ ICAP_BITDEPTHREDUCTION = 4396, /** * If TRUE the Source will issue a MSG_XFERREADY before starting the scan. * Note= The Source may need to scan the image before initiating the transfer. * This is the case if the scanned image is rotated or merged with another scanned image. */ ICAP_UNDEFINEDIMAGESIZE = 4397, /** * Allows the application to query the data source to see if it supports extended image attribute capabilities, * such as Barcode Recognition, Shaded Area Detection and Removal, Skew detection and Removal, and so on. */ ICAP_EXTIMAGEINFO = 4399, /** Allows the source to define the minimum height (Y-axis) that the source can acquire. */ ICAP_MINIMUMHEIGHT = 4400, /** Allows the source to define theminimum width (X-axis) that the source can acquire. */ ICAP_MINIMUMWIDTH = 4401, /** * Use this capability to have the Source discard blank images. The Application never sees these * images during the scanning session. * TWBP_DISABLE – this must be the default state for the Source. It indicates that all images will * be delivered to the Application, none of them will be discarded. * TWBP_AUTO – if this is used, then the Source will decide if an image is blank or not and discard * as appropriate. * If the specified value is a positive number in the range 0 to 231–1, then this capability will use it * as the byte size cutoff point to identify which images are to be discarded. If the size of the image * is less than or equal to this value, then it will be discarded. If the size of the image is greater * than this value, then it will be kept so that it can be transferred to the Application. */ ICAP_AUTODISCARDBLANKPAGES = 4404, /** * Flip rotation is used to properly orient images that flip orientation every other image. * TWFR_BOOK The images to be scanned are viewed in book form, flipping each page from left to right or right to left. * TWFR_FANFOLD The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ ICAP_FLIPROTATION = 4406, /** Turns bar code detection on and off. */ ICAP_BARCODEDETECTIONENABLED = 4407, /** Provides a list of bar code types that can be detected by the current Data Source. */ ICAP_SUPPORTEDBARCODETYPES = 4408, /** The maximum number of supported search priorities. */ ICAP_BARCODEMAXSEARCHPRIORITIES = 4409, /** A prioritized list of bar code types dictating the order in which bar codes will be sought. */ ICAP_BARCODESEARCHPRIORITIES = 4410, /** Restricts bar code searching to certain orientations, or prioritizes one orientation over the other. */ ICAP_BARCODESEARCHMODE = 4411, /** Restricts the number of times a search will be retried if none are found on each page. */ ICAP_BARCODEMAXRETRIES = 4412, /** Restricts the total time spent on searching for a bar code on each page. */ ICAP_BARCODETIMEOUT = 4413, /** When used with CapGet(), returns all camera supported lens zooming range. */ ICAP_ZOOMFACTOR = 4414, /** Turns patch code detection on and off. */ ICAP_PATCHCODEDETECTIONENABLED = 4415, /** A list of patch code types that may be detected by the current Data Source. */ ICAP_SUPPORTEDPATCHCODETYPES = 4416, /** The maximum number of supported search priorities. */ ICAP_PATCHCODEMAXSEARCHPRIORITIES = 4417, /** A prioritized list of patch code types dictating the order in which patch codes will be sought. */ ICAP_PATCHCODESEARCHPRIORITIES = 4418, /** Restricts patch code searching to certain orientations, or prioritizes one orientation over the other. */ ICAP_PATCHCODESEARCHMODE = 4419, /** Restricts the number of times a search will be retried if none are found on each page. */ ICAP_PATCHCODEMAXRETRIES = 4420, /** Restricts the total time spent on searching for a patch code on each page. */ ICAP_PATCHCODETIMEOUT = 4421, /** * For devices that support flash. CapSet() selects the flash to be used (if any). CapGet() reports the current setting. * This capability replaces ICAP_FLASHUSED, which is only able to negotiate the flash being on or off. */ ICAP_FLASHUSED2 = 4422, /** For devices that support image enhancement filtering. This capability selects the algorithm used to improve the quality of the image. */ ICAP_IMAGEFILTER = 4423, /** For devices that support noise filtering. This capability selects the algorithm used to remove noise. */ ICAP_NOISEFILTER = 4424, /** * Overscan is used to scan outside of the boundaries described by ICAP_FRAMES, and is used to help acquire image data that * may be lost because of skewing. * This is primarily of use for transport scanners which rely on edge detection to begin scanning. * If overscan is supported, then the device is capable of scanning in the inter-document gap to get the skewed image information. */ ICAP_OVERSCAN = 4425, /** Turns automatic border detection on and off. */ ICAP_AUTOMATICBORDERDETECTION = 4432, /** Turns automatic deskew correction on and off. */ ICAP_AUTOMATICDESKEW = 4433, /** * When TRUE this capability depends on intelligent features within the Source to automatically * rotate the image to the correct position. */ ICAP_AUTOMATICROTATE = 4434, /** Added 1.9 */ ICAP_JPEGQUALITY = 4435, /** Added 1.91 */ ICAP_FEEDERTYPE = 4436, /** Added 1.91 */ ICAP_ICCPROFILE = 4437, /** Added 2.0 */ ICAP_AUTOSIZE = 4438, /** Added 2.1 */ ICAP_AUTOMATICCROPUSESFRAME = 4439, /** Added 2.1 */ ICAP_AUTOMATICLENGTHDETECTION = 4440, /** Added 2.1 */ ICAP_AUTOMATICCOLORENABLED = 4441, /** Added 2.1 */ ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE = 4442, /** Added 2.1 */ ICAP_COLORMANAGEMENTENABLED = 4443, /** Added 2.1 */ ICAP_IMAGEMERGE = 4444, /** Added 2.1 */ ICAP_IMAGEMERGEHEIGHTTHRESHOLD = 4445, /** Added 2.1 */ ICAP_SUPPORTEDEXTIMAGEINFO = 4446 } /** ICAP_BITORDER values. */ enum EnumDWT_CapBitOrder { TWBO_LSBFIRST = 0, /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ TWBO_MSBFIRST = 1 } /** ICAP_BITDEPTHREDUCTION values. */ enum EnumDWT_CapBitdepthReduction { TWBR_THRESHOLD = 0, TWBR_HALFTONE = 1, TWBR_CUSTHALFTONE = 2, TWBR_DIFFUSION = 3 } /** CAP_FEEDERALIGNMENT values. */ enum EnumDWT_CapFeederAlignment { /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ TWFA_NONE = 0, /** The alignment is to the left. */ TWFA_LEFT = 1, /** * The alignment is centered. This means that the paper will be fed in the middle of * the ICAP_PHYSICALWIDTH of the device. If this is set, then the Application should * calculate any frames with a left offset of zero. */ TWFA_CENTER = 2, /** The alignment is to the right. */ TWFA_RIGHT = 3 } /** CAP_FEEDERORDER values. */ enum EnumDWT_CapFeederOrder { /** The feeder starts with the top of the first page. */ TWFO_FIRSTPAGEFIRST = 0, /** The feeder starts with the top of the last page. */ TWFO_LASTPAGEFIRST = 1 } /** ICAP_FILTER values. */ enum EnumDWT_CapFilterType { TWFT_RED = 0, TWFT_GREEN = 1, TWFT_BLUE = 2, TWFT_NONE = 3, TWFT_WHITE = 4, TWFT_CYAN = 5, TWFT_MAGENTA = 6, TWFT_YELLOW = 7, TWFT_BLACK = 8 } /** ICAP_FLASHUSED2 values. */ enum EnumDWT_CapFlash { TWFL_NONE = 0, TWFL_OFF = 1, TWFL_ON = 2, TWFL_AUTO = 3, TWFL_REDEYE = 4 } /** ICAP_FLIPROTATION values. */ enum EnumDWT_CapFlipRotation { /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ TWFR_BOOK = 0, /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ TWFR_FANFOLD = 1 } /** ICAP_IMAGEFILTER values. */ enum EnumDWT_CapImageFilter { TWIF_NONE = 0, TWIF_AUTO = 1, /** Good for halftone images. */ TWIF_LOWPASS = 2, /** Good for improving text. */ TWIF_BANDPASS = 3, /** Good for improving fine lines. */ TWIF_HIGHPASS = 4, TWIF_TEXT = 3, TWIF_FINELINE = 4 } /** CAP_LANGUAGE values. */ enum EnumDWT_CapLanguage { /** Danish */ TWLG_DAN = 0, /** Dutch */ TWLG_DUT = 1, /** International English */ TWLG_ENG = 2, /** French Canadian */ TWLG_FCF = 3, /** Finnish */ TWLG_FIN = 4, /** French */ TWLG_FRN = 5, /** German */ TWLG_GER = 6, /** Icelandic */ TWLG_ICE = 7, /** Italian */ TWLG_ITN = 8, /** Norwegian */ TWLG_NOR = 9, /** Portuguese */ TWLG_POR = 10, /** Spanish */ TWLG_SPA = 11, /** Swedish */ TWLG_SWE = 12, /** U.S. English */ TWLG_USA = 13, /** Added for 1.8 */ TWLG_USERLOCALE = -1, TWLG_AFRIKAANS = 14, TWLG_ALBANIA = 15, TWLG_ARABIC = 16, TWLG_ARABIC_ALGERIA = 17, TWLG_ARABIC_BAHRAIN = 18, TWLG_ARABIC_EGYPT = 19, TWLG_ARABIC_IRAQ = 20, TWLG_ARABIC_JORDAN = 21, TWLG_ARABIC_KUWAIT = 22, TWLG_ARABIC_LEBANON = 23, TWLG_ARABIC_LIBYA = 24, TWLG_ARABIC_MOROCCO = 25, TWLG_ARABIC_OMAN = 26, TWLG_ARABIC_QATAR = 27, TWLG_ARABIC_SAUDIARABIA = 28, TWLG_ARABIC_SYRIA = 29, TWLG_ARABIC_TUNISIA = 30, /** United Arabic Emirates */ TWLG_ARABIC_UAE = 31, TWLG_ARABIC_YEMEN = 32, TWLG_BASQUE = 33, TWLG_BYELORUSSIAN = 34, TWLG_BULGARIAN = 35, TWLG_CATALAN = 36, TWLG_CHINESE = 37, TWLG_CHINESE_HONGKONG = 38, /** People's Republic of China */ TWLG_CHINESE_PRC = 39, TWLG_CHINESE_SINGAPORE = 40, TWLG_CHINESE_SIMPLIFIED = 41, TWLG_CHINESE_TAIWAN = 42, TWLG_CHINESE_TRADITIONAL = 43, TWLG_CROATIA = 44, TWLG_CZECH = 45, TWLG_DANISH = 0, TWLG_DUTCH = 1, TWLG_DUTCH_BELGIAN = 46, TWLG_ENGLISH = 2, TWLG_ENGLISH_AUSTRALIAN = 47, TWLG_ENGLISH_CANADIAN = 48, TWLG_ENGLISH_IRELAND = 49, TWLG_ENGLISH_NEWZEALAND = 50, TWLG_ENGLISH_SOUTHAFRICA = 51, TWLG_ENGLISH_UK = 52, TWLG_ENGLISH_USA = 13, TWLG_ESTONIAN = 53, TWLG_FAEROESE = 54, TWLG_FARSI = 55, TWLG_FINNISH = 4, TWLG_FRENCH = 5, TWLG_FRENCH_BELGIAN = 56, TWLG_FRENCH_CANADIAN = 3, TWLG_FRENCH_LUXEMBOURG = 57, TWLG_FRENCH_SWISS = 58, TWLG_GERMAN = 6, TWLG_GERMAN_AUSTRIAN = 59, TWLG_GERMAN_LUXEMBOURG = 60, TWLG_GERMAN_LIECHTENSTEIN = 61, TWLG_GERMAN_SWISS = 62, TWLG_GREEK = 63, TWLG_HEBREW = 64, TWLG_HUNGARIAN = 65, TWLG_ICELANDIC = 7, TWLG_INDONESIAN = 66, TWLG_ITALIAN = 8, TWLG_ITALIAN_SWISS = 67, TWLG_JAPANESE = 68, TWLG_KOREAN = 69, TWLG_KOREAN_JOHAB = 70, TWLG_LATVIAN = 71, TWLG_LITHUANIAN = 72, TWLG_NORWEGIAN = 9, TWLG_NORWEGIAN_BOKMAL = 73, TWLG_NORWEGIAN_NYNORSK = 74, TWLG_POLISH = 75, TWLG_PORTUGUESE = 10, TWLG_PORTUGUESE_BRAZIL = 76, TWLG_ROMANIAN = 77, TWLG_RUSSIAN = 78, TWLG_SERBIAN_LATIN = 79, TWLG_SLOVAK = 80, TWLG_SLOVENIAN = 81, TWLG_SPANISH = 11, TWLG_SPANISH_MEXICAN = 82, TWLG_SPANISH_MODERN = 83, TWLG_SWEDISH = 12, TWLG_THAI = 84, TWLG_TURKISH = 85, TWLG_UKRANIAN = 86, /** More stuff added for 1.8 */ TWLG_ASSAMESE = 87, TWLG_BENGALI = 88, TWLG_BIHARI = 89, TWLG_BODO = 90, TWLG_DOGRI = 91, TWLG_GUJARATI = 92, TWLG_HARYANVI = 93, TWLG_HINDI = 94, TWLG_KANNADA = 95, TWLG_KASHMIRI = 96, TWLG_MALAYALAM = 97, TWLG_MARATHI = 98, TWLG_MARWARI = 99, TWLG_MEGHALAYAN = 100, TWLG_MIZO = 101, TWLG_NAGA = 102, TWLG_ORISSI = 103, TWLG_PUNJABI = 104, TWLG_PUSHTU = 105, TWLG_SERBIAN_CYRILLIC = 106, TWLG_SIKKIMI = 107, TWLG_SWEDISH_FINLAND = 108, TWLG_TAMIL = 109, TWLG_TELUGU = 110, TWLG_TRIPURI = 111, TWLG_URDU = 112, TWLG_VIETNAMESE = 113 } /** ICAP_LIGHTPATH values. */ enum EnumDWT_CapLightPath { TWLP_REFLECTIVE = 0, TWLP_TRANSMISSIVE = 1 } /** ICAP_LIGHTSOURCE values. */ enum EnumDWT_CapLightSource { TWLS_RED = 0, TWLS_GREEN = 1, TWLS_BLUE = 2, TWLS_NONE = 3, TWLS_WHITE = 4, TWLS_UV = 5, TWLS_IR = 6 } /** ICAP_NOISEFILTER values. */ enum EnumDWT_CapNoiseFilter { TWNF_NONE = 0, TWNF_AUTO = 1, TWNF_LONEPIXEL = 2, TWNF_MAJORITYRULE = 3 } /** ICAP_ORIENTATION values. */ enum EnumDWT_CapORientation { TWOR_ROT0 = 0, TWOR_ROT90 = 1, TWOR_ROT180 = 2, TWOR_ROT270 = 3, TWOR_PORTRAIT = 0, TWOR_LANDSCAPE = 3, /** 2.0 */ TWOR_AUTO = 4, /** 2.0 */ TWOR_AUTOTEXT = 5, /** 2.0 */ TWOR_AUTOPICTURE = 6 } /** ICAP_OVERSCAN values. */ enum EnumDWT_CapOverscan { TWOV_NONE = 0, TWOV_AUTO = 1, TWOV_TOPBOTTOM = 2, TWOV_LEFTRIGHT = 3, TWOV_ALL = 4 } /** ICAP_PIXELFLAVOR values. */ enum EnumDWT_CapPixelFlavor { /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ TWPF_CHOCOLATE = 0, /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ TWPF_VANILLA = 1 } /** ICAP_PLANARCHUNKY values. */ enum EnumDWT_CapPlanarChunky { TWPC_CHUNKY = 0, TWPC_PLANAR = 1 } /** CAP_PRINTER values. */ enum EnumDWT_CapPrinter { TWPR_IMPRINTERTOPBEFORE = 0, TWPR_IMPRINTERTOPAFTER = 1, TWPR_IMPRINTERBOTTOMBEFORE = 2, TWPR_IMPRINTERBOTTOMAFTER = 3, TWPR_ENDORSERTOPBEFORE = 4, TWPR_ENDORSERTOPAFTER = 5, TWPR_ENDORSERBOTTOMBEFORE = 6, TWPR_ENDORSERBOTTOMAFTER = 7 } /** CAP_PRINTERMODE values. */ enum EnumDWT_CapPrinterMode { /** Specifies that the printed text will consist of a single string. */ TWPM_SINGLESTRING = 0, /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ TWPM_MULTISTRING = 1, /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ TWPM_COMPOUNDSTRING = 2 } /** TWAIN Supported sizes. */ enum EnumDWT_CapSupportedSizes { /** 0 */ TWSS_NONE = 0, /** 1 */ TWSS_A4LETTER = 1, /** 2 */ TWSS_B5LETTER = 2, /** 3 */ TWSS_USLETTER = 3, /** 4 */ TWSS_USLEGAL = 4, /** * Added 1.5 * 5 */ TWSS_A5 = 5, /** 6 */ TWSS_B4 = 6, /** 7 */ TWSS_B6 = 7, /** * Added 1.7 * 9 */ TWSS_USLEDGER = 9, /** 10 */ TWSS_USEXECUTIVE = 10, /** 11 */ TWSS_A3 = 11, /** 12 */ TWSS_B3 = 12, /** 13 */ TWSS_A6 = 13, /** 14 */ TWSS_C4 = 14, /** 15 */ TWSS_C5 = 15, /** 16 */ TWSS_C6 = 16, /** * Added 1.8 * 17 */ TWSS_4A0 = 17, /** 18 */ TWSS_2A0 = 18, /** 19 */ TWSS_A0 = 19, /** 20 */ TWSS_A1 = 20, /** 21 */ TWSS_A2 = 21, /** 1 */ TWSS_A4 = 1, /** 22 */ TWSS_A7 = 22, /** 23 */ TWSS_A8 = 23, /** 24 */ TWSS_A9 = 24, /** 25 */ TWSS_A10 = 25, /** 26 */ TWSS_ISOB0 = 26, /** 27 */ TWSS_ISOB1 = 27, /** 28 */ TWSS_ISOB2 = 28, /** 12 */ TWSS_ISOB3 = 12, /** 6 */ TWSS_ISOB4 = 6, /** 29 */ TWSS_ISOB5 = 29, /** 7 */ TWSS_ISOB6 = 7, /** 30 */ TWSS_ISOB7 = 30, /** 31 */ TWSS_ISOB8 = 31, /** 32 */ TWSS_ISOB9 = 32, /** 33 */ TWSS_ISOB10 = 33, /** 34 */ TWSS_JISB0 = 34, /** 35 */ TWSS_JISB1 = 35, /** 36 */ TWSS_JISB2 = 36, /** 37 */ TWSS_JISB3 = 37, /** 38 */ TWSS_JISB4 = 38, /** 2 */ TWSS_JISB5 = 2, /** 39 */ TWSS_JISB6 = 39, /** 40 */ TWSS_JISB7 = 40, /** 41 */ TWSS_JISB8 = 41, /** 41 */ TWSS_JISB9 = 42, /** 43 */ TWSS_JISB10 = 43, /** 44 */ TWSS_C0 = 44, /** 45 */ TWSS_C1 = 45, /** 46 */ TWSS_C2 = 46, /** 47 */ TWSS_C3 = 47, /** 48 */ TWSS_C7 = 48, /** 49 */ TWSS_C8 = 49, /** 50 */ TWSS_C9 = 50, /** 51 */ TWSS_C10 = 51, /** 52 */ TWSS_USSTATEMENT = 52, /** 53 */ TWSS_BUSINESSCARD = 53, /** 54. Added 2.1 */ TWSS_MAXSIZE = 54 } /** * Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. */ enum EnumDWT_CapType { /** Nothing. */ TWON_NONE = 0, /** * A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS * capability, would use this type of container. */ TWON_ARRAY = 3, /** * This is the most general type because it defines a list of values from which the Current Value can be chosen. * The values do not progress uniformly through a range and there is not a consistent step size between the values. * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). */ TWON_ENUMERATION = 4, /** * A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. * For example, a capability that indicates the presence of a document feeder could be of this type. */ TWON_ONEVALUE = 5, /** * Many capabilities allow users to select their current value from a range of regularly spaced values. * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). */ TWON_RANGE = 6 } /** The kind of data stored in the container. */ enum EnumDWT_CapValueType { TWTY_INT8 = 0, /** Means Item is a TW_INT16 */ TWTY_INT16 = 1, /** Means Item is a TW_INT32 */ TWTY_INT32 = 2, /** Means Item is a TW_UINT8 */ TWTY_UINT8 = 3, /** Means Item is a TW_UINT16 */ TWTY_UINT16 = 4, /** Means Item is a TW_int */ TWTY_int = 5, /** Means Item is a TW_BOOL */ TWTY_BOOL = 6, /** Means Item is a TW_FIX32 */ TWTY_FIX32 = 7, /** Means Item is a TW_FRAME */ TWTY_FRAME = 8, /** Means Item is a TW_STR32 */ TWTY_STR32 = 9, /** Means Item is a TW_STR64 */ TWTY_STR64 = 10, /** Means Item is a TW_STR128 */ TWTY_STR128 = 11, /** Means Item is a TW_STR255 */ TWTY_STR255 = 12 } /** * TWAIN compression types. */ enum EnumDWT_CompressionType { TWCP_BITFIELDS = 12, TWCP_GROUP4 = 5, TWCP_GROUP31D = 2, TWCP_GROUP31DEOL = 3, TWCP_GROUP32D = 4, TWCP_JBIG = 8, TWCP_JPEG = 6, TWCP_JPEG2000 = 14, TWCP_LZW = 7, TWCP_NONE = 0, TWCP_PACKBITS = 1, TWCP_PNG = 9, TWCP_RLE4 = 10, TWCP_RLE8 = 11, TWCP_ZIP = 13 } /** ICAP_DUPLEX values. */ enum EnumDWT_DUPLEX { TWDX_NONE = 0, TWDX_1PASSDUPLEX = 1, TWDX_2PASSDUPLEX = 2 } /** Data source status. */ enum EnumDWT_DataSourceStatus { /** Indicate the data source is closed. */ TWDSS_CLOSED = 0, /** Indicate the data source is opened. */ TWDSS_OPENED = 1, /** Indicate the data source is enabled. */ TWDSS_ENABLED = 2, /** Indicate the data source is acquiring image. */ TWDSS_ACQUIRING = 3 } /** * Driver Type */ enum EnumDWT_Driver { ICA = 3, SANE = 3, TWAIN = 0, TWAIN_AND_ICA = 4, TWAIN_AND_TWAIN64 = 4, TWAIN64 = 5 } /** ICAP_IMAGEFILEFORMAT values. */ enum EnumDWT_FileFormat { /** Used for document imaging. Tagged Image File Format */ TWFF_TIFF = 0, /** Native Macintosh format. Macintosh PICT */ TWFF_PICT = 1, /** Native Microsoft format. Windows Bitmap */ TWFF_BMP = 2, /** Used for document imaging. X-Windows Bitmap */ TWFF_XBM = 3, /** Wrapper for JPEG images. JPEG File Interchange Format */ TWFF_JFIF = 4, /** FlashPix, used with digital cameras. Flash Pix */ TWFF_FPX = 5, /** Multi-page TIFF files. Multi-page tiff file */ TWFF_TIFFMULTI = 6, /** An image format standard intended for use on the web, replaces GIF. */ TWFF_PNG = 7, /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ TWFF_SPIFF = 8, /** File format for use with digital cameras. */ TWFF_EXIF = 9, /** A file format from Adobe. 1.91 NB= this is not PDF/A */ TWFF_PDF = 10, /** A file format from the Joint Photographic Experts Group. 1.91 */ TWFF_JP2 = 11, /** 1.91 */ TWFF_JPN = 12, /** 1.91 */ TWFF_JPX = 13, /** A file format from LizardTech. 1.91 */ TWFF_DEJAVU = 14, /** A file format from Adobe. 2.0 */ TWFF_PDFA = 15, /** 2.1 Adobe PDF/A, Version 2 */ TWFF_PDFA2 = 16 } /** Fit window type */ enum EnumDWT_FitWindowType { /** Fit the image to the width and height of the window */ enumFitWindow = 0, /** Fit the image to the height of the window */ enumFitWindowHeight = 1, /** Fit the image to the width of the window */ enumFitWindowWidth = 2 } /** Image type */ enum EnumDWT_ImageType { /** Native Microsoft format. */ IT_BMP = 0, /** JPEG format. */ IT_JPG = 1, /** Tagged Image File Format. */ IT_TIF = 2, /** An image format standard intended for use on the web, replaces GIF. */ IT_PNG = 3, /** A file format from Adobe. */ IT_PDF = 4, /** All supported formats which are bmp, jpg, tif, png and pdf */ IT_ALL = 5, IT_MULTIPAGE_PDF = 7, IT_MULTIPAGE_TIF = 8 } enum EnumDWT_InitMsg { Info = 1, Error = 2, NotInstalledError = 3, DownloadError = 4, DownloadNotRestartError = 5 } /** The method to do interpolation. */ enum EnumDWT_InterpolationMethod { IM_NEARESTNEIGHBOUR = 1, IM_BILINEAR = 2, IM_BICUBIC = 3, IM_BESTQUALITY = 5 } enum EnumDWT_Language { English = 0, French = 1, Arabic = 2, Spanish = 3, Portuguese = 4, German = 5, Italian = 6, Russian = 7, Chinese = 8 } /** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ enum EnumDWT_MagType { /** Added 2.0 */ TWMD_MICR = 0, /** added 2.1 */ TWMD_RAW = 1, /** added 2.1 */ TWMD_INVALID = 2 } /** * For query the operation that are supported by the data source on a capability . * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT */ enum EnumDWT_MessageType { TWQC_GET = 1, TWQC_SET = 2, TWQC_GETDEFAULT = 4, TWQC_GETCURRENT = 8, TWQC_RESET = 16 } /** * Mouse cursor shape. */ enum EnumDWT_MouseShape { Default = 0, Hand = 1, Crosshair = 2, Zoom = 3 } /** PDF file compression type. */ enum EnumDWT_PDFCompressionType { /** Auto mode. */ PDF_AUTO = 0, /** CCITT Group 3 fax encoding. */ PDF_FAX3 = 1, /** CCITT Group 4 fax encoding */ PDF_FAX4 = 2, /** Lempel Ziv and Welch */ PDF_LZW = 3, /** CCITT modified Huffman RLE. */ PDF_RLE = 4, /** JPEG compression. */ PDF_JPEG = 5 } /** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ enum EnumDWT_PixelType { TWPT_BW = 0, TWPT_GRAY = 1, TWPT_RGB = 2, TWPT_PALLETE = 3, TWPT_CMY = 4, TWPT_CMYK = 5, TWPT_YUV = 6, TWPT_YUVK = 7, TWPT_CIEXYZ = 8, TWPT_LAB = 9, TWPT_SRGB = 10, TWPT_SCRGB = 11, TWPT_INFRARED = 16 } enum EnumDWT_PlatformType { /// Fit the image to the width and height of the window enumWindow = 0, /// Fit the image to the height of the window enumMac = 1, /// Fit the image to the width of the window enumLinux = 2 } enum EnumDWT_ShowMode { /** Activates the window and displays it in its current size and position. */ SW_ACTIVE = 0, /** Maximizes the window */ SW_MAX = 1, /** Minimize the window */ SW_MIN = 2, /** Close the latest opened editor window */ SW_CLOSE = 3, /** Check whether a window exists */ SW_IFLIVE = 4 } /** TIFF file compression type. */ enum EnumDWT_TIFFCompressionType { /** Auto mode. */ TIFF_AUTO = 0, /** Dump mode. */ TIFF_NONE = 1, /** CCITT modified Huffman RLE. */ TIFF_RLE = 2, /** CCITT Group 3 fax encoding. */ TIFF_FAX3 = 3, /** CCITT T.4 (TIFF 6 name). */ TIFF_T4 = 3, /** CCITT Group 4 fax encoding */ TIFF_FAX4 = 4, /** CCITT T.6 (TIFF 6 name). */ TIFF_T6 = 4, /** Lempel Ziv and Welch */ TIFF_LZW = 5, TIFF_JPEG = 7, TIFF_PACKBITS = 32773 } /** ICAP_XFERMECH values. */ enum EnumDWT_TransferMode { /** * Native transfers require the data to be transferred to a single large block of RAM. Therefore, * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. */ TWSX_NATIVE = 0, /** Disk File Mode Transfers. */ TWSX_FILE = 1, /** Buffered Memory Mode Transfers. */ TWSX_MEMORY = 2/*,*/ /** * added 1.91 , not supported in DWT yet */ // TWSX_MEMFILE = 4 } /** ICAP_UNITS values. */ enum EnumDWT_UnitType { TWUN_INCHES = 0, TWUN_CENTIMETERS = 1, TWUN_PICAS = 2, TWUN_POINTS = 3, TWUN_TWIPS = 4, TWUN_PIXELS = 5, TWUN_MILLIMETERS = 6 } enum EnumDWT_UploadDataFormat { Binary = 0, Base64 = 1 } enum Enum_ErrorMessage { FILE_STREAM_ERROR = "File Stream Error= ", PARAMETER_TYPE_ERROR = "Parameter Type not Supported= ", TIMEOUT = "Timeout no Response= " } enum Enum_ImageType { IT_ALL = 5, IT_BMP = 0, IT_DIB = -1, IT_JPG = 1, IT_PNG = 3, IT_RGBA = -2, } enum Enum_ReturnType { RT_AUTO = -1, RT_BASE64 = 2, RT_BINARY = 1, } enum EnumAccompanyingTextRecognitionMode { ATRM_GENERAL = 1, ATRM_SKIP = 0, } enum EnumBinarizationMode { BM_AUTO = 1, BM_LOCAL_BLOCK = 2, BM_SKIP = 0 } enum EnumClarityCalculationMethod { ECCM_CONTRAST = 1, } enum EnumClarityFilterMode { CFM_GENERAL = 1 } enum EnumColourClusteringMode { CCM_AUTO = 1, CCM_GENERAL_HSV = 2, CCM_SKIP = 0, } enum EnumColourConversionMode { CICM_GENERAL = 1, CICM_SKIP = 0, } enum EnumConflictMode { CM_IGNORE = 1, CM_OVERWRITE = 2, } enum EnumDeformationResistingMode { DRM_AUTO = 1, DRM_GENERAL = 2, DRM_SKIP = 0, } enum EnumDPMCodeReadingMode { DPMCRM_AUTO = 1, DPMCRM_GENERAL = 2, DPMCRM_SKIP = 0 } enum EnumGrayscaleTransformationMode { GTM_INVERTED = 1, GTM_ORIGINAL = 2, GTM_SKIP = 0 } enum EnumImagePixelFormat { IPF_ABGR_8888 = 10, IPF_ABGR_16161616 = 11, IPF_ARGB_8888 = 7, IPF_ARGB_16161616 = 9, IPF_BGR_888 = 12, IPF_Binary = 0, IPF_BinaryInverted = 1, IPF_GrayScaled = 2, IPF_NV21 = 3, IPF_RGB_555 = 5, IPF_RGB_565 = 4, IPF_RGB_888 = 6, IPF_RGB_161616 = 8 } enum EnumImagePreprocessingMode { IPM_AUTO = 1, IPM_GENERAL = 2, IPM_GRAY_EQUALIZE = 4, IPM_GRAY_SMOOTH = 8, IPM_MORPHOLOGY = 32, IPM_SHARPEN_SMOOTH = 16, IPM_SKIP = 0 } enum EnumIMResultDataType { IMRDT_CONTOUR = 2, IMRDT_IMAGE = 1, IMRDT_LINESEGMENT = 4, IMRDT_LOCALIZATIONRESULT = 8, IMRDT_QUADRILATERAL = 32, IMRDT_REGIONOFINTEREST = 16 } enum EnumIntermediateResultSavingMode { IRSM_BOTH = 4, IRSM_FILESYSTEM = 2, IRSM_MEMORY = 1 } enum EnumIntermediateResultType { IRT_BINARIZED_IMAGE = 64, IRT_COLOUR_CLUSTERED_IMAGE = 2, IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE = 4, IRT_CONTOUR = 256, IRT_FORM = 1024, IRT_LINE_SEGMENT = 512, IRT_NO_RESULT = 0, IRT_ORIGINAL_IMAGE = 1, IRT_PREDETECTED_QUADRILATERAL = 8192, IRT_PREDETECTED_REGION = 16, IRT_PREPROCESSED_IMAGE = 32, IRT_SEGMENTATION_BLOCK = 2048, IRT_TEXT_ZONE = 128, IRT_TRANSFORMED_GRAYSCALE_IMAGE = 8, IRT_TYPED_BARCODE_ZONE = 4096 } enum EnumLocalizationMode { LM_AUTO = 1, LM_CONNECTED_BLOCKS = 2, LM_LINES = 8, LM_SCAN_DIRECTLY = 16, LM_SKIP = 0, LM_STATISTICS = 4, LM_STATISTICS_MARKS = 32, LM_STATISTICS_POSTAL_CODE = 64 } enum EnumPDFReadingMode { PDFRM_AUTO = 2, PDFRM_RASTER = 1, PDFRM_VECTOR = 4 } enum EnumQRCodeErrorCorrectionLevel { QRECL_ERROR_CORRECTION_H = 0, QRECL_ERROR_CORRECTION_L = 1, QRECL_ERROR_CORRECTION_M = 2, QRECL_ERROR_CORRECTION_Q = 3 } enum EnumRegionPredetectionMode { RPM_AUTO = 1, RPM_GENERAL = 2, RPM_GENERAL_GRAY_CONTRAST = 8, RPM_GENERAL_HSV_CONTRAST = 16, RPM_GENERAL_RGB_CONTRAST = 4, RPM_SKIP = 0 } enum EnumResultCoordinateType { RCT_PERCENTAGE = 2, RCT_PIXEL = 1 } enum EnumResultType { RT_CANDIDATE_TEXT = 2, RT_PARTIAL_TEXT = 3, RT_RAW_TEXT = 1, RT_STANDARD_TEXT = 0 } enum EnumScaleUpMode { SUM_AUTO = 1, SUM_LINEAR_INTERPOLATION = 2, SUM_NEAREST_NEIGHBOUR_INTERPOLATION = 4, SUM_SKIP = 0 } enum EnumTerminatePhase { TP_BARCODE_LOCALIZED = 8, TP_BARCODE_RECOGNIZED = 32, TP_BARCODE_TYPE_DETERMINED = 16, TP_IMAGE_BINARIZED = 4, TP_IMAGE_PREPROCESSED = 2, TP_REGION_PREDETECTED = 1 } enum EnumTextAssistedCorrectionMode { TACM_AUTO = 1, TACM_SKIP = 0, TACM_VERIFYING = 2, TACM_VERIFYING_PATCHING = 4 } enum EnumTextFilterMode { TFM_AUTO = 1, TFM_GENERAL_CONTOUR = 2, TFM_SKIP = 0 } enum EnumTextResultOrderMode { TROM_CONFIDENCE = 1, TROM_FORMAT = 4, TROM_POSITION = 2, TROM_SKIP = 0 } enum EnumTextureDetectionMode { TDM_AUTO = 1, TDM_GENERAL_WIDTH_CONCENTRATION = 2, TDM_SKIP = 0 } }
the_stack
import { borderRadius as borderRadiusTokens, CanvasBorderRadiusKeys, colors as colorTokens, CanvasColor, } from '@workday/canvas-kit-react/tokens'; import { ContentDirection, PartialEmotionCanvasTheme, useTheme, } from '@workday/canvas-kit-react/common'; import {PropertyBorder} from './types'; /** style props to set the border properties */ export type BorderShorthandStyleProps = { /** sets `border` property */ border?: string; /** sets `border-top` property */ borderTop?: string; /** sets `border-right` property (no bidirectional support) */ borderRight?: string; /** sets `border-bottom` property */ borderBottom?: string; /** sets `border-left` property (no bidirectional support) */ borderLeft?: string; }; /** style props to set the border color properties */ export type BorderColorStyleProps = { /** sets `border-color` property */ borderColor?: CanvasColor | (string & {}); /** sets `border-top-color` property */ borderTopColor?: CanvasColor | (string & {}); /** sets `border-right-color` property (no bidirectional support) */ borderRightColor?: CanvasColor | (string & {}); /** sets `border-bottom-color` property */ borderBottomColor?: CanvasColor | (string & {}); /** sets `border-left-color` property (no bidirectional support) */ borderLeftColor?: CanvasColor | (string & {}); }; /** style props to set the border radius properties */ export type BorderRadiusStyleProps = { /** sets `border-radius` property */ borderRadius?: CanvasBorderRadiusKeys | number | (string & {}); /** sets `border-top-left-radius` property */ borderTopLeftRadius?: CanvasBorderRadiusKeys | number | (string & {}); /** sets `border-top-right-radius` property */ borderTopRightRadius?: CanvasBorderRadiusKeys | number | (string & {}); /** sets `border-bottom-left-radius` property */ borderBottomLeftRadius?: CanvasBorderRadiusKeys | number | (string & {}); /** sets `border-bottom-right-radius` property */ borderBottomRightRadius?: CanvasBorderRadiusKeys | number | (string & {}); }; /** style props to set the border style properties */ export type BorderLineStyleProps = { /** sets `border-style` property */ borderStyle?: PropertyBorder; /** sets `border-top-style` property */ borderTopStyle?: PropertyBorder; /** sets `border-right-style` property (no bidirectional support) */ borderRightStyle?: PropertyBorder; /** sets `border-bottom-style` property */ borderBottomStyle?: PropertyBorder; /** sets `border-left-style` property (no bidirectional support) */ borderLeftStyle?: PropertyBorder; }; /** style props to set the border width properties */ export type BorderWidthStyleProps = { /** sets `border-width` property */ borderWidth?: string | number; /** sets `border-top-width` property */ borderTopWidth?: string | number; /** sets `border-right-width` property (no bidirectional support) */ borderRightWidth?: string | number; /** sets `border-bottom-width` property */ borderBottomWidth?: string | number; /** sets `border-left-width` property (no bidirectional support) */ borderLeftWidth?: string | number; }; export type BorderLogicalStyleProps = { /** sets `border-left` property (bidirectional support) */ borderInlineStart?: string; /** sets `border-left-color` property (bidirectional support) */ borderInlineStartColor?: CanvasColor | (string & {}); /** sets `border-left-style` property (bidirectional support) */ borderInlineStartStyle?: PropertyBorder; /** sets `border-left-width` property (bidirectional support) */ borderInlineStartWidth?: string | number; /** sets `border-right` property (bidirectional support) */ borderInlineEnd?: string; /** sets `border-right-color` property (bidirectional support) */ borderInlineEndColor?: CanvasColor | (string & {}); /** sets `border-right-style` property (bidirectional support) */ borderInlineEndStyle?: PropertyBorder; /** sets `border-right-width` property (bidirectional support) */ borderInlineEndWidth?: string | number; }; /** a collection style props for border properties */ export type BorderStyleProps = BorderShorthandStyleProps & BorderColorStyleProps & BorderRadiusStyleProps & BorderLineStyleProps & BorderWidthStyleProps & BorderLogicalStyleProps; // border logical prop handlers const borderInlineStart = (isRTL: boolean) => (isRTL ? 'borderRight' : 'borderLeft'); const borderInlineEnd = (isRTL: boolean) => (isRTL ? 'borderLeft' : 'borderRight'); const borderInlineStartColor = (isRTL: boolean) => (isRTL ? 'borderRightColor' : 'borderLeftColor'); const borderInlineEndColor = (isRTL: boolean) => (isRTL ? 'borderLeftColor' : 'borderRightColor'); const borderInlineStartStyle = (isRTL: boolean) => (isRTL ? 'borderRightStyle' : 'borderLeftStyle'); const borderInlineEndStyle = (isRTL: boolean) => (isRTL ? 'borderLeftStyle' : 'borderRightStyle'); const borderInlineStartWidth = (isRTL: boolean) => (isRTL ? 'borderRightWidth' : 'borderLeftWidth'); const borderInlineEndWidth = (isRTL: boolean) => (isRTL ? 'borderLeftWidth' : 'borderRightWidth'); const borderShorthandProps = { border: 'border', borderTop: 'borderTop', borderRight: 'borderRight', borderBottom: 'borderBottom', borderLeft: 'borderLeft', borderInlineStart, borderInlineEnd, }; const borderColors = { borderColor: 'borderColor', borderTopColor: 'borderTopColor', borderRightColor: 'borderRightColor', borderBottomColor: 'borderBottomColor', borderLeftColor: 'borderLeftColor', borderInlineStartColor, borderInlineEndColor, }; const borderRadii = { borderRadius: 'borderRadius', borderTopLeftRadius: 'borderTopLeftRadius', borderTopRightRadius: 'borderTopRightRadius', borderBottomLeftRadius: 'borderBottomLeftRadius', borderBottomRightRadius: 'borderBottomRightRadius', }; const borderStyles = { borderStyle: 'borderStyle', borderTopStyle: 'borderTopStyle', borderRightStyle: 'borderRightStyle', borderBottomStyle: 'borderBottomStyle', borderLeftStyle: 'borderLeftStyle', borderInlineStartStyle, borderInlineEndStyle, }; const borderWidths = { borderWidth: 'borderWidth', borderTopWidth: 'borderTopWidth', borderRightWidth: 'borderRightWidth', borderBottomWidth: 'borderBottomWidth', borderLeftWidth: 'borderLeftWidth', borderInlineStartWidth, borderInlineEndWidth, }; /** * A style prop function that takes components props and returns border styles. Some props, such as borderRadius and borderColor, are connected to our design tokens. * If no `BorderStyleProps` are found, it returns an empty object. * * @example * // You'll most likely use `border` with low-level, styled components * const BoxExample = () => ( * <Box border={`solid 1px #333333 ${colors.blackPepper400}`}>Hello, border styles!</Box> * ); * */ export function border<P extends BorderStyleProps & {theme?: PartialEmotionCanvasTheme}>(props: P) { // border will always be used within the context of a component, but eslint doesn't know that // eslint-disable-next-line react-hooks/rules-of-hooks const {canvas} = useTheme(props.theme); const isRTL = canvas.direction === ContentDirection.RTL; const styles = {}; for (const key in props) { if (props.hasOwnProperty(key)) { if (key in borderShorthandProps) { const value = props[key as keyof BorderShorthandStyleProps]; let attr: string; if (key === 'borderInlineStart') { attr = borderInlineStart(isRTL); } else if (key === 'borderInlineEnd') { attr = borderInlineEnd(isRTL); } else { attr = borderShorthandProps[key as keyof BorderShorthandStyleProps]; } // @ts-ignore TS doesn't like adding a potentially unknown key to an object, but because we own this object, it's fine. styles[attr] = value; continue; } if (key in borderColors) { const propValue = props[key as keyof BorderColorStyleProps] as CanvasColor | string; const value = colorTokens[propValue as CanvasColor] || propValue; let attr: string; if (key === 'borderInlineStartColor') { attr = borderInlineStartColor(isRTL); } else if (key === 'borderInlineEndColor') { attr = borderInlineEndColor(isRTL); } else { attr = borderColors[key as keyof BorderColorStyleProps]; } // @ts-ignore TS doesn't like adding a potentially unknown key to an object, but because we own this object, it's fine. styles[attr] = value; continue; } if (key in borderRadii) { const propValue = props[key as keyof BorderRadiusStyleProps] as | CanvasBorderRadiusKeys | number | string; const value = borderRadiusTokens[propValue as CanvasBorderRadiusKeys] || propValue; const attr = borderRadii[key as keyof BorderRadiusStyleProps]; // @ts-ignore TS doesn't like adding a potentially unknown key to an object, but because we own this object, it's fine. styles[attr] = value; continue; } if (key in borderStyles) { const value = props[key as keyof BorderLineStyleProps]; let attr: string; if (key === 'borderInlineStartStyle') { attr = borderInlineStartStyle(isRTL); } else if (key === 'borderInlineEndStyle') { attr = borderInlineEndStyle(isRTL); } else { attr = borderStyles[key as keyof BorderLineStyleProps]; } // @ts-ignore TS doesn't like adding a potentially unknown key to an object, but because we own this object, it's fine. styles[attr] = value; continue; } if (key in borderWidths) { const value = props[key as keyof BorderWidthStyleProps]; let attr: string; if (key === 'borderInlineStartWidth') { attr = borderInlineStartWidth(isRTL); } else if (key === 'borderInlineEndWidth') { attr = borderInlineEndWidth(isRTL); } else { attr = borderWidths[key as keyof BorderWidthStyleProps]; } // @ts-ignore TS doesn't like adding a potentially unknown key to an object, but because we own this object, it's fine. styles[attr] = value; } } } return styles; }
the_stack
import { AES, enc, lib, mode, pad, HmacSHA256, PBKDF2, SHA3 } from "crypto-js" export type Encoder = typeof enc.Base64 export type Encoders = typeof enc & { Default: Encoder } export type PlainData = object | string | number | boolean export type PlainText = string export type CipherText = string /** * SimpleCrypto * * @class */ export class SimpleCrypto { private _dataBuffer: string private _encoder: Encoder private _secret: lib.WordArray private readonly _keySize: number private readonly _iterations: number /** * Represent a SimpleCrypto instance * * @constructor * @param {string} secret The secret key for cryptographic process. */ public constructor(secret: string | lib.WordArray) { if (secret === void 0) { throw new Error("SimpleCrypto object MUST BE initialised with a SECRET KEY.") } this._dataBuffer = "" this._encoder = enc.Utf8 this._secret = SHA3(typeof secret === "string" ? secret : secret.toString()) this._keySize = 256 this._iterations = 100 } private static sanitiseData(data: PlainData): PlainText { if (data === void 0 || data === null) { throw new Error("There is no data provided. Process halted.") } const sanitised: string = typeof data === "object" ? JSON.stringify(data) : typeof data === "string" || typeof data === "number" || typeof data === "boolean" ? data.toString() : null if (null === sanitised) { throw new Error("Invalid data type. Only object, string, number and boolean data types are allowed.") } return sanitised } private static transform(src: CipherText): PlainData { if (src.toLowerCase() === "true" || src.toLowerCase() === "false") { return src.toLowerCase() === "true" } try { return JSON.parse(src) } catch (jsonError) { return /^-?[\d.]+(?:e-?\d+)?$/.test(src) && !isNaN(parseFloat(src)) ? parseFloat(src) : src } } /** * Encoders * * Get Encoder instance available. * * @since 2017.10.16 * @access public * * @memberOf SimpleCrypto * * @see WordArray * * @return {Encoders} Returns object of Encoder instances. */ public static get encoders(): Encoders { return { Default: enc.Utf8, ...enc, } } /** * Generate Random * * Generate a random string or WordArray. * * @since 2017.10.16 * @access public * * @memberOf SimpleCrypto * * @see WordArray * * @param {number} length The length of random to be generated. * @param {boolean} expectsWordArray Set to true to return WordArray instance. * Default is false and return a string. * * @return {string | WordArray} Returns a random string or WordArray. */ public static generateRandom(length = 128, expectsWordArray = false): string | lib.WordArray { const random = lib.WordArray.random(length / 8) return expectsWordArray ? random : random.toString() } /** * Generate Random String * * Generate a random string * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @see WordArray * * @param {number} length The length of random to be generated. * * @return {string | WordArray} Returns a random string. */ public static generateRandomString(length = 128): string { return <string>SimpleCrypto.generateRandom(length, false) } /** * Generate Random Word Array * * Generate a random WordArray. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @see WordArray * * @param {number} length The length of random to be generated. * * @return {string | WordArray} Returns a random WordArray. */ public static generateRandomWordArray(length = 128): lib.WordArray { return <lib.WordArray>SimpleCrypto.generateRandom(length, true) } private _decrypt(): PlainData { if (this._dataBuffer.length <= 64) { throw new Error("Invalid cipher text. Decryption halted.") } const salt = enc.Hex.parse(this._dataBuffer.substring(0, 32)) const initialVector = enc.Hex.parse(this._dataBuffer.substring(32, 64)) const encrypted = this._dataBuffer.substring(64, this._dataBuffer.length - 64) const key = PBKDF2(this._secret.toString(), salt, { keySize: this._keySize / 32, iterations: this._iterations, }) const hashedCipherText = this._dataBuffer.substring(this._dataBuffer.length - 64) const cipherText = this._dataBuffer.substring(0, this._dataBuffer.length - 64) if (hashedCipherText != HmacSHA256(cipherText, key).toString()) { throw new Error("Invalid encrypted text received. Decryption halted.") } const decrypted = AES.decrypt(encrypted, key, { iv: initialVector, padding: pad.Pkcs7, mode: mode.CBC, }) return SimpleCrypto.transform(decrypted.toString(SimpleCrypto.encoders.Default)) } private _encrypt(): string { const salt = SimpleCrypto.generateRandom(128, true) const initialVector = SimpleCrypto.generateRandom(128, true) const key = PBKDF2(this._secret.toString(), salt, { keySize: this._keySize / 32, iterations: this._iterations, }) const encrypted = AES.encrypt(this._dataBuffer, key, { iv: initialVector as lib.WordArray, padding: pad.Pkcs7, mode: mode.CBC, }) // Combining the encrypted string with salt and IV to form cipher-text const cipherText = salt.toString() + initialVector.toString() + encrypted.toString() // Generate authentication tag and append that to the cipher-text using the key derived from PBKDF2. // (Optional TODO: Include a module to generate authentication key. Possibly HKDF-SHA256.) const hashedCipherText = HmacSHA256(cipherText, key).toString() return cipherText + hashedCipherText } /** * Decrypt * * Decrypt a encrypted string backs to its proper type, either it JavaScript * object, string, number, or boolean. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @return {string} The decrypted data of the encrypted string. */ public decrypt(): PlainData /** * Decrypt * * Decrypt a encrypted string backs to its proper type, either it JavaScript * object, string, number, or boolean. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @param {string} cipher The encrypted string of the data. * * @return {string} The decrypted data of the encrypted string. */ public decrypt(cipher: string): PlainData /** * Decrypt * * Decrypt a encrypted string backs to its proper type, either it JavaScript * object, string, number, or boolean. * * @since 2020.05.09 * @access public * @deprecated Since version 2.4.0, use decrypt(cipher: CipherText, encoder: Encoder) instead. * * @memberOf SimpleCrypto * * @param {string} cipher The encrypted string of the data. * @param {boolean} expectsObject Setting this to true will return an object instead of string. * * @return {string} The decrypted data of the encrypted string. */ public decrypt(cipher: CipherText, expectsObject: boolean): PlainData /** * Decrypt * * Decrypt a encrypted string backs to its proper type, either it JavaScript * object, string, number, or boolean. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @param {string} cipher The encrypted string of the data. * @param {Encoder} encoder Set the encoding for the string conversion. * * @return {string} The decrypted data of the encrypted string. */ public decrypt(cipher: CipherText, encoder: Encoder): PlainData /** * Decrypt * * Decrypt a encrypted string backs to its proper type, either it JavaScript * object, string, number, or boolean. * * @since 2017.10.16 * @access public * @deprecated Since version 2.4.0, use decrypt(cipher: CipherText, encoder: Encoder) instead. * * @memberOf SimpleCrypto * * @param {string} cipher The encrypted string of the data. * @param {boolean} expectsObject Setting this to true will return an object instead of string. * @param {Encoder} encoder Set the encoding for the string conversion. * * @return {string} The decrypted data of the encrypted string. */ public decrypt(cipher: CipherText, expectsObject: boolean, encoder: Encoder): PlainData public decrypt(cipher?: CipherText, secondArg?: boolean | Encoder, thirdArg?: Encoder): PlainData { const setDecryptionOption = (arg: boolean | Encoder): void => { if (typeof arg !== "boolean") this.setEncoder(arg) } try { if (cipher !== void 0) { this.update(cipher) } if (secondArg !== void 0) { setDecryptionOption(secondArg) } if (thirdArg !== void 0) { setDecryptionOption(thirdArg) } return this._decrypt() } catch (error) { throw error } } /** * Encrypt * * Encrypt the data provided using append() or update. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @return {string} The encrypted string of the data. */ public encrypt(): CipherText /** * Encrypt * * Encrypt any JavaScript object, string, number or boolean. * * @since 2017.10.16 * @access public * * @memberOf SimpleCrypto * * @param {object | string | number | boolean} data The data to be encrypted. * * @return {string} The encrypted string of the data. */ public encrypt(data: PlainData): CipherText public encrypt(data?: PlainData): CipherText { try { if (data !== void 0) { this.update(data) } return this._encrypt() } catch (error) { throw error } } /** * Decrypt Object * * Decrypt a encrypted string and try to convert it back to object. * * @since 2017.10.16 * @access public * @deprecated Since version 2.0.0, use decrypt(cipher: CipherText) instead. * * @memberOf SimpleCrypto * * @see decrypt * * @param {string} cipher The encrypted string of the data. * * @return {string} The decrypted data of the encrypted string in the form * of object. */ public decryptObject(cipher: CipherText): object { return <object>this.update(cipher).decrypt() } /** * Encrypt Object * * Encrypt an object. * * @since 2017.10.16 * @access public * @deprecated Since version 2.0.0, use encrypt(data: PlainData) instead. * * @memberOf SimpleCrypto * * @see encrypt * * @param {object} object The object to be encrypted. * * @return {string} The encrypted string of the object. */ public encryptObject(object: object): string { return this.update(object).encrypt() } /** * Append * * Append the data to be encrypted or decrypted. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @param {object | string | number | boolean} data Data to be encrypted or decrypted. * * @return {SimpleCrypto} Current SimpleCrypto instance. */ public append(data: PlainData): SimpleCrypto { try { this._dataBuffer = this._dataBuffer + SimpleCrypto.sanitiseData(data) return this } catch (error) { throw error } } /** * Update * * Change data to be encrypted or decrypted. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @param {object | string | number | boolean} data Data to be encrypted or decrypted. * * @return {SimpleCrypto} Current SimpleCrypto instance. */ public update(data: PlainData): SimpleCrypto { try { this._dataBuffer = SimpleCrypto.sanitiseData(data) return this } catch (error) { throw error } } /** * Set Encoder * * Change the default encoding type for the decryption process. * * @since 2020.05.09 * @access public * * @memberOf SimpleCrypto * * @param {Encoder} encoder The new Encoder object. * * @return {SimpleCrypto} Current SimpleCrypto instance. */ public setEncoder(encoder: Encoder): SimpleCrypto { /* * TODO: Encoding support is dropped at the moment, both for encryption * and decryption. We should figure out how we have to implement encoding * support in the simplest way possible. * */ this._encoder = encoder return this } /** * Set Secret * * Change the secret key by setting a new one. By changing the secret key, * any encrypted string that encrypted by previous secret key will not be * able to decrypted, unless the secret key is set to the one used to * encrypt the data. * * @since 2017.10.16 * @access public * * @memberOf SimpleCrypto * * @param {string} secret The new secret key as string. * * @return {SimpleCrypto} Current SimpleCrypto instance. */ public setSecret(secret: string | lib.WordArray): SimpleCrypto { this._secret = SHA3(typeof secret === "string" ? secret : secret.toString()) return this } } export default SimpleCrypto
the_stack
import { BackSide, Color, Group, MathUtils, Mesh, MeshBasicMaterial, ShaderMaterial, SphereGeometry } from 'three'; import { Rendering } from '../core'; import { BoxSidesType, CanvasBox } from './canvas-box'; import SkyFragmentShader from './shaders/sky/fragment.glsl'; import SkyVertexShader from './shaders/sky/vertex.glsl'; type SkyOptionsType = { skyOffset: number; voidOffset: number; dimension: number; topColor: string; middleColor: string; bottomColor: string; lerpFactor: number; starsCount: number; moonRadius: number; moonColor: string; sunColor: string; speed: number; checkInterval: number; }; const defaultSkyOptions: SkyOptionsType = { skyOffset: 0, voidOffset: 0, dimension: 6000, // topColor: '#74B3FF', // bottomColor: '#ffffff', topColor: '#222', middleColor: '#222', bottomColor: '#222', lerpFactor: 0.2, starsCount: 300, moonRadius: 20, moonColor: '#e6e2d1', sunColor: '#f8ffb5', speed: 0.08, checkInterval: 4000, }; const STAR_COLORS = [ '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#8589FF', '#FF8585', ]; const VOID_OFFSET = 1200; const SKY_CONFIGS = { hours: { 0: { color: { top: new Color('#000'), middle: new Color('#000'), bottom: new Color('#000'), }, skyOffset: 200, voidOffset: VOID_OFFSET, }, // start of sunrise 600: { color: { top: new Color('#7694CF'), middle: new Color('#B0483A'), bottom: new Color('#222'), }, skyOffset: 100, voidOffset: VOID_OFFSET, }, // end of sunrise, start of day 700: { color: { top: new Color('#73A3FB'), middle: new Color('#B1CCFD'), bottom: new Color('#222'), }, skyOffset: 0, voidOffset: VOID_OFFSET, }, // start of sunset 1700: { color: { top: new Color('#A57A59'), middle: new Color('#FC5935'), bottom: new Color('#222'), }, skyOffset: 100, voidOffset: VOID_OFFSET, }, // end of sunset, back to night 1800: { color: { top: new Color('#000'), middle: new Color('#000'), bottom: new Color('#000'), }, skyOffset: 200, voidOffset: VOID_OFFSET, }, }, }; class Sky { public options: SkyOptionsType; public shadingGeometry: SphereGeometry; public shadingMaterial: ShaderMaterial; public shadingMesh: Mesh; public skyBox: CanvasBox; public tracker = { day: 0, time: 0, last: 0, until: 0, initialized: false, sunlight: 0.1, skyOffset: 0, voidOffset: 0, }; private topColor: Color; private middleColor: Color; private bottomColor: Color; private newTopColor: Color; private newMiddleColor: Color; private newBottomColor: Color; private newTime = -1; private meshGroup = new Group(); constructor(public rendering: Rendering, options: Partial<SkyOptionsType> = {}) { const { checkInterval } = (this.options = { ...defaultSkyOptions, ...options, }); this.createSkyShading(); this.createSkyBox(); rendering.scene.add(this.meshGroup); setInterval(async () => { if (!rendering.engine.network.connected || rendering.engine.tickSpeed === 0) return; const sentTime = Date.now(); const [, serverReceivedTime] = JSON.parse(await rendering.engine.network.fetchData('/time')); const receivedTime = Date.now(); const offset = serverReceivedTime - (sentTime + receivedTime) / 2; this.newTime = this.tracker.time + offset; }, checkInterval); } init = () => { this.paint('sides', 'stars'); this.paint('top', 'stars'); this.paint('top', 'moon'); this.paint('bottom', 'sun'); }; createSkyShading = () => { const { dimension, topColor, middleColor, bottomColor, skyOffset, voidOffset } = this.options; this.topColor = new Color(topColor); this.middleColor = new Color(middleColor); this.bottomColor = new Color(bottomColor); const uniforms = { topColor: { value: this.topColor }, middleColor: { value: this.middleColor }, bottomColor: { value: this.bottomColor }, skyOffset: { value: skyOffset }, voidOffset: { value: voidOffset }, exponent: { value: 0.6 }, exponent2: { value: 1.2 }, }; this.shadingGeometry = new SphereGeometry(dimension); this.shadingMaterial = new ShaderMaterial({ uniforms, vertexShader: SkyVertexShader, fragmentShader: SkyFragmentShader, depthWrite: false, side: BackSide, }); this.shadingMesh = new Mesh(this.shadingGeometry, this.shadingMaterial); this.shadingMesh.frustumCulled = false; this.meshGroup.add(this.shadingMesh); }; createSkyBox = () => { const { dimension } = this.options; this.skyBox = new CanvasBox({ dimension: dimension * 0.9, side: BackSide, width: 512 }); this.skyBox.boxMaterials.forEach((m) => (m.depthWrite = false)); const { mesh } = this.skyBox; mesh.frustumCulled = false; mesh.renderOrder = -1; this.meshGroup.add(mesh); }; setTopColor = (color: Color | string) => { this.newTopColor = new Color(color); }; setBottomColor = (color: Color | string) => { this.newBottomColor = new Color(color); }; paint = (side: BoxSidesType[] | BoxSidesType, art: 'sun' | 'moon' | 'stars' | 'clear') => { const { skyBox } = this; switch (art) { case 'sun': skyBox.paint(side, this.drawSun); break; case 'moon': skyBox.paint(side, this.drawMoon); break; case 'stars': skyBox.paint(side, this.drawStars); break; case 'clear': skyBox.paint(side, this.clear); break; } }; drawMoon = (material: MeshBasicMaterial, phase = 1) => { const canvas = <HTMLCanvasElement>material.map.image; if (!canvas) return; const { moonRadius: radius, moonColor } = this.options; const color = new Color(moonColor); const context = canvas.getContext('2d'); const x = canvas.width / 2; const y = canvas.height / 2; // bg glow context.beginPath(); const grd = context.createRadialGradient( x + radius / 2, y + radius / 2, 1, x + radius / 2, y + radius / 2, radius * 2, ); grd.addColorStop(0, this.rgba(1, 1, 1, 0.3)); grd.addColorStop(1, this.rgba(1, 1, 1, 0)); context.arc(x + radius / 2, y + radius / 2, radius * 2, 0, 2 * Math.PI, false); context.fillStyle = grd; context.fill(); context.closePath(); // clipping region context.save(); context.beginPath(); context.rect(x, y, radius, radius); context.clip(); // moon bg context.beginPath(); context.rect(x, y, radius, radius); context.fillStyle = this.rgba(color.r, color.g, color.b, 1); context.fill(); context.translate(x, y); // lighter inside context.beginPath(); context.rect(4, 4, radius - 8, radius - 8); context.fillStyle = this.rgba(1, 1, 1, 0.8); context.fill(); // moon phase const px = phase * radius * 2 - radius; context.beginPath(); context.rect(px, 0, radius, radius); context.fillStyle = this.rgba(0, 0, 0, 0.8); context.fill(); context.beginPath(); context.rect(2 + px, 2, radius - 4, radius - 4); context.fillStyle = this.rgba(0, 0, 0, 0.9); context.fill(); context.restore(); }; drawStars = (material: MeshBasicMaterial) => { const canvas = <HTMLCanvasElement>material.map.image; if (!canvas) return; const { starsCount } = this.options; const context = canvas.getContext('2d'); const alpha = context.globalAlpha; for (let i = 0; i < starsCount; i++) { context.globalAlpha = Math.random() * 1 + 0.5; context.beginPath(); context.arc( Math.random() * canvas.width, Math.random() * canvas.height, Math.random() * 0.5, 0, 2 * Math.PI, false, ); context.fillStyle = STAR_COLORS[Math.floor(Math.random() * STAR_COLORS.length)]; context.fill(); } context.globalAlpha = alpha; }; drawSun = (material: MeshBasicMaterial, radius = 50) => { const canvas = <HTMLCanvasElement>material.map.image; if (!canvas) return; const { sunColor } = this.options; const context = canvas.getContext('2d'); const color = new Color(sunColor); context.save(); // bg glow context.beginPath(); let x = canvas.width / 2; let y = canvas.height / 2; const grd = context.createRadialGradient(x, y, 1, x, y, radius * 2); grd.addColorStop(0, this.rgba(1, 1, 1, 0.3)); grd.addColorStop(1, this.rgba(1, 1, 1, 0)); context.arc(x, y, radius * 3, 0, 2 * Math.PI, false); context.fillStyle = grd; context.fill(); context.closePath(); // outer sun context.beginPath(); x = canvas.width / 2 - radius / 2; y = canvas.height / 2 - radius / 2; context.rect(x, y, radius, radius); context.fillStyle = this.rgba(color.r, color.g, color.b, 1); context.fill(); context.closePath(); // inner sun context.beginPath(); const r = radius / 1.6; x = canvas.width / 2 - r / 2; y = canvas.height / 2 - r / 2; context.rect(x, y, r, r); context.fillStyle = this.rgba(1, 1, 1, 0.5); context.fill(); context.closePath(); context.restore(); }; clear = (material: MeshBasicMaterial) => { const canvas = <HTMLCanvasElement>material.map.image; if (!canvas) return; const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); }; rgba = (r: number, g: number, b: number, a: number) => { return `rgba(${r * 255}, ${g * 255}, ${b * 255}, ${a})`; }; spin = (rotation: number, isFastForward: boolean) => { this.skyBox.mesh.rotation.z = isFastForward ? rotation : MathUtils.lerp(this.skyBox.mesh.rotation.z, rotation, this.options.lerpFactor); }; tick = (delta = 0, isFastForward = false, overwrittenTick = 0.1) => { const { tracker } = this; if (!tracker.initialized) { this.init(); tracker.initialized = true; } // add speed to time, and spin box meshes const speed = isFastForward ? overwrittenTick : this.rendering.engine.tickSpeed; tracker.time += speed * delta; // sync with server if (this.newTime > 0) { tracker.time = (tracker.time + this.newTime) / 2; this.newTime = -1; } tracker.time = tracker.time % 2400; this.spin(Math.PI * 2 * (tracker.time / 2400), isFastForward); const hour = Math.round(tracker.time / 100) * 100; tracker.last = tracker.time; if (SKY_CONFIGS.hours[hour]) { if (!tracker.until) { const { color, skyOffset, voidOffset } = SKY_CONFIGS.hours[hour]; this.newTopColor = new Color(); this.newMiddleColor = new Color(); this.newBottomColor = new Color(); this.newTopColor.copy(color.top); this.newMiddleColor.copy(color.middle); this.newBottomColor.copy(color.bottom); tracker.skyOffset = skyOffset; tracker.voidOffset = voidOffset; tracker.until = hour + 100; } } if (tracker.until === hour) tracker.until = 0; const sunlightStartTime = 600; const sunlightEndTime = 1800; const sunlightChangeSpan = 200; // turn on sunlight if ( tracker.time >= -sunlightChangeSpan / 2 + sunlightStartTime && tracker.time <= sunlightChangeSpan / 2 + sunlightStartTime ) tracker.sunlight = (tracker.time - (sunlightStartTime - sunlightChangeSpan / 2)) / sunlightChangeSpan; // turn off sunlight if ( tracker.time >= -sunlightChangeSpan / 2 + sunlightEndTime && tracker.time <= sunlightChangeSpan / 2 + sunlightEndTime ) tracker.sunlight = Math.max( 0.1, 1 - (tracker.time - (sunlightEndTime - sunlightChangeSpan / 2)) / sunlightChangeSpan, ); // lerp sunlight const sunlightLerpFactor = 0.008 * speed * delta; const { uSunlightIntensity } = this.rendering.engine.world; uSunlightIntensity.value = MathUtils.lerp(uSunlightIntensity.value, tracker.sunlight, sunlightLerpFactor); const cloudColor = this.rendering.engine.world.clouds.material.uniforms.uCloudColor.value; const cloudColorHSL = cloudColor.getHSL({}); cloudColor.setHSL(cloudColorHSL.h, cloudColorHSL.s, MathUtils.clamp(uSunlightIntensity.value, 0, 1)); const { skyOffset, voidOffset } = this.shadingMaterial.uniforms; skyOffset.value = MathUtils.lerp(skyOffset.value, tracker.skyOffset, sunlightLerpFactor); voidOffset.value = MathUtils.lerp(voidOffset.value, tracker.voidOffset, sunlightLerpFactor); // lerp sky colors ['top', 'right', 'left', 'front', 'back'].forEach((face) => { const mat = this.skyBox.boxMaterials.get(face); if (mat) { mat.opacity = MathUtils.lerp(mat.opacity, 1.2 - tracker.sunlight, sunlightLerpFactor); } }); const colorLerpFactor = 0.006 * speed * delta; if (this.newTopColor) { this.topColor.lerp(this.newTopColor, colorLerpFactor); } if (this.newMiddleColor) { this.middleColor.lerp(this.newMiddleColor, colorLerpFactor); this.rendering.fogNearColor.lerp(this.newMiddleColor, colorLerpFactor); this.rendering.fogFarColor.lerp(this.newMiddleColor, colorLerpFactor); } // reposition sky box to player position const { object } = this.rendering.engine.player.controls; this.meshGroup.position.x = object.position.x; this.meshGroup.position.z = object.position.z; }; } export { Sky };
the_stack
import { BlobServiceClient, newPipeline } from "@azure/storage-blob"; import * as assert from "assert"; import { configLogger } from "../../src/common/Logger"; import BlobTestServerFactory from "../BlobTestServerFactory"; import { generateJWTToken, getUniqueName } from "../testutils"; import { SimpleTokenCredential } from "../simpleTokenCredential"; // Set true to enable debug log configLogger(false); describe("Blob OAuth Basic", () => { const factory = new BlobTestServerFactory(); let server = factory.createServer(false, false, true, "basic"); const baseURL = `https://${server.config.host}:${server.config.port}/devstoreaccount1`; before(async () => { await server.start(); }); after(async () => { await server.close(); await server.clean(); }); it(`Should work with create container @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://storage.azure.com", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); await containerClient.create(); await containerClient.delete(); }); it(`Should not work with invalid JWT token @loki @sql`, async () => { const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential("invalid token"), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); return; } assert.fail(); }); it(`Should work with valid audiences @loki @sql`, async () => { const audiences = [ "https://storage.azure.com", "https://storage.azure.com/", "e406a681-f3d4-42a8-90b6-c2b029497af1", "https://devstoreaccount1.blob.core.windows.net", "https://devstoreaccount1.blob.core.windows.net/", "https://devstoreaccount1.blob.core.chinacloudapi.cn", "https://devstoreaccount1.blob.core.chinacloudapi.cn/", "https://devstoreaccount1.blob.core.usgovcloudapi.net", "https://devstoreaccount1.blob.core.usgovcloudapi.net/", "https://devstoreaccount1.blob.core.cloudapi.de", "https://devstoreaccount1.blob.core.cloudapi.de/" ]; for (const audience of audiences) { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", audience, "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); await containerClient.create(); await containerClient.delete(); } }); it(`Should not work with invalid audiences @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://invalidaccount.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("audience"), true); return; } assert.fail(); }); it(`Should work with valid issuers @loki @sql`, async () => { const issuerPrefixes = [ "https://sts.windows.net/", "https://sts.microsoftonline.de/", "https://sts.chinacloudapi.cn/", "https://sts.windows-ppe.net" ]; for (const issuerPrefix of issuerPrefixes) { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), `${issuerPrefix}/ab1f708d-50f6-404c-a006-d71b2ac7a606/`, "e406a681-f3d4-42a8-90b6-c2b029497af1", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); await containerClient.create(); await containerClient.delete(); } }); it(`Should not work with invalid issuers @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://invalidissuer/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://invalidaccount.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("issuer"), true); return; } assert.fail(); }); it(`Should not work with invalid nbf @loki @sql`, async () => { const token = generateJWTToken( new Date("2119/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("Lifetime"), true); return; } assert.fail(); }); it(`Should not work with invalid exp @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2019/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("expire"), true); return; } assert.fail(); }); it(`Should not work with get container ACL @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); await containerClient.create(); try { await containerClient.getAccessPolicy(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthorizationFailure"), true ); await containerClient.delete(); return; } await containerClient.delete(); assert.fail(); }); it(`Should not work with set container ACL @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( baseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); await containerClient.create(); try { await containerClient.setAccessPolicy("container"); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthorizationFailure"), true ); await containerClient.delete(); return; } await containerClient.delete(); assert.fail(); }); it(`Should not work with HTTP @loki @sql`, async () => { await server.close(); await server.clean(); server = factory.createServer(false, false, false, "basic"); await server.start(); const httpBaseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1`; const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2019/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.blob.core.windows.net", "user_impersonation" ); const serviceClient = new BlobServiceClient( httpBaseURL, newPipeline(new SimpleTokenCredential(token), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } }) ); const containerName: string = getUniqueName("1container-with-dash"); const containerClient = serviceClient.getContainerClient(containerName); try { await containerClient.create(); await containerClient.delete(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("HTTP"), true); return; } assert.fail(); }); });
the_stack
import { JSONPath } from 'jsonpath-plus'; import { KeyStore, Signer } from '../../../types/ExternalInterfaces'; import * as TezosTypes from '../../../types/tezos/TezosChainTypes'; import { TezosMessageUtils } from '../TezosMessageUtil'; import { TezosNodeReader } from '../TezosNodeReader'; import { TezosNodeWriter } from '../TezosNodeWriter'; import { TezosContractUtils } from './TezosContractUtils'; import { TezosConseilClient } from '../../../reporting/tezos/TezosConseilClient' import { ConseilServerInfo } from '../../../types/conseil/QueryTypes'; import { TezosConstants } from '../../../types/tezos/TezosConstants'; import { ContractMapDetailsItem } from '../../../types/conseil/ConseilTezosTypes'; import { TezosParameterFormat } from '../../../types/tezos/TezosChainTypes'; /** The expected checksum for the Wrapped Tezos contracts. */ const CONTRACT_CHECKSUMS = { token: 'd48b45bd77d2300026fe617c5ba7670e', oven: '5e3c30607da21a0fc30f7be61afb15c7', core: '7b9b5b7e7f0283ff6388eb783e23c452' } /** The expected checksum for the Wrapped Tezos scripts. */ const SCRIPT_CHECKSUMS = { // TODO(keefertaylor): Compute this checksum correctly. token: '', // TODO(keefertaylor): Compute this checksum correctly. oven: '', // TODO(keefertaylor): Compute this checksum correctly. core: '' } /** * Property bag containing the results of opening an oven. */ export type OpenOvenResult = { // The operation hash of the request to open an oven. operationHash: string // The address of the new oven contract. ovenAddress: string } export interface WrappedTezosStorage { balanceMap: number; approvalsMap: number; supply: number; administrator: string; paused: boolean; pauseGuardian: string; outcomeMap: number; swapMap: number; } export interface WrappedTezosBalanceRecord { } export interface WrappedTezosApprovalRecord { } export interface WrappedTezosOutcomeRecord { } export interface WrappedTezosSwapRecord { } /** * Types for the Oven Map . * * Key: The oven's address. * Value: The oven owner's address. */ export type OvenMapSchema = { key: string, value: string } /** * Interface for the Wrapped XTZ Token and Oven implementation. * * @see {@link https://forum.tezosagora.org/t/wrapped-tezos/2195|wXTZ on Tezos Agora} * * The token represented by these contracts trades with symbol 'WXTZ' and is specified with 10^-6 precision. Put * simply, 1 XTZ = 1 WXTZ, and 0.000_001 XTZ = 1 Mutez = 0.000_001 WXTZ. * * Canonical Data: * - Delphinet: * - Token Contract: KT1JYf7xjCJAqFDfNpuump9woSMaapy1WcMY * - Core Contract: KT1S98ELFTo6mdMBqhAVbGgKAVgLbdPP3AX8 * - Token Balances Map ID: 14566 * - Oven List Map ID: 14569 * TODO(keefertaylor): Add additional data for mainnet here. * * @author Keefer Taylor, Staker Services Ltd <keefer@stakerdao.com> */ export namespace WrappedTezosHelper { /** * Verifies that contract code for Wrapped Tezos matches the expected code. * * Note: This function processes contracts in the Micheline format. * * @param nodeUrl The URL of the Tezos node which serves data. * @param tokenContractAddress The address of the token contract. * @param ovenContractAddress The address of an oven contract. * @param coreContractAddress The address of the core contract. * @returns A boolean indicating if the code was the expected sum. */ export async function verifyDestination( nodeUrl: string, tokenContractAddress: string, ovenContractAddress: string, coreContractAddress: string ): Promise<boolean> { const tokenMatched = await TezosContractUtils.verifyDestination(nodeUrl, tokenContractAddress, CONTRACT_CHECKSUMS.token) const ovenMatched = await TezosContractUtils.verifyDestination(nodeUrl, ovenContractAddress, CONTRACT_CHECKSUMS.oven) const coreMatched = await TezosContractUtils.verifyDestination(nodeUrl, coreContractAddress, CONTRACT_CHECKSUMS.core) return tokenMatched && ovenMatched && coreMatched } /** * Verifies that Michelson script for Wrapped Tezos contracts matches the expected code. * * Note: This function processes scrips in Michelson format. * * @param tokenScript The script of the token contract. * @param ovenScript The script of an oven contract. * @param coreScript The script of the core contract. * @returns A boolean indicating if the code was the expected sum. */ export function verifyScript( tokenScript: string, ovenScript: string, coreScript: string ): boolean { const tokenMatched = TezosContractUtils.verifyScript(tokenScript, SCRIPT_CHECKSUMS.token) const ovenMatched = TezosContractUtils.verifyScript(ovenScript, SCRIPT_CHECKSUMS.oven) const coreMatched = TezosContractUtils.verifyScript(coreScript, SCRIPT_CHECKSUMS.core) return tokenMatched && ovenMatched && coreMatched } /** * * @param server * @param address */ export async function getSimpleStorage(server: string, address: string): Promise<WrappedTezosStorage> { const storageResult = await TezosNodeReader.getContractStorage(server, address); return { balanceMap: Number(JSONPath({ path: '$.args[1].args[1].int', json: storageResult })[0]), approvalsMap: Number(JSONPath({ path: '$.args[1].args[0].args[1].int', json: storageResult })[0]), supply: Number(JSONPath({ path: '$.args[3].int', json: storageResult })[0]), administrator: JSONPath({ path: '$.args[1].args[0].args[0].string', json: storageResult })[0], paused: (JSONPath({ path: '$.args[2].prim', json: storageResult })[0]).toString().toLowerCase().startsWith('t'), pauseGuardian: JSONPath({ path: '$.args[1].args[2].string', json: storageResult })[0], outcomeMap: Number(JSONPath({ path: '$.args[0].args[0].args[1].int', json: storageResult })[0]), swapMap: Number(JSONPath({ path: '$.args[0].args[1].int', json: storageResult })[0]) }; } /** * Get the balance of WXTZ tokens for an address. * * @param nodeUrl The URL of the Tezos node which serves data. * @param mapId The ID of the BigMap which contains balances. * @param account The account to fetch the token balance for. * @returns The balance of the account. */ export async function getAccountBalance(server: string, mapid: number, account: string): Promise<number> { const packedKey = TezosMessageUtils.encodeBigMapKey(Buffer.from(TezosMessageUtils.writePackedData(account, 'address'), 'hex')); const mapResult = await TezosNodeReader.getValueForBigMapKey(server, mapid, packedKey); if (mapResult === undefined) { return 0 } const numberString = JSONPath({ path: '$.int', json: mapResult }); return Number(numberString); } /** * Transfer some WXTZ between addresses. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param tokenContractAddress The address of the token contract. * @param fee The fee to use. * @param sourceAddress The address which will send tokens. * @param destinationAddress The address which will receive tokens. * @param amount The amount of tokens to send. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A string representing the operation hash. */ export async function transferBalance( nodeUrl: string, signer: Signer, keystore: KeyStore, tokenContractAddress: string, fee: number, sourceAddress: string, destinationAddress: string, amount: number | string, gasLimit: number = 51_300, storageLimit: number = 70 ): Promise<string> { const parameters = `Pair "${sourceAddress}" (Pair "${destinationAddress}" ${amount})`; const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, tokenContractAddress, 0, fee, storageLimit, gasLimit, 'transfer', parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ); return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Deposit XTZ into an oven to mint WXTZ. * * WXTZ will be minted for the owner of the oven, *not* the source address. This allows bakers * to payout delegated ovens. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param ovenAddress The address of the oven contract. * @param fee The fee to use. * @param amountMutez The amount of XTZ to deposit, specified in mutez. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A string representing the operation hash. */ export async function depositToOven( nodeUrl: string, signer: Signer, keystore: KeyStore, ovenAddress: string, fee: number, amountMutez: number, gasLimit: number = 150_000, storageLimit: number = 10 ): Promise<string> { const parameters = 'Unit' const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, ovenAddress, amountMutez, fee, storageLimit, gasLimit, '', parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ) return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Withdraw XTZ from an oven by repaying WXTZ. * * This operation will fail if: * - The sending account is not the oven owner. * - The sending account does not possess the equivalent amount of WXTZ to the withdrawal amount * - The oven has less XTZ in it than is requested to be withdrawn. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param ovenAddress The address of the oven contract. * @param fee The fee to use. * @param amountMutez The amount of XTZ to withdraw, specified in mutez. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A string representing the operation hash. */ export async function withdrawFromOven( nodeUrl: string, signer: Signer, keystore: KeyStore, ovenAddress: string, fee: number, amountMutez: number, gasLimit: number = 121_000, storageLimit: number = 0 ): Promise<string> { const parameters = `${amountMutez}` const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, ovenAddress, 0, fee, storageLimit, gasLimit, 'withdraw', parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ) return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Retrieve a list of all oven addresses a user owns. * * @param serverInfo Connection info for Conseil. * @param coreContractAddress The core contract address * @param ovenOwner The oven owner to search for * @param ovenListBigMapId The BigMap ID of the oven list. */ export async function listOvens( serverInfo: ConseilServerInfo, coreContractAddress: string, ovenOwner: string, ovenListBigMapId: number ): Promise<Array<string>> { // Fetch map data. const mapData = await TezosConseilClient.getBigMapData(serverInfo, coreContractAddress) if (mapData === undefined) { throw new Error("Could not fetch map data!") } // Find the Map that contains the oven list. const { maps } = mapData let ovenListMap: ContractMapDetailsItem | undefined = undefined for (let i = 0; i < maps.length; i++) { if (maps[i].definition.index === ovenListBigMapId) { ovenListMap = maps[i] break } } if (ovenListMap === undefined) { throw new Error("Could not find specified map ID!") } // Conseil reports addresses as quoted michelson encoded hex prefixed // with '0x'. Normalize these to base58check encoded addresses. const { content } = ovenListMap const normalizedOvenList: Array<OvenMapSchema> = content.map((oven: OvenMapSchema) => { return { key: TezosMessageUtils.readAddress(oven.key.replace(/\"/g, '').replace(/\n/, '').replace("0x", "")), value: TezosMessageUtils.readAddress(oven.value.replace(/\"/g, '').replace(/\n/, '').replace("0x", "")) } }) // Filter oven list for ovens belonging to the owner. const ownedOvens = normalizedOvenList.filter((oven: OvenMapSchema): boolean => { return ovenOwner === oven.value }) // Map filtered array to only contain oven addresses. return ownedOvens.map((oven: OvenMapSchema) => { return oven.key }) } /** * Deploy a new oven contract. * * The oven's owner is assigned to the sender's address. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param fee The fee to use. * @param coreAddress The address of the core contract. * @param baker The inital baker for the Oven. If `undefined` the oven will not have an initial baker. Defaults to `undefined`. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A property bag of data about the operation. */ export async function deployOven( nodeUrl: string, signer: Signer, keystore: KeyStore, fee: number, coreAddress: string, baker: string | undefined = undefined, gasLimit: number = 115_000, storageLimit: number = 1100 ): Promise<OpenOvenResult> { const entryPoint = 'runEntrypointLambda' const lambdaName = 'createOven' const bakerParam = baker !== undefined ? `Some "${baker}"` : 'None' const bytes = TezosMessageUtils.writePackedData(`Pair ${bakerParam} "${keystore.publicKeyHash}"`, 'pair (option key_hash) address', TezosParameterFormat.Michelson) const parameters = `Pair "${lambdaName}" 0x${bytes}` const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, coreAddress, 0, fee, storageLimit, gasLimit, entryPoint, parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ) const operationHash = TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); const ovenAddress = TezosMessageUtils.calculateContractAddress(operationHash, 0) return { operationHash, ovenAddress } } /** * Set the baker for an oven. * * This operation will fail if the sender is not the oven owner. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param fee The fee to use. * @param ovenAddress The address of the oven contract. * @param bakerAddress The address of the baker for the oven. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A string representing the operation hash. */ export async function setOvenBaker( nodeUrl: string, signer: Signer, keystore: KeyStore, fee: number, ovenAddress: string, bakerAddress: string, gasLimit: number = 23_500, storageLimit: number = 0, ): Promise<string> { const parameters = `Some "${bakerAddress}"` const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, ovenAddress, 0, fee, storageLimit, gasLimit, 'setDelegate', parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ) return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } /** * Clear the baker for an oven. * * This operation will fail if the sender is not the oven owner. * * @param nodeUrl The URL of the Tezos node which serves data. * @param signer A Signer for the sourceAddress. * @param keystore A Keystore for the sourceAddress. * @param fee The fee to use. * @param ovenAddress The address of the oven contract. * @param gasLimit The gas limit to use. * @param storageLimit The storage limit to use. * @returns A string representing the operation hash. */ export async function clearOvenBaker( nodeUrl: string, signer: Signer, keystore: KeyStore, fee: number, ovenAddress: string, gasLimit: number = 23_500, storageLimit: number = 0, ): Promise<string> { const parameters = `None` const nodeResult = await TezosNodeWriter.sendContractInvocationOperation( nodeUrl, signer, keystore, ovenAddress, 0, fee, storageLimit, gasLimit, 'setDelegate', parameters, TezosTypes.TezosParameterFormat.Michelson, TezosConstants.HeadBranchOffset, true ) return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID); } }
the_stack
import { HttpResponseError } from '@taquito/http-utils'; import { DerivationType } from '@taquito/ledger-signer'; import { localForger } from '@taquito/local-forging'; import { InMemorySigner } from '@taquito/signer'; import { CompositeForger, RpcForger, Signer, TezosOperationError, TezosToolkit } from '@taquito/taquito'; import * as TaquitoUtils from '@taquito/utils'; import { LedgerTempleBridgeTransport } from '@temple-wallet/ledger-bridge'; import * as Bip39 from 'bip39'; import * as Ed25519 from 'ed25519-hd-key'; import { getMessage } from 'lib/i18n'; import { PublicError } from 'lib/temple/back/defaults'; import { TempleLedgerSigner } from 'lib/temple/back/ledger-signer'; import { encryptAndSaveMany, encryptAndSaveManyLegacy, fetchAndDecryptOne, fetchAndDecryptOneLegacy, getPlain, isStored, isStoredLegacy, removeMany, removeManyLegacy, savePlain } from 'lib/temple/back/safe-storage'; import { formatOpParamsBeforeSend, loadFastRpcClient, michelEncoder, transformHttpResponseError } from 'lib/temple/helpers'; import { isLedgerLiveEnabled } from 'lib/temple/ledger-live'; import * as Passworder from 'lib/temple/passworder'; import { clearStorage } from 'lib/temple/reset'; import { TempleAccount, TempleAccountType, TempleContact, TempleSettings } from 'lib/temple/types'; const TEZOS_BIP44_COINTYPE = 1729; const STORAGE_KEY_PREFIX = 'vault'; const DEFAULT_SETTINGS: TempleSettings = {}; enum StorageEntity { Check = 'check', MigrationLevel = 'migration', Mnemonic = 'mnemonic', AccPrivKey = 'accprivkey', AccPubKey = 'accpubkey', Accounts = 'accounts', Settings = 'settings', LegacyMigrationLevel = 'mgrnlvl' } const checkStrgKey = createStorageKey(StorageEntity.Check); const migrationLevelStrgKey = createStorageKey(StorageEntity.MigrationLevel); const mnemonicStrgKey = createStorageKey(StorageEntity.Mnemonic); const accPrivKeyStrgKey = createDynamicStorageKey(StorageEntity.AccPrivKey); const accPubKeyStrgKey = createDynamicStorageKey(StorageEntity.AccPubKey); const accountsStrgKey = createStorageKey(StorageEntity.Accounts); const settingsStrgKey = createStorageKey(StorageEntity.Settings); const legacyMigrationLevelStrgKey = createStorageKey(StorageEntity.LegacyMigrationLevel); export class Vault { static async isExist() { const stored = await isStored(checkStrgKey); if (stored) return stored; return isStoredLegacy(checkStrgKey); } static async setup(password: string) { return withError('Failed to unlock wallet', async () => { await Vault.runMigrations(password); const passKey = await Vault.toValidPassKey(password); return new Vault(passKey); }); } static async spawn(password: string, mnemonic?: string) { return withError('Failed to create wallet', async () => { if (!mnemonic) { mnemonic = Bip39.generateMnemonic(128); } const seed = Bip39.mnemonicToSeedSync(mnemonic); const hdAccIndex = 0; const accPrivateKey = seedToHDPrivateKey(seed, hdAccIndex); const [accPublicKey, accPublicKeyHash] = await getPublicKeyAndHash(accPrivateKey); const initialAccount: TempleAccount = { type: TempleAccountType.HD, name: 'Account 1', publicKeyHash: accPublicKeyHash, hdIndex: hdAccIndex }; const newAccounts = [initialAccount]; const passKey = await Passworder.generateKey(password); await clearStorage(); await encryptAndSaveMany( [ [checkStrgKey, generateCheck()], [mnemonicStrgKey, mnemonic], [accPrivKeyStrgKey(accPublicKeyHash), accPrivateKey], [accPubKeyStrgKey(accPublicKeyHash), accPublicKey], [accountsStrgKey, newAccounts] ], passKey ); await savePlain(migrationLevelStrgKey, MIGRATIONS.length); }); } static async runMigrations(password: string) { await Vault.assertValidPassword(password); let migrationLevel: number; const legacyMigrationLevelStored = await isStoredLegacy(legacyMigrationLevelStrgKey); if (legacyMigrationLevelStored) { migrationLevel = await withError('Invalid password', async () => { const legacyPassKey = await Passworder.generateKeyLegacy(password); return fetchAndDecryptOneLegacy<number>(legacyMigrationLevelStrgKey, legacyPassKey); }); } else { const saved = await getPlain<number>(migrationLevelStrgKey); migrationLevel = saved ?? 0; /** * The code below is a fix for production issue that occurred * due to an incorrect migration to the new migration type. * * The essence of the problem: * if you enter the password incorrectly after the upgrade, * the migration will not work (as it should), * but it will save that it passed. * And the next unlock attempt will go on a new path. * * Solution: * Check if there is an legacy version of checkStrgKey field in storage * and if there is both it and new migration record, * then overwrite migration level. */ const legacyCheckStored = await isStoredLegacy(checkStrgKey); if (saved !== undefined && legacyCheckStored) { // Override migration level, force migrationLevel = 3; } } try { const migrationsToRun = MIGRATIONS.filter((_m, i) => i >= migrationLevel); if (migrationsToRun.length === 0) { return; } for (const migrate of migrationsToRun) { await migrate(password); } } catch (err: any) { console.error(err); } finally { if (legacyMigrationLevelStored) { await removeManyLegacy([legacyMigrationLevelStrgKey]); } await savePlain(migrationLevelStrgKey, MIGRATIONS.length); } } static async revealMnemonic(password: string) { const passKey = await Vault.toValidPassKey(password); return withError('Failed to reveal seed phrase', () => fetchAndDecryptOne<string>(mnemonicStrgKey, passKey)); } static async revealPrivateKey(accPublicKeyHash: string, password: string) { const passKey = await Vault.toValidPassKey(password); return withError('Failed to reveal private key', async () => { const privateKeySeed = await fetchAndDecryptOne<string>(accPrivKeyStrgKey(accPublicKeyHash), passKey); const signer = await createMemorySigner(privateKeySeed); return signer.secretKey(); }); } static async removeAccount(accPublicKeyHash: string, password: string) { const passKey = await Vault.toValidPassKey(password); return withError('Failed to remove account', async doThrow => { const allAccounts = await fetchAndDecryptOne<TempleAccount[]>(accountsStrgKey, passKey); const acc = allAccounts.find(a => a.publicKeyHash === accPublicKeyHash); if (!acc || acc.type === TempleAccountType.HD) { doThrow(); } const newAllAcounts = allAccounts.filter(acc => acc.publicKeyHash !== accPublicKeyHash); await encryptAndSaveMany([[accountsStrgKey, newAllAcounts]], passKey); await removeMany([accPrivKeyStrgKey(accPublicKeyHash), accPubKeyStrgKey(accPublicKeyHash)]); return newAllAcounts; }); } private static toValidPassKey(password: string) { return withError('Invalid password', async doThrow => { const passKey = await Passworder.generateKey(password); try { await fetchAndDecryptOne<any>(checkStrgKey, passKey); } catch (err: any) { console.log(err); doThrow(); } return passKey; }); } private static assertValidPassword(password: string) { return withError('Invalid password', async () => { const legacyCheckStored = await isStoredLegacy(checkStrgKey); if (legacyCheckStored) { const legacyPassKey = await Passworder.generateKeyLegacy(password); await fetchAndDecryptOneLegacy<any>(checkStrgKey, legacyPassKey); } else { const passKey = await Passworder.generateKey(password); await fetchAndDecryptOne<any>(checkStrgKey, passKey); } }); } constructor(private passKey: CryptoKey) {} revealPublicKey(accPublicKeyHash: string) { return withError('Failed to reveal public key', () => fetchAndDecryptOne<string>(accPubKeyStrgKey(accPublicKeyHash), this.passKey) ); } fetchAccounts() { return fetchAndDecryptOne<TempleAccount[]>(accountsStrgKey, this.passKey); } async fetchSettings() { let saved; try { saved = await fetchAndDecryptOne<TempleSettings>(settingsStrgKey, this.passKey); } catch {} return saved ? { ...DEFAULT_SETTINGS, ...saved } : DEFAULT_SETTINGS; } async createHDAccount(name?: string, hdAccIndex?: number): Promise<TempleAccount[]> { return withError('Failed to create account', async () => { const [mnemonic, allAccounts] = await Promise.all([ fetchAndDecryptOne<string>(mnemonicStrgKey, this.passKey), this.fetchAccounts() ]); const seed = Bip39.mnemonicToSeedSync(mnemonic); if (!hdAccIndex) { const allHDAccounts = allAccounts.filter(a => a.type === TempleAccountType.HD); hdAccIndex = allHDAccounts.length; } const accPrivateKey = seedToHDPrivateKey(seed, hdAccIndex); const [accPublicKey, accPublicKeyHash] = await getPublicKeyAndHash(accPrivateKey); const accName = name || getNewAccountName(allAccounts); if (allAccounts.some(a => a.publicKeyHash === accPublicKeyHash)) { return this.createHDAccount(accName, hdAccIndex + 1); } const newAccount: TempleAccount = { type: TempleAccountType.HD, name: accName, publicKeyHash: accPublicKeyHash, hdIndex: hdAccIndex }; const newAllAcounts = concatAccount(allAccounts, newAccount); await encryptAndSaveMany( [ [accPrivKeyStrgKey(accPublicKeyHash), accPrivateKey], [accPubKeyStrgKey(accPublicKeyHash), accPublicKey], [accountsStrgKey, newAllAcounts] ], this.passKey ); return newAllAcounts; }); } async importAccount(accPrivateKey: string, encPassword?: string) { const errMessage = 'Failed to import account.\nThis may happen because provided Key is invalid'; return withError(errMessage, async () => { const allAccounts = await this.fetchAccounts(); const signer = await createMemorySigner(accPrivateKey, encPassword); const [realAccPrivateKey, accPublicKey, accPublicKeyHash] = await Promise.all([ signer.secretKey(), signer.publicKey(), signer.publicKeyHash() ]); const newAccount: TempleAccount = { type: TempleAccountType.Imported, name: getNewAccountName(allAccounts), publicKeyHash: accPublicKeyHash }; const newAllAcounts = concatAccount(allAccounts, newAccount); await encryptAndSaveMany( [ [accPrivKeyStrgKey(accPublicKeyHash), realAccPrivateKey], [accPubKeyStrgKey(accPublicKeyHash), accPublicKey], [accountsStrgKey, newAllAcounts] ], this.passKey ); return newAllAcounts; }); } async importMnemonicAccount(mnemonic: string, password?: string, derivationPath?: string) { return withError('Failed to import account', async () => { let seed; try { seed = Bip39.mnemonicToSeedSync(mnemonic, password); } catch (_err) { throw new PublicError('Invalid Mnemonic or Password'); } if (derivationPath) { seed = deriveSeed(seed, derivationPath); } const privateKey = seedToPrivateKey(seed); return this.importAccount(privateKey); }); } async importFundraiserAccount(email: string, password: string, mnemonic: string) { return withError('Failed to import fundraiser account', async () => { const seed = Bip39.mnemonicToSeedSync(mnemonic, `${email}${password}`); const privateKey = seedToPrivateKey(seed); return this.importAccount(privateKey); }); } async importManagedKTAccount(accPublicKeyHash: string, chainId: string, owner: string) { return withError('Failed to import Managed KT account', async () => { const allAccounts = await this.fetchAccounts(); const newAccount: TempleAccount = { type: TempleAccountType.ManagedKT, name: getNewAccountName( allAccounts.filter(({ type }) => type === TempleAccountType.ManagedKT), 'defaultManagedKTAccountName' ), publicKeyHash: accPublicKeyHash, chainId, owner }; const newAllAcounts = concatAccount(allAccounts, newAccount); await encryptAndSaveMany([[accountsStrgKey, newAllAcounts]], this.passKey); return newAllAcounts; }); } async importWatchOnlyAccount(accPublicKeyHash: string, chainId?: string) { return withError('Failed to import Watch Only account', async () => { const allAccounts = await this.fetchAccounts(); const newAccount: TempleAccount = { type: TempleAccountType.WatchOnly, name: getNewAccountName( allAccounts.filter(({ type }) => type === TempleAccountType.WatchOnly), 'defaultWatchOnlyAccountName' ), publicKeyHash: accPublicKeyHash, chainId }; const newAllAcounts = concatAccount(allAccounts, newAccount); await encryptAndSaveMany([[accountsStrgKey, newAllAcounts]], this.passKey); return newAllAcounts; }); } async createLedgerAccount(name: string, derivationPath?: string, derivationType?: DerivationType) { return withError('Failed to connect Ledger account', async () => { if (!derivationPath) derivationPath = getMainDerivationPath(0); const { signer, cleanup } = await createLedgerSigner(derivationPath, derivationType); try { const accPublicKey = await signer.publicKey(); const accPublicKeyHash = await signer.publicKeyHash(); const newAccount: TempleAccount = { type: TempleAccountType.Ledger, name, publicKeyHash: accPublicKeyHash, derivationPath, derivationType }; const allAccounts = await this.fetchAccounts(); const newAllAcounts = concatAccount(allAccounts, newAccount); await encryptAndSaveMany( [ [accPubKeyStrgKey(accPublicKeyHash), accPublicKey], [accountsStrgKey, newAllAcounts] ], this.passKey ); return newAllAcounts; } finally { cleanup(); } }); } async editAccountName(accPublicKeyHash: string, name: string) { return withError('Failed to edit account name', async () => { const allAccounts = await this.fetchAccounts(); if (!allAccounts.some(acc => acc.publicKeyHash === accPublicKeyHash)) { throw new PublicError('Account not found'); } if (allAccounts.some(acc => acc.publicKeyHash !== accPublicKeyHash && acc.name === name)) { throw new PublicError('Account with same name already exist'); } const newAllAcounts = allAccounts.map(acc => (acc.publicKeyHash === accPublicKeyHash ? { ...acc, name } : acc)); await encryptAndSaveMany([[accountsStrgKey, newAllAcounts]], this.passKey); return newAllAcounts; }); } async updateSettings(settings: Partial<TempleSettings>) { return withError('Failed to update settings', async () => { const current = await this.fetchSettings(); const newSettings = { ...current, ...settings }; await encryptAndSaveMany([[settingsStrgKey, newSettings]], this.passKey); return newSettings; }); } async sign(accPublicKeyHash: string, bytes: string, watermark?: string) { return withError('Failed to sign', () => this.withSigner(accPublicKeyHash, async signer => { const watermarkBuf = watermark ? TaquitoUtils.hex2buf(watermark) : undefined; return signer.sign(bytes, watermarkBuf); }) ); } async sendOperations(accPublicKeyHash: string, rpc: string, opParams: any[]) { return this.withSigner(accPublicKeyHash, async signer => { const batch = await withError('Failed to send operations', async () => { const tezos = new TezosToolkit(loadFastRpcClient(rpc)); tezos.setSignerProvider(signer); tezos.setForgerProvider(new CompositeForger([tezos.getFactory(RpcForger)(), localForger])); tezos.setPackerProvider(michelEncoder); return tezos.contract.batch(opParams.map(formatOpParamsBeforeSend)); }); try { return await batch.send(); } catch (err: any) { console.error(err); switch (true) { case err instanceof PublicError: case err instanceof TezosOperationError: throw err; case err instanceof HttpResponseError: throw transformHttpResponseError(err); default: throw new Error(`Failed to send operations. ${err.message}`); } } }); } private async withSigner<T>(accPublicKeyHash: string, factory: (signer: Signer) => Promise<T>) { const { signer, cleanup } = await this.getSigner(accPublicKeyHash); try { return await factory(signer); } finally { cleanup(); } } private async getSigner(accPublicKeyHash: string) { const allAccounts = await this.fetchAccounts(); const acc = allAccounts.find(a => a.publicKeyHash === accPublicKeyHash); if (!acc) { throw new PublicError('Account not found'); } switch (acc.type) { case TempleAccountType.Ledger: const publicKey = await this.revealPublicKey(accPublicKeyHash); return createLedgerSigner(acc.derivationPath, acc.derivationType, publicKey, accPublicKeyHash); case TempleAccountType.WatchOnly: throw new PublicError('Cannot sign Watch-only account'); default: const privateKey = await fetchAndDecryptOne<string>(accPrivKeyStrgKey(accPublicKeyHash), this.passKey); return createMemorySigner(privateKey).then(signer => ({ signer, cleanup: () => {} })); } } } /** * Migrations * * -> -> -> */ const MIGRATIONS = [ // [1] Fix derivation async (password: string) => { const passKey = await Passworder.generateKeyLegacy(password); const [mnemonic, accounts] = await Promise.all([ fetchAndDecryptOneLegacy<string>(mnemonicStrgKey, passKey), fetchAndDecryptOneLegacy<TempleAccount[]>(accountsStrgKey, passKey) ]); const migratedAccounts = accounts.map(acc => acc.type === TempleAccountType.HD ? { ...acc, type: TempleAccountType.Imported } : acc ); const seed = Bip39.mnemonicToSeedSync(mnemonic); const hdAccIndex = 0; const accPrivateKey = seedToHDPrivateKey(seed, hdAccIndex); const [accPublicKey, accPublicKeyHash] = await getPublicKeyAndHash(accPrivateKey); const newInitialAccount: TempleAccount = { type: TempleAccountType.HD, name: getNewAccountName(accounts), publicKeyHash: accPublicKeyHash, hdIndex: hdAccIndex }; const newAccounts = [newInitialAccount, ...migratedAccounts]; await encryptAndSaveManyLegacy( [ [accPrivKeyStrgKey(accPublicKeyHash), accPrivateKey], [accPubKeyStrgKey(accPublicKeyHash), accPublicKey], [accountsStrgKey, newAccounts] ], passKey ); }, // [2] Add hdIndex prop to HD Accounts async (password: string) => { const passKey = await Passworder.generateKeyLegacy(password); const accounts = await fetchAndDecryptOneLegacy<TempleAccount[]>(accountsStrgKey, passKey); let hdAccIndex = 0; const newAccounts = accounts.map(acc => acc.type === TempleAccountType.HD ? { ...acc, hdIndex: hdAccIndex++ } : acc ); await encryptAndSaveManyLegacy([[accountsStrgKey, newAccounts]], passKey); }, // [3] Improve token managing flow // Migrate from tokens{netId}: TempleToken[] + hiddenTokens{netId}: TempleToken[] // to tokens{chainId}: TempleToken[] async () => { // The code base for this migration has been removed // because it is no longer needed, // but this migration is required for version compatibility. }, // [4] Improve crypto security // Migrate legacy crypto storage // New crypto updates: // - Use password hash in memory when unlocked(instead of plain password) // - Wrap storage keys in sha256(instead of plain) // - Concat storage values to bytes(instead of json) // - Increase PBKDF rounds async (password: string) => { const legacyPassKey = await Passworder.generateKeyLegacy(password); const fetchLegacySafe = async <T>(storageKey: string) => { try { return await fetchAndDecryptOneLegacy<T>(storageKey, legacyPassKey); } catch { return undefined; } }; let [mnemonic, accounts, settings] = await Promise.all([ fetchLegacySafe<string>(mnemonicStrgKey), fetchLegacySafe<TempleAccount[]>(accountsStrgKey), fetchLegacySafe<TempleSettings>(settingsStrgKey) ]); // Address book contacts migration const contacts = await getPlain<TempleContact[]>('contacts'); settings = { ...settings, contacts }; const accountsStrgKeys = accounts! .map(acc => [accPrivKeyStrgKey(acc.publicKeyHash), accPubKeyStrgKey(acc.publicKeyHash)]) .flat(); const accountsStrgValues = await Promise.all(accountsStrgKeys.map(fetchLegacySafe)); const toSave = [ [checkStrgKey, generateCheck()], [mnemonicStrgKey, mnemonic], [accountsStrgKey, accounts], [settingsStrgKey, settings], ...accountsStrgKeys.map((key, i) => [key, accountsStrgValues[i]]) ].filter(([_key, value]) => value !== undefined) as [string, any][]; // Save new storage items const passKey = await Passworder.generateKey(password); await encryptAndSaveMany(toSave, passKey); // Remove old await removeManyLegacy([...toSave.map(([key]) => key), 'contacts']); } ]; /** * Misc */ function generateCheck() { return Bip39.generateMnemonic(128); } function removeMFromDerivationPath(dPath: string) { return dPath.startsWith('m/') ? dPath.substring(2) : dPath; } function concatAccount(current: TempleAccount[], newOne: TempleAccount) { if (current.every(a => a.publicKeyHash !== newOne.publicKeyHash)) { return [...current, newOne]; } throw new PublicError('Account already exists'); } function getNewAccountName(allAccounts: TempleAccount[], templateI18nKey = 'defaultAccountName') { return getMessage(templateI18nKey, String(allAccounts.length + 1)); } async function getPublicKeyAndHash(privateKey: string) { const signer = await createMemorySigner(privateKey); return Promise.all([signer.publicKey(), signer.publicKeyHash()]); } async function createMemorySigner(privateKey: string, encPassword?: string) { return InMemorySigner.fromSecretKey(privateKey, encPassword); } let transport: LedgerTempleBridgeTransport; async function createLedgerSigner( derivationPath: string, derivationType?: DerivationType, publicKey?: string, publicKeyHash?: string ) { const ledgerLiveEnabled = await isLedgerLiveEnabled(); if (!transport || ledgerLiveEnabled !== transport.ledgerLiveUsed) { await transport?.close(); const bridgeUrl = process.env.TEMPLE_WALLET_LEDGER_BRIDGE_URL; if (!bridgeUrl) { throw new Error("Require a 'TEMPLE_WALLET_LEDGER_BRIDGE_URL' environment variable to be set"); } transport = await LedgerTempleBridgeTransport.open(bridgeUrl); if (ledgerLiveEnabled) { transport.useLedgerLive(); } } // After Ledger Live bridge was setuped, we don't close transport // Probably we do not need to close it // But if we need, we can close it after not use timeout const cleanup = () => {}; // transport.close(); const signer = new TempleLedgerSigner( transport, removeMFromDerivationPath(derivationPath), true, derivationType, publicKey, publicKeyHash ); return { signer, cleanup }; } function seedToHDPrivateKey(seed: Buffer, hdAccIndex: number) { return seedToPrivateKey(deriveSeed(seed, getMainDerivationPath(hdAccIndex))); } function getMainDerivationPath(accIndex: number) { return `m/44'/${TEZOS_BIP44_COINTYPE}'/${accIndex}'/0'`; } function seedToPrivateKey(seed: Buffer) { return TaquitoUtils.b58cencode(seed.slice(0, 32), TaquitoUtils.prefix.edsk2); } function deriveSeed(seed: Buffer, derivationPath: string) { try { const { key } = Ed25519.derivePath(derivationPath, seed.toString('hex')); return key; } catch (_err) { throw new PublicError('Invalid derivation path'); } } function createStorageKey(id: StorageEntity) { return combineStorageKey(STORAGE_KEY_PREFIX, id); } function createDynamicStorageKey(id: StorageEntity) { const keyBase = combineStorageKey(STORAGE_KEY_PREFIX, id); return (...subKeys: (number | string)[]) => combineStorageKey(keyBase, ...subKeys); } function combineStorageKey(...parts: (string | number)[]) { return parts.join('_'); } async function withError<T>(errMessage: string, factory: (doThrow: () => void) => Promise<T>) { try { return await factory(() => { throw new Error('<stub>'); }); } catch (err: any) { throw err instanceof PublicError ? err : new PublicError(errMessage); } }
the_stack
import { DocNode, DocComment, DocNodeKind, DocPlainText, DocSection, DocBlock, DocParagraph, DocBlockTag, DocCodeSpan, DocFencedCode, DocDeclarationReference, DocErrorText, DocEscapedText, DocHtmlEndTag, DocHtmlStartTag, DocHtmlAttribute, DocInheritDocTag, DocInlineTagBase, DocInlineTag, DocLinkTag, DocMemberIdentifier, DocMemberReference, DocMemberSymbol, DocMemberSelector, DocParamBlock } from '../nodes'; import { IStringBuilder } from './StringBuilder'; import { DocNodeTransforms } from '../transforms/DocNodeTransforms'; import { StandardTags } from '../details/StandardTags'; import { DocParamCollection } from '../nodes/DocParamCollection'; enum LineState { Closed, StartOfLine, MiddleOfLine } /** * Renders a DocNode tree as a code comment. */ export class TSDocEmitter { public readonly eol: string = '\n'; // Whether to emit the /** */ framing private _emitCommentFraming: boolean = true; private _output: IStringBuilder | undefined; // This state machine is used by the writer functions to generate the /** */ framing around the emitted lines private _lineState: LineState = LineState.Closed; // State for _ensureLineSkipped() private _previousLineHadContent: boolean = false; // Normally a paragraph is precede by a blank line (unless it's the first thing written). // But sometimes we want the paragraph to be attached to the previous element, e.g. when it's part of // an "@param" block. Setting _hangingParagraph=true accomplishes that. private _hangingParagraph: boolean = false; public renderComment(output: IStringBuilder, docComment: DocComment): void { this._emitCommentFraming = true; this._renderCompleteObject(output, docComment); } public renderHtmlTag(output: IStringBuilder, htmlTag: DocHtmlStartTag | DocHtmlEndTag): void { this._emitCommentFraming = false; this._renderCompleteObject(output, htmlTag); } public renderDeclarationReference( output: IStringBuilder, declarationReference: DocDeclarationReference ): void { this._emitCommentFraming = false; this._renderCompleteObject(output, declarationReference); } private _renderCompleteObject(output: IStringBuilder, docNode: DocNode): void { this._output = output; this._lineState = LineState.Closed; this._previousLineHadContent = false; this._hangingParagraph = false; this._renderNode(docNode); this._writeEnd(); } private _renderNode(docNode: DocNode | undefined): void { if (docNode === undefined) { return; } switch (docNode.kind) { case DocNodeKind.Block: const docBlock: DocBlock = docNode as DocBlock; this._ensureLineSkipped(); this._renderNode(docBlock.blockTag); if (docBlock.blockTag.tagNameWithUpperCase === StandardTags.returns.tagNameWithUpperCase) { this._writeContent(' '); this._hangingParagraph = true; } this._renderNode(docBlock.content); break; case DocNodeKind.BlockTag: const docBlockTag: DocBlockTag = docNode as DocBlockTag; if (this._lineState === LineState.MiddleOfLine) { this._writeContent(' '); } this._writeContent(docBlockTag.tagName); break; case DocNodeKind.CodeSpan: const docCodeSpan: DocCodeSpan = docNode as DocCodeSpan; this._writeContent('`'); this._writeContent(docCodeSpan.code); this._writeContent('`'); break; case DocNodeKind.Comment: const docComment: DocComment = docNode as DocComment; this._renderNodes([ docComment.summarySection, docComment.remarksBlock, docComment.privateRemarks, docComment.deprecatedBlock, docComment.params, docComment.typeParams, docComment.returnsBlock, ...docComment.customBlocks, ...docComment.seeBlocks, docComment.inheritDocTag ]); if (docComment.modifierTagSet.nodes.length > 0) { this._ensureLineSkipped(); this._renderNodes(docComment.modifierTagSet.nodes); } break; case DocNodeKind.DeclarationReference: const docDeclarationReference: DocDeclarationReference = docNode as DocDeclarationReference; this._writeContent(docDeclarationReference.packageName); this._writeContent(docDeclarationReference.importPath); if ( docDeclarationReference.packageName !== undefined || docDeclarationReference.importPath !== undefined ) { this._writeContent('#'); } this._renderNodes(docDeclarationReference.memberReferences); break; case DocNodeKind.ErrorText: const docErrorText: DocErrorText = docNode as DocErrorText; this._writeContent(docErrorText.text); break; case DocNodeKind.EscapedText: const docEscapedText: DocEscapedText = docNode as DocEscapedText; this._writeContent(docEscapedText.encodedText); break; case DocNodeKind.FencedCode: const docFencedCode: DocFencedCode = docNode as DocFencedCode; this._ensureAtStartOfLine(); this._writeContent('```'); this._writeContent(docFencedCode.language); this._writeNewline(); this._writeContent(docFencedCode.code); this._writeContent('```'); this._writeNewline(); this._writeNewline(); break; case DocNodeKind.HtmlAttribute: const docHtmlAttribute: DocHtmlAttribute = docNode as DocHtmlAttribute; this._writeContent(docHtmlAttribute.name); this._writeContent(docHtmlAttribute.spacingAfterName); this._writeContent('='); this._writeContent(docHtmlAttribute.spacingAfterEquals); this._writeContent(docHtmlAttribute.value); this._writeContent(docHtmlAttribute.spacingAfterValue); break; case DocNodeKind.HtmlEndTag: const docHtmlEndTag: DocHtmlEndTag = docNode as DocHtmlEndTag; this._writeContent('</'); this._writeContent(docHtmlEndTag.name); this._writeContent('>'); break; case DocNodeKind.HtmlStartTag: const docHtmlStartTag: DocHtmlStartTag = docNode as DocHtmlStartTag; this._writeContent('<'); this._writeContent(docHtmlStartTag.name); this._writeContent(docHtmlStartTag.spacingAfterName); let needsSpace: boolean = docHtmlStartTag.spacingAfterName === undefined || docHtmlStartTag.spacingAfterName.length === 0; for (const attribute of docHtmlStartTag.htmlAttributes) { if (needsSpace) { this._writeContent(' '); } this._renderNode(attribute); needsSpace = attribute.spacingAfterValue === undefined || attribute.spacingAfterValue.length === 0; } this._writeContent(docHtmlStartTag.selfClosingTag ? '/>' : '>'); break; case DocNodeKind.InheritDocTag: const docInheritDocTag: DocInheritDocTag = docNode as DocInheritDocTag; this._renderInlineTag(docInheritDocTag, () => { if (docInheritDocTag.declarationReference) { this._writeContent(' '); this._renderNode(docInheritDocTag.declarationReference); } }); break; case DocNodeKind.InlineTag: const docInlineTag: DocInlineTag = docNode as DocInlineTag; this._renderInlineTag(docInlineTag, () => { if (docInlineTag.tagContent.length > 0) { this._writeContent(' '); this._writeContent(docInlineTag.tagContent); } }); break; case DocNodeKind.LinkTag: const docLinkTag: DocLinkTag = docNode as DocLinkTag; this._renderInlineTag(docLinkTag, () => { if (docLinkTag.urlDestination !== undefined || docLinkTag.codeDestination !== undefined) { if (docLinkTag.urlDestination !== undefined) { this._writeContent(' '); this._writeContent(docLinkTag.urlDestination); } else if (docLinkTag.codeDestination !== undefined) { this._writeContent(' '); this._renderNode(docLinkTag.codeDestination); } } if (docLinkTag.linkText !== undefined) { this._writeContent(' '); this._writeContent('|'); this._writeContent(' '); this._writeContent(docLinkTag.linkText); } }); break; case DocNodeKind.MemberIdentifier: const docMemberIdentifier: DocMemberIdentifier = docNode as DocMemberIdentifier; if (docMemberIdentifier.hasQuotes) { this._writeContent('"'); this._writeContent(docMemberIdentifier.identifier); // todo: encoding this._writeContent('"'); } else { this._writeContent(docMemberIdentifier.identifier); } break; case DocNodeKind.MemberReference: const docMemberReference: DocMemberReference = docNode as DocMemberReference; if (docMemberReference.hasDot) { this._writeContent('.'); } if (docMemberReference.selector) { this._writeContent('('); } if (docMemberReference.memberSymbol) { this._renderNode(docMemberReference.memberSymbol); } else { this._renderNode(docMemberReference.memberIdentifier); } if (docMemberReference.selector) { this._writeContent(':'); this._renderNode(docMemberReference.selector); this._writeContent(')'); } break; case DocNodeKind.MemberSelector: const docMemberSelector: DocMemberSelector = docNode as DocMemberSelector; this._writeContent(docMemberSelector.selector); break; case DocNodeKind.MemberSymbol: const docMemberSymbol: DocMemberSymbol = docNode as DocMemberSymbol; this._writeContent('['); this._renderNode(docMemberSymbol.symbolReference); this._writeContent(']'); break; case DocNodeKind.Section: const docSection: DocSection = docNode as DocSection; this._renderNodes(docSection.nodes); break; case DocNodeKind.Paragraph: const trimmedParagraph: DocParagraph = DocNodeTransforms.trimSpacesInParagraph( docNode as DocParagraph ); if (trimmedParagraph.nodes.length > 0) { if (this._hangingParagraph) { // If it's a hanging paragraph, then don't skip a line this._hangingParagraph = false; } else { this._ensureLineSkipped(); } this._renderNodes(trimmedParagraph.nodes); this._writeNewline(); } break; case DocNodeKind.ParamBlock: const docParamBlock: DocParamBlock = docNode as DocParamBlock; this._ensureLineSkipped(); this._renderNode(docParamBlock.blockTag); this._writeContent(' '); this._writeContent(docParamBlock.parameterName); this._writeContent(' - '); this._hangingParagraph = true; this._renderNode(docParamBlock.content); this._hangingParagraph = false; break; case DocNodeKind.ParamCollection: const docParamCollection: DocParamCollection = docNode as DocParamCollection; this._renderNodes(docParamCollection.blocks); break; case DocNodeKind.PlainText: const docPlainText: DocPlainText = docNode as DocPlainText; this._writeContent(docPlainText.text); break; } } private _renderInlineTag(docInlineTagBase: DocInlineTagBase, writeInlineTagContent: () => void): void { this._writeContent('{'); this._writeContent(docInlineTagBase.tagName); writeInlineTagContent(); this._writeContent('}'); } private _renderNodes(docNodes: ReadonlyArray<DocNode | undefined>): void { for (const docNode of docNodes) { this._renderNode(docNode); } } // Calls _writeNewline() only if we're not already at the start of a new line private _ensureAtStartOfLine(): void { if (this._lineState === LineState.MiddleOfLine) { this._writeNewline(); } } // Calls _writeNewline() if needed to ensure that we have skipped at least one line private _ensureLineSkipped(): void { this._ensureAtStartOfLine(); if (this._previousLineHadContent) { this._writeNewline(); } } // Writes literal text content. If it contains newlines, they will automatically be converted to // _writeNewline() calls, to ensure that "*" is written at the start of each line. private _writeContent(content: string | undefined): void { if (content === undefined || content.length === 0) { return; } const splitLines: string[] = content.split(/\r?\n/g); if (splitLines.length > 1) { let firstLine: boolean = true; for (const line of splitLines) { if (firstLine) { firstLine = false; } else { this._writeNewline(); } this._writeContent(line); } return; } if (this._lineState === LineState.Closed) { if (this._emitCommentFraming) { this._output!.append('/**' + this.eol + ' *'); } this._lineState = LineState.StartOfLine; } if (this._lineState === LineState.StartOfLine) { if (this._emitCommentFraming) { this._output!.append(' '); } } this._output!.append(content); this._lineState = LineState.MiddleOfLine; this._previousLineHadContent = true; } // Starts a new line, and inserts "/**" or "*" as appropriate. private _writeNewline(): void { if (this._lineState === LineState.Closed) { if (this._emitCommentFraming) { this._output!.append('/**' + this.eol + ' *'); } this._lineState = LineState.StartOfLine; } this._previousLineHadContent = this._lineState === LineState.MiddleOfLine; if (this._emitCommentFraming) { this._output!.append(this.eol + ' *'); } else { this._output!.append(this.eol); } this._lineState = LineState.StartOfLine; this._hangingParagraph = false; } // Closes the comment, adding the final "*/" delimiter private _writeEnd(): void { if (this._lineState === LineState.MiddleOfLine) { if (this._emitCommentFraming) { this._writeNewline(); } } if (this._lineState !== LineState.Closed) { if (this._emitCommentFraming) { this._output!.append('/' + this.eol); } this._lineState = LineState.Closed; } } }
the_stack
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { StoreModule, Store } from '@ngrx/store'; import { MockComponent } from 'ng2-mock-component'; import { NgrxStateAtom, runtimeChecks, ngrxReducers } from 'app/ngrx.reducers'; import { ChefPipesModule } from 'app/pipes/chef-pipes.module'; import { using } from 'app/testing/spec-helpers'; import { FeatureFlagsService } from 'app/services/feature-flags/feature-flags.service'; import { IndexedEntities } from 'app/entities/entities'; import { UserPermEntity } from 'app/entities/userperms/userperms.entity'; import { PermEntityState, Status } from 'app/entities/userperms/userperms.reducer'; import { ProjectStatus } from 'app/entities/rules/rule.model'; import { Project } from 'app/entities/projects/project.model'; import { ProjectService } from 'app/entities/projects/project.service'; import { ApplyRulesStatusState } from 'app/entities/projects/project.reducer'; import { GetProjectsSuccess, GetApplyRulesStatusSuccess, GetApplyRulesStatusSuccessPayload } from 'app/entities/projects/project.actions'; import { PendingEditsBarComponent } from './pending-edits-bar.component'; describe('PendingEditsBarComponent', () => { let component: PendingEditsBarComponent; let fixture: ComponentFixture<PendingEditsBarComponent>; let element: HTMLElement; let projectService: ProjectService; let store: Store<NgrxStateAtom>; beforeEach(waitForAsync(() => { configureWith({ '/apis/iam/v2/projects': genPerm('/apis/iam/v2/projects', true) }); })); beforeEach(() => { projectService = TestBed.inject(ProjectService); fixture = TestBed.createComponent(PendingEditsBarComponent); component = fixture.componentInstance; element = fixture.debugElement.query(By.css('#pending-edits-bar')).nativeElement; store = TestBed.inject(Store); fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); describe('update-start-confirmation modal', () => { describe('when it emits a cancellation', () => { it('it hides the modal', () => { component.openConfirmUpdateStartModal(); component.cancelApplyStart(); expect(component.confirmApplyStartModalVisible).toEqual(false); }); }); describe('when it emits a confirmation', () => { beforeEach(() => { spyOn(projectService, 'applyRulesStart'); component.openConfirmUpdateStartModal(); component.confirmApplyStart(); }); it('it hides the modal', () => { expect(component.confirmApplyStartModalVisible).toEqual(false); }); it('the projectService starts the rule updates', () => { expect(projectService.applyRulesStart).toHaveBeenCalled(); }); }); }); describe('pending edits bar', () => { it('is hidden if no project has changes', () => { const uneditedProject1 = genProject('uuid-111', 'RULES_APPLIED'); const uneditedProject2 = genProject('uuid-112', 'RULES_APPLIED'); store.dispatch(new GetProjectsSuccess({ projects: [uneditedProject1, uneditedProject2] })); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is visible if some project has changes', () => { const editedProject = genProject('uuid-99', 'EDITS_PENDING'); const uneditedProject = genProject('uuid-111', 'RULES_APPLIED'); store.dispatch(new GetProjectsSuccess({ projects: [uneditedProject, editedProject] })); component.updateDisplay(); expect(component.isBarHidden).toEqual(false); }); it('is visible if some project has changes... UNLESS progress bar is active', () => { const editedProject = genProject('uuid-99', 'EDITS_PENDING'); const uneditedProject = genProject('uuid-111', 'RULES_APPLIED'); store.dispatch(new GetProjectsSuccess({ projects: [uneditedProject, editedProject] })); component.updateDisplay(); component.layoutFacade.layout.userNotifications.updatesProcessing = true; expect(component.isBarHidden).toEqual(true); }); it('is visible if rules are not being applied', () => { // isolate rules being applied because bar would be visible with just this store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'EDITS_PENDING')] })); component.confirmApplyStart(); // update running store.dispatch(new GetApplyRulesStatusSuccess( // update finished genState(ApplyRulesStatusState.NotRunning))); component.updateDisplay(); expect(component.isBarHidden).toEqual(false); }); it('is visible if update fails', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.NotRunning, true, false))); component.updateDisplay(); expect(component.isBarHidden).toEqual(false); }); it('is visible if update is cancelled', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.NotRunning, false, true))); component.updateDisplay(); expect(component.isBarHidden).toEqual(false); }); it('is visible if update is cancelled but update is still running', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.Running, false, true))); component.updateDisplay(); expect(component.isBarHidden).toEqual(false); }); it('displays edits pending message before update is applied', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'EDITS_PENDING')] })); fixture.detectChanges(); expect(element.textContent).toContain('Project edits pending'); }); using([ ['is cancelled', false, true, 'edits pending'], ['fails', true, false, 'update failed'], // if it could happen, failure takes precedence: ['both fails and is cancelled', true, true, 'update failed'] ], function (description: string, failed: boolean, cancelled: boolean, message: string) { it(`displays "${message}" message when update ${description}`, () => { store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.NotRunning, failed, cancelled))); fixture.detectChanges(); expect(element.textContent).toContain(`Project ${message}`); }); }); }); }); describe('PendingEditsBarComponent--unauthorized', () => { let component: PendingEditsBarComponent; let fixture: ComponentFixture<PendingEditsBarComponent>; let store: Store<NgrxStateAtom>; beforeEach(waitForAsync(() => { configureWith({ '/apis/iam/v2/projects': genPerm('/apis/iam/v2/projects', false) }); })); beforeEach(() => { fixture = TestBed.createComponent(PendingEditsBarComponent); component = fixture.componentInstance; store = TestBed.inject(Store); fixture.detectChanges(); }); // This section contains a copy of the relevant tests from above that are affected // when the user is NOT authorized, i.e. all the tests where the bar was previously visible. describe('pending edits bar', () => { it('is hidden if no project has changes', () => { const uneditedProject1 = genProject('uuid-111', 'RULES_APPLIED'); const uneditedProject2 = genProject('uuid-112', 'RULES_APPLIED'); store.dispatch(new GetProjectsSuccess({ projects: [uneditedProject1, uneditedProject2] })); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is hidden if some project has changes', () => { const editedProject = genProject('uuid-99', 'EDITS_PENDING'); const uneditedProject = genProject('uuid-111', 'RULES_APPLIED'); store.dispatch(new GetProjectsSuccess({ projects: [uneditedProject, editedProject] })); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is hidden if rules are not being applied', () => { // isolate rules being applied because bar would be visible with just this store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'EDITS_PENDING')] })); component.confirmApplyStart(); // update running store.dispatch(new GetApplyRulesStatusSuccess( // update finished genState(ApplyRulesStatusState.NotRunning))); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is hidden if update fails', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.NotRunning, true, false))); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is hidden if update is cancelled', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.NotRunning, false, true))); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); it('is hidden if update is cancelled but update is still running', () => { store.dispatch( new GetProjectsSuccess({ projects: [genProject('uuid-99', 'RULES_APPLIED')] })); component.confirmApplyStart(); store.dispatch(new GetApplyRulesStatusSuccess( genState(ApplyRulesStatusState.Running, false, true))); component.updateDisplay(); expect(component.isBarHidden).toEqual(true); }); }); }); function configureWith(perms: IndexedEntities<UserPermEntity>): void { TestBed.configureTestingModule({ declarations: [ MockComponent({ selector: 'chef-toolbar', template: '<ng-content></ng-content>' }), MockComponent({ selector: 'app-authorized', inputs: ['allOf', 'not'], template: '<ng-content></ng-content>' }), MockComponent({ selector: 'app-message-modal', inputs: ['visible'], outputs: ['close'] }), MockComponent({ selector: 'app-confirm-apply-start-modal', inputs: ['visible'], outputs: ['confirm', 'cancel'] }), MockComponent({ selector: 'app-confirm-apply-stop-modal', inputs: ['visible', 'applyRulesStatus', 'stopRulesInProgress'], outputs: ['confirm', 'cancel'] }), MockComponent({ selector: 'mat-progress-bar', inputs: ['mode', 'value', 'bufferValue'] }), MockComponent({ selector: 'mat-select' }), MockComponent({ selector: 'mat-option' }), MockComponent({ selector: 'chef-button', inputs: ['disabled'] }), MockComponent({ selector: 'chef-heading' }), MockComponent({ selector: 'chef-loading-spinner' }), MockComponent({ selector: 'chef-page-header' }), MockComponent({ selector: 'chef-subheading' }), MockComponent({ selector: 'chef-table' }), MockComponent({ selector: 'chef-thead' }), MockComponent({ selector: 'chef-tbody' }), MockComponent({ selector: 'chef-tr' }), MockComponent({ selector: 'chef-th' }), MockComponent({ selector: 'chef-td' }), PendingEditsBarComponent ], imports: [ ReactiveFormsModule, RouterTestingModule, ChefPipesModule, StoreModule.forRoot({ ...ngrxReducers, userperms: () => <PermEntityState>{ status: Status.loadingSuccess, byId: perms } }, { runtimeChecks }) ], providers: [ FeatureFlagsService, ProjectService ] }).compileComponents(); } function genPerm(name: string, state: boolean): UserPermEntity { return new UserPermEntity( { get: state, put: state, post: state, delete: state, patch: state }, name); } function genProject(id: string, status: ProjectStatus): Project { return { id, status, name: id, // unused type: 'CUSTOM' // unused }; } function genState( state: ApplyRulesStatusState, failed = false, cancelled = false ): GetApplyRulesStatusSuccessPayload { return { state, failed, cancelled, estimated_time_complete: '', // unused percentage_complete: 0.5, // unused failure_message: '' // unused }; }
the_stack
import AlertMedium from '@spectrum-icons/ui/AlertMedium'; import {AriaButtonProps} from '@react-types/button'; import CheckmarkMedium from '@spectrum-icons/ui/CheckmarkMedium'; import {classNames} from '@react-spectrum/utils'; import {ClearButton} from '@react-spectrum/button'; import {ComboBoxState, useComboBoxState} from '@react-stately/combobox'; import {DismissButton} from '@react-aria/overlays'; import {Field} from '@react-spectrum/label'; import {FocusableRef, ValidationState} from '@react-types/shared'; import {FocusRing, FocusScope} from '@react-aria/focus'; import {focusSafely} from '@react-aria/focus'; // @ts-ignore import intlMessages from '../intl/*.json'; import {ListBoxBase, useListBoxLayout} from '@react-spectrum/listbox'; import Magnifier from '@spectrum-icons/ui/Magnifier'; import {mergeProps, useId} from '@react-aria/utils'; import {ProgressCircle} from '@react-spectrum/progress'; import React, {HTMLAttributes, ReactElement, ReactNode, RefObject, useCallback, useEffect, useRef, useState} from 'react'; import searchAutocompleteStyles from './searchautocomplete.css'; import searchStyles from '@adobe/spectrum-css-temp/components/search/vars.css'; import {setInteractionModality, useHover} from '@react-aria/interactions'; import {SpectrumSearchAutocompleteProps} from '@react-types/autocomplete'; import styles from '@adobe/spectrum-css-temp/components/inputgroup/vars.css'; import {TextFieldBase} from '@react-spectrum/textfield'; import textfieldStyles from '@adobe/spectrum-css-temp/components/textfield/vars.css'; import {Tray} from '@react-spectrum/overlays'; import {useButton} from '@react-aria/button'; import {useDialog} from '@react-aria/dialog'; import {useFilter, useMessageFormatter} from '@react-aria/i18n'; import {useFocusableRef} from '@react-spectrum/utils'; import {useLabel} from '@react-aria/label'; import {useOverlayTrigger} from '@react-aria/overlays'; import {useProviderProps} from '@react-spectrum/provider'; import {useSearchAutocomplete} from '@react-aria/autocomplete'; export const MobileSearchAutocomplete = React.forwardRef(function MobileSearchAutocomplete<T extends object>(props: SpectrumSearchAutocompleteProps<T>, ref: FocusableRef<HTMLElement>) { props = useProviderProps(props); let { isQuiet, isDisabled, validationState, isReadOnly, onSubmit = () => {} } = props; let {contains} = useFilter({sensitivity: 'base'}); let state = useComboBoxState({ ...props, defaultFilter: contains, allowsEmptyCollection: true, // Needs to be false here otherwise we double up on commitSelection/commitCustomValue calls when // user taps on underlay (i.e. initial tap will call setFocused(false) -> commitSelection/commitCustomValue via onBlur, // then the closing of the tray will call setFocused(false) again due to cleanup effect) shouldCloseOnBlur: false, allowsCustomValue: true, onSelectionChange: (key) => key !== null && onSubmit(null, key), selectedKey: undefined, defaultSelectedKey: undefined }); let buttonRef = useRef<HTMLElement>(); let domRef = useFocusableRef(ref, buttonRef); let {triggerProps, overlayProps} = useOverlayTrigger({type: 'listbox'}, state, buttonRef); let {labelProps, fieldProps} = useLabel({ ...props, labelElementType: 'span' }); // Focus the button and show focus ring when clicking on the label labelProps.onClick = () => { if (!props.isDisabled) { buttonRef.current.focus(); setInteractionModality('keyboard'); } }; let onClose = () => state.commit(); return ( <> <Field {...props} labelProps={labelProps} elementType="span" ref={domRef} includeNecessityIndicatorInAccessibilityName> <SearchAutocompleteButton {...mergeProps(triggerProps, fieldProps, {autoFocus: props.autoFocus})} ref={buttonRef} isQuiet={isQuiet} isDisabled={isDisabled} isReadOnly={isReadOnly} isPlaceholder={!state.inputValue} validationState={validationState} inputValue={state.inputValue} clearInput={() => state.setInputValue('')} onPress={() => !isReadOnly && state.open(null, 'manual')}> {state.inputValue || props.placeholder || ''} </SearchAutocompleteButton> </Field> <Tray isOpen={state.isOpen} onClose={onClose} isFixedHeight isNonModal {...overlayProps}> <SearchAutocompleteTray {...props} onClose={onClose} overlayProps={overlayProps} state={state} /> </Tray> </> ); }); interface SearchAutocompleteButtonProps extends AriaButtonProps { isQuiet?: boolean, isDisabled?: boolean, isReadOnly?: boolean, isPlaceholder?: boolean, validationState?: ValidationState, inputValue?: string, clearInput?: () => void, children?: ReactNode, style?: React.CSSProperties, className?: string } const SearchAutocompleteButton = React.forwardRef(function SearchAutocompleteButton(props: SearchAutocompleteButtonProps, ref: RefObject<HTMLElement>) { let { isQuiet, isDisabled, isReadOnly, isPlaceholder, validationState, inputValue, clearInput, children, style, className } = props; let formatMessage = useMessageFormatter(intlMessages); let valueId = useId(); let invalidId = useId(); let validationIcon = validationState === 'invalid' ? <AlertMedium id={invalidId} aria-label={formatMessage('invalid')} /> : <CheckmarkMedium />; let searchIcon = ( <Magnifier data-testid="searchicon" /> ); let icon = React.cloneElement(searchIcon, { UNSAFE_className: classNames( textfieldStyles, 'spectrum-Textfield-icon' ), size: 'S' }); let clearButton = ( <ClearButton onPress={(e) => { clearInput(); props.onPress(e); }} preventFocus aria-label={formatMessage('clear')} excludeFromTabOrder UNSAFE_className={ classNames( searchStyles, 'spectrum-ClearButton' ) } isDisabled={isDisabled} /> ); let validation = React.cloneElement(validationIcon, { UNSAFE_className: classNames( textfieldStyles, 'spectrum-Textfield-validationIcon', classNames( styles, 'spectrum-InputGroup-input-validationIcon' ) ) }); let {hoverProps, isHovered} = useHover({}); let {buttonProps} = useButton({ ...props, 'aria-labelledby': [ props['aria-labelledby'], props['aria-label'] && !props['aria-labelledby'] ? props.id : null, valueId, validationState === 'invalid' ? invalidId : null ].filter(Boolean).join(' '), elementType: 'div' }, ref); return ( <FocusRing focusClass={classNames(styles, 'is-focused')} focusRingClass={classNames(styles, 'focus-ring')}> <div {...mergeProps(hoverProps, buttonProps)} aria-haspopup="dialog" ref={ref as RefObject<HTMLDivElement>} style={{...style, outline: 'none'}} className={ classNames( styles, 'spectrum-InputGroup', { 'spectrum-InputGroup--quiet': isQuiet, 'is-disabled': isDisabled, 'spectrum-InputGroup--invalid': validationState === 'invalid', 'is-hovered': isHovered }, classNames( searchAutocompleteStyles, 'mobile-searchautocomplete' ), className ) }> <div className={ classNames( textfieldStyles, 'spectrum-Textfield', { 'spectrum-Textfield--invalid': validationState === 'invalid', 'spectrum-Textfield--valid': validationState === 'valid', 'spectrum-Textfield--quiet': isQuiet }, classNames( searchStyles, 'spectrum-Search', { 'is-disabled': isDisabled, 'is-quiet': isQuiet, 'spectrum-Search--invalid': validationState === 'invalid', 'spectrum-Search--valid': validationState === 'valid' } ) ) }> <div className={ classNames( textfieldStyles, 'spectrum-Textfield-input', 'spectrum-Textfield-inputIcon', { 'is-hovered': isHovered, 'is-placeholder': isPlaceholder, 'is-disabled': isDisabled, 'is-quiet': isQuiet }, classNames( searchStyles, 'spectrum-Search-input' ) ) }> {icon} <span id={valueId} className={ classNames( searchAutocompleteStyles, 'mobile-value' ) }> {children} </span> </div> {validationState ? validation : null} {(inputValue !== '' || validationState != null) && !isReadOnly && clearButton} </div> </div> </FocusRing> ); }); interface SearchAutocompleteTrayProps extends SpectrumSearchAutocompleteProps<unknown> { state: ComboBoxState<unknown>, overlayProps: HTMLAttributes<HTMLElement>, loadingIndicator?: ReactElement, onClose: () => void } function SearchAutocompleteTray(props: SearchAutocompleteTrayProps) { let { // completionMode = 'suggest', state, isDisabled, validationState, label, overlayProps, loadingState, onLoadMore, onClose, onSubmit } = props; let timeout = useRef(null); let [showLoading, setShowLoading] = useState(false); let inputRef = useRef<HTMLInputElement>(); let popoverRef = useRef<HTMLDivElement>(); let listBoxRef = useRef<HTMLDivElement>(); let layout = useListBoxLayout(state); let formatMessage = useMessageFormatter(intlMessages); let {inputProps, listBoxProps, labelProps, clearButtonProps} = useSearchAutocomplete( { ...props, keyboardDelegate: layout, popoverRef: popoverRef, listBoxRef, inputRef }, state ); React.useEffect(() => { focusSafely(inputRef.current); // When the tray unmounts, set state.isFocused (i.e. the tray input's focus tracker) to false. // This is to prevent state.isFocused from being set to true when the tray closes via tapping on the underlay // (FocusScope attempts to restore focus to the tray input when tapping outside the tray due to "contain") // Have to do this manually since React doesn't call onBlur when a component is unmounted: https://github.com/facebook/react/issues/12363 return () => { state.setFocused(false); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); let {dialogProps} = useDialog({ 'aria-labelledby': useId(labelProps.id) }, popoverRef); // Override the role of the input to "searchbox" instead of "combobox". // Since the listbox is always visible, the combobox role doesn't really give us anything. // VoiceOver on iOS reads "double tap to collapse" when focused on the input rather than // "double tap to edit text", as with a textbox or searchbox. We'd like double tapping to // open the virtual keyboard rather than closing the tray. inputProps.role = 'searchbox'; inputProps['aria-haspopup'] = 'listbox'; delete inputProps.onTouchEnd; let clearButton = ( <ClearButton {...clearButtonProps} preventFocus aria-label={formatMessage('clear')} excludeFromTabOrder UNSAFE_className={ classNames( searchStyles, 'spectrum-ClearButton' ) } isDisabled={isDisabled} /> ); let loadingCircle = ( <ProgressCircle aria-label={formatMessage('loading')} size="S" isIndeterminate UNSAFE_className={classNames( searchStyles, 'spectrum-Search-circleLoader', classNames( textfieldStyles, 'spectrum-Textfield-circleLoader' ) )} /> ); // Close the software keyboard on scroll to give the user a bigger area to scroll. // But only do this if scrolling with touch, otherwise it can cause issues with touch // screen readers. let isTouchDown = useRef(false); let onTouchStart = () => { isTouchDown.current = true; }; let onTouchEnd = () => { isTouchDown.current = false; }; let onScroll = useCallback(() => { if (!inputRef.current || document.activeElement !== inputRef.current || !isTouchDown.current) { return; } popoverRef.current.focus(); }, [inputRef, popoverRef, isTouchDown]); let inputValue = inputProps.value; let lastInputValue = useRef(inputValue); useEffect(() => { if (loadingState === 'filtering' && !showLoading) { if (timeout.current === null) { timeout.current = setTimeout(() => { setShowLoading(true); }, 500); } // If user is typing, clear the timer and restart since it is a new request if (inputValue !== lastInputValue.current) { clearTimeout(timeout.current); timeout.current = setTimeout(() => { setShowLoading(true); }, 500); } } else if (loadingState !== 'filtering') { // If loading is no longer happening, clear any timers and hide the loading circle setShowLoading(false); clearTimeout(timeout.current); timeout.current = null; } lastInputValue.current = inputValue; }, [loadingState, inputValue, showLoading]); let onKeyDown = (e) => { // Close virtual keyboard, close tray, and fire onSubmit if user hits Enter w/o any focused options if (e.key === 'Enter' && state.selectionManager.focusedKey == null) { popoverRef.current.focus(); onClose(); onSubmit(inputValue.toString(), null); } else { inputProps.onKeyDown(e); } }; let searchIcon = ( <Magnifier data-testid="searchicon" /> ); let icon = React.cloneElement(searchIcon, { UNSAFE_className: classNames( textfieldStyles, 'spectrum-Textfield-icon' ), size: 'S' }); return ( <FocusScope restoreFocus contain> <div {...mergeProps(overlayProps, dialogProps)} ref={popoverRef} className={ classNames( searchAutocompleteStyles, 'tray-dialog' ) }> <DismissButton onDismiss={onClose} /> <TextFieldBase label={label} labelProps={labelProps} inputProps={{...inputProps, onKeyDown}} inputRef={inputRef} isDisabled={isDisabled} isLoading={showLoading && loadingState === 'filtering'} loadingIndicator={loadingState != null && loadingCircle} validationState={validationState} wrapperChildren={(state.inputValue !== '' || loadingState === 'filtering' || validationState != null) && !props.isReadOnly && clearButton} icon={icon} UNSAFE_className={ classNames( searchStyles, 'spectrum-Search', 'spectrum-Textfield', 'spectrum-Search--loadable', { 'spectrum-Search--invalid': validationState === 'invalid', 'spectrum-Search--valid': validationState === 'valid' }, classNames( searchAutocompleteStyles, 'tray-textfield', { 'has-label': !!props.label } ) ) } inputClassName={ classNames( searchStyles, 'spectrum-Search-input' ) } validationIconClassName={ classNames( searchStyles, 'spectrum-Search-validationIcon' ) } /> <ListBoxBase {...listBoxProps} domProps={{onTouchStart, onTouchEnd}} disallowEmptySelection shouldSelectOnPressUp focusOnPointerEnter layout={layout} state={state} shouldUseVirtualFocus renderEmptyState={() => loadingState !== 'loading' && ( <span className={classNames(searchAutocompleteStyles, 'no-results')}> {formatMessage('noResults')} </span> )} UNSAFE_className={ classNames( searchAutocompleteStyles, 'tray-listbox' ) } ref={listBoxRef} onScroll={onScroll} onLoadMore={onLoadMore} isLoading={loadingState === 'loading' || loadingState === 'loadingMore'} /> <DismissButton onDismiss={onClose} /> </div> </FocusScope> ); }
the_stack
import {Schema, Field, Bool, Utf8, Float64, TimestampMillisecond} from '@loaders.gl/schema'; import BinaryChunkReader from '../streaming/binary-chunk-reader'; type DBFRowsOutput = object[]; interface DBFTableOutput { schema?: Schema; rows: DBFRowsOutput; } type DBFHeader = { // Last updated date year: number; month: number; day: number; // Number of records in data file nRecords: number; // Length of header in bytes headerLength: number; // Length of each record recordLength: number; // Not sure if this is usually set languageDriver: number; }; type DBFField = { name: string; dataType: string; fieldLength: number; decimal: number; }; type DBFResult = { data: {[key: string]: any}[]; schema?: Schema; error?: string; dbfHeader?: DBFHeader; dbfFields?: DBFField[]; progress?: { bytesUsed: number; rowsTotal: number; rows: number; }; }; const LITTLE_ENDIAN = true; const DBF_HEADER_SIZE = 32; enum STATE { START = 0, // Expecting header FIELD_DESCRIPTORS = 1, FIELD_PROPERTIES = 2, END = 3, ERROR = 4 } class DBFParser { binaryReader = new BinaryChunkReader(); textDecoder: TextDecoder; state = STATE.START; result: DBFResult = { data: [] }; constructor(options: {encoding: string}) { this.textDecoder = new TextDecoder(options.encoding); } /** * @param arrayBuffer */ write(arrayBuffer: ArrayBuffer): void { this.binaryReader.write(arrayBuffer); this.state = parseState(this.state, this.result, this.binaryReader, this.textDecoder); // this.result.progress.bytesUsed = this.binaryReader.bytesUsed(); // important events: // - schema available // - first rows available // - all rows available } end(): void { this.binaryReader.end(); this.state = parseState(this.state, this.result, this.binaryReader, this.textDecoder); // this.result.progress.bytesUsed = this.binaryReader.bytesUsed(); if (this.state !== STATE.END) { this.state = STATE.ERROR; this.result.error = 'DBF incomplete file'; } } } /** * @param arrayBuffer * @param options * @returns DBFTable or rows */ export function parseDBF( arrayBuffer: ArrayBuffer, options: any = {} ): DBFRowsOutput | DBFTableOutput { const loaderOptions = options.dbf || {}; const {encoding} = loaderOptions; const dbfParser = new DBFParser({encoding}); dbfParser.write(arrayBuffer); dbfParser.end(); const {data, schema} = dbfParser.result; switch (options.tables && options.tables.format) { case 'table': // TODO - parse columns return {schema, rows: data}; case 'rows': default: return data; } } /** * @param asyncIterator * @param options */ export async function* parseDBFInBatches( asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>, options: any = {} ): AsyncIterable<DBFHeader | DBFRowsOutput | DBFTableOutput> { const loaderOptions = options.dbf || {}; const {encoding} = loaderOptions; const parser = new DBFParser({encoding}); let headerReturned = false; for await (const arrayBuffer of asyncIterator) { parser.write(arrayBuffer); if (!headerReturned && parser.result.dbfHeader) { headerReturned = true; yield parser.result.dbfHeader; } if (parser.result.data.length > 0) { yield parser.result.data; parser.result.data = []; } } parser.end(); if (parser.result.data.length > 0) { yield parser.result.data; } } /** * https://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm * @param state * @param result * @param binaryReader * @param textDecoder * @returns */ /* eslint-disable complexity, max-depth */ function parseState( state: STATE, result: DBFResult, binaryReader: {[key: string]: any}, textDecoder: TextDecoder ): STATE { // eslint-disable-next-line no-constant-condition while (true) { try { switch (state) { case STATE.ERROR: case STATE.END: return state; case STATE.START: // Parse initial file header const dataView = binaryReader.getDataView(DBF_HEADER_SIZE, 'DBF header'); if (!dataView) { return state; } result.dbfHeader = parseDBFHeader(dataView); result.progress = { bytesUsed: 0, rowsTotal: result.dbfHeader.nRecords, rows: 0 }; state = STATE.FIELD_DESCRIPTORS; break; case STATE.FIELD_DESCRIPTORS: // Parse DBF field descriptors (schema) const fieldDescriptorView = binaryReader.getDataView( // @ts-ignore result.dbfHeader.headerLength - DBF_HEADER_SIZE, 'DBF field descriptors' ); if (!fieldDescriptorView) { return state; } result.dbfFields = parseFieldDescriptors(fieldDescriptorView, textDecoder); result.schema = new Schema(result.dbfFields.map((dbfField) => makeField(dbfField))); state = STATE.FIELD_PROPERTIES; // TODO(kyle) Not exactly sure why start offset needs to be headerLength + 1? // parsedbf uses ((fields.length + 1) << 5) + 2; binaryReader.skip(1); break; case STATE.FIELD_PROPERTIES: const {recordLength = 0, nRecords = 0} = result?.dbfHeader || {}; while (result.data.length < nRecords) { const recordView = binaryReader.getDataView(recordLength - 1); if (!recordView) { return state; } // Note: Avoid actually reading the last byte, which may not be present binaryReader.skip(1); // @ts-ignore const row = parseRow(recordView, result.dbfFields, textDecoder); result.data.push(row); // @ts-ignore result.progress.rows = result.data.length; } state = STATE.END; break; default: state = STATE.ERROR; result.error = `illegal parser state ${state}`; return state; } } catch (error) { state = STATE.ERROR; result.error = `DBF parsing failed: ${(error as Error).message}`; return state; } } } /** * @param headerView */ function parseDBFHeader(headerView: DataView): DBFHeader { return { // Last updated date year: headerView.getUint8(1) + 1900, month: headerView.getUint8(2), day: headerView.getUint8(3), // Number of records in data file nRecords: headerView.getUint32(4, LITTLE_ENDIAN), // Length of header in bytes headerLength: headerView.getUint16(8, LITTLE_ENDIAN), // Length of each record recordLength: headerView.getUint16(10, LITTLE_ENDIAN), // Not sure if this is usually set languageDriver: headerView.getUint8(29) }; } /** * @param view */ function parseFieldDescriptors(view: DataView, textDecoder: TextDecoder): DBFField[] { // NOTE: this might overestimate the number of fields if the "Database // Container" container exists and is included in the headerLength const nFields = (view.byteLength - 1) / 32; const fields: DBFField[] = []; let offset = 0; for (let i = 0; i < nFields; i++) { const name = textDecoder .decode(new Uint8Array(view.buffer, view.byteOffset + offset, 11)) // eslint-disable-next-line no-control-regex .replace(/\u0000/g, ''); fields.push({ name, dataType: String.fromCharCode(view.getUint8(offset + 11)), fieldLength: view.getUint8(offset + 16), decimal: view.getUint8(offset + 17) }); offset += 32; } return fields; } /* * @param {BinaryChunkReader} binaryReader function parseRows(binaryReader, fields, nRecords, recordLength, textDecoder) { const rows = []; for (let i = 0; i < nRecords; i++) { const recordView = binaryReader.getDataView(recordLength - 1); binaryReader.skip(1); // @ts-ignore rows.push(parseRow(recordView, fields, textDecoder)); } return rows; } */ /** * * @param view * @param fields * @param textDecoder * @returns */ function parseRow( view: DataView, fields: DBFField[], textDecoder: TextDecoder ): {[key: string]: any} { const out = {}; let offset = 0; for (const field of fields) { const text = textDecoder.decode( new Uint8Array(view.buffer, view.byteOffset + offset, field.fieldLength) ); out[field.name] = parseField(text, field.dataType); offset += field.fieldLength; } return out; } /** * Should NaN be coerced to null? * @param text * @param dataType * @returns Field depends on a type of the data */ function parseField(text: string, dataType: string): string | number | boolean | null { switch (dataType) { case 'B': return parseNumber(text); case 'C': return parseCharacter(text); case 'F': return parseNumber(text); case 'N': return parseNumber(text); case 'O': return parseNumber(text); case 'D': return parseDate(text); case 'L': return parseBoolean(text); default: throw new Error('Unsupported data type'); } } /** * Parse YYYYMMDD to date in milliseconds * @param str YYYYMMDD * @returns new Date as a number */ function parseDate(str: any): number { return Date.UTC(str.slice(0, 4), parseInt(str.slice(4, 6), 10) - 1, str.slice(6, 8)); } /** * Read boolean value * any of Y, y, T, t coerce to true * any of N, n, F, f coerce to false * otherwise null * @param value * @returns boolean | null */ function parseBoolean(value: string): boolean | null { return /^[nf]$/i.test(value) ? false : /^[yt]$/i.test(value) ? true : null; } /** * Return null instead of NaN * @param text * @returns number | null */ function parseNumber(text: string): number | null { const number = parseFloat(text); return isNaN(number) ? null : number; } /** * * @param text * @returns string | null */ function parseCharacter(text: string): string | null { return text.trim() || null; } /** * Create a standard Arrow-style `Field` from field descriptor. * TODO - use `fieldLength` and `decimal` to generate smaller types? * @param param0 * @returns Field */ // eslint-disable function makeField({name, dataType, fieldLength, decimal}): Field { switch (dataType) { case 'B': return new Field(name, new Float64(), true); case 'C': return new Field(name, new Utf8(), true); case 'F': return new Field(name, new Float64(), true); case 'N': return new Field(name, new Float64(), true); case 'O': return new Field(name, new Float64(), true); case 'D': return new Field(name, new TimestampMillisecond(), true); case 'L': return new Field(name, new Bool(), true); default: throw new Error('Unsupported data type'); } }
the_stack
import { CoinGeckoClient } from "../clients/coinGeckoClient"; import { FixerClient } from "../clients/fixerClient"; import { ServiceFactory } from "../factories/serviceFactory"; import { IConfiguration } from "../models/configuration/IConfiguration"; import { ICurrencyState } from "../models/db/ICurrencyState"; import { IMarket } from "../models/db/IMarket"; import { IStorageService } from "../models/services/IStorageService"; /** * Service to handle the currency. */ export class CurrencyService { /** * Milliseconds per minute. */ private static readonly MS_PER_MINUTE: number = 60000; /** * Milliseconds per day. */ private static readonly MS_PER_DAY: number = 86400000; /** * Is the service already updating. */ private _isUpdating: boolean; /** * The configuration. */ private readonly _config: IConfiguration; /** * Create a new instance of CurrencyService. * @param config The configuration for the service. */ constructor(config: IConfiguration) { this._isUpdating = false; this._config = config; } /** * Update the stored currencies. * @param force Force the update. * @returns Log of operations. */ public async update(force: boolean = false): Promise<string> { let log = `Currency Updating ${new Date().toUTCString()}\n`; try { if (this._isUpdating) { log += "Already updating\n"; } else { this._isUpdating = true; const currencyStorageService = ServiceFactory.get<IStorageService<ICurrencyState>>("currency-storage"); let currentState: ICurrencyState; if (currencyStorageService) { currentState = await currencyStorageService.get("default"); } currentState = currentState || { id: "default", lastCurrencyUpdate: 0, lastFxUpdate: 0, currentPriceEUR: 0, marketCapEUR: 0, volumeEUR: 0, exchangeRatesEUR: {} }; // If now date, default to 2 days ago const lastCurrencyUpdate = currentState.lastCurrencyUpdate ? new Date(currentState.lastCurrencyUpdate) : new Date(Date.now() - (2 * CurrencyService.MS_PER_DAY)); const lastFxUpdate = currentState.lastFxUpdate ? new Date(currentState.lastFxUpdate) : new Date(Date.now() - (2 * CurrencyService.MS_PER_DAY)); const now = new Date(); const nowMs = now.getTime(); // If we have no state, an update over 5 minutes old, the day has changed, or force update if (!currentState || nowMs - lastCurrencyUpdate.getTime() > (CurrencyService.MS_PER_MINUTE * 5) || (lastCurrencyUpdate.getDate() !== now.getDate()) || force) { // Update FX rates every 4 hours so we dont hit rate limit if (nowMs - lastFxUpdate.getTime() > (CurrencyService.MS_PER_MINUTE * 240)) { if ((this._config.fixerApiKey || "FIXER-API-KEY") !== "FIXER-API-KEY") { log += "Updating FX Rates\n"; const fixerClient = new FixerClient(this._config.fixerApiKey); const data = await fixerClient.latest("EUR"); if (data?.rates) { log += `Rates ${JSON.stringify(data?.rates)}\n`; currentState.exchangeRatesEUR = data?.rates; currentState.lastFxUpdate = nowMs; } } else { log += "Not updating fixer, no API Key\n"; } } const marketStorage = ServiceFactory.get<IStorageService<IMarket>>("market-storage"); const markets = await marketStorage.getAll(); const startDate = new Date(2017, 5, 14); const endDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()); const dates: number[] = []; // Look for gaps in the data const eur = markets.find(m => m.currency === "eur"); if (eur) { const numDays = (endDate.getTime() - startDate.getTime()) / CurrencyService.MS_PER_DAY; const sortedByDate = eur.data.map(d => d.d).sort((a, b) => a.localeCompare(b)); for (let i = 0; i < numDays; i++) { const iMs = startDate.getTime() + (i * CurrencyService.MS_PER_DAY); const iDate = this.indexDate(new Date(iMs)); const idx = sortedByDate.indexOf(iDate); if (idx < 0) { dates.push(iMs); } } } // Make sure we have the final figures for yesterday if (!dates.includes(endDate.getTime() - CurrencyService.MS_PER_DAY)) { dates.push(endDate.getTime() - CurrencyService.MS_PER_DAY); } // Finally todays date if (!dates.includes(endDate.getTime())) { dates.push(endDate.getTime()); } for (let i = 0; i < dates.length; i++) { log += await this.updateMarketsForDate( markets, new Date(dates[i]), currentState, i === dates.length - 1); } for (const market of markets) { market.data.sort((a, b) => a.d.localeCompare(b.d)); } await marketStorage.setAll(markets); currentState.lastCurrencyUpdate = nowMs; if (currencyStorageService) { await currencyStorageService.set(currentState); } } else { log += "No update required\n"; } this._isUpdating = false; } } catch (err) { log += `Error updating currencies ${err.toString()}\n`; this._isUpdating = false; } return log; } /** * Update the market data for the given date. * @param markets The markets. * @param date The date to update the market for. * @param currentState Current state of currency. * @param isToday Update the state. * @returns Log of the operations. */ private async updateMarketsForDate( markets: IMarket[], date: Date, currentState: ICurrencyState, isToday: boolean): Promise<string> { const year = date.getFullYear().toString(); const month = `0${(date.getMonth() + 1).toString()}`.slice(-2); const day = `0${date.getDate().toString()}`.slice(-2); const fullDate = `${year}-${month}-${day}`; let log = `Coin Gecko ${fullDate}\n`; let priceEUR; let marketCapEUR; let volumeEUR; const dayData: { t: number; p: number; m: number; v: number; }[] = []; const coinGeckoClient = new CoinGeckoClient(); if (isToday) { const coinMarkets = await coinGeckoClient.coinMarkets("iota", "eur"); if (coinMarkets && coinMarkets.length > 0) { priceEUR = coinMarkets[0].current_price; marketCapEUR = coinMarkets[0].market_cap; volumeEUR = coinMarkets[0].total_volume; } log += `Markets ${JSON.stringify(coinMarkets)}\n`; const coinMarketChart = await coinGeckoClient.coinMarketChartDay("iota", "eur"); if (coinMarketChart?.prices && coinMarketChart.market_caps && coinMarketChart.total_volumes) { for (let i = 0; i < coinMarketChart.prices.length; i++) { dayData.push({ t: coinMarketChart.prices[i][0], p: coinMarketChart.prices[i][1], m: coinMarketChart.market_caps[i][1], v: coinMarketChart.total_volumes[i][1] }); } log += `Market Chart ${JSON.stringify(dayData)}\n`; } } else { const coinHistory = await coinGeckoClient.coinsHistory("iota", date); // eslint-disable-next-line camelcase if (coinHistory?.market_data && currentState.exchangeRatesEUR) { log += `History ${JSON.stringify(coinHistory)}\n`; priceEUR = coinHistory.market_data.current_price.eur; marketCapEUR = coinHistory.market_data.market_cap.eur; volumeEUR = coinHistory.market_data.total_volume.eur; } } if (priceEUR && marketCapEUR && volumeEUR) { if (isToday || !currentState.currentPriceEUR) { currentState.currentPriceEUR = priceEUR; currentState.marketCapEUR = marketCapEUR; currentState.volumeEUR = volumeEUR; } for (const currency in currentState.exchangeRatesEUR) { let market: IMarket = markets.find(m => m.currency === currency.toLowerCase()); if (!market) { market = { currency: currency.toLowerCase(), data: [], day: [] }; markets.push(market); } const conversionRate = currentState.exchangeRatesEUR[currency]; const data = { d: fullDate, p: priceEUR * conversionRate, m: marketCapEUR * conversionRate, v: volumeEUR * conversionRate }; const idx = market.data.findIndex(d => d.d === fullDate); if (idx >= 0) { market.data[idx] = data; } else { market.data.push(data); } if (dayData.length > 0) { market.day = dayData.map(d => ({ t: d.t, p: d.p * conversionRate, m: d.m * conversionRate, v: d.v * conversionRate })); } } } return log; } /** * Return the date in the formatted form. * @param date The date to format; * @returns The formatted date. */ private indexDate(date: Date): string { const year = date.getFullYear().toString(); const month = `0${(date.getMonth() + 1).toString()}`.slice(-2); const day = `0${date.getDate().toString()}`.slice(-2); return `${year}-${month}-${day}`; } }
the_stack
import joplin from 'api'; import { NoteTabs } from './noteTabs'; import { Settings, LayoutMode } from './settings'; export class Panel { private _panel: any; private _tabs: NoteTabs; private _settings: Settings; constructor(tabs: NoteTabs, settings: Settings) { this._tabs = tabs; this._settings = settings; } private get tabs() { return this._tabs; } private get sets() { return this._settings; } private async toggleTodoState(noteId: string, checked: any) { try { const note: any = await joplin.data.get(['notes', noteId], { fields: ['id', 'is_todo', 'todo_completed'] }); if (note.is_todo && checked) { await joplin.data.put(['notes', note.id], null, { todo_completed: Date.now() }); } else { await joplin.data.put(['notes', note.id], null, { todo_completed: 0 }); } // updateWebview() is called from onNoteChange event } catch (error) { return; } } /** * Register plugin panel and update webview for the first time. */ async register() { this._panel = await joplin.views.panels.create('note.tabs.panel'); await joplin.views.panels.addScript(this._panel, './webview.css'); if (this.sets.hasLayoutMode(LayoutMode.Auto)) { await joplin.views.panels.addScript(this._panel, './webview_auto.css'); } if (this.sets.hasLayoutMode(LayoutMode.Vertical)) { await joplin.views.panels.addScript(this._panel, './webview_vertical.css'); } await joplin.views.panels.addScript(this._panel, './webview.js'); // message handler await joplin.views.panels.onMessage(this._panel, async (message: any) => { if (message.name === 'tabsOpenFolder') { await joplin.commands.execute('openFolder', message.id); } if (message.name === 'tabsOpen') { await joplin.commands.execute('openNote', message.id); } if (message.name === 'tabsPinNote') { let id: string[] = [message.id]; await joplin.commands.execute('tabsPinNote', id); } if (message.name === 'tabsUnpinNote') { let id: string[] = [message.id]; await joplin.commands.execute('tabsUnpinNote', id); } if (message.name === 'tabsToggleTodo') { await this.toggleTodoState(message.id, message.checked); } if (message.name === 'tabsMoveLeft') { await joplin.commands.execute('tabsMoveLeft'); } if (message.name === 'tabsMoveRight') { await joplin.commands.execute('tabsMoveRight'); } if (message.name === 'tabsBack') { await joplin.commands.execute('historyBackward'); } if (message.name === 'tabsForward') { await joplin.commands.execute('historyForward'); } if (message.name === 'tabsDrag') { await this.tabs.moveWithId(message.sourceId, message.targetId); await this.updateWebview(); } if (message.name === 'tabsDragNotes') { await joplin.commands.execute('tabsPinNote', message.noteIds, message.targetId); } }); // set init message await joplin.views.panels.setHtml(this._panel, ` <div id="container" style="background:${this.sets.background};font-family:${this.sets.fontFamily},sans-serif;font-size:${this.sets.fontSize};"> <div id="tabs-container"> <p style="padding-left:8px;">Loading panel...</p> </div> </div> `); } private escapeHtml(key: any): String { return String(key) .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); } /** * Gets an array of all parents starting from the handled parent_id. * Consider first entry is handled parent. */ private async getNoteParents(parent_id: string): Promise<any[]> { const parents: any[] = new Array(); let last_id: string = parent_id; while (last_id) { const parent: any = await joplin.data.get(['folders', last_id], { fields: ['id', 'title', 'parent_id'] }); if (!parent) break; last_id = parent.parent_id; parents.push(parent); } return parents; } /** * Gets all checklist items (with checked state) from the notes body. */ private getNoteChecklistItems(noteBody: string): any[] { let items: any[] = []; for (const line of noteBody.split('\n')) { const match = line.match(/^\s*(-\s+\[(x|\s)\])/); if (match) { items.push({ checked: match[2].includes("x", 0) }); } } return items; } /** * Prepares HTML for all tabs */ private async getNoteTabsHtml(selectedNote: any): Promise<string> { const showCompletedTodos: boolean = await this.sets.showCompletedTodos; const noteTabsHtml: any = []; for (const noteTab of this.tabs.tabs) { let note: any = null; // get real note from database, if no longer exists remove tab and continue with next one try { note = await joplin.data.get(['notes', noteTab.id], { fields: ['id', 'title', 'is_todo', 'todo_completed'] }); // console.log(`add note: ${JSON.stringify(note)}`); } catch (error) { // console.log(`delete note: ${noteTab.id}`); await this.tabs.delete(noteTab.id); continue; } if (note) { // continue with next tab if completed todos shall not be shown if ((!showCompletedTodos) && note.todo_completed) continue; // prepare tab style attributes const title: String = this.escapeHtml(note.title); const bg: string = (selectedNote && note.id == selectedNote.id) ? this.sets.actBackground : this.sets.background; const fg: string = (selectedNote && note.id == selectedNote.id) ? this.sets.actForeground : this.sets.foreground; const active: string = (selectedNote && note.id == selectedNote.id) ? 'active' : ''; const newTab: string = (NoteTabs.isTemporary(noteTab)) ? ' new' : ''; const icon: string = (NoteTabs.isPinned(noteTab)) ? 'fa-times' : 'fa-thumbtack'; const iconTitle: string = (NoteTabs.isPinned(noteTab)) ? 'Unpin' : 'Pin'; const textDecoration: string = (note.is_todo && note.todo_completed) ? 'line-through' : ''; // prepare checkbox for todo let checkboxHtml: string = ''; if (this.sets.showTodoCheckboxes && note.is_todo) { checkboxHtml = `<input id="check" type="checkbox" ${(note.todo_completed) ? "checked" : ''}>`; } noteTabsHtml.push(` <div id="tab" ${active} data-id="${note.id}" data-bg="${bg}" draggable="${this.sets.enableDragAndDrop}" class="${newTab}" role="tab" title="${title}" onclick="tabClick(event);" ondblclick="pinNote(event);" onauxclick="onAuxClick(event);" onmouseover="setBackground(event,'${this.sets.hoverBackground}');" onmouseout="resetBackground(this);" ondragstart="dragStart(event);" ondragend="dragEnd(event);" ondragover="dragOver(event, '${this.sets.hoverBackground}');" ondragleave="dragLeave(event);" ondrop="drop(event);" style="height:${this.sets.tabHeight}px;min-width:${this.sets.minTabWidth}px;max-width:${this.sets.maxTabWidth}px;border-color:${this.sets.dividerColor};background:${bg};"> <span class="tab-inner"> ${checkboxHtml} <span class="tab-title" style="color:${fg};text-decoration: ${textDecoration};"> ${title} </span> <a href="#" id="${iconTitle}" class="fas ${icon}" title="${iconTitle}" style="color:${fg};"></a> </span> </div> `); } } return noteTabsHtml.join('\n'); } /** * Prepares HTML for control buttons. Only if drag&drop is disabled. */ private getControlsHtml(): string { let controlsHtml: string = ''; if (!this.sets.enableDragAndDrop) { controlsHtml = ` <div id="controls" style="height:${this.sets.tabHeight}px;"> <a href="#" class="fas fa-chevron-left" title="Move active tab left" style="color:${this.sets.foreground};" onclick="message('tabsMoveLeft');"></a> <a href="#" class="fas fa-chevron-right" title="Move active tab right" style="color:${this.sets.foreground};" onclick="message('tabsMoveRight');"></a> </div> `; } return controlsHtml; } /** * Prepares HTML for navigation buttons, checklist states and breadcrumbs. Only if enabled. */ private async getInfoBarHtml(selectedNote: any): Promise<string> { let navigationHtml: string = ''; let checklistStatusHtml: string = ''; let breadcrumbsHtml: string = ''; let infobarHtml: string = ''; // prepare html for navigation buttons, if necessary if (this.sets.showNavigationButtons) { navigationHtml = ` <div class="navigation-icons" style="border-color:${this.sets.dividerColor};"> <a href="#" class="fas fa-chevron-left" title="Back" style="color:${this.sets.foreground};" onclick="message('tabsBack');"></a> <a href="#" class="fas fa-chevron-right" title="Forward" style="color:${this.sets.foreground};" onclick="message('tabsForward');"></a> </div> `; } // prepare html for checklist items, if necessary if (this.sets.showChecklistStatus && selectedNote) { const checklistItems: any[] = this.getNoteChecklistItems(selectedNote.body); if (checklistItems.length > 0) { const all: number = checklistItems.length; const checked: number = checklistItems.filter(x => x.checked).length; const completed: string = (checked == all) ? 'completed' : ''; checklistStatusHtml = ` <div class="checklist-state" style="color:${this.sets.foreground};border-color:${this.sets.dividerColor};"> <div class="checklist-state-inner"> <span class="checklist-state-text ${completed}"> <span class="fas fa-check-square" style=""></span> ${checked} / ${all} </span> </div> </div> `; } } // prepare html for breadcrumbs, if necessary if (this.sets.showBreadcrumbs && selectedNote) { let parentsHtml: any[] = new Array(); // collect all parent folders and prepare html container for each let parents: any[] = await this.getNoteParents(selectedNote.parent_id); while (parents) { const parent: any = parents.pop(); if (!parent) break; parentsHtml.push(` <div class="breadcrumb" data-id="${parent.id}" onClick="openFolder(event);" style="max-width:${this.sets.breadcrumbsMaxWidth}px;"> <span class="breadcrumb-inner"> <a href="#" class="breadcrumb-title" style="color:${this.sets.foreground};" title="${parent.title}">${parent.title}</a> <span class="fas fa-chevron-right" style="color:${this.sets.foreground};"></span> </span> </div> `); } if (parentsHtml) { breadcrumbsHtml = ` <div class="breadcrumbs-icon"> <span class="fas fa-book" style="color:${this.sets.foreground};"></span> </div> <div id="breadcrumbs-container"> ${parentsHtml.join(`\n`)} </div> `; } } // setup infobar container html, if any of the childs != empty string if (navigationHtml || checklistStatusHtml || breadcrumbsHtml) { infobarHtml = ` <div id="infobar-container" style="background:${this.sets.breadcrumbsBackground};"> ${navigationHtml} ${checklistStatusHtml} ${breadcrumbsHtml} </div> `; } return infobarHtml; } /** * Update the HTML webview with actual content. */ async updateWebview() { const selectedNote: any = await joplin.workspace.selectedNote(); const noteTabsHtml: string = await this.getNoteTabsHtml(selectedNote); const controlsHtml: string = this.getControlsHtml(); const infoBarHtml: string = await this.getInfoBarHtml(selectedNote); // add entries to container and push to panel await joplin.views.panels.setHtml(this._panel, ` <div id="container" style="background:${this.sets.background};font-family:${this.sets.fontFamily},sans-serif;font-size:${this.sets.fontSize};"> <div id="tabs-container" role="tablist" draggable="${this.sets.enableDragAndDrop}" ondragover="dragOver(event, '${this.sets.hoverBackground}');" ondragleave="dragLeave(event);" ondrop="drop(event);" ondragend="dragEnd(event);"> ${noteTabsHtml} ${controlsHtml} </div> ${infoBarHtml} </div> `); } /** * Toggle visibility of the panel. */ async toggleVisibility() { const isVisible: boolean = await joplin.views.panels.visible(this._panel); await joplin.views.panels.show(this._panel, (!isVisible)); } }
the_stack
import { AbstractConnector } from '@jsplumb/core'; import { BehaviouralTypeDescriptor } from '@jsplumb/core'; import { BoundingBox } from '@jsplumb/util'; import { Component } from '@jsplumb/core'; import { Connection } from '@jsplumb/core'; import { DeleteConnectionOptions } from '@jsplumb/core'; import { Dictionary } from '@jsplumb/util'; import { Endpoint } from '@jsplumb/core'; import { Extents } from '@jsplumb/util'; import { Grid } from '@jsplumb/util'; import { JsPlumbDefaults } from '@jsplumb/core'; import { jsPlumbElement } from '@jsplumb/core'; import { JsPlumbInstance } from '@jsplumb/core'; import { LabelOverlay } from '@jsplumb/core'; import { Overlay } from '@jsplumb/core'; import { PaintStyle } from '@jsplumb/common'; import { PointXY } from '@jsplumb/util'; import { RedrawResult } from '@jsplumb/core'; import { Size } from '@jsplumb/util'; import { SourceSelector } from '@jsplumb/core'; import { TypeDescriptor } from '@jsplumb/core'; import { UIGroup } from '@jsplumb/core'; export declare function addClass(el: Element | NodeListOf<Element>, clazz: string): void; /** * @public */ export declare const ATTRIBUTE_CONTAINER = "data-jtk-container"; /** * @public */ export declare const ATTRIBUTE_GROUP_CONTENT = "data-jtk-group-content"; /** * @public */ export declare const ATTRIBUTE_JTK_ENABLED = "data-jtk-enabled"; /** * @public */ export declare const ATTRIBUTE_JTK_SCOPE = "data-jtk-scope"; declare abstract class Base { protected el: jsPlumbDOMElement; protected k: Collicat; abstract _class: string; uuid: string; private enabled; scopes: Array<string>; protected constructor(el: jsPlumbDOMElement, k: Collicat); setEnabled(e: boolean): void; isEnabled(): boolean; toggleEnabled(): void; addScope(scopes: string): void; removeScope(scopes: string): void; toggleScope(scopes: string): void; } export declare interface BeforeStartEventParams extends DragStartEventParams { } export declare interface BrowserJsPlumbDefaults extends JsPlumbDefaults<Element> { /** * Whether or not elements should be draggable. Default value is `true`. */ elementsDraggable?: boolean; /** * Options for dragging - containment, grid, callbacks etc. */ dragOptions?: DragOptions; managedElementsSelector?: string; } /** * JsPlumbInstance that renders to the DOM in a browser, and supports dragging of elements/connections. * */ export declare class BrowserJsPlumbInstance extends JsPlumbInstance<ElementType> { _instanceIndex: number; private dragSelection; dragManager: DragManager; _connectorClick: Function; _connectorDblClick: Function; _connectorTap: Function; _connectorDblTap: Function; _endpointClick: Function; _endpointDblClick: Function; _overlayClick: Function; _overlayDblClick: Function; _overlayTap: Function; _overlayDblTap: Function; _connectorMouseover: Function; _connectorMouseout: Function; _endpointMouseover: Function; _endpointMouseout: Function; _overlayMouseover: Function; _overlayMouseout: Function; _elementClick: Function; _elementTap: Function; _elementDblTap: Function; _elementMouseenter: Function; _elementMouseexit: Function; eventManager: EventManager; draggingClass: string; elementDraggingClass: string; hoverClass: string; sourceElementDraggingClass: string; targetElementDraggingClass: string; hoverSourceClass: string; hoverTargetClass: string; dragSelectClass: string; managedElementsSelector: string; /** * Whether or not elements should be draggable. This can be provided in the constructor arguments, or simply toggled on the * class. The default value is `true`. */ elementsDraggable: boolean; private elementDragHandler; private groupDragOptions; private elementDragOptions; constructor(_instanceIndex: number, defaults?: BrowserJsPlumbDefaults); private fireOverlayMethod; /** * Adds a filter to the list of filters used to determine whether or not a given event should start an element drag. * @param filter CSS3 selector, or function that takes an element and returns true/false * @param exclude If true, the filter is inverted: anything _but_ this value. */ addDragFilter(filter: Function | string, exclude?: boolean): void; /** * Removes a filter from the list of filters used to determine whether or not a given event should start an element drag. * @param filter CSS3 selector, or function that takes an element and returns true/false */ removeDragFilter(filter: Function | string): void; /** * Sets the grid that should be used when dragging elements. * @param grid [x, y] grid. */ setDragGrid(grid: Grid): void; _removeElement(element: Element): void; _appendElement(el: Element, parent: Element): void; _getAssociatedElements(el: Element): Array<Element>; shouldFireEvent(event: string, value: any, originalEvent?: Event): boolean; getClass(el: Element): string; /** * Add one or more classes to the given element or list of elements. * @param el Element, or list of elements to which to add the class(es) * @param clazz A space separated list of classes to add. */ addClass(el: Element | NodeListOf<Element>, clazz: string): void; /** * Returns whether or not the given element has the given class. * @param el * @param clazz */ hasClass(el: Element, clazz: string): boolean; /** * Remove one or more classes from the given element or list of elements. * @param el Element, or list of elements from which to remove the class(es) * @param clazz A space separated list of classes to remove. */ removeClass(el: Element | NodeListOf<Element>, clazz: string): void; /** * Toggles one or more classes on the given element or list of elements. * @param el Element, or list of elements on which to toggle the class(es) * @param clazz A space separated list of classes to toggle. */ toggleClass(el: Element | NodeListOf<Element>, clazz: string): void; setAttribute(el: Element, name: string, value: string): void; getAttribute(el: Element, name: string): string; setAttributes(el: Element, atts: Dictionary<string>): void; removeAttribute(el: Element, attName: string): void; /** * Bind an event listener to the given element or elements. * @param el Element, or elements, to bind the event listener to. * @param event Name of the event to bind to. * @param callbackOrSelector Either a callback function, or a CSS 3 selector. When this is a selector the event listener is bound as a "delegate", ie. the event listeners * listens to events on children of the given `el` that match the selector. * @param callback Callback function for event. Only supplied when you're binding a delegated event handler. */ on(el: Document | Element | NodeListOf<Element>, event: string, callbackOrSelector: Function | string, callback?: Function): this; /** * Remove an event binding from the given element or elements. * @param el Element, or elements, from which to remove the event binding. * @param event Name of the event to unbind. * @param callback The function you wish to unbind. */ off(el: Document | Element | NodeListOf<Element>, event: string, callback: Function): this; /** * Trigger an event on the given element. * @param el Element to trigger the event on. * @param event Name of the event to trigger. * @param originalEvent Optional event that gave rise to this method being called. * @param payload Optional `payload` to set on the Event that is created. */ trigger(el: Document | Element, event: string, originalEvent?: Event, payload?: any, detail?: number): void; getOffsetRelativeToRoot(el: Element): PointXY; getOffset(el: Element): PointXY; getSize(el: Element): Size; getStyle(el: Element, prop: string): any; getGroupContentArea(group: UIGroup<any>): ElementType["E"]; getSelector(ctx: string | Element, spec?: string): ArrayLike<jsPlumbDOMElement>; /** * Sets the position of the given element. * @param el Element to change position for * @param p New location for the element. */ setPosition(el: Element, p: PointXY): void; setDraggable(element: Element, draggable: boolean): void; isDraggable(el: Element): boolean; toggleDraggable(el: Element): boolean; private _attachEventDelegates; private _detachEventDelegates; setContainer(newContainer: Element): void; reset(): void; destroy(): void; unmanage(el: Element, removeElement?: boolean): void; addToDragSelection(...el: Array<Element>): void; clearDragSelection(): void; removeFromDragSelection(...el: Array<Element>): void; toggleDragSelection(...el: Array<Element>): void; /** * Adds the given element(s) to the given drag group. * @param spec Either the ID of some drag group, in which case the elements are all added as 'active', or an object of the form * { id:"someId", active:boolean }. In the latter case, `active`, if true, which is the default, indicates whether * dragging the given element(s) should cause all the elements in the drag group to be dragged. If `active` is false it means the * given element(s) is "passive" and should only move when an active member of the drag group is dragged. * @param els Elements to add to the drag group. */ addToDragGroup(spec: DragGroupSpec, ...els: Array<Element>): void; /** * Removes the given element(s) from any drag group they may be in. You don't need to supply the drag group id, as elements * can only be in one drag group anyway. * @param els Elements to remove from drag groups. */ removeFromDragGroup(...els: Array<Element>): void; /** * Sets the active/passive state for the given element(s).You don't need to supply the drag group id, as elements * can only be in one drag group anyway. * @param state true for active, false for passive. * @param els */ setDragGroupState(state: boolean, ...els: Array<Element>): void; /** * Consumes the given event. * @param e * @param doNotPreventDefault */ consume(e: Event, doNotPreventDefault?: boolean): void; rotate(element: Element, rotation: number, doNotRepaint?: boolean): RedrawResult; svg: { node: (name: string, attributes?: Dictionary<string | number>) => SVGElement; attr: (node: SVGElement, attributes: Dictionary<string | number>) => void; pos: (d: [number, number]) => string; }; addOverlayClass(o: Overlay, clazz: string): void; removeOverlayClass(o: Overlay, clazz: string): void; paintOverlay(o: Overlay, params: any, extents: any): void; setOverlayVisible(o: Overlay, visible: boolean): void; reattachOverlay(o: Overlay, c: Component): void; setOverlayHover(o: Overlay, hover: boolean): void; destroyOverlay(o: Overlay): void; drawOverlay(o: Overlay, component: any, paintStyle: PaintStyle, absolutePosition?: PointXY): any; updateLabel(o: LabelOverlay): void; setHover(component: Component, hover: boolean): void; paintConnector(connector: AbstractConnector, paintStyle: PaintStyle, extents?: Extents): void; setConnectorHover(connector: AbstractConnector, h: boolean, doNotCascade?: boolean): void; destroyConnector(connection: Connection): void; addConnectorClass(connector: AbstractConnector, clazz: string): void; removeConnectorClass(connector: AbstractConnector, clazz: string): void; getConnectorClass(connector: AbstractConnector): string; setConnectorVisible(connector: AbstractConnector, v: boolean): void; applyConnectorType(connector: AbstractConnector, t: TypeDescriptor): void; addEndpointClass(ep: Endpoint, c: string): void; applyEndpointType<C>(ep: Endpoint, t: TypeDescriptor): void; destroyEndpoint(ep: Endpoint): void; renderEndpoint(ep: Endpoint, paintStyle: PaintStyle): void; removeEndpointClass(ep: Endpoint, c: string): void; getEndpointClass(ep: Endpoint): string; setEndpointHover(endpoint: Endpoint, h: boolean, doNotCascade?: boolean): void; setEndpointVisible(ep: Endpoint, v: boolean): void; setGroupVisible(group: UIGroup<Element>, state: boolean): void; deleteConnection(connection: Connection, params?: DeleteConnectionOptions): boolean; addSourceSelector(selector: string, params?: BehaviouralTypeDescriptor, exclude?: boolean): SourceSelector; removeSourceSelector(selector: SourceSelector): void; } export declare class Collicat implements jsPlumbDragManager { eventManager: EventManager; private zoom; css: Dictionary<string>; inputFilterSelector: string; constructor(options?: CollicatOptions); getZoom(): number; setZoom(z: number): void; private _prepareParams; /** * Gets the selector identifying which input elements to filter from drag events. * @returns Current input filter selector. */ getInputFilterSelector(): string; /** * Sets the selector identifying which input elements to filter from drag events. * @param selector Input filter selector to set. * @returns Current instance; method may be chained. */ setInputFilterSelector(selector: string): this; draggable(el: jsPlumbDOMElement, params: DragParams): Drag; destroyDraggable(el: jsPlumbDOMElement): void; } export declare interface CollicatOptions { zoom?: number; css?: Dictionary<string>; inputFilterSelector?: string; } export declare function compoundEvent(stem: string, event: string, subevent?: string): string; /** * @public */ export declare const CONNECTION = "connection"; export declare type ConstrainFunction = (desiredLoc: PointXY, dragEl: HTMLElement, constrainRect: Size, size: Size) => PointXY; export declare function consume(e: Event, doNotPreventDefault?: boolean): void; export declare enum ContainmentType { notNegative = "notNegative", parent = "parent", parentEnclosed = "parentEnclosed" } export declare function createElement(tag: string, style?: Dictionary<any>, clazz?: string, atts?: Dictionary<string>): jsPlumbDOMElement; export declare function createElementNS(ns: string, tag: string, style?: Dictionary<any>, clazz?: string, atts?: Dictionary<string | number>): jsPlumbDOMElement; export declare class Drag extends Base { _class: string; rightButtonCanDrag: boolean; consumeStartEvent: boolean; clone: boolean; scroll: boolean; trackScroll: boolean; private _downAt; private _posAtDown; private _pagePosAtDown; private _pageDelta; private _moving; private _lastPosition; private _lastScrollValues; private _initialScroll; _size: Size; private _currentParentPosition; private _ghostParentPosition; private _dragEl; private _multipleDrop; private _ghostProxyOffsets; private _ghostDx; private _ghostDy; _isConstrained: boolean; _ghostProxyParent: jsPlumbDOMElement; _useGhostProxy: Function; _ghostProxyFunction: GhostProxyGenerator; _activeSelectorParams: DragParams; _availableSelectors: Array<DragParams>; _canDrag: Function; private _consumeFilteredEvents; private _parent; private _ignoreZoom; _filters: Dictionary<[Function, boolean]>; _constrainRect: { w: number; h: number; }; _elementToDrag: jsPlumbDOMElement; downListener: (e: MouseEvent) => void; moveListener: (e: MouseEvent) => void; upListener: (e?: MouseEvent) => void; listeners: Dictionary<Array<Function>>; constructor(el: jsPlumbDOMElement, params: DragParams, k: Collicat); on(evt: string, fn: Function): void; off(evt: string, fn: Function): void; private _upListener; private _downListener; private _moveListener; private mark; private unmark; moveBy(dx: number, dy: number, e?: MouseEvent): void; abort(): void; getDragElement(retrieveOriginalElement?: boolean): jsPlumbDOMElement; stop(e?: MouseEvent, force?: boolean): void; private _dispatch; private resolveGrid; /** * Snap the given position to a grid, if the active selector has declared a grid. * @param pos */ private toGrid; setUseGhostProxy(val: boolean): void; private _doConstrain; _testFilter(e: any): boolean; addFilter(f: Function | string, _exclude?: boolean): void; removeFilter(f: Function | string): void; clearAllFilters(): void; addSelector(params: DragHandlerOptions, atStart?: boolean): void; destroy(): void; } export declare interface DragEventParams extends DragStartEventParams { originalPos: PointXY; } export declare type DraggedElement = { el: jsPlumbDOMElement; id: string; pos: PointXY; originalPos: PointXY; originalGroup: UIGroup; redrawResult: RedrawResult; reverted: boolean; dropGroup: UIGroup; }; export declare type DragGroupSpec = string | { id: string; active: boolean; }; declare interface DragHandler { selector: string; onStart: (params: DragStartEventParams) => boolean; onDrag: (params: DragEventParams) => void; onStop: (params: DragStopEventParams) => void; onDragInit: (el: Element) => Element; onDragAbort: (el: Element) => void; reset: () => void; init: (drag: Drag) => void; onBeforeStart?: (beforeStartParams: BeforeStartEventParams) => void; } export declare interface DragHandlerOptions { selector?: string; start?: (p: DragStartEventParams) => any; stop?: (p: DragStopEventParams) => any; drag?: (p: DragEventParams) => any; beforeStart?: (beforeStartParams: BeforeStartEventParams) => void; dragInit?: (el: Element) => any; dragAbort?: (el: Element) => any; ghostProxy?: GhostProxyGenerator | boolean; makeGhostProxy?: GhostProxyGenerator; useGhostProxy?: (container: any, dragEl: jsPlumbDOMElement) => boolean; ghostProxyParent?: Element; constrainFunction?: ConstrainFunction | boolean; revertFunction?: RevertFunction; filter?: string; filterExclude?: boolean; snapThreshold?: number; grid?: Grid; containment?: ContainmentType; containmentPadding?: number; } declare class DragManager { protected instance: BrowserJsPlumbInstance; protected dragSelection: DragSelection; private collicat; private drag; _draggables: Dictionary<any>; _dlist: Array<any>; _elementsWithEndpoints: Dictionary<any>; _draggablesForElements: Dictionary<any>; handlers: Array<{ handler: DragHandler; options: DragHandlerOptions; }>; private _trackScroll; private _filtersToAdd; constructor(instance: BrowserJsPlumbInstance, dragSelection: DragSelection, options?: DragManagerOptions); addHandler(handler: DragHandler, dragOptions?: DragHandlerOptions): void; addFilter(filter: Function | string, exclude?: boolean): void; removeFilter(filter: Function | string): void; setFilters(filters: Array<[string, boolean]>): void; reset(): Array<[string, boolean]>; setOption(handler: DragHandler, options: DragHandlerOptions): void; } declare interface DragManagerOptions { trackScroll?: boolean; } /** * Payload for `drag:move` event. */ export declare interface DragMovePayload extends DragPayload { } export declare interface DragOptions { containment?: ContainmentType; start?: (params: DragStartEventParams) => void; drag?: (params: DragEventParams) => void; stop?: (params: DragStopEventParams) => void; cursor?: string; zIndex?: number; grid?: Grid; trackScroll?: boolean; } export declare interface DragParams extends DragHandlerOptions { rightButtonCanDrag?: boolean; consumeStartEvent?: boolean; clone?: boolean; scroll?: boolean; trackScroll?: boolean; multipleDrop?: boolean; canDrag?: Function; consumeFilteredEvents?: boolean; events?: Dictionary<Function>; parent?: any; ignoreZoom?: boolean; scope?: string; } /** * Base payload for drag events. Contains the element being dragged, the corresponding mouse event, the current position, and the position when drag started. */ export declare interface DragPayload { el: Element; e: Event; pos: PointXY; originalPosition: PointXY; payload?: Record<string, any>; } declare class DragSelection { private instance; private _dragSelection; private _dragSizes; private _dragElements; private _dragElementStartPositions; private _dragElementPositions; private __activeSet; private readonly _activeSet; constructor(instance: BrowserJsPlumbInstance); readonly length: number; filterActiveSet(fn: (p: { id: string; jel: jsPlumbDOMElement; }) => boolean): void; /** * Reset all computed values and remove all elements from the selection. */ clear(): void; /** * Reset all computed values. Does not remove elements from the selection. Use `clear()` for that. This method is intended for * use after (or before) a drag. * @internal */ reset(): void; initialisePositions(): void; updatePositions(currentPosition: PointXY, originalPosition: PointXY, callback: (el: jsPlumbDOMElement, id: string, s: Size, b: BoundingBox) => any): void; /** * Iterate through the contents of the drag selection and execute the given function on each entry. * @param f */ each(f: (el: jsPlumbDOMElement, id: string, o: PointXY, s: Size, originalPosition: PointXY) => any): void; add(el: Element, id?: string): void; remove(el: Element): void; toggle(el: Element): void; } export declare interface DragStartEventParams { e: MouseEvent; el: jsPlumbDOMElement; pos: PointXY; drag: Drag; size: Size; } /** * Payload for `drag:start` event. */ export declare interface DragStartPayload extends DragPayload { } export declare interface DragStopEventParams extends DragEventParams { finalPos: PointXY; selection: Array<[jsPlumbDOMElement, PointXY, Drag, Size]>; } /** * Payload for `drag:stop` event. In addition to the base payload, contains a redraw result object, listing all the connections and endpoints that were affected by the drag. */ export declare interface DragStopPayload { elements: Array<DraggedElement>; e: Event; el: Element; payload?: Record<string, any>; } /** * @public */ export declare const ELEMENT = "element"; /** * @public */ export declare const ELEMENT_DIV = "div"; export declare class ElementDragHandler implements DragHandler { protected instance: BrowserJsPlumbInstance; protected _dragSelection: DragSelection; selector: string; private _dragOffset; private _groupLocations; protected _intersectingGroups: Array<IntersectingGroup>; private _currentDragParentGroup; private _dragGroupByElementIdMap; private _dragGroupMap; private _currentDragGroup; private _currentDragGroupOffsets; private _currentDragGroupSizes; private _dragPayload; protected drag: Drag; originalPosition: PointXY; constructor(instance: BrowserJsPlumbInstance, _dragSelection: DragSelection); onDragInit(el: Element): Element; onDragAbort(el: Element): void; protected getDropGroup(): IntersectingGroup | null; onStop(params: DragStopEventParams): void; private _cleanup; reset(): void; init(drag: Drag): void; onDrag(params: DragEventParams): void; onStart(params: { e: MouseEvent; el: jsPlumbDOMElement; pos: PointXY; drag: Drag; }): boolean; addToDragGroup(spec: DragGroupSpec, ...els: Array<Element>): void; removeFromDragGroup(...els: Array<Element>): void; setDragGroupState(state: boolean, ...els: Array<Element>): void; /** * Perhaps prune or orphan the element represented by the given drag params. * @param params * @param doNotTransferToAncestor Used when dealing with nested groups. When true, it means remove the element from any groups; when false, which is * the default, elements that are orphaned will be added to this group's ancestor, if it has one. * @param isDefinitelyNotInsideParent Used internally when this method is called and we've already done an intersections test. This flag saves us repeating the calculation. * @internal */ private _pruneOrOrphan; } export declare type ElementType = { E: Element; }; /** * @public */ export declare const ENDPOINT = "endpoint"; export declare type EndpointHelperFunctions<E> = { makeNode: (ep: E, paintStyle: PaintStyle) => void; updateNode: (ep: E, node: SVGElement) => void; }; export declare const EVENT_BEFORE_START = "beforeStart"; /** * @public */ export declare const EVENT_CLICK = "click"; /** * @public */ export declare const EVENT_CONNECTION_ABORT = "connection:abort"; /** * @public */ export declare const EVENT_CONNECTION_CLICK: string; /** * @public */ export declare const EVENT_CONNECTION_DBL_CLICK: string; /** * @public */ export declare const EVENT_CONNECTION_DBL_TAP: string; /** * @public */ export declare const EVENT_CONNECTION_DRAG = "connection:drag"; /** * @public */ export declare const EVENT_CONNECTION_MOUSEOUT: string; /** * @public */ export declare const EVENT_CONNECTION_MOUSEOVER: string; /** * @public */ export declare const EVENT_CONNECTION_TAP: string; /** * @public */ export declare const EVENT_CONTEXTMENU = "contextmenu"; /** * @public */ export declare const EVENT_DBL_CLICK = "dblclick"; /** * @public */ export declare const EVENT_DBL_TAP = "dbltap"; export declare const EVENT_DRAG = "drag"; /** * @public */ export declare const EVENT_DRAG_MOVE = "drag:move"; /** * @public */ export declare const EVENT_DRAG_START = "drag:start"; /** * @public */ export declare const EVENT_DRAG_STOP = "drag:stop"; export declare const EVENT_DROP = "drop"; /** * @public */ export declare const EVENT_ELEMENT_CLICK: string; /** * @public */ export declare const EVENT_ELEMENT_DBL_CLICK: string; /** * @public */ export declare const EVENT_ELEMENT_DBL_TAP: string; /** * @public */ export declare const EVENT_ELEMENT_MOUSE_OUT: string; /** * @public */ export declare const EVENT_ELEMENT_MOUSE_OVER: string; /** * @public */ export declare const EVENT_ELEMENT_TAP: string; /** * @public */ export declare const EVENT_ENDPOINT_CLICK: string; /** * @public */ export declare const EVENT_ENDPOINT_DBL_CLICK: string; /** * @public */ export declare const EVENT_ENDPOINT_DBL_TAP: string; /** * @public */ export declare const EVENT_ENDPOINT_MOUSEOUT: string; /** * @public */ export declare const EVENT_ENDPOINT_MOUSEOVER: string; /** * @public */ export declare const EVENT_ENDPOINT_TAP: string; /** * @public */ export declare const EVENT_FOCUS = "focus"; /** * @public */ export declare const EVENT_MOUSEDOWN = "mousedown"; /** * @public */ export declare const EVENT_MOUSEENTER = "mouseenter"; /** * @public */ export declare const EVENT_MOUSEEXIT = "mouseexit"; /** * @public */ export declare const EVENT_MOUSEMOVE = "mousemove"; /** * @public */ export declare const EVENT_MOUSEOUT = "mouseout"; /** * @public */ export declare const EVENT_MOUSEOVER = "mouseover"; /** * @public */ export declare const EVENT_MOUSEUP = "mouseup"; export declare const EVENT_OUT = "out"; export declare const EVENT_OVER = "over"; /** * @public */ export declare const EVENT_REVERT = "revert"; export declare const EVENT_START = "start"; export declare const EVENT_STOP = "stop"; /** * @public */ export declare const EVENT_TAP = "tap"; export declare class EventManager { clickThreshold: number; dblClickThreshold: number; private readonly tapHandler; private readonly mouseEnterExitHandler; constructor(params?: EventManagerOptions); private _doBind; on(el: any, event: string, children?: string | Function, fn?: Function, options?: { passive?: boolean; capture?: boolean; once?: boolean; }): this; off(el: any, event: string, fn: any): this; trigger(el: any, event: string, originalEvent: any, payload?: any, detail?: number): this; } declare interface EventManagerOptions { clickThreshold?: number; dblClickThreshold?: number; } export declare function findParent(el: jsPlumbDOMElement, selector: string, container: HTMLElement, matchOnElementAlso: boolean): jsPlumbDOMElement; export declare function getClass(el: Element): string; export declare function getEventSource(e: Event): jsPlumbDOMElement; export declare function getPositionOnElement(evt: Event, el: Element, zoom: number): PointXY; export declare function getTouch(touches: TouchList, idx: number): Touch; export declare type GhostProxyGenerator = (el: Element) => Element; export declare function groupDragConstrain(desiredLoc: PointXY, dragEl: jsPlumbDOMElement, constrainRect: BoundingBox, size: Size): PointXY; export declare type GroupLocation = { el: Element; r: BoundingBox; group: UIGroup<Element>; }; export declare function hasClass(el: Element, clazz: string): boolean; export declare type IntersectingGroup = { groupLoc: GroupLocation; d: number; intersectingElement: Element; }; export declare function isArrayLike(el: any): el is ArrayLike<Element>; export declare function isInsideParent(instance: BrowserJsPlumbInstance, _el: HTMLElement, pos: PointXY): boolean; export declare function isNodeList(el: any): el is NodeListOf<Element>; export declare interface jsPlumbDOMElement extends HTMLElement, jsPlumbElement<Element> { _isJsPlumbGroup: boolean; _jsPlumbOrphanedEndpoints: Array<Endpoint>; offsetParent: jsPlumbDOMElement; parentNode: jsPlumbDOMElement; jtk: jsPlumbDOMInformation; _jsPlumbScrollHandler?: Function; _katavorioDrag?: Drag; cloneNode: (deep?: boolean) => jsPlumbDOMElement; } export declare interface jsPlumbDOMInformation { connector?: AbstractConnector; endpoint?: Endpoint; overlay?: Overlay; } export declare interface jsPlumbDragManager { getZoom(): number; setZoom(z: number): void; getInputFilterSelector(): string; setInputFilterSelector(selector: string): void; draggable(el: jsPlumbDOMElement, params: DragParams): Drag; destroyDraggable(el: jsPlumbDOMElement): void; } export declare function matchesSelector(el: jsPlumbDOMElement, selector: string, ctx?: Element): boolean; export declare function newInstance(defaults?: BrowserJsPlumbDefaults): BrowserJsPlumbInstance; export declare function offsetRelativeToRoot(el: Element): PointXY; export declare function pageLocation(e: Event): PointXY; /** * @public */ export declare const PROPERTY_POSITION = "position"; export declare function ready(f: Function): void; export declare function registerEndpointRenderer<C>(name: string, fns: EndpointHelperFunctions<C>): void; export declare function removeClass(el: Element | NodeListOf<Element>, clazz: string): void; export declare type RevertEventParams = jsPlumbDOMElement; export declare type RevertFunction = (dragEl: HTMLElement, pos: PointXY) => boolean; /** * @public */ export declare const SELECTOR_CONNECTOR: string; /** * @public */ export declare const SELECTOR_ENDPOINT: string; /** * @public */ export declare const SELECTOR_GROUP: string; /** * @public */ export declare const SELECTOR_GROUP_CONTAINER: string; /** * @public */ export declare const SELECTOR_OVERLAY: string; export declare function size(el: Element): Size; export declare function toggleClass(el: Element | NodeListOf<Element>, clazz: string): void; export declare function touchCount(e: Event): number; export declare function touches(e: any): TouchList; export declare interface UIComponent { canvas: HTMLElement; svg: SVGElement; } export { }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { Connector } from '../../../src/diagram/objects/connector'; import { Node } from '../../../src/diagram/objects/node'; import { ConnectorModel } from '../../../src/diagram/objects/connector-model'; import { NodeModel, BasicShapeModel } from '../../../src/diagram/objects/node-model'; import { MouseEvents } from './mouseevents.spec'; import { NodeConstraints, ConnectorConstraints, hasSelection, SelectorModel, PointModel } from '../../../src/diagram/index'; import { IDraggingEventArgs, IPropertyChangeEventArgs, IDropEventArgs, IElement } from '../../../src/diagram/objects/interface/IElement'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; describe('Testing AllowDrop', () => { let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'allowDrop' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 90, offsetY: 90 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 290, offsetY: 90, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 490, offsetY: 90, }; let node4: NodeModel = { id: 'node4', width: 100, height: 100, offsetX: 490, offsetY: 290, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let connector1: ConnectorModel = { id: 'connector1', sourcePoint: { x: 190, y: 290 }, targetPoint: { x: 290, y: 290 }, constraints: ConnectorConstraints.Default | ConnectorConstraints.AllowDrop }; diagram = new Diagram({ width: 700, height: 600, nodes: [node1, node2, node3, node4], connectors: [connector1], }); diagram.appendTo('#allowDrop'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking node with AlllowDrop Constraint', (done: Function) => { let node1: NodeModel = diagram.nodes[0]; let node2: NodeModel = diagram.nodes[1]; let highlighter: HTMLElement = null; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 100, 100, 260, 100); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter !== null).toBe(true); diagram.drop = (args: IDropEventArgs) => { highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter === null && args.target === node2).toBe(true); } mouseEvents.mouseUpEvent(diagramCanvas, 255, 100); mouseEvents.dragEvent(diagramCanvas, 225, 100, 100, 100); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking node without AlllowDrop Constraint', (done: Function) => { let highlighter: HTMLElement = null; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 100, 100, 450, 100); mouseEvents.mouseMoveEvent(diagramCanvas, 455, 100); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter === null).toBe(true); mouseEvents.mouseMoveEvent(diagramCanvas, 100, 100); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking AlllowDrop Constraint', (done: Function) => { let highlighter: HTMLElement = null; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 100, 100, 450, 300); mouseEvents.mouseMoveEvent(diagramCanvas, 455, 300); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter !== null).toBe(true); mouseEvents.mouseMoveEvent(diagramCanvas, 470, 300); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter !== null).toBe(true); mouseEvents.mouseMoveEvent(diagramCanvas, 100, 100); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking connector with AlllowDrop Constraint', (done: Function) => { let connector1: ConnectorModel = diagram.connectors[0]; let highlighter: HTMLElement = null; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 100, 100, 250, 100); mouseEvents.mouseMoveEvent(diagramCanvas, 255, 100); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter !== null).toBe(true); mouseEvents.mouseMoveEvent(diagramCanvas, 250, 295); highlighter = document.getElementById(diagram.element.id + '_diagramAdorner_svg_highlighter'); expect(highlighter !== null).toBe(true); mouseEvents.mouseMoveEvent(diagramCanvas, 100, 100); mouseEvents.mouseMoveEvent(diagramCanvas, 105, 100); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); }); describe('Testing Object Sorting - 1', () => { let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'allowDrop_1' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, zIndex: 4 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 300, offsetY: 100, zIndex: 3, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, zIndex: 2, }; let node4: NodeModel = { id: 'node4', width: 100, height: 100, offsetX: 500, offsetY: 300, zIndex: 1, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let connector1: ConnectorModel = { id: 'connector1', sourcePoint: { x: 200, y: 300 }, targetPoint: { x: 300, y: 300 }, constraints: ConnectorConstraints.Default | ConnectorConstraints.AllowDrop }; diagram = new Diagram({ width: 700, height: 600, nodes: [node1, node2, node3, node4], connectors: [connector1], }); diagram.appendTo('#allowDrop_1'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking inserting of the first element to the collection', (done: Function) => { let node = diagram.nodes[0]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.mouseMoveEvent(diagramCanvas, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Select', false); expect(objects.length !== 0 && objects[0] === node).toBe(true); done(); }); it('Checking inserting two elements with reverse zIndex to the collection', (done: Function) => { let node = diagram.nodes[0]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 300, 100, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[1] === node).toBe(true); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking inserting of the three elements with reverse zIndex to the collection', (done: Function) => { let node = diagram.nodes[0]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 500, 100, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[2] === node).toBe(true); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking inserting of the four elements with reverse zIndex to the collection', (done: Function) => { let node = diagram.nodes[0]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 500, 300, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[3] === node).toBe(true) mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); }); describe('Testing Object Sorting - 2', () => { let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'allowDrop_2' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 300, offsetY: 100, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, }; let node4: NodeModel = { id: 'node4', width: 100, height: 100, offsetX: 500, offsetY: 300, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; diagram = new Diagram({ width: 700, height: 600, nodes: [node1, node2, node3, node4], }); diagram.appendTo('#allowDrop_2'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking inserting two elements with Normal zIndex to the collection', (done: Function) => { let node = diagram.nodes[1]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 300, 100, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[1] === node).toBe(true); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking inserting of the three elements with Normal zIndex to the collection', (done: Function) => { let node = diagram.nodes[2]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 500, 100, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[2] === node).toBe(true); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('Checking inserting of the four elements with Normal zIndex to the collection', (done: Function) => { let node = diagram.nodes[3]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragEvent(diagramCanvas, 500, 300, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[3] === node).toBe(true) mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); }); describe('Testing Object Sorting - 3', () => { let diagram: Diagram; let ele: HTMLElement; let mouseEvents: MouseEvents = new MouseEvents(); beforeAll((): void => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } ele = createElement('div', { id: 'allowDrop_3' }); document.body.appendChild(ele); let selArray: (NodeModel | ConnectorModel)[] = []; let node1: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, zIndex: 3 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 300, offsetY: 100, zIndex: 1, constraints: NodeConstraints.Default | NodeConstraints.AllowDrop }; let node3: NodeModel = { id: 'node3', width: 100, height: 100, offsetX: 500, offsetY: 100, zIndex: 2, }; diagram = new Diagram({ width: 700, height: 600, nodes: [node1, node2, node3], }); diagram.appendTo('#allowDrop_3'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking inserting of the three elements with randomly arranged zIndex to the collection', (done: Function) => { let node = diagram.nodes[2]; let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id + 'content'); mouseEvents.dragAndDropEvent(diagramCanvas, 300, 100, 100, 100); mouseEvents.dragEvent(diagramCanvas, 500, 100, 100, 100); let currentPosition: PointModel = { x: 100, y: 100 }; let objects: IElement[] = diagram.findObjectsUnderMouse(currentPosition); let object: IElement = diagram.findObjectUnderMouse(objects, 'Drag', true); expect(objects.length !== 0 && objects[1] === node).toBe(true); mouseEvents.mouseUpEvent(diagramCanvas, 100, 100); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import * as data from "./data"; import * as React from "react"; import * as core from "./core"; import * as workspace from "./workspace"; import * as pkg from "./package"; import * as codecard from "./codecard"; import { Button } from "../../react-common/components/controls/Button"; import { workerOpAsync } from "./compiler"; import { SearchInput } from "./components/searchInput"; import { useState, useEffect } from "react"; import { ImportModal } from "../../react-common/components/extensions/ImportModal"; import { DeleteConfirmationModal } from "../../react-common/components/extensions/DeleteConfirmationModal"; import { Modal } from "../../react-common/components/controls/Modal"; type ExtensionMeta = pxtc.service.ExtensionMeta; type EmptyCard = { name: string, loading?: boolean } const emptyCard: EmptyCard = { name: "", loading: true } interface ExtensionsProps { hideExtensions: () => void; header: pxt.workspace.Header; reloadHeaderAsync: () => Promise<void>; } enum TabState { Recommended, Installed, InDevelopment } export const ExtensionsBrowser = (props: ExtensionsProps) => { const [searchFor, setSearchFor] = useState(""); const [allExtensions, setAllExtensions] = useState(fetchBundled()); const [extensionsToShow, setExtensionsToShow] = useState<(ExtensionMeta & EmptyCard)[]>([]); const [selectedTag, setSelectedTag] = useState(""); const [currentTab, setCurrentTab] = useState(TabState.Recommended); const [showImportExtensionDialog, setShowImportExtensionDialog] = useState(false); const [installedExtensions, setInstalledExtensions] = useState<(ExtensionMeta & EmptyCard)[]>([]) const [deletionCandidate, setDeletionCandidate] = useState(undefined) const [preferredExts, setPreferredExts] = useState<(ExtensionMeta & EmptyCard)[]>([]) const [extensionTags, setExtensionTags] = useState(new Map<string, pxt.RepoData[]>()) useEffect(() => { updateInstalledExts(); updateExtensionTags(); updatePreferredExts(); }, []) useEffect(() => { if (searchFor && searchFor != "") { searchForBundledAndGithubAsync(); } }, [searchFor]) /** * Github search */ async function searchForBundledAndGithubAsync() { setExtensionsToShow([emptyCard, emptyCard, emptyCard, emptyCard]) const exts = await fetchGithubDataAsync([searchFor]) const parsedExt = exts.map(repo => parseGithubRepo(repo)) //Search bundled extensions as well fetchBundled().forEach(e => { if (e.name.toLowerCase().indexOf(searchFor.toLowerCase()) > -1) { //Fuzzy search here? parsedExt.unshift(e) } }) addExtensionsToPool(parsedExt) setExtensionsToShow(parsedExt) } function addExtensionsToPool(newExtension: ExtensionMeta[]) { if (!newExtension) { return; } const addedExtensions = allExtensions; newExtension.forEach(e => { if (!addedExtensions.has(e.name.toLowerCase())) { addedExtensions.set(e.name.toLowerCase(), e) } }) setAllExtensions(addedExtensions); } function getExtensionFromFetched(extensionUrl: string) { const fullName = allExtensions.get(extensionUrl.toLowerCase()) if (fullName) { return fullName } const parsedGithubRepo = pxt.github.parseRepoId(extensionUrl) if (!parsedGithubRepo) return undefined; return allExtensions.get(parsedGithubRepo.slug.toLowerCase()) } async function removeDepAsync(dep: ExtensionMeta) { setDeletionCandidate(undefined) props.hideExtensions() await pkg.mainEditorPkg().removeDepAsync(dep.name) await pxt.Util.delay(1000) // TODO VVN: Without a delay the reload still tries to load the extension await props.reloadHeaderAsync() } async function addDepIfNoConflict(config: pxt.PackageConfig, version: string) { try { props.hideExtensions(); core.showLoading("installingextension", lf("Installing extension...")) const added = await pkg.mainEditorPkg() .addDependencyAsync({ ...config, isExtension: true }, version, false) if (added) { await pxt.Util.delay(1000) await props.reloadHeaderAsync(); } } finally { core.hideLoading("installingextension") } } function updateExtensionTags() { if (extensionTags.size > 0) return let trgConfigFetch = data.getDataWithStatus("target-config:"); let trgConfig = trgConfigFetch.data as pxt.TargetConfig; if (!trgConfig || !trgConfig.packages || !trgConfig.packages.preferredRepoLib) return; const allRepos = [...trgConfig.packages.preferredRepoLib, ...trgConfig.packages.approvedRepoLib] const newMap = extensionTags allRepos.forEach(repo => { repo.tags?.forEach(tag => { if (!newMap.has(tag)) { newMap.set(tag, []) } const repos = newMap.get(tag) if (!repos.find(r => r.slug.toLowerCase() == repo.slug.toLowerCase())) newMap.set(tag, [...newMap.get(tag), repo]) }) }) setExtensionTags(newMap) } async function addGithubPackage(scr: ExtensionMeta) { let r: { version: string, config: pxt.PackageConfig }; try { core.showLoading("downloadingpackage", lf("downloading extension...")); const pkg = getExtensionFromFetched(scr.name); if (pkg) { r = await pxt.github.downloadLatestPackageAsync(pkg.repo); } else { const res = await fetchGithubDataAsync([scr.name]); if (res && res.length > 0) { const parsed = parseGithubRepo(res[0]) addExtensionsToPool([parsed]) r = await pxt.github.downloadLatestPackageAsync(parsed.repo) } } } catch (e) { core.handleNetworkError(e); } finally { core.hideLoading("downloadingpackage"); } return await addDepIfNoConflict(r.config, r.version) } async function fetchGithubDataAsync(preferredRepos: string[]): Promise<pxt.github.GitRepo[]> { // When searching multiple repos at the same time, use 'extension-search' which caches results // for much longer than 'gh-search' const virtualApi = preferredRepos.length == 1 ? 'gh-search' : 'extension-search'; return data.getAsync<pxt.github.GitRepo[]>(`${virtualApi}:${preferredRepos.join("|")}`); } async function fetchGithubDataAndAddAsync(repos: string[]): Promise<ExtensionMeta[]> { const fetched = await fetchGithubDataAsync(repos) if (!fetched) { return [] } const parsed = fetched.map(r => parseGithubRepo(r)) addExtensionsToPool(parsed) return parsed; } function fetchLocalRepositories(): pxt.workspace.Header[] { let r = workspace.getHeaders() if (!/localdependencies=1/i.test(window.location.href)) r = r.filter(h => !!h.githubId); if (props.header) r = r.filter(h => h.id != props.header.id) // don't self-reference return r; } function addLocal(hd: pxt.workspace.Header) { workspace.getTextAsync(hd.id) .then(files => { let cfg = JSON.parse(files[pxt.CONFIG_NAME]) as pxt.PackageConfig return addDepIfNoConflict(cfg, "workspace:" + hd.id) }) } function installExtension(scr: ExtensionMeta) { switch (scr.type) { case pxtc.service.ExtensionType.Bundled: pxt.tickEvent("packages.bundled", { name: scr.name }); props.hideExtensions(); addDepIfNoConflict(scr.pkgConfig, "*") break; case pxtc.service.ExtensionType.Github: props.hideExtensions(); addGithubPackage(scr); break; } updateInstalledExts() } function ghName(scr: pxt.github.GitRepo) { let n = scr.name.replace(/^pxt-/, ""); return n; } function parseGithubRepo(r: pxt.github.GitRepo): ExtensionMeta { return { name: ghName(r), type: pxtc.service.ExtensionType.Github, imageUrl: pxt.github.repoIconUrl(r), repo: r, description: r.description, fullName: r.fullName } } function getCategoryNames(): string[] { if (!extensionTags) return []; return Array.from(extensionTags.keys()) } function handleInstalledCardClick(src: ExtensionMeta) { setDeletionCandidate(src) } async function handleCategoryClick(category: string) { if (category == selectedTag) { setSelectedTag("") setExtensionsToShow([]) return; } setSelectedTag(category) setSearchFor("") const categoryExtensions = extensionTags.get(category) const toBeFetched: string[] = [] const extensionsWeHave: ExtensionMeta[] = [] categoryExtensions.forEach(e => { const fetched = getExtensionFromFetched(e.slug); if (!fetched) { toBeFetched.push(e.slug) } else { extensionsWeHave.push(fetched) } }) const loadingCards = [] for (let i = 0; i < toBeFetched.length; i++) { loadingCards.push(emptyCard) } setExtensionsToShow([...extensionsWeHave, ...loadingCards]); if (toBeFetched.length > 0) { const exts = await fetchGithubDataAndAddAsync(toBeFetched) setExtensionsToShow([...extensionsWeHave, ...exts]) } } function packageConfigToExtensionMeta(p: pxt.PackageConfig): ExtensionMeta { return { name: p.name, imageUrl: p.icon, type: pxtc.service.ExtensionType.Bundled, pkgConfig: p, description: p.description } } function handleHomeButtonClick() { setSelectedTag("") setSearchFor("") } function fetchBundled(): Map<string, ExtensionMeta> { const bundled = pxt.appTarget.bundledpkgs; const extensionsMap = new Map<string, ExtensionMeta>(); Object.keys(bundled).filter(k => !/prj$/.test(k)) .map(k => JSON.parse(bundled[k]["pxt.json"]) as pxt.PackageConfig) .filter(pk => !pk.hidden) .filter(pk => !/---/.test(pk.name)) .filter(pk => pk.name != "core") .filter(pk => false == !!pk.core) // show core in "boards" mode .forEach(e => extensionsMap.set(e.name, packageConfigToExtensionMeta(e))) return extensionsMap } async function updatePreferredExts() { const bundled = fetchBundled(); const repos: ExtensionMeta[] = []; bundled.forEach(e => { repos.push(e) }) let trgConfigFetch = data.getDataWithStatus("target-config:"); let trgConfig = trgConfigFetch.data as pxt.TargetConfig; const toBeFetched: string[] = []; if (trgConfig && trgConfig.packages && trgConfig.packages.preferredRepoLib) { trgConfig.packages.preferredRepoLib.forEach(r => { const fetched = getExtensionFromFetched(r.slug) if (fetched) { repos.push(fetched) } else { toBeFetched.push(r.slug) } }) } const loadingCards = []; for (let i = 0; i < toBeFetched.length; i++) { loadingCards.push(emptyCard) } setPreferredExts([...repos, ...loadingCards]) const exts = await fetchGithubDataAndAddAsync(toBeFetched); setPreferredExts([...repos, ...exts]) } /** * Loads installed extensions' info from Github * */ async function updateInstalledExts() { const installed: ExtensionMeta[] = [] const reposToFetch: string[] = []; Object.keys(pkg.mainPkg?.deps as Object).forEach((k) => { if (k == "this" || k == "core") { return; } const ext = pkg.mainPkg.deps[k]; if (ext?.installedVersion?.includes("github")) { const match = /github:(\S*)#?/.exec(ext.installedVersion); const repoName = match[1] let fetchedRepo = getExtensionFromFetched(k); if (fetchedRepo) { installed.push(fetchedRepo) } else { reposToFetch.push(repoName) } } else { installed.push({ name: ext?.config?.name, imageUrl: ext?.config?.icon, description: ext?.config?.description }) } }) if (reposToFetch && reposToFetch.length > 0) { // Set the installed extensions before waiting for the dependencies setInstalledExtensions([...installed]) const exts = await fetchGithubDataAndAddAsync(reposToFetch) setInstalledExtensions([...installed, ...exts]) } } async function handleImportUrl(url: string) { setShowImportExtensionDialog(false) props.hideExtensions() const ext = getExtensionFromFetched(url) if (!ext) { const exts = await fetchGithubDataAndAddAsync([url]) addExtensionsToPool(exts) } else { addGithubPackage(ext) } } enum ExtensionView { Tabbed, Search, Tags } let displayMode: ExtensionView; if (searchFor != "") { displayMode = ExtensionView.Search } else if (selectedTag != "") { displayMode = ExtensionView.Tags } else { displayMode = ExtensionView.Tabbed; } const categoryNames = getCategoryNames(); const local = currentTab == TabState.InDevelopment ? fetchLocalRepositories() : undefined return ( <Modal title={lf("Extensions")} fullscreen={true} className={"extensions-browser"} onClose={props.hideExtensions} helpUrl={"/extensions"} > <div className="ui"> {showImportExtensionDialog && <ImportModal onCancelClick={() => setShowImportExtensionDialog(false)} onImportClick={handleImportUrl} /> } {deletionCandidate && <DeleteConfirmationModal ns={deletionCandidate.name} onCancelClick={() => { setDeletionCandidate(undefined) }} onDeleteClick={() => { removeDepAsync(deletionCandidate) }} /> } <div className="extension-search-header"> <div className="header">{(lf(`Do more with ${pxt.appTarget.appTheme.boardName}`))}</div> <SearchInput searchHandler={setSearchFor}/> <div className="extension-tags"> {categoryNames.map(c => <Button title={pxt.Util.rlf(c)} key={c} label={pxt.Util.rlf(c)} onClick={() => handleCategoryClick(c)} onKeydown={() => handleCategoryClick} className={"extension-tag " + (selectedTag == c ? "selected" : "")} /> )} </div> {/* TODO bring in the import modal in later! <div className="importButton"> <span>{lf("or ")}</span> <div className="importButtonLink" onClick={() => setShowImportExtensionDialog(true)}>{lf("import extension")}</div> </div> */} </div> {displayMode == ExtensionView.Search && <div className="extension-display"> <div className="breadcrumbs"> <span className="link" onClick={handleHomeButtonClick}>{lf("Home")}</span> </div> <div className="ui cards left"> {extensionsToShow?.map((scr, index) => <ExtensionCard key={`searched:${index}`} name={scr.name ?? `${index}`} description={scr.description} imageUrl={scr.imageUrl} scr={scr} onCardClick={installExtension} learnMoreUrl={scr.fullName ? `/pkg/${scr.fullName}` : undefined} loading={scr.loading} role="button" />)} </div> </div>} {displayMode == ExtensionView.Tags && <div className="extension-display"> <div className="breadcrumbs"> <span className="link" onClick={handleHomeButtonClick}>{lf("Home")}</span> <span>/</span> <span>{selectedTag}</span> </div> <div className="ui cards left"> {extensionsToShow?.map((scr, index) => <ExtensionCard key={`tagged:${index}`} name={scr.name ?? `${index}`} description={scr.description} imageUrl={scr.imageUrl} scr={scr} onCardClick={installExtension} learnMoreUrl={scr.fullName ? `/pkg/${scr.fullName}` : undefined} loading={scr.loading} role="button" />)} </div> </div>} {displayMode == ExtensionView.Tabbed && <div className="extension-display"> <div className="tab-header"> <Button key={"Recommended"} title={lf("Recommended")} label={lf("Recommended")} onClick={() => { setCurrentTab(TabState.Recommended) }} className={currentTab == TabState.Recommended ? "selected" : ""} /> <Button key={"Installed"} title={lf("Installed")} label={lf("Installed")} onClick={() => { setCurrentTab(TabState.Installed) }} className={currentTab == TabState.Installed ? "selected" : ""} /> <Button key={"In Development"} title={lf("In Development")} label={lf("In Development")} onClick={() => { setCurrentTab(TabState.InDevelopment) }} className={currentTab == TabState.InDevelopment ? "selected" : ""} /> </div> <div className="ui cards left"> {currentTab == TabState.Recommended && preferredExts.map((e, index) => <ExtensionCard key={`preferred:${index}`} scr={e} name={e.name ?? `${index}`} onCardClick={installExtension} imageUrl={e.imageUrl} description={e.description} learnMoreUrl={e.fullName ? `/pkg/${e.fullName}` : undefined} loading={e.loading} role="button" /> ) } {currentTab == TabState.Installed && installedExtensions.map((e, index) => <ExtensionCard key={`installed:${index}`} scr={e} name={e.name} onCardClick={() => handleInstalledCardClick(e)} imageUrl={e.imageUrl} description={e.description} learnMoreUrl={e.fullName ? `/pkg/${e.fullName}` : undefined} role="button" /> ) } {currentTab == TabState.InDevelopment && local.forEach((p, index) => <ExtensionCard key={`local:${index}`} name={p.name} description={lf("Local copy of {0} hosted on github.com", p.githubId)} url={"https://github.com/" + p.githubId} imageUrl={p.icon} scr={p} onCardClick={addLocal} label={lf("Local")} title={lf("Local GitHub extension")} labelClass="blue right ribbon" role="button" /> ) } </div> </div> } </div> </Modal> ) } interface ExtensionCardProps extends pxt.CodeCard { scr: pxtc.service.ExtensionMeta; onCardClick: (scr: any) => void; loading?: boolean; } const ExtensionCard = (props: ExtensionCardProps) => { const handleClick = () => { props.onCardClick(props.scr); } return <codecard.CodeCardView {...props} onClick={handleClick} key={props.name}/> }
the_stack
import { extend, objectMap, virtualElements, tagNameLower, domData, objectForEach, arrayIndexOf, arrayForEach, options } from '@tko/utils' import { dependencyDetection } from '@tko/observable' import { computed } from '@tko/computed' import { dataFor, bindingContext, boundElementDomDataKey, contextSubscribeSymbol } from './bindingContext' import { bindingEvent } from './bindingEvent' import { BindingResult } from './BindingResult' import { LegacyBindingHandler } from './LegacyBindingHandler' // The following element types will not be recursed into during binding. const bindingDoesNotRecurseIntoElementTypes = { // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents, // because it's unexpected and a potential XSS issue. // Also bindings should not operate on <template> elements since this breaks in Internet Explorer // and because such elements' contents are always intended to be bound in a different context // from where they appear in the document. 'script': true, 'textarea': true, 'template': true } function getBindingProvider () { return options.bindingProviderInstance.instance || options.bindingProviderInstance } function isProviderForNode (provider, node) { const nodeTypes = provider.FOR_NODE_TYPES || [1, 3, 8] return nodeTypes.includes(node.nodeType) } function asProperHandlerClass (handler, bindingKey) { if (!handler) { return } return handler.isBindingHandlerClass ? handler : LegacyBindingHandler.getOrCreateFor(bindingKey, handler) } function getBindingHandlerFromComponent (bindingKey, $component) { if (!$component || typeof $component.getBindingHandler !== 'function') { return } return asProperHandlerClass($component.getBindingHandler(bindingKey)) } export function getBindingHandler (bindingKey) { const bindingDefinition = options.getBindingHandler(bindingKey) || getBindingProvider().bindingHandlers.get(bindingKey) return asProperHandlerClass(bindingDefinition, bindingKey) } // Returns the value of a valueAccessor function function evaluateValueAccessor (valueAccessor) { return valueAccessor() } function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, asyncBindingsApplied) { let nextInQueue = virtualElements.firstChild(elementOrVirtualElement) if (!nextInQueue) { return } let currentChild const provider = getBindingProvider() const preprocessNode = provider.preprocessNode // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that // trigger insertion of <template> contents at that point in the document. if (preprocessNode) { while (currentChild = nextInQueue) { nextInQueue = virtualElements.nextSibling(currentChild) preprocessNode.call(provider, currentChild) } // Reset nextInQueue for the next loop nextInQueue = virtualElements.firstChild(elementOrVirtualElement) } while (currentChild = nextInQueue) { // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position nextInQueue = virtualElements.nextSibling(currentChild) applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, asyncBindingsApplied) } bindingEvent.notify(elementOrVirtualElement, bindingEvent.childrenComplete) } function hasBindings (node) { const provider = getBindingProvider() return isProviderForNode(provider, node) && provider.nodeHasBindings(node) } function nodeOrChildHasBindings (node) { return hasBindings(node) || [...node.childNodes].some(c => nodeOrChildHasBindings(c)) } function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, asyncBindingsApplied) { var isElement = nodeVerified.nodeType === 1 if (isElement) { // Workaround IE <= 8 HTML parsing weirdness virtualElements.normaliseVirtualElementDomStructure(nodeVerified) } // Perf optimisation: Apply bindings only if... // (1) We need to store the binding info for the node (all element nodes) // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template) let shouldApplyBindings = isElement || // Case (1) hasBindings(nodeVerified) // Case (2) const { shouldBindDescendants } = shouldApplyBindings ? applyBindingsToNodeInternal(nodeVerified, null, bindingContext, asyncBindingsApplied) : { shouldBindDescendants: true } if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[tagNameLower(nodeVerified)]) { // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So, // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode, // hence bindingContextsMayDifferFromDomParentElement is false // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may // skip over any number of intermediate virtual elements, any of which might define a custom binding context, // hence bindingContextsMayDifferFromDomParentElement is true applyBindingsToDescendantsInternal(bindingContext, nodeVerified, asyncBindingsApplied) } } function * topologicalSortBindings (bindings, $component) { const results = [] // Depth-first sort const bindingsConsidered = {} // A temporary record of which bindings are already in 'result' const cyclicDependencyStack = [] // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it objectForEach(bindings, function pushBinding (bindingKey) { if (!bindingsConsidered[bindingKey]) { const binding = getBindingHandlerFromComponent(bindingKey, $component) || getBindingHandler(bindingKey) if (!binding) { return } // First add dependencies (if any) of the current binding if (binding.after) { cyclicDependencyStack.push(bindingKey) arrayForEach(binding.after, function (bindingDependencyKey) { if (!bindings[bindingDependencyKey]) { return } if (arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) { throw Error('Cannot combine the following bindings, because they have a cyclic dependency: ' + cyclicDependencyStack.join(', ')) } else { pushBinding(bindingDependencyKey) } }) cyclicDependencyStack.length-- } // Next add the current binding results.push([ bindingKey, binding ]) } bindingsConsidered[bindingKey] = true }) for (const result of results) { yield result } } function applyBindingsToNodeInternal (node, sourceBindings, bindingContext, asyncBindingsApplied) { const bindingInfo = domData.getOrSet(node, boundElementDomDataKey, {}) // Prevent multiple applyBindings calls for the same node, except when a binding value is specified const alreadyBound = bindingInfo.alreadyBound if (!sourceBindings) { if (alreadyBound) { if (!nodeOrChildHasBindings(node)) { return false } onBindingError({ during: 'apply', errorCaptured: new Error('You cannot apply bindings multiple times to the same element.'), element: node, bindingContext }) return false } bindingInfo.alreadyBound = true } if (!alreadyBound) { bindingInfo.context = bindingContext } // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings var bindings if (sourceBindings && typeof sourceBindings !== 'function') { bindings = sourceBindings } else { const provider = getBindingProvider() const getBindings = provider.getBindingAccessors if (isProviderForNode(provider, node)) { // Get the binding from the provider within a computed observable so that we can update the bindings whenever // the binding context is updated or if the binding provider accesses observables. var bindingsUpdater = computed( function () { bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext) // Register a dependency on the binding context to support observable view models. if (bindings && bindingContext[contextSubscribeSymbol]) { bindingContext[contextSubscribeSymbol]() } return bindings }, null, { disposeWhenNodeIsRemoved: node } ) if (!bindings || !bindingsUpdater.isActive()) { bindingsUpdater = null } } } var bindingHandlerThatControlsDescendantBindings if (bindings) { const $component = bindingContext.$component || {} const allBindingHandlers = {} domData.set(node, 'bindingHandlers', allBindingHandlers) // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding // context update), just return the value accessor from the binding. Otherwise, return a function that always gets // the latest binding value and registers a dependency on the binding updater. const getValueAccessor = bindingsUpdater ? (bindingKey) => function (optionalValue) { const valueAccessor = bindingsUpdater()[bindingKey] if (arguments.length === 0) { return evaluateValueAccessor(valueAccessor) } else { return valueAccessor(optionalValue) } } : (bindingKey) => bindings[bindingKey] // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated function allBindings () { return objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor) } // The following is the 3.x allBindings API allBindings.has = (key) => key in bindings allBindings.get = (key) => bindings[key] && evaluateValueAccessor(getValueAccessor(key)) if (bindingEvent.childrenComplete in bindings) { bindingEvent.subscribe(node, bindingEvent.childrenComplete, () => { const callback = evaluateValueAccessor(bindings[bindingEvent.childrenComplete]) if (!callback) { return } const nodes = virtualElements.childNodes(node) if (nodes.length) { callback(nodes, dataFor(nodes[0])) } }) } const bindingsGenerated = topologicalSortBindings(bindings, $component) const nodeAsyncBindingPromises = new Set() for (const [key, BindingHandlerClass] of bindingsGenerated) { // Go through the sorted bindings, calling init and update for each function reportBindingError (during, errorCaptured) { onBindingError({ during, errorCaptured, bindings, allBindings, bindingKey: key, bindingContext, element: node, valueAccessor: getValueAccessor(key) }) } if (node.nodeType === 8 && !BindingHandlerClass.allowVirtualElements) { throw new Error(`The binding '${key}' cannot be used with virtual elements`) } try { const bindingHandler = dependencyDetection.ignore(() => new BindingHandlerClass({ allBindings, $element: node, $context: bindingContext, onError: reportBindingError, valueAccessor (...v) { return getValueAccessor(key)(...v) } }) ) if (bindingHandler.onValueChange) { dependencyDetection.ignore(() => bindingHandler.computed('onValueChange') ) } // Expose the bindings via domData. allBindingHandlers[key] = bindingHandler if (bindingHandler.controlsDescendants) { if (bindingHandlerThatControlsDescendantBindings !== undefined) { throw new Error('Multiple bindings (' + bindingHandlerThatControlsDescendantBindings + ' and ' + key + ') are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.') } bindingHandlerThatControlsDescendantBindings = key } if (bindingHandler.bindingCompleted instanceof Promise) { asyncBindingsApplied.add(bindingHandler.bindingCompleted) nodeAsyncBindingPromises.add(bindingHandler.bindingCompleted) } } catch (err) { reportBindingError('creation', err) } } triggerDescendantsComplete(node, bindings, nodeAsyncBindingPromises) } const shouldBindDescendants = bindingHandlerThatControlsDescendantBindings === undefined return { shouldBindDescendants } } /** * * @param {HTMLElement} node * @param {Object} bindings * @param {[Promise]} nodeAsyncBindingPromises */ function triggerDescendantsComplete (node, bindings, nodeAsyncBindingPromises) { /** descendantsComplete ought to be an instance of the descendantsComplete * binding handler. */ const hasBindingHandler = bindingEvent.descendantsComplete in bindings const hasFirstChild = virtualElements.firstChild(node) const accessor = hasBindingHandler && evaluateValueAccessor(bindings[bindingEvent.descendantsComplete]) const callback = () => { bindingEvent.notify(node, bindingEvent.descendantsComplete) if (accessor && hasFirstChild) { accessor(node) } } if (nodeAsyncBindingPromises.size) { Promise.all(nodeAsyncBindingPromises).then(callback) } else { callback() } } function getBindingContext (viewModelOrBindingContext, extendContextCallback) { return viewModelOrBindingContext && (viewModelOrBindingContext instanceof bindingContext) ? viewModelOrBindingContext : new bindingContext(viewModelOrBindingContext, undefined, undefined, extendContextCallback) } export function applyBindingAccessorsToNode (node, bindings, viewModelOrBindingContext, asyncBindingsApplied) { if (node.nodeType === 1) { // If it's an element, workaround IE <= 8 HTML parsing weirdness virtualElements.normaliseVirtualElementDomStructure(node) } return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), asyncBindingsApplied) } export function applyBindingsToNode (node, bindings, viewModelOrBindingContext) { const asyncBindingsApplied = new Set() const bindingContext = getBindingContext(viewModelOrBindingContext) const bindingAccessors = getBindingProvider().makeBindingAccessors(bindings, bindingContext, node) applyBindingAccessorsToNode(node, bindingAccessors, bindingContext, asyncBindingsApplied) return new BindingResult({asyncBindingsApplied, rootNode: node, bindingContext}) } export function applyBindingsToDescendants (viewModelOrBindingContext, rootNode) { const asyncBindingsApplied = new Set() if (rootNode.nodeType === 1 || rootNode.nodeType === 8) { const bindingContext = getBindingContext(viewModelOrBindingContext) applyBindingsToDescendantsInternal(bindingContext, rootNode, asyncBindingsApplied) return new BindingResult({asyncBindingsApplied, rootNode, bindingContext}) } return new BindingResult({asyncBindingsApplied, rootNode}) } export function applyBindings (viewModelOrBindingContext, rootNode, extendContextCallback) { const asyncBindingsApplied = new Set() // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here. if (!options.jQuery === undefined && options.jQuery) { options.jQuery = options.jQuery } // rootNode is optional if (!rootNode) { rootNode = window.document.body if (!rootNode) { throw Error('ko.applyBindings: could not find window.document.body; has the document been loaded?') } } else if (rootNode.nodeType !== 1 && rootNode.nodeType !== 8) { throw Error('ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node') } const rootContext = getBindingContext(viewModelOrBindingContext, extendContextCallback) applyBindingsToNodeAndDescendantsInternal(rootContext, rootNode, asyncBindingsApplied) return Promise.all(asyncBindingsApplied) } function onBindingError (spec) { var error, bindingText if (spec.bindingKey) { // During: 'init' or initial 'update' error = spec.errorCaptured spec.message = 'Unable to process binding "' + spec.bindingKey + '" in binding "' + spec.bindingKey + '"\nMessage: ' + (error.message ? error.message : error) } else { // During: 'apply' error = spec.errorCaptured } try { extend(error, spec) } catch (e) { // Read-only error e.g. a DOMEXception. spec.stack = error.stack error = new Error(error.message ? error.message : error) extend(error, spec) } options.onError(error) }
the_stack
import { Divider, Drawer, Icon, List, Select, Switch, Tooltip } from 'antd'; import React, { Component } from 'react'; import BlockCheckbox from './BlockCheckbox'; import ThemeColor from './ThemeColor'; import globalConfig from 'global.config'; import { getLocales } from 'locale'; import './index.less'; import { MenuTheme } from 'antd/es/menu/MenuContext'; export declare type ContentWidth = 'Fluid' | 'Fixed'; export interface Settings { /** * theme for nav menu */ navTheme: MenuTheme | undefined; /** * nav menu position: `sidemenu` or `topmenu` */ layout: 'sidemenu' | 'topmenu'; /** * layout of content: `Fluid` or `Fixed`, only works when layout is topmenu */ contentWidth: ContentWidth; /** * 主题色 */ primaryColor: string; /** * sticky header */ fixedHeader: boolean; /** * auto hide header */ autoHideHeader: boolean; /** * sticky siderbar */ fixSiderbar: boolean; menu: { locale: boolean; }; title: string; iconfontUrl: string; /** * 弹框类型 * * @type {("Modal" | "Drawer")} * @memberof Settings */ infoType?: "Modal" | "Drawer"; /** * AgGrid 主题 * ag-theme-balham * ag-theme-material */ agGridTheme?: "ag-theme-balham" | "ag-theme-material" | 'ag-theme-alpine'; /** *页签 页面 * * @type {boolean} * @memberof Settings */ tabsPage?: boolean; } // import { isBrowser } from '../utils/utils'; const isBrowser = () => typeof window !== 'undefined'; const { Option } = Select; interface BodyProps { title: string; } type MergerSettingsType<T> = Partial<T> & { primaryColor?: string; colorWeak?: boolean; }; const Body: React.FC<BodyProps> = ({ children, title }) => ( <div style={{ marginBottom: 24 }}> <h3 className="ant-pro-setting-drawer-title">{title}</h3> {children} </div> ); interface SettingItemProps { title: React.ReactNode; action: React.ReactElement; disabled?: boolean; disabledReason?: React.ReactNode; } export interface SettingDrawerProps { settings: MergerSettingsType<Settings>; collapse?: boolean; // for test getContainer?: any; onCollapseChange?: (collapse: boolean) => void; onSettingChange?: (settings: MergerSettingsType<Settings>) => void; } export interface SettingDrawerState extends MergerSettingsType<Settings> { collapse?: boolean; language?: string; } class SettingDrawer extends Component<SettingDrawerProps, SettingDrawerState> { state: SettingDrawerState = { collapse: false, language: globalConfig.language, }; static getDerivedStateFromProps( props: SettingDrawerProps, ): SettingDrawerState | null { if ('collapse' in props) { return { collapse: !!props.collapse, }; } return null; } componentDidMount(): void { if (isBrowser()) { window.addEventListener('languagechange', this.onLanguageChange, { passive: true, }); } } componentWillUnmount(): void { if (isBrowser()) { window.removeEventListener('languagechange', this.onLanguageChange); } } onLanguageChange = (): void => { const language = globalConfig.language;//getLanguage(); if (language !== this.state.language) { this.setState({ language, }); } }; getLayoutSetting = (): SettingItemProps[] => { const { settings } = this.props; const formatMessage = this.getFormatMessage(); const { contentWidth, fixedHeader, layout, autoHideHeader, fixSiderbar, infoType = "Modal", agGridTheme = 'ag-theme-material', tabsPage } = settings; return [ { title: formatMessage({ id: 'app.setting.content-width', defaultMessage: 'Content Width', }), action: ( <Select<string> value={contentWidth} size="small" onSelect={value => this.changeSetting('contentWidth', value)} style={{ width: 80 }} > {layout === 'sidemenu' ? null : ( <Option value="Fixed"> {formatMessage({ id: 'app.setting.content-width.fixed', defaultMessage: 'Fixed', })} </Option> )} <Option value="Fluid"> {formatMessage({ id: 'app.setting.content-width.fluid', defaultMessage: 'Fluid', })} </Option> </Select> ), }, { title: formatMessage({ id: 'app.setting.infoType', defaultMessage: 'Info Type', }), action: ( <Select<string> value={infoType} size="small" onSelect={value => this.changeSetting('infoType', value)} style={{ width: 80 }} > <Option value="Modal"> {formatMessage({ id: 'app.setting.infoType.Modal', defaultMessage: 'Modal', })} </Option> <Option value="Drawer"> {formatMessage({ id: 'app.setting.infoType.Drawer', defaultMessage: 'Drawer', })} </Option> </Select> ), }, { title: formatMessage({ id: 'app.setting.agGridTheme', defaultMessage: 'Ag Grid Theme', }), action: ( <Select<string> value={agGridTheme} size="small" onSelect={value => this.changeSetting('agGridTheme', value)} style={{ width: 80 }} > <Option value="ag-theme-balham"> {formatMessage({ id: 'app.setting.agGridTheme.balham', defaultMessage: 'balham', })} </Option> <Option value="ag-theme-material"> {formatMessage({ id: 'app.setting.agGridTheme.material', defaultMessage: 'material', })} </Option> <Option value="ag-theme-alpine"> {formatMessage({ id: 'app.setting.agGridTheme.alpine', defaultMessage: 'alpine', })} </Option> </Select> ), }, { title: formatMessage({ id: 'app.setting.tabsPage', defaultMessage: 'Tabs Page', }), disabled: contentWidth === "Fixed", action: ( <Switch size="small" checked={!!tabsPage} onChange={checked => this.changeSetting('tabsPage', checked)} /> ), }, { title: formatMessage({ id: 'app.setting.fixedheader', defaultMessage: 'Fixed Header', }), disabled: tabsPage, action: ( <Switch size="small" checked={!!fixedHeader} onChange={checked => this.changeSetting('fixedHeader', checked)} /> ), }, { title: formatMessage({ id: 'app.setting.hideheader', defaultMessage: 'Hidden Header when scrolling', }), disabled: tabsPage || !fixedHeader, disabledReason: formatMessage({ id: 'app.setting.hideheader.hint', defaultMessage: 'Works when Hidden Header is enabled', }), action: ( <Switch size="small" checked={!!autoHideHeader} onChange={checked => this.changeSetting('autoHideHeader', checked)} /> ), }, { title: formatMessage({ id: 'app.setting.fixedsidebar', defaultMessage: 'Fixed Sidebar', }), disabled: tabsPage || layout === 'topmenu', disabledReason: formatMessage({ id: 'app.setting.fixedsidebar.hint', defaultMessage: 'Works on Side Menu Layout', }), action: ( <Switch size="small" checked={!!fixSiderbar} onChange={checked => this.changeSetting('fixSiderbar', checked)} /> ), }, ]; }; changeSetting = (key: string, value: string | boolean) => { const { settings } = this.props; const nextState = { ...settings }; nextState[key] = value; if (key === 'layout') { nextState.contentWidth = value === 'topmenu' ? 'Fixed' : 'Fluid'; nextState.tabsPage = value === 'sidemenu'; } else if (key === 'fixedHeader' && !value) { nextState.autoHideHeader = false; } this.setState(nextState, () => { const { onSettingChange } = this.props; if (onSettingChange) { onSettingChange(this.state as MergerSettingsType<Settings>); } }); }; togglerContent = () => { const { collapse } = this.state; const { onCollapseChange } = this.props; if (onCollapseChange) { onCollapseChange(!collapse); return; } this.setState({ collapse: !collapse }); }; renderLayoutSettingItem = (item: SettingItemProps) => { const action = React.cloneElement(item.action, { disabled: item.disabled, }); return ( <Tooltip title={item.disabled ? item.disabledReason : ''} placement="left" > <List.Item actions={[action]}> <span style={{ opacity: item.disabled ? 0.5 : 1 }}>{item.title}</span> </List.Item> </Tooltip> ); }; getFormatMessage = (): ((data: { id: string; defaultMessage?: string; }) => string) => { const formatMessage = ({ id, defaultMessage, }: { id: string; defaultMessage?: string; }): string => { const locales = getLocales(); if (locales[id]) { return locales[id]; } if (defaultMessage) { return defaultMessage as string; } return id; }; return formatMessage; }; render(): React.ReactNode { const { settings, getContainer } = this.props; const { navTheme = 'dark', primaryColor = '1890FF', layout = 'sidemenu', colorWeak, } = (settings) as any; const { collapse } = this.state; const formatMessage = this.getFormatMessage(); return ( <Drawer visible={collapse} width={300} onClose={this.togglerContent} placement="right" getContainer={getContainer} // handler={ // <div // className="ant-pro-setting-drawer-handle" // onClick={this.togglerContent} // > // <Icon // type={collapse ? 'close' : 'setting'} // style={{ // color: '#fff', // fontSize: 20, // }} // /> // </div> // } style={{ zIndex: 999, }} > <div className="ant-pro-setting-drawer-content"> <Body title={formatMessage({ id: 'app.setting.pagestyle', defaultMessage: 'Page style setting', })} > <BlockCheckbox list={[ { key: 'dark', url: 'https://gw.alipayobjects.com/zos/antfincdn/XwFOFbLkSM/LCkqqYNmvBEbokSDscrm.svg', title: formatMessage({ id: 'app.setting.pagestyle.dark', defaultMessage: '', }), }, { key: 'light', url: 'https://gw.alipayobjects.com/zos/antfincdn/NQ%24zoisaD2/jpRkZQMyYRryryPNtyIC.svg', title: formatMessage({ id: 'app.setting.pagestyle.light' }), }, ]} value={navTheme} onChange={value => this.changeSetting('navTheme', value)} /> </Body> <ThemeColor title={formatMessage({ id: 'app.setting.themecolor' })} value={primaryColor} formatMessage={formatMessage} onChange={color => this.changeSetting('primaryColor', color)} /> <Divider /> <Body title={formatMessage({ id: 'app.setting.navigationmode' })}> <BlockCheckbox list={[ { key: 'sidemenu', url: 'https://gw.alipayobjects.com/zos/antfincdn/XwFOFbLkSM/LCkqqYNmvBEbokSDscrm.svg', title: formatMessage({ id: 'app.setting.sidemenu' }), }, { key: 'topmenu', url: 'https://gw.alipayobjects.com/zos/antfincdn/URETY8%24STp/KDNDBbriJhLwuqMoxcAr.svg', title: formatMessage({ id: 'app.setting.topmenu' }), }, ]} value={layout} onChange={value => this.changeSetting('layout', value)} /> </Body> <List split={false} dataSource={this.getLayoutSetting()} renderItem={this.renderLayoutSettingItem} /> <Divider /> {/* <Body title={formatMessage({ id: 'app.setting.othersettings' })}> <List split={false} renderItem={this.renderLayoutSettingItem} dataSource={[ { title: formatMessage({ id: 'app.setting.weakmode' }), action: ( <Switch size="small" checked={!!colorWeak} onChange={checked => this.changeSetting('colorWeak', checked) } /> ), }, ]} /> </Body> <Divider /> */} {/* <CopyToClipboard text={JSON.stringify(omit(settings, ['colorWeak']), null, 2)} onCopy={() => message.success(formatMessage({ id: 'app.setting.copyinfo' })) } > <Button block icon="copy"> {formatMessage({ id: 'app.setting.copy' })} </Button> </CopyToClipboard> */} </div> </Drawer> ); } } export default SettingDrawer;
the_stack