text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { ArrayHelper } from "../ExtensionMethods"; import { ComplexProperty } from "./ComplexProperty"; import { Contact } from "../Core/ServiceObjects/Items/Contact"; import { EmailAddress } from "./EmailAddress"; import { EmailAddressKey } from "../Enumerations/EmailAddressKey"; import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter"; import { EwsUtilities } from "../Core/EwsUtilities"; import { ExchangeService } from "../Core/ExchangeService"; import { ItemId } from "./ItemId"; import { MailboxType } from "../Enumerations/MailboxType"; import { MemberStatus } from "../Enumerations/MemberStatus"; import { ServiceLocalException } from "../Exceptions/ServiceLocalException"; import { Strings } from "../Strings"; import { XmlAttributeNames } from "../Core/XmlAttributeNames"; import { XmlElementNames } from "../Core/XmlElementNames"; import { XmlNamespace } from "../Enumerations/XmlNamespace"; /** * Represents a group member * [RequiredServerVersion(ExchangeVersion.Exchange2010)] ** needs implementation */ export class GroupMember extends ComplexProperty { // todo: need implementation for [RequiredServerVersion(ExchangeVersion.Exchange2010)] /** * AddressInformation field. */ private addressInformation: EmailAddress = null; /** * Status field. */ private status: MemberStatus; /** * Member key field. */ private key: string; /** * ets the key of the member. */ get Key(): string { return this.key; } /** * Gets the address information of the member. */ get AddressInformation(): EmailAddress { return this.addressInformation; } /** * @internal Sets the address information of the member. */ set AddressInformation(value: EmailAddress) { if (this.addressInformation !== null) { ArrayHelper.RemoveEntry(this.addressInformation.OnChange, this.AddressInformationChanged); } this.addressInformation = value; if (this.addressInformation !== null) { this.addressInformation.OnChange.push(this.AddressInformationChanged.bind(this)); } } /** * Gets the status of the member. */ get Status(): MemberStatus { return this.status; } /** * Initializes a new instance of the **GroupMember** class. * */ constructor(); /** * Initializes a new instance of the **GroupMember** class. * * @param {string} smtpAddress The SMTP address of the member. */ constructor(smtpAddress: string); /** * Initializes a new instance of the **GroupMember** class. * * @param {ItemId} contactGroupId The Id of the contact group to link the member to. */ constructor(contactGroupId: ItemId); /** * Initializes a new instance of the **GroupMember** class. * * @param {EmailAddress} addressInformation The e-mail address of the member. */ constructor(addressInformation: EmailAddress); /** * @internal Initializes a new instance of the **GroupMember** class from another GroupMember instance. * * @param {GroupMember} member GroupMember class instance to copy. */ constructor(member: GroupMember); /** * Initializes a new instance of the **GroupMember** class. * * @param {string} smtpAddress The SMTP address of the member. * @param {MailboxType} mailboxType The mailbox type of the member. */ constructor(smtpAddress: string, mailboxType: MailboxType); /** * Initializes a new instance of the **GroupMember** class. * * @param {string} name The name of the one-off member. * @param {string} smtpAddress The SMTP address of the one-off member. */ constructor(name: string, smtpAddress: string); /** * Initializes a new instance of the **GroupMember** class. * * @param {ItemId} contactId The Id of the contact member. * @param {string} addressToLink The Id of the contact to link the member to. */ constructor(contactId: ItemId, addressToLink: string); /** * Initializes a new instance of the **GroupMember** class from a Contact instance indexed by the specified key. * * @param {Contact} contact The contact to link to. * @param {EmailAddressKey} emailAddressKey The contact's e-mail address to link to. */ constructor(contact: Contact, emailAddressKey: EmailAddressKey); /** * Initializes a new instance of the **GroupMember** class. * * @param {string} address The address of the member. * @param {string} routingType The routing type of the address. * @param {MailboxType} mailboxType The mailbox type of the member. */ constructor(address: string, routingType: string, mailboxType: MailboxType); /** * Initializes a new instance of the **GroupMember** class. * * @param {string} name The name of the one-off member. * @param {string} address The address of the one-off member. * @param {string} routingType The routing type of the address. */ constructor(name: string, address: string, routingType: string); constructor(_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId?: string | ItemId | EmailAddress | GroupMember | Contact, _2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey?: string | MailboxType | EmailAddressKey, _3mbxTypeOrRoutingType?: MailboxType | string) { super(); // Key is assigned by server this.key = null; // Member status is calculated by server this.status = MemberStatus.Unrecognized; let argsLength = arguments.length; if (argsLength == 1) { if (typeof _1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId === 'string') { // smtpAddress this.AddressInformation = new EmailAddress(_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId); } else if (_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId instanceof ItemId) { // contactGroupId this.AddressInformation = new EmailAddress( null, null, null, MailboxType.ContactGroup, _1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId); } else if (_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId instanceof GroupMember) { // contactGroupId EwsUtilities.ValidateParam(_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId, "member"); this.AddressInformation = new EmailAddress(_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId.AddressInformation); } else { this.AddressInformation = new EmailAddress(<EmailAddress>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId); } } if (argsLength === 2) { if (typeof _1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId === 'string') { if (typeof _2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey === 'string') { this.AddressInformation = new EmailAddress(<string>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId, <string>_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey, EmailAddress.SmtpRoutingType, MailboxType.OneOff); } else { this.constructor_str_str_mbType(<string>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId, EmailAddress.SmtpRoutingType, <MailboxType>_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey); } } else if (_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId instanceof ItemId) { this.AddressInformation = new EmailAddress( null, <string>_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey, // addressToLink null, MailboxType.Contact, _1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId); //contactId } else { let contact: Contact = <Contact>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId; EwsUtilities.ValidateParam(contact, "contact"); let emailAddress: EmailAddress = contact.EmailAddresses[_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey /* emailAddressKey */]; this.AddressInformation = new EmailAddress(emailAddress); this.addressInformation.Id = contact.Id; } } if (argsLength === 3) { if (typeof _3mbxTypeOrRoutingType === 'string') { // mailboxType this.AddressInformation = new EmailAddress(<string>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId, <string>_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey, _3mbxTypeOrRoutingType, MailboxType.OneOff); } else { this.constructor_str_str_mbType(<string>_1smtpOrCGIdOrAddrInfoOrMemberOrAddrOrNameOrContactOrCId, <string>_2routingTypeOrMbxTypeOrAddressOrSmtpOrAddr2LinkOrEmailKey, _3mbxTypeOrRoutingType); } } } //#region Constructor methods private constructor_str_str_mbType(address: string, routingType: string, mailboxType: MailboxType) { switch (mailboxType) { case MailboxType.PublicGroup: case MailboxType.PublicFolder: case MailboxType.Mailbox: case MailboxType.Contact: case MailboxType.OneOff: this.AddressInformation = new EmailAddress(null, address, routingType, mailboxType); break; default: throw new ServiceLocalException(Strings.InvalidMailboxType); } } //#endregion /** * AddressInformation instance is changed. * * @param {} complexProperty Changed property. */ private AddressInformationChanged(complexProperty: ComplexProperty): void { this.Changed(); } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void { for (let key in jsObject) { switch (key) { case XmlAttributeNames.Key: this.key = jsObject[key]; break; case XmlElementNames.Status: this.status = MemberStatus[<string>jsObject[key]]; break; case XmlElementNames.Mailbox: this.AddressInformation = new EmailAddress(); this.AddressInformation.LoadFromXmlJsObject(jsObject[key], service); break; default: break; } } } /** * @internal Writes the member key attribute to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteAttributesToXml(writer: EwsServiceXmlWriter): void { // if this.key is null or empty, writer skips the attribute writer.WriteAttributeValue(XmlAttributeNames.Key, this.key); } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteElementsToXml(writer: EwsServiceXmlWriter): void { // No need to write member Status back to server // Write only AddressInformation container element this.AddressInformation.WriteToXml( writer, XmlElementNames.Mailbox, XmlNamespace.Types); } }
the_stack
* Classes to manipulate Wasm memories. */ import { Pointer, PtrOffset, SizeOf } from "./ctypes"; import { Disposable } from "./types"; import { assert, StringToUint8Array } from "./support"; import * as ctypes from "./ctypes"; /** * Wasm Memory wrapper to perform JS side raw memory access. */ export class Memory { memory: WebAssembly.Memory; wasm32 = true; private buffer: ArrayBuffer | SharedArrayBuffer; private viewU8: Uint8Array; private viewU16: Uint16Array; private viewI32: Int32Array; private viewU32: Uint32Array; private viewF32: Float32Array; private viewF64: Float64Array; constructor(memory: WebAssembly.Memory) { this.memory = memory; this.buffer = this.memory.buffer; this.viewU8 = new Uint8Array(this.buffer); this.viewU16 = new Uint16Array(this.buffer); this.viewI32 = new Int32Array(this.buffer); this.viewU32 = new Uint32Array(this.buffer); this.viewF32 = new Float32Array(this.buffer); this.viewF64 = new Float64Array(this.buffer); } loadU8(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewU8[ptr >> 0]; } loadU16(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewU16[ptr >> 1]; } loadU32(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewU32[ptr >> 2]; } loadI32(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewI32[ptr >> 2]; } loadI64(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } const base = ptr >> 2; // assumes little endian, for now truncate high. return this.viewI32[base]; } loadF32(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewF32[ptr >> 2]; } loadF64(ptr: Pointer): number { if (this.buffer != this.memory.buffer) { this.updateViews(); } return this.viewF64[ptr >> 3]; } loadPointer(ptr: Pointer): Pointer { if (this.buffer != this.memory.buffer) { this.updateViews(); } if (this.wasm32) { return this.loadU32(ptr); } else { return this.loadI64(ptr); } } loadUSize(ptr: Pointer): Pointer { if (this.buffer != this.memory.buffer) { this.updateViews(); } if (this.wasm32) { return this.loadU32(ptr); } else { return this.loadI64(ptr); } } sizeofPtr(): number { return this.wasm32 ? SizeOf.I32 : SizeOf.I64; } /** * Load raw bytes from ptr. * @param ptr The head address * @param numBytes The number */ loadRawBytes(ptr: Pointer, numBytes: number): Uint8Array { if (this.buffer != this.memory.buffer) { this.updateViews(); } const result = new Uint8Array(numBytes); result.set(this.viewU8.slice(ptr, ptr + numBytes)); return result; } /** * Load TVMByteArray from ptr. * * @param ptr The address of the header. */ loadTVMBytes(ptr: Pointer): Uint8Array { const data = this.loadPointer(ptr); const length = this.loadUSize(ptr + this.sizeofPtr()); return this.loadRawBytes(data, length); } /** * Load null-terminated C-string from ptr. * @param ptr The head address */ loadCString(ptr: Pointer): string { if (this.buffer != this.memory.buffer) { this.updateViews(); } // NOTE: the views are still valid for read. const ret = []; let ch = 1; while (ch != 0) { ch = this.viewU8[ptr]; if (ch != 0) { ret.push(String.fromCharCode(ch)); } ++ptr; } return ret.join(""); } /** * Store raw bytes to the ptr. * @param ptr The head address. * @param bytes The bytes content. */ storeRawBytes(ptr: Pointer, bytes: Uint8Array): void { if (this.buffer != this.memory.buffer) { this.updateViews(); } this.viewU8.set(bytes, ptr); } /** * Update memory view after the memory growth. */ private updateViews(): void { this.buffer = this.memory.buffer; this.viewU8 = new Uint8Array(this.buffer); this.viewU16 = new Uint16Array(this.buffer); this.viewI32 = new Int32Array(this.buffer); this.viewU32 = new Uint32Array(this.buffer); this.viewF32 = new Float32Array(this.buffer); this.viewF64 = new Float64Array(this.buffer); } } /** * Auxiliary call stack for the FFI calls. * * Lifecyle of a call stack. * - Calls into allocXX to allocate space, mixed with storeXXX to store data. * - Calls into ptrFromOffset, no further allocation(as ptrFromOffset can change), * can still call into storeXX * - Calls into commitToWasmMemory once. * - reset. */ export class CachedCallStack implements Disposable { /** List of temporay arguments that can be disposed during reset. */ tempArgs: Array<Disposable> = []; private memory: Memory; private cAllocSpace: ctypes.FTVMWasmAllocSpace; private cFreeSpace: ctypes.FTVMWasmFreeSpace; private buffer: ArrayBuffer; private viewU8: Uint8Array; private viewI32: Int32Array; private viewU32: Uint32Array; private viewF64: Float64Array; private stackTop: PtrOffset = 0; private basePtr: Pointer = 0; private addressToSetTargetValue: Array<[PtrOffset, PtrOffset]> = []; constructor( memory: Memory, allocSpace: ctypes.FTVMWasmAllocSpace, freeSpace: ctypes.FTVMWasmFreeSpace ) { const initCallStackSize = 128; this.memory = memory; this.cAllocSpace = allocSpace; this.cFreeSpace = freeSpace; this.buffer = new ArrayBuffer(initCallStackSize); this.basePtr = this.cAllocSpace(initCallStackSize); this.viewU8 = new Uint8Array(this.buffer); this.viewI32 = new Int32Array(this.buffer); this.viewU32 = new Uint32Array(this.buffer); this.viewF64 = new Float64Array(this.buffer); this.updateViews(); } dispose(): void { if (this.basePtr != 0) { this.cFreeSpace(this.basePtr); this.basePtr = 0; } } /** * Rest the call stack so that it can be reused again. */ reset(): void { this.stackTop = 0; assert(this.addressToSetTargetValue.length == 0); while (this.tempArgs.length != 0) { (this.tempArgs.pop() as Disposable).dispose(); } } /** * Commit all the cached data to WasmMemory. * This function can only be called once. * No further store function should be called. * * @param nbytes Number of bytes to be stored. */ commitToWasmMemory(nbytes: number = this.stackTop): void { // commit all pointer values. while (this.addressToSetTargetValue.length != 0) { const [targetOffset, valueOffset] = this.addressToSetTargetValue.pop() as [ number, number ]; this.storePtr(targetOffset, this.ptrFromOffset(valueOffset)); } this.memory.storeRawBytes(this.basePtr, this.viewU8.slice(0, nbytes)); } /** * Allocate space by number of bytes * @param nbytes Number of bytes. * @note This function always allocate space that aligns to 64bit. */ allocRawBytes(nbytes: number): PtrOffset { // always aligns to 64bit nbytes = ((nbytes + 7) >> 3) << 3; if (this.stackTop + nbytes > this.buffer.byteLength) { const newSize = Math.max( this.buffer.byteLength * 2, this.stackTop + nbytes ); const oldU8 = this.viewU8; this.buffer = new ArrayBuffer(newSize); this.updateViews(); this.viewU8.set(oldU8); if (this.basePtr != 0) { this.cFreeSpace(this.basePtr); } this.basePtr = this.cAllocSpace(newSize); } const retOffset = this.stackTop; this.stackTop += nbytes; return retOffset; } /** * Allocate space for pointers. * @param count Number of pointers. * @returns The allocated pointer array. */ allocPtrArray(count: number): PtrOffset { return this.allocRawBytes(this.memory.sizeofPtr() * count); } /** * Get the real pointer from offset values. * Note that the returned value becomes obsolete if alloc is called on the stack. * @param offset The allocated offset. */ ptrFromOffset(offset: PtrOffset): Pointer { return this.basePtr + offset; } // Store APIs storePtr(offset: PtrOffset, value: Pointer): void { if (this.memory.wasm32) { this.storeU32(offset, value); } else { this.storeI64(offset, value); } } storeUSize(offset: PtrOffset, value: Pointer): void { if (this.memory.wasm32) { this.storeU32(offset, value); } else { this.storeI64(offset, value); } } storeI32(offset: PtrOffset, value: number): void { this.viewI32[offset >> 2] = value; } storeU32(offset: PtrOffset, value: number): void { this.viewU32[offset >> 2] = value; } storeI64(offset: PtrOffset, value: number): void { // For now, just store as 32bit // NOTE: wasm always uses little endian. const low = value & 0xffffffff; const base = offset >> 2; this.viewI32[base] = low; this.viewI32[base + 1] = 0; } storeF64(offset: PtrOffset, value: number): void { this.viewF64[offset >> 3] = value; } storeRawBytes(offset: PtrOffset, bytes: Uint8Array): void { this.viewU8.set(bytes, offset); } /** * Allocate then set C-String pointer to the offset. * This function will call into allocBytes to allocate necessary data. * The address won't be set immediately(because the possible change of basePtr) * and will be filled when we commit the data. * * @param offset The offset to set ot data pointer. * @param data The string content. */ allocThenSetArgString(offset: PtrOffset, data: string): void { const strOffset = this.allocRawBytes(data.length + 1); this.storeRawBytes(strOffset, StringToUint8Array(data)); this.addressToSetTargetValue.push([offset, strOffset]); } /** * Allocate then set the argument location with a TVMByteArray. * Allocate new temporary space for bytes. * * @param offset The offset to set ot data pointer. * @param data The string content. */ allocThenSetArgBytes(offset: PtrOffset, data: Uint8Array): void { // Note: size of size_t equals sizeof ptr. const headerOffset = this.allocRawBytes(this.memory.sizeofPtr() * 2); const dataOffset = this.allocRawBytes(data.length); this.storeRawBytes(dataOffset, data); this.storeUSize(headerOffset + this.memory.sizeofPtr(), data.length); this.addressToSetTargetValue.push([offset, headerOffset]); this.addressToSetTargetValue.push([headerOffset, dataOffset]); } /** * Update internal cache views. */ private updateViews(): void { this.viewU8 = new Uint8Array(this.buffer); this.viewI32 = new Int32Array(this.buffer); this.viewU32 = new Uint32Array(this.buffer); this.viewF64 = new Float64Array(this.buffer); } }
the_stack
import { configure } from "mobx"; import { types, Instance } from "mobx-state-tree"; import { SubForm, Form, Field, RepeatingForm, converters } from "../src"; import { debounce, until } from "./utils"; jest.useFakeTimers(); // "always" leads to trouble during initialization. configure({ enforceActions: "observed" }); test("backend process sets error messages", async () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO" }); const form = new Form(M, { foo: new Field(converters.string) }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "error" }] }, ], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const field = state.field("foo"); field.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(field.error).toEqual("error"); }); test("backend process wipes out error messages", async () => { const M = types.model("M", { a: types.string, b: types.string, }); const o = M.create({ a: "A", b: "B" }); const form = new Form(M, { a: new Field(converters.string), b: new Field(converters.string), }); let called = false; // the idea is that the form processor only returns errors related // to the field that was just touched under an id. if that id is wiped out, // those errors are removed. but other error structures (like for 'beta' here) // are not affected and remain const myProcess = async (node: Instance<typeof M>, path: string) => { if (!called) { called = true; return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/a", message: "error a" }], }, { id: "beta", messages: [{ path: "/b", message: "error b" }], }, ], warningValidations: [], }; } else { return { updates: [], accessUpdates: [], errorValidations: [{ id: "alpha", messages: [] }], warningValidations: [], }; } }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const a = state.field("a"); const b = state.field("b"); a.setRaw("a!"); jest.runAllTimers(); await state.processPromise; expect(a.error).toEqual("error a"); expect(b.error).toEqual("error b"); a.setRaw("a!!"); jest.runAllTimers(); await state.processPromise; expect(a.error).toBeUndefined(); expect(b.error).toEqual("error b"); }); test("backend process two requests are synced", async () => { const M = types.model("M", { a: types.string, b: types.string, }); const o = M.create({ a: "A", b: "B" }); const form = new Form(M, { a: new Field(converters.string), b: new Field(converters.string), }); const untilA = until(); const requests: string[] = []; const myProcess = async (node: Instance<typeof M>, path: string) => { // if the 'a' path is passed, we await a promise // This way we can test a long-duration promise and that // the code ensures the next call to run is only executed after the // first is resolved. if (path === "a") { await untilA.finished; } requests.push(path); return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/a", message: `error ${path}` }] }, ], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const a = state.field("a"); const b = state.field("b"); // we run for 'a', it halts until we call resolveA a.setRaw("a!"); // we now run 'b', which should only run once 'a' is resolved b.setRaw("b!"); jest.runAllTimers(); // we resolve 'a' untilA.resolve(); await state.processPromise; // these should both be called, in that order expect(requests).toEqual(["/a", "/b"]); // and we expect the error message to be set expect(a.error).toEqual("error /b"); }); test("backend process three requests are synced", async () => { const M = types.model("M", { a: types.string, b: types.string, c: types.string, }); const o = M.create({ a: "A", b: "B", c: "C" }); const form = new Form(M, { a: new Field(converters.string), b: new Field(converters.string), c: new Field(converters.string), }); const untilA = until(); const untilB = until(); const requests: string[] = []; const myProcess = async (node: Instance<typeof M>, path: string) => { // if the 'a' path is passed, we await a promise // This way we can test a long-duration promise and that // the code ensures the next call to run is only executed after the // first is resolved. if (path === "a") { await untilA.finished; } if (path === "b") { await untilB.finished; } requests.push(path); return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/a", message: `error ${path}` }] }, ], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const a = state.field("a"); const b = state.field("b"); const c = state.field("c"); // we run for 'a', it halts until we call resolveA a.setRaw("a!"); // we now run 'b', which should only run once 'b' is resolved b.setRaw("b!"); // and 'c' which should only run once 'b' is resolved c.setRaw("c!"); jest.runAllTimers(); // we resolve 'b' untilB.resolve(); // we resolve 'a' untilA.resolve(); await state.processPromise; // these should all be called, in the right order expect(requests).toEqual(["/a", "/b", "/c"]); // and we expect the error message to be set expect(a.error).toEqual("error /c"); }); test("backend process does update", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const o = M.create({ foo: "FOO", bar: "BAR" }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [{ path: "/foo", value: "BAR" }], accessUpdates: [], errorValidations: [], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const foo = state.field("foo"); const bar = state.field("bar"); bar.setRaw("BAR!"); jest.runAllTimers(); await state.processPromise; expect(o.foo).toEqual("BAR"); expect(foo.raw).toEqual("BAR"); }); test("backend process ignores update if path re-modified during processing", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const o = M.create({ foo: "FOO", bar: "BAR" }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); let called = false; const myProcess = async (node: Instance<typeof M>, path: string) => { // we ensure that only the first time we call this we // try to update foo if (!called) { called = true; return { updates: [{ path: "/foo", value: "BAR" }], accessUpdates: [], errorValidations: [], warningValidations: [], }; } else { return { updates: [], accessUpdates: [], errorValidations: [], warningValidations: [], }; } }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const foo = state.field("foo"); const bar = state.field("bar"); // trigger the update of foo bar.setRaw("BAR!"); jest.runAllTimers(); // we change things while we are processing // user input should never be overridden by the backend, // even if timers haven't yet run foo.setRaw("CHANGED!"); await state.processPromise; // since only the first change tried to update, and the second change // isn't even triggered yet (and doesn't update anyhow), the value should // be unchanged expect(o.foo).toEqual("CHANGED!"); expect(foo.raw).toEqual("CHANGED!"); }); test("backend process stops ignoring update", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const o = M.create({ foo: "FOO", bar: "BAR" }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); let called = false; const myProcess = async (node: Instance<typeof M>, path: string) => { // we ensure that only the first time we call this we // try to update foo if (!called) { called = true; return { updates: [{ path: "/foo", value: "IGNORED" }], accessUpdates: [], errorValidations: [], warningValidations: [], }; } else { return { updates: [{ path: "/foo", value: "NOW REALLY" }], accessUpdates: [], errorValidations: [], warningValidations: [], }; } }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const foo = state.field("foo"); const bar = state.field("bar"); bar.setRaw("BAR!"); jest.runAllTimers(); // we change things while we are processing // user input should never be overridden by the backend, // even if timers haven't yet run foo.setRaw("CHANGED!"); await state.processPromise; // since only the first change tried to update, and the second change // isn't even triggered yet, the value should // be unchanged expect(o.foo).toEqual("CHANGED!"); expect(foo.raw).toEqual("CHANGED!"); // process the second change now, see it take effect jest.runAllTimers(); await state.processPromise; expect(o.foo).toEqual("NOW REALLY"); }); test("configuration with state", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); async function myProcess(node: Instance<typeof M>, path: string) { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "error!" }] }, ], warningValidations: [], }; } const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const field = state.field("foo"); field.setRaw("BAR"); jest.runAllTimers(); await state.processPromise; expect(field.error).toEqual("error!"); }); test("configuration other getError", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); async function myProcess(node: Instance<typeof M>, path: string) { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "external error" }], }, ], warningValidations: [], }; } const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, getError() { return "getError"; }, }); const field = state.field("foo"); expect(field.error).toEqual("getError"); field.setRaw("BAR"); jest.runAllTimers(); await state.processPromise; expect(field.error).toEqual("external error"); }); test("update", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); const o = M.create({ foo: "FOO", bar: "unchanged" }); async function myProcess(node: Instance<typeof M>, path: string) { return { updates: [{ path: "/bar", value: "BAR" }], accessUpdates: [], errorValidations: [], warningValidations: [], }; } const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const fooField = state.field("foo"); const barField = state.field("bar"); fooField.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(barField.value).toEqual("BAR"); }); test("backend process is rejected, recovery", async () => { const M = types.model("M", { a: types.string, b: types.string, }); const o = M.create({ a: "A", b: "B" }); const form = new Form(M, { a: new Field(converters.string), b: new Field(converters.string), }); const fakeError = jest.fn(); console.error = fakeError; const requests: string[] = []; let crashy = true; const myProcess = async (node: Instance<typeof M>, path: string) => { requests.push(path); if (crashy) { crashy = false; // crash only the first time throw new Error("We crash out"); } return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/a", message: `error ${path}` }] }, ], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const a = state.field("a"); const b = state.field("b"); // we run for 'a', it crashes a.setRaw("A!"); // we now run 'b', should succeed with a message b.setRaw("B!"); jest.runAllTimers(); await state.processPromise; expect(crashy).toBeFalsy(); expect(fakeError.mock.calls.length).toEqual(1); // these should both be called, in that order expect(requests).toEqual(["/a", "/b"]); // and we expect the error message to be set expect(a.error).toEqual("error /b"); }); test("backend process all", async () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO" }); const myProcessAll = async (node: Instance<typeof M>) => { return { updates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "error" }] }, ], warningValidations: [], }; }; const form = new Form(M, { foo: new Field(converters.string), }); const state = form.state(o, { backend: { processAll: myProcessAll, debounce, }, }); await state.processAll(); expect(state.field("foo").error).toEqual("error"); }); test("process all configuration with state", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); const o = M.create({ foo: "FOO", bar: "BAR" }); let setting = "a"; async function myProcessAll(node: Instance<typeof M>) { if (setting === "a") { return { updates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "foo error!" }] }, ], warningValidations: [], }; } else if (setting === "b") { return { updates: [], errorValidations: [ { id: "beta", messages: [{ path: "/bar", message: "bar error!" }] }, ], warningValidations: [], }; } else { return {}; } } const state = form.state(o, { backend: { debounce: debounce, processAll: myProcessAll, }, }); const fooField = state.field("foo"); const barField = state.field("bar"); await state.processAll(); expect(fooField.error).toEqual("foo error!"); expect(barField.error).toBeUndefined(); // now modify settings so we get different results // it should have wiped out all errors setting = "b"; await state.processAll(); expect(fooField.error).toBeUndefined(); expect(barField.error).toEqual("bar error!"); }); test("process & live", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); const liveSeen: boolean[] = []; async function myProcess( node: Instance<typeof M>, path: string, liveOnly: boolean ) { liveSeen.push(liveOnly); return { updates: [], accessUpdates: [], errorValidations: [], warningValidations: [], }; } async function mySave(node: Instance<typeof M>) { return null; } const state = form.state(o, { backend: { process: myProcess, save: mySave, debounce: debounce, }, }); const fooField = state.field("foo"); // before a save, we only want the live fields fooField.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(liveSeen).toEqual([true]); // a successful save const success = await state.save(); expect(success).toBeTruthy(); fooField.setRaw("FOO!!!"); jest.runAllTimers(); await state.processPromise; // now we've seen validation that includes non-live validations expect(liveSeen).toEqual([true, false]); }); test("process & live save error", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); const liveSeen: boolean[] = []; async function myProcess( node: Instance<typeof M>, path: string, liveOnly: boolean ) { liveSeen.push(liveOnly); return { updates: [], accessUpdates: [], errorValidations: [], warningValidations: [], }; } async function mySave(node: Instance<typeof M>) { // this counts as an unsuccessful save return { updates: [], accessUpdates: [], errorValidations: [], warningValidations: [], }; } const state = form.state(o, { backend: { process: myProcess, save: mySave, debounce: debounce, }, }); const fooField = state.field("foo"); // before a save, we only want the live fields fooField.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(liveSeen).toEqual([true]); // an unsuccessful save const success = await state.save(); expect(success).toBeFalsy(); fooField.setRaw("FOO!!!"); jest.runAllTimers(); await state.processPromise; // now we've seen validation that includes non-live validations expect(liveSeen).toEqual([true, false]); }); test("processAll and liveOnly", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); const liveSeen: boolean[] = []; async function myProcessAll(node: Instance<typeof M>, liveOnly: boolean) { liveSeen.push(liveOnly); return { updates: [], errorValidations: [], warningValidations: [], }; } async function mySave(node: Instance<typeof M>) { return null; } const state = form.state(o, { backend: { processAll: myProcessAll, save: mySave, debounce: debounce, }, }); await state.processAll(); expect(liveSeen).toEqual([true]); await state.save(); await state.processAll(); expect(liveSeen).toEqual([true, false]); }); test("processAll and liveOnly overrule", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); const liveSeen: boolean[] = []; async function myProcessAll(node: Instance<typeof M>, liveOnly: boolean) { liveSeen.push(liveOnly); return { updates: [], errorValidations: [], warningValidations: [], }; } async function mySave(node: Instance<typeof M>) { return null; } const state = form.state(o, { backend: { processAll: myProcessAll, save: mySave, debounce: debounce, }, }); await state.processAll(false); expect(liveSeen).toEqual([false]); await state.save(); await state.processAll(true); expect(liveSeen).toEqual([false, true]); }); test("reset liveOnly status", async () => { const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field(converters.string), }); const o = M.create({ foo: "FOO" }); const liveSeen: boolean[] = []; async function myProcess( node: Instance<typeof M>, path: string, liveOnly: boolean ) { liveSeen.push(liveOnly); return { updates: [], accessUpdates: [], errorValidations: [], warningValidations: [], }; } async function mySave(node: Instance<typeof M>) { return null; } const state = form.state(o, { backend: { process: myProcess, save: mySave, debounce: debounce, }, }); const fooField = state.field("foo"); // before a save, we only want the live fields fooField.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(liveSeen).toEqual([true]); // a successful save const success = await state.save(); expect(success).toBeTruthy(); fooField.setRaw("FOO!!!"); jest.runAllTimers(); await state.processPromise; // now we've seen validation that includes non-live validations expect(liveSeen).toEqual([true, false]); // now we reset again to the before save status state.resetSaveStatus(); fooField.setRaw("FOO???"); jest.runAllTimers(); await state.processPromise; expect(liveSeen).toEqual([true, false, true]); }); test("error messages and repeating form", async () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: types.array(N), }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo/0/bar", message: "error" }] }, ], warningValidations: [], }; }; const o = M.create({ foo: [{ bar: "FOO" }] }); const form = new Form(M, { foo: new RepeatingForm({ bar: new Field(converters.string), }), }); const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const foo = state.repeatingForm("foo"); const bar0 = foo.index(0).field("bar"); bar0.setRaw("CHANGED!"); jest.runAllTimers(); await state.processPromise; expect(bar0.error).toEqual("error"); // now insert a new entry above the current one foo.insert(0, { bar: "BEFORE" }, ["bar"]); const barBefore = foo.index(0).field("bar"); expect(barBefore.raw).toEqual("BEFORE"); expect(bar0.raw).toEqual("CHANGED!"); // the error should still be associated with bar0 expect(bar0.error).toEqual("error"); // and the new entry shouldn't have one expect(barBefore.error).toBeUndefined(); }); test("error messages and sub form", async () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: N, }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo/bar", message: "error" }] }, ], warningValidations: [], }; }; const o = M.create({ foo: { bar: "FOO" } }); const form = new Form(M, { foo: new SubForm({ bar: new Field(converters.string), }), }); const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const foo = state.subForm("foo"); const bar = foo.field("bar"); bar.setRaw("CHANGED!"); jest.runAllTimers(); await state.processPromise; expect(bar.error).toEqual("error"); }); test("backend process controls field access", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const o = M.create({ foo: "FOO", bar: "BAR" }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [ { path: "/foo", readOnly: true, disabled: false, required: false, hidden: false, }, ], errorValidations: [], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const foo = state.field("foo"); const bar = state.field("bar"); expect(foo.readOnly).toBeFalsy(); bar.setRaw("BAR!"); jest.runAllTimers(); await state.processPromise; expect(foo.readOnly).toBeTruthy(); expect(bar.readOnly).toBeFalsy(); }); test("backend process controls field access, omission", async () => { const M = types.model("M", { foo: types.string, bar: types.string, }); const o = M.create({ foo: "FOO", bar: "BAR" }); const form = new Form(M, { foo: new Field(converters.string), bar: new Field(converters.string), }); let counter = 0; const accessUpdates = [ { path: "/foo", readOnly: true, disabled: false, required: false, hidden: false, }, { path: "/foo", disabled: true, }, ]; const myProcess = async (node: Instance<typeof M>, path: string) => { const result = { updates: [], accessUpdates: [accessUpdates[counter]], errorValidations: [], warningValidations: [], }; counter++; return result; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const foo = state.field("foo"); const bar = state.field("bar"); expect(foo.readOnly).toBeFalsy(); bar.setRaw("BAR!"); jest.runAllTimers(); await state.processPromise; expect(foo.readOnly).toBeTruthy(); expect(foo.disabled).toBeFalsy(); bar.setRaw("BAR!!"); jest.runAllTimers(); await state.processPromise; expect(foo.readOnly).toBeTruthy(); expect(foo.disabled).toBeTruthy(); }); test("backend process controls field access for repeating form", async () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: types.array(N), }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [ { path: "/foo/0", readOnly: false, disabled: true, required: false, hidden: false, }, ], errorValidations: [], warningValidations: [], }; }; const o = M.create({ foo: [{ bar: "FOO" }] }); const form = new Form(M, { foo: new RepeatingForm({ bar: new Field(converters.string), }), }); const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const foo = state.repeatingForm("foo"); const bar0 = foo.index(0).field("bar"); expect(bar0.disabled).toBeFalsy(); bar0.setRaw("CHANGED!"); jest.runAllTimers(); await state.processPromise; expect(bar0.disabled).toBeTruthy(); // now insert a new entry above the current one foo.insert(0, { bar: "BEFORE" }, ["bar"]); const barBefore = foo.index(0).field("bar"); expect(barBefore.disabled).toBeFalsy(); expect(bar0.disabled).toBeTruthy(); }); test("backend process controls field access for sub form", async () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: N, }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [ { path: "foo/bar", hidden: true, }, ], errorValidations: [], warningValidations: [], }; }; const o = M.create({ foo: { bar: "FOO" } }); const form = new Form(M, { foo: new SubForm({ bar: new Field(converters.string), }), }); const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const foo = state.subForm("foo"); const bar = foo.field("bar"); bar.setRaw("CHANGED!"); jest.runAllTimers(); await state.processPromise; expect(bar.hidden).toBeTruthy(); }); test("backend process required", async () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: N, }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [ { path: "foo", required: true, }, ], errorValidations: [], warningValidations: [], }; }; const o = M.create({ foo: { bar: "FOO" } }); const form = new Form(M, { foo: new SubForm({ bar: new Field(converters.string), }), }); const state = form.state(o, { backend: { process: myProcess, debounce: debounce, }, }); const foo = state.subForm("foo"); const bar = foo.field("bar"); bar.setRaw("CHANGED!"); jest.runAllTimers(); await state.processPromise; expect(bar.required).toBeFalsy(); }); test("backend clearAllValidations", async () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO" }); const form = new Form(M, { foo: new Field(converters.string) }); const myProcess = async (node: Instance<typeof M>, path: string) => { return { updates: [], accessUpdates: [], errorValidations: [ { id: "alpha", messages: [{ path: "/foo", message: "error" }] }, ], warningValidations: [], }; }; const state = form.state(o, { backend: { process: myProcess, debounce, }, }); const field = state.field("foo"); field.setRaw("FOO!"); jest.runAllTimers(); await state.processPromise; expect(field.error).toEqual("error"); state.clearAllValidations(); expect(field.error).toBeUndefined(); }); test("backend process all global error", async () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO" }); const myProcessAll = async (node: Instance<typeof M>) => { return { updates: [], errorValidations: [ { id: "alpha", messages: [{ path: "", message: "error" }] }, ], warningValidations: [], }; }; const form = new Form(M, { foo: new Field(converters.string), }); const state = form.state(o, { backend: { processAll: myProcessAll, debounce, }, }); await state.processAll(); expect(state.error).toEqual("error"); state.clearAllValidations(); expect(state.error).toBeUndefined(); }); test("backend process all global warning", async () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO" }); const myProcessAll = async (node: Instance<typeof M>) => { return { updates: [], errorValidations: [], warningValidations: [ { id: "alpha", messages: [{ path: "", message: "warning" }] }, ], }; }; const form = new Form(M, { foo: new Field(converters.string), }); const state = form.state(o, { backend: { processAll: myProcessAll, debounce, }, }); await state.processAll(); expect(state.warning).toEqual("warning"); state.clearAllValidations(); expect(state.warning).toBeUndefined(); });
the_stack
import { aTimeout, fixture, fixtureCleanup, html } from '@open-wc/testing/index-no-side-effects'; import { assert } from 'chai'; import { css, customElement, LitElement, property } from 'lit-element'; import * as sinon from 'sinon'; import { provider } from './context'; import { IntersectionNotifier, lazyRendering, observer, ObserverElement, ProgressiveNotifier, provideNotifier, RenderPlaceHolder, } from './observer_element'; @customElement('milo-enter-view-observer-notifier-provider-test') @provider class EnterViewObserverNotifierProviderElement extends LitElement { @property() @provideNotifier() notifier = new IntersectionNotifier({ root: this }); protected render() { return html`<slot></slot>`; } static styles = css` :host { display: block; height: 100px; overflow-y: auto; } `; } @customElement('milo-enter-view-observer-test-entry') @observer class EnterViewObserverTestEntryElement extends LitElement implements ObserverElement { @property() onEnterCallCount = 0; notify() { this.onEnterCallCount++; } protected render() { return html`content`; } static styles = css` :host { display: block; height: 10px; } `; } describe('enterViewObserver', () => { let listView: EnterViewObserverNotifierProviderElement; let entries: NodeListOf<EnterViewObserverTestEntryElement>; beforeEach(async () => { listView = await fixture<EnterViewObserverNotifierProviderElement>(html` <milo-enter-view-observer-notifier-provider-test> ${new Array(100) .fill(0) .map(() => html`<milo-enter-view-observer-test-entry></milo-enter-view-observer-test-entry>`)} </milo-enter-view-observer-notifier-provider-test> `); entries = listView.querySelectorAll<EnterViewObserverTestEntryElement>('milo-enter-view-observer-test-entry'); }); afterEach(fixtureCleanup); it('should notify entries in the view.', async () => { await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.onEnterCallCount, i <= 10 ? 1 : 0); }); }); it('should notify new entries scrolls into the view.', async () => { await aTimeout(20); listView.scrollBy(0, 50); await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.onEnterCallCount, i <= 15 ? 1 : 0); }); }); it('should re-notify old entries when scrolling back and forth.', async () => { await aTimeout(20); listView.scrollBy(0, 50); await aTimeout(20); listView.scrollBy(0, -50); await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.onEnterCallCount, i <= 15 ? 1 : 0); }); }); it('different instances can have different notifiers', async () => { const notifier1 = new IntersectionNotifier(); const notifier2 = new IntersectionNotifier(); const notifierStub1 = sinon.stub(notifier1); const notifierStub2 = sinon.stub(notifier2); const provider1 = await fixture<EnterViewObserverNotifierProviderElement>(html` <milo-enter-view-observer-notifier-provider-test .notifier=${notifier1}> <milo-enter-view-observer-test-entry></milo-enter-view-observer-test-entry> </milo-enter-view-observer-notifier-provider-test> `); const provider2 = await fixture<EnterViewObserverNotifierProviderElement>(html` <milo-enter-view-observer-notifier-provider-test .notifier=${notifier2}> <milo-enter-view-observer-test-entry></milo-enter-view-observer-test-entry> </milo-enter-view-observer-notifier-provider-test> `); const entry1 = provider1.querySelector('milo-enter-view-observer-test-entry') as EnterViewObserverTestEntryElement; const entry2 = provider2.querySelector('milo-enter-view-observer-test-entry') as EnterViewObserverTestEntryElement; fixtureCleanup(); assert.strictEqual(notifierStub1.subscribe.callCount, 1); assert.strictEqual(notifierStub1.subscribe.getCall(0).args[0], entry1); assert.strictEqual(notifierStub2.subscribe.callCount, 1); assert.strictEqual(notifierStub2.subscribe.getCall(0).args[0], entry2); assert.strictEqual(notifierStub1.unsubscribe.callCount, 1); assert.strictEqual(notifierStub1.unsubscribe.getCall(0).args[0], entry1); assert.strictEqual(notifierStub2.unsubscribe.callCount, 1); assert.strictEqual(notifierStub2.unsubscribe.getCall(0).args[0], entry2); }); it('updating observer should works correctly', async () => { const notifier1 = new IntersectionNotifier(); const notifier2 = new IntersectionNotifier(); const notifierStub1 = sinon.stub(notifier1); const notifierStub2 = sinon.stub(notifier2); const provider = await fixture<EnterViewObserverNotifierProviderElement>(html` <milo-enter-view-observer-notifier-provider-test .notifier=${notifier1}> <milo-enter-view-observer-test-entry></milo-enter-view-observer-test-entry> </milo-enter-view-observer-notifier-provider-test> `); const entry = provider.querySelector('milo-enter-view-observer-test-entry') as EnterViewObserverTestEntryElement; assert.strictEqual(notifierStub1.subscribe.callCount, 1); assert.strictEqual(notifierStub1.subscribe.getCall(0).args[0], entry); provider.notifier = notifier2; await aTimeout(20); assert.strictEqual(notifierStub2.subscribe.callCount, 1); assert.strictEqual(notifierStub2.subscribe.getCall(0).args[0], entry); assert.strictEqual(notifierStub1.unsubscribe.callCount, 1); assert.strictEqual(notifierStub1.unsubscribe.getCall(0).args[0], entry); fixtureCleanup(); assert.strictEqual(notifierStub2.unsubscribe.callCount, 1); assert.strictEqual(notifierStub2.unsubscribe.getCall(0).args[0], entry); }); }); @customElement('milo-lazy-rendering-test-entry') @lazyRendering class LazyRenderingElement extends LitElement implements RenderPlaceHolder { renderPlaceHolder() { return html`placeholder`; } protected render() { return html`content`; } static styles = css` :host { display: block; height: 10px; } `; } describe('lazyRendering', () => { let listView: EnterViewObserverNotifierProviderElement; let entries: NodeListOf<LazyRenderingElement>; beforeEach(async () => { listView = await fixture<EnterViewObserverNotifierProviderElement>(html` <milo-enter-view-observer-notifier-provider-test> ${new Array(100).fill(0).map(() => html`<milo-lazy-rendering-test-entry></milo-lazy-rendering-test-entry>`)} </milo-enter-view-observer-notifier-provider-test> `); entries = listView.querySelectorAll<LazyRenderingElement>('milo-lazy-rendering-test-entry'); }); afterEach(fixtureCleanup); it('should only render content for elements entered the view.', async () => { await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 10 ? 'content' : 'placeholder'); }); }); it('should work with scrolling', async () => { await aTimeout(20); listView.scrollBy(0, 50); await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 15 ? 'content' : 'placeholder'); }); }); }); @customElement('milo-progressive-rendering-test-entry') @lazyRendering class ProgressiveRenderingElement extends LitElement implements RenderPlaceHolder { renderPlaceHolder() { return html`placeholder`; } protected render() { return html`content`; } static styles = css` :host { display: block; height: 10px; } `; } @customElement('milo-progressive-rendering-notifier-provider-test') @provider class ProgressiveNotifierProviderElement extends LitElement { @provideNotifier() notifier = new ProgressiveNotifier({ batchInterval: 100, batchSize: 10, root: this }); protected render() { return html`<slot></slot>`; } static styles = css` :host { display: block; height: 100px; overflow-y: auto; } `; } describe('progressiveNotifier', () => { let listView: ProgressiveNotifierProviderElement; let entries: NodeListOf<ProgressiveRenderingElement>; beforeEach(async () => { listView = await fixture<ProgressiveNotifierProviderElement>(html` <milo-progressive-rendering-notifier-provider-test> ${new Array(100) .fill(0) .map(() => html`<milo-progressive-rendering-test-entry></milo-progressive-rendering-test-entry>`)} </milo-progressive-rendering-notifier-provider-test> `); entries = listView.querySelectorAll<ProgressiveRenderingElement>('milo-progressive-rendering-test-entry'); }); afterEach(fixtureCleanup); it('should only render content for elements entered the view.', async () => { await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 10 ? 'content' : 'placeholder'); }); }); it('should work with scrolling', async () => { await aTimeout(20); listView.scrollBy(0, 50); await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 15 ? 'content' : 'placeholder'); }); }); it('should notify some of the remaining entries after certain interval', async () => { await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 10 ? 'content' : 'placeholder'); }); await aTimeout(150); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 20 ? 'content' : 'placeholder'); }); }); it('new notification should reset interval', async () => { await aTimeout(20); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 10 ? 'content' : 'placeholder'); }); await aTimeout(60); listView.scrollBy(0, 50); await aTimeout(60); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 15 ? 'content' : 'placeholder'); }); await aTimeout(50); entries.forEach((entry, i) => { assert.equal(entry.shadowRoot!.textContent, i <= 25 ? 'content' : 'placeholder'); }); }); });
the_stack
import { Trans, t } from "@lingui/macro"; import { i18nMark, withI18n } from "@lingui/react"; import classNames from "classnames"; import isEqual from "lodash.isequal"; import PropTypes from "prop-types"; import * as React from "react"; import { Confirm } from "reactjs-components"; import { Hooks } from "PluginSDK"; import { routerShape } from "react-router"; import { combineParsers } from "#SRC/js/utils/ParserUtil"; import { combineReducers } from "#SRC/js/utils/ReducerUtil"; import { DCOS_CHANGE } from "#SRC/js/constants/EventTypes"; import DCOSStore from "#SRC/js/stores/DCOSStore"; import AppValidators from "#SRC/resources/raml/marathon/v2/types/app.raml"; import DataValidatorUtil from "#SRC/js/utils/DataValidatorUtil"; import FullScreenModal from "#SRC/js/components/modals/FullScreenModal"; import FullScreenModalHeader from "#SRC/js/components/modals/FullScreenModalHeader"; import FullScreenModalHeaderActions from "#SRC/js/components/modals/FullScreenModalHeaderActions"; import ModalHeading from "#SRC/js/components/modals/ModalHeading"; import PodValidators from "#SRC/resources/raml/marathon/v2/types/pod.raml"; import ToggleButton from "#SRC/js/components/ToggleButton"; import UserSettingsStore from "#SRC/js/stores/UserSettingsStore"; import Util from "#SRC/js/utils/Util"; import Application from "../../structs/Application"; import ApplicationSpec from "../../structs/ApplicationSpec"; import PodSpec from "../../structs/PodSpec"; import Service from "../../structs/Service"; import MarathonActions from "../../events/MarathonActions"; import MarathonStore from "../../stores/MarathonStore"; import { MARATHON_SERVICE_CREATE_ERROR, MARATHON_SERVICE_CREATE_SUCCESS, MARATHON_SERVICE_EDIT_ERROR, MARATHON_SERVICE_EDIT_SUCCESS, } from "../../constants/EventTypes"; import { DEFAULT_APP_SPEC } from "../../constants/DefaultApp"; import { DEFAULT_POD_SPEC } from "../../constants/DefaultPod"; import ContainerServiceFormSection from "../forms/ContainerServiceFormSection"; import CreateServiceJsonOnly from "./CreateServiceJsonOnly"; import EnvironmentFormSection from "../forms/EnvironmentFormSection"; import MarathonAppValidators from "../../validators/MarathonAppValidators"; import MarathonPodValidators from "../../validators/MarathonPodValidators"; import MarathonErrorUtil from "../../utils/MarathonErrorUtil"; import CreateServiceModalServicePicker from "./CreateServiceModalServicePicker"; import CreateServiceModalForm from "./CreateServiceModalForm"; import ServiceConfigDisplay from "../../service-configuration/ServiceConfigDisplay"; import GeneralServiceFormSection from "../forms/GeneralServiceFormSection"; import HealthChecksFormSection from "../forms/HealthChecksFormSection"; import JSONSingleContainerReducers from "../../reducers/JSONSingleContainerReducers"; import JSONMultiContainerParser from "../../reducers/JSONMultiContainerParser"; import JSONMultiContainerReducers from "../../reducers/JSONMultiContainerReducers"; import JSONSingleContainerParser from "../../reducers/JSONSingleContainerParser"; import MultiContainerNetworkingFormSection from "../forms/MultiContainerNetworkingFormSection"; import MultiContainerVolumesFormSection from "../forms/MultiContainerVolumesFormSection"; import NetworkingFormSection from "../forms/NetworkingFormSection"; import * as ServiceErrorTypes from "../../constants/ServiceErrorTypes"; import VolumesFormSection from "../forms/VolumesFormSection"; import VipLabelsValidators from "../../validators/VipLabelsValidators"; import PlacementsValidators from "../../validators/PlacementsValidators"; import { getBaseID, getServiceJSON } from "../../utils/ServiceUtil"; const APP_VALIDATORS = [ AppValidators.App, MarathonAppValidators.containsCmdArgsOrContainer, MarathonAppValidators.mustContainImageOnDocker, MarathonAppValidators.validateConstraints, MarathonAppValidators.validateLabels, MarathonAppValidators.mustNotContainUris, MarathonAppValidators.validateProfileVolumes, VipLabelsValidators.mustContainPort, ]; const POD_VALIDATORS = [ PodValidators.Pod, MarathonPodValidators.validateProfileVolumes, VipLabelsValidators.mustContainPort, PlacementsValidators.mustHaveUniqueOperatorField, ]; class CreateServiceModal extends React.Component { static propTypes = { params: PropTypes.object.isRequired, location: PropTypes.object.isRequired, }; state = this.getResetState(this.props); componentDidMount() { const { location, route } = this.props; const { service } = this.state; const { router } = this.context; // Add store change listeners the traditional way as React Router is // not able to pass down correct props if we are using StoreMixin MarathonStore.addChangeListener( MARATHON_SERVICE_CREATE_ERROR, this.onMarathonStoreServiceCreateError ); MarathonStore.addChangeListener( MARATHON_SERVICE_CREATE_SUCCESS, this.onMarathonStoreServiceCreateSuccess ); MarathonStore.addChangeListener( MARATHON_SERVICE_EDIT_ERROR, this.onMarathonStoreServiceEditError ); MarathonStore.addChangeListener( MARATHON_SERVICE_EDIT_SUCCESS, this.onMarathonStoreServiceEditSuccess ); this.unregisterLeaveHook = router.setRouteLeaveHook( route, this.handleRouterWillLeave ); // Only add change listener if we didn't receive our service in first try if (!service && this.isLocationEdit(location)) { DCOSStore.addChangeListener(DCOS_CHANGE, this.handleStoreChange); } } UNSAFE_componentWillReceiveProps(nextProps) { const { location, params } = this.props; // Skip update if there was no change to props if ( nextProps.location.pathname === location.pathname && isEqual(nextProps.params, params) ) { return; } this.setState(this.getResetState(nextProps)); } UNSAFE_componentWillUpdate(nextProps, nextState) { const requestCompleted = this.state.isPending && !nextState.isPending; const shouldClose = requestCompleted && !nextState.apiErrors.length; if (shouldClose) { const serviceID = nextProps.params.id || ""; const { path } = nextProps.route; const routePrefix = path.startsWith("edit") ? // When edit: navigate to the detail of the service which was edited "/services/detail/" : // When create: navigate to the group service was created in "/services/overview/"; this.context.router.push(routePrefix + encodeURIComponent(serviceID)); } } componentWillUnmount() { MarathonStore.removeChangeListener( MARATHON_SERVICE_CREATE_ERROR, this.onMarathonStoreServiceCreateError ); MarathonStore.removeChangeListener( MARATHON_SERVICE_CREATE_SUCCESS, this.onMarathonStoreServiceCreateSuccess ); MarathonStore.removeChangeListener( MARATHON_SERVICE_EDIT_ERROR, this.onMarathonStoreServiceEditError ); MarathonStore.removeChangeListener( MARATHON_SERVICE_EDIT_SUCCESS, this.onMarathonStoreServiceEditSuccess ); // Clean up router leave hook this.unregisterLeaveHook(); // Also remove DCOS change listener, if still subscribed DCOSStore.removeChangeListener(DCOS_CHANGE, this.handleStoreChange); } onMarathonStoreServiceCreateError = (errors) => { this.setState({ apiErrors: MarathonErrorUtil.parseErrors(errors), isPending: false, }); }; onMarathonStoreServiceCreateSuccess = () => { this.setState({ apiErrors: [], isPending: false }); }; onMarathonStoreServiceEditError = (errors) => { this.setState({ apiErrors: MarathonErrorUtil.parseErrors(errors), isPending: false, }); }; onMarathonStoreServiceEditSuccess = () => { this.setState({ apiErrors: [], isPending: false }); }; shouldForceSubmit() { return this.state.apiErrors.some( (error) => error.type === ServiceErrorTypes.SERVICE_DEPLOYING ); } handleRouterWillLeave = () => { const { isOpen, hasChangesApplied, serviceReviewActive } = this.state; // If we are not about to close the modal and not on the review screen, // confirm before navigating away if (isOpen && hasChangesApplied && !serviceReviewActive) { this.handleOpenConfirm(); // Cancel route change, if it is already open return false; } return true; }; handleConfirmGoBack = () => { const { location } = this.props; const { serviceFormActive, serviceJsonActive } = this.state; // Close if editing a service in the form if (serviceFormActive && this.isLocationEdit(location)) { this.handleClose(); return; } // Switch back from form to picker if (serviceFormActive) { this.setState({ isConfirmOpen: false, hasChangesApplied: false, servicePickerActive: true, serviceFormActive: false, }); return; } // Switch back from JSON to picker if (serviceJsonActive) { this.setState({ isConfirmOpen: false, hasChangesApplied: false, servicePickerActive: true, serviceJsonActive: false, }); } }; handleStoreChange = () => { // Unsubscribe from further events DCOSStore.removeChangeListener(DCOS_CHANGE, this.handleStoreChange); const { params } = this.props; const serviceID = decodeURIComponent(params.id || "/"); const service = DCOSStore.serviceTree.findItemById(serviceID); this.setState({ service, serviceSpec: service.getSpec() }); }; handleGoBack = (event) => { const { tabViewID } = event; const { hasChangesApplied, serviceFormActive, servicePickerActive, serviceReviewActive, } = this.state; if (serviceReviewActive) { // Remove the 'Application is deploying' error when we havigate back // since it's not related to the form const apiErrors = this.state.apiErrors.filter( (error) => error.type !== ServiceErrorTypes.SERVICE_DEPLOYING ); // Just hide review screen. Form or JSON mode will be // activated automatically depending on their last state this.setState({ activeTab: tabViewID, apiErrors, serviceReviewActive: false, showAllErrors: true, }); return; } // Close if picker is open if (servicePickerActive && !serviceFormActive) { this.handleClose(); return; } // Close if editing a service in the form, but confirm before // if changes has been applied to the form if (serviceFormActive && hasChangesApplied) { this.handleOpenConfirm(); return; } this.handleConfirmGoBack(); }; handleTabChange = (activeTab) => { this.setState({ activeTab }); }; handleClearError = () => { this.setState({ apiErrors: [], showAllErrors: false, }); }; handleOpenConfirm() { this.setState({ isConfirmOpen: true }); } handleCloseConfirmModal = () => { this.setState({ isConfirmOpen: false }); }; handleClose = () => { // Start the animation of the modal by setting isOpen to false this.setState({ isConfirmOpen: false, isOpen: false }, () => { // Once state is set, start a timer for the length of the animation and // navigate away once the animation is over. setTimeout(this.context.router.goBack, 300); }); }; handleConvertToPod = () => { this.handleServiceSelection({ type: "pod" }); }; handleJSONToggle = () => { UserSettingsStore.setJSONEditorExpandedSetting( !this.state.isJSONModeActive ); this.setState({ isJSONModeActive: !this.state.isJSONModeActive }); }; handleServiceChange = (newService) => { // If there were previous error messages visible it's better to revalidate // on each change going forward const formErrors = this.state.submitFailed ? this.validateServiceSpec(newService) : []; this.setState({ serviceSpec: newService, hasChangesApplied: true, formErrors, }); }; handleServiceErrorsChange = (errors) => { this.setState({ serviceFormErrors: errors }); }; handleServicePropertyChange = (path) => { const refPath = path.join("."); let { apiErrors } = this.state; apiErrors = apiErrors.filter((error) => { const errorPath = error.path.join("."); // Remove all root errors on a simple update if (errorPath === "") { return false; } // Otherwise remove errors on the given path return errorPath !== refPath; }); this.setState({ apiErrors }); }; handleServiceSelection = (event) => { const { route, type } = event; const { params } = this.props; const baseID = getBaseID(decodeURIComponent(params.id || "/")); switch (type) { case "app": this.setState({ activeTab: null, apiErrors: [], formErrors: [], serviceFormErrors: [], servicePickerActive: false, serviceFormActive: true, serviceSpec: new ApplicationSpec({ id: baseID, ...DEFAULT_APP_SPEC, }), showAllErrors: false, }); break; case "pod": this.setState({ activeTab: null, apiErrors: [], formErrors: [], serviceFormErrors: [], servicePickerActive: false, serviceFormActive: true, serviceSpec: new PodSpec({ id: baseID, ...DEFAULT_POD_SPEC, }), showAllErrors: false, }); break; case "json": this.setState({ activeTab: null, apiErrors: [], formErrors: [], serviceFormErrors: [], servicePickerActive: false, serviceJsonActive: true, serviceSpec: new ApplicationSpec({ id: baseID, ...DEFAULT_APP_SPEC, }), showAllErrors: false, }); break; case "redirect": this.context.router.push(route); break; } }; handleServiceReview = () => { const expandAdvancedSettings = this.getExpandAdvancedSettings(); if (this.criticalFormErrors().length === 0) { this.setState({ apiErrors: [], formErrors: [], serviceReviewActive: true, expandAdvancedSettings, }); } else { this.setState({ showAllErrors: true, submitFailed: true, formErrors: this.validateServiceSpec(this.state.serviceSpec), expandAdvancedSettings, }); } }; handleServiceRun = () => { const { location } = this.props; const { service, serviceSpec } = this.state; const force = this.shouldForceSubmit(); if (this.isLocationEdit(location) && service instanceof Service) { MarathonActions.editService(service, serviceSpec, force); } else { MarathonActions.createService(serviceSpec, force); } this.setState({ isPending: true }); }; getExpandAdvancedSettings = () => { // If we have errors inside the advanced options, expand the options to allow the user to see the errors. const { serviceSpec } = this.state; const isDockerContainer = Util.findNestedPropertyInObject(serviceSpec, "container.type") === "DOCKER"; return this.criticalFormErrors().some( ({ path }) => isEqual(path, ["gpus"]) || isEqual(path, ["disk"]) || (isDockerContainer && isEqual(path, ["container", "docker", "image"])) ); }; isLocationEdit(location) { return location.pathname.includes("/edit"); } /** * Determines whether or not the form can be submitted * @returns {array} of critical errors that are present */ criticalFormErrors() { const formErrors = this.validateServiceSpec(this.state.serviceSpec); const criticalFormErrors = formErrors.filter( (error) => !error.isPermissive ); return criticalFormErrors.concat(this.state.serviceFormErrors); } /** * This function returns errors produced by the form validators * @param {Object} serviceSpec The service spec to validate * @returns {Array} - An array of error objects */ validateServiceSpec(serviceSpec) { let validationErrors = []; const appValidators = APP_VALIDATORS.concat( Hooks.applyFilter("appValidators", []) ); const podValidators = POD_VALIDATORS.concat( Hooks.applyFilter("podValidators", []) ); // Validate Application or Pod according to the contents // of the serviceSpec property. if (serviceSpec instanceof ApplicationSpec) { validationErrors = DataValidatorUtil.validate( getServiceJSON(serviceSpec), appValidators ); } if (serviceSpec instanceof PodSpec) { validationErrors = DataValidatorUtil.validate( getServiceJSON(serviceSpec), podValidators ); } return validationErrors; } /** * This function combines the errors received from marathon and the errors * produced by the form into a unified error array * * @returns {Array} - An array of error objects */ getAllErrors() { return this.state.apiErrors .concat(this.state.formErrors) .concat(this.state.serviceFormErrors); } getHeader() { // NOTE: Always prioritize review screen check if (this.state.serviceReviewActive) { return ( <FullScreenModalHeader> <FullScreenModalHeaderActions actions={this.getSecondaryActions()} type="secondary" /> <div className="modal-full-screen-header-title"> <Trans render="span">Review & Run Service</Trans> </div> <FullScreenModalHeaderActions actions={this.getPrimaryActions()} type="primary" /> </FullScreenModalHeader> ); } let title = <Trans render="span">Run a Service</Trans>; const { location } = this.props; const { service } = this.state; if (this.isLocationEdit(location)) { title = service ? ( <Trans render="span">Edit {service.getName()}</Trans> ) : ( <Trans render="span">Edit Service</Trans> ); } return ( <FullScreenModalHeader> <FullScreenModalHeaderActions actions={this.getSecondaryActions()} type="secondary" /> <div className="modal-full-screen-header-title">{title}</div> <FullScreenModalHeaderActions actions={this.getPrimaryActions()} type="primary" /> </FullScreenModalHeader> ); } resetExpandAdvancedSettings = () => { // Reset, otherwise every change in the form will open the advanced options // after they are opened once if (this.state.expandAdvancedSettings) { this.setState({ expandAdvancedSettings: false }); } }; getModalContent() { const { isJSONModeActive, serviceSpec, serviceFormActive, serviceJsonActive, servicePickerActive, serviceReviewActive, expandAdvancedSettings, } = this.state; // NOTE: Always prioritize review screen check if (serviceReviewActive) { return ( <div className="flex-item-grow-1"> <div className="container"> <ServiceConfigDisplay onEditClick={this.handleGoBack} appConfig={serviceSpec} errors={this.getAllErrors()} /> </div> </div> ); } if (servicePickerActive) { return ( <CreateServiceModalServicePicker onServiceSelect={this.handleServiceSelection} /> ); } if (serviceFormActive) { const { location } = this.props; const { showAllErrors } = this.state; const SINGLE_CONTAINER_SECTIONS = [ ContainerServiceFormSection, EnvironmentFormSection, GeneralServiceFormSection, HealthChecksFormSection, NetworkingFormSection, VolumesFormSection, ]; const MULTI_CONTAINER_SECTIONS = [ ContainerServiceFormSection, EnvironmentFormSection, GeneralServiceFormSection, HealthChecksFormSection, NetworkingFormSection, VolumesFormSection, MultiContainerVolumesFormSection, MultiContainerNetworkingFormSection, ]; let jsonParserReducers; let jsonConfigReducers; let inputConfigReducers; if (serviceSpec instanceof PodSpec) { jsonParserReducers = combineParsers( Hooks.applyFilter( "multiContainerCreateJsonParserReducers", JSONMultiContainerParser ) ); jsonConfigReducers = combineReducers( Hooks.applyFilter( "multiContainerJsonConfigReducers", JSONMultiContainerReducers ) ); inputConfigReducers = combineReducers( Hooks.applyFilter( "multiContainerInputConfigReducers", Object.assign( {}, ...MULTI_CONTAINER_SECTIONS.map((item) => item.configReducers) ) ) ); } else { jsonParserReducers = combineParsers( Hooks.applyFilter( "serviceCreateJsonParserReducers", JSONSingleContainerParser ) ); jsonConfigReducers = combineReducers( Hooks.applyFilter( "serviceJsonConfigReducers", JSONSingleContainerReducers ) ); inputConfigReducers = combineReducers( Hooks.applyFilter( "serviceInputConfigReducers", Object.assign( {}, ...SINGLE_CONTAINER_SECTIONS.map((item) => item.configReducers) ) ) ); } return ( <CreateServiceModalForm activeTab={this.state.activeTab} errors={this.getAllErrors()} expandAdvancedSettings={expandAdvancedSettings} jsonParserReducers={jsonParserReducers} jsonConfigReducers={jsonConfigReducers} handleTabChange={this.handleTabChange} inputConfigReducers={inputConfigReducers} isEdit={this.isLocationEdit(location)} isJSONModeActive={isJSONModeActive} ref={(ref) => (this.createComponent = ref)} onChange={this.handleServiceChange} onConvertToPod={this.handleConvertToPod} onErrorsChange={this.handleServiceErrorsChange} service={serviceSpec} showAllErrors={showAllErrors} resetExpandAdvancedSettings={this.resetExpandAdvancedSettings} /> ); } if (serviceJsonActive) { // TODO (DCOS-13561): serviceSpec should be service return ( <CreateServiceJsonOnly errors={this.getAllErrors()} onChange={this.handleServiceChange} onErrorsChange={this.handleServiceErrorsChange} onPropertyChange={this.handleServicePropertyChange} ref={(ref) => (this.createComponent = ref)} service={serviceSpec} /> ); } return null; } getPrimaryActions() { const { serviceFormActive, serviceJsonActive, servicePickerActive, serviceReviewActive, } = this.state; const force = this.shouldForceSubmit(); const runButtonLabel = force ? i18nMark("Force Run Service") : i18nMark("Run Service"); const runButtonClassNames = classNames("flush-vertical", { "button-primary": !force, "button-danger": force, }); // NOTE: Always prioritize review screen check if (serviceReviewActive) { return [ { className: runButtonClassNames, clickHandler: this.handleServiceRun, label: this.state.isPending ? i18nMark("Deploying...") : runButtonLabel, disabled: this.state.isPending, }, ]; } if (servicePickerActive) { return []; } if (serviceFormActive) { return [ { node: ( <ToggleButton className="flush" checkboxClassName="toggle-button toggle-button-align-left" checked={this.state.isJSONModeActive} onChange={this.handleJSONToggle} key="json-editor" > <Trans render="span">JSON Editor</Trans> </ToggleButton> ), }, { className: "button-primary flush-vertical", clickHandler: this.handleServiceReview, label: i18nMark("Review & Run"), }, ]; } if (serviceJsonActive) { return [ { className: "button-primary flush-vertical", clickHandler: this.handleServiceReview, label: i18nMark("Review & Run"), }, ]; } return []; } getResetState(nextProps = this.props) { const { location, params } = nextProps; const isEdit = this.isLocationEdit(location); const serviceID = decodeURIComponent(params.id || "/"); const service = isEdit ? DCOSStore.serviceTree.findItemById(serviceID) : null; const isSpecificVersion = service instanceof Application && params.version; let serviceSpec = new ApplicationSpec({ id: getBaseID(serviceID), ...DEFAULT_APP_SPEC, }); if (isEdit && service instanceof Service && !isSpecificVersion) { serviceSpec = service.getSpec(); } if (isEdit && isSpecificVersion) { serviceSpec = service .constructor(service.getVersions().get(params.version)) .getSpec(); } const newState = { activeTab: null, apiErrors: [], expandAdvancedSettings: false, formErrors: [], // Errors detected by form validation hasChangesApplied: false, isConfirmOpen: false, isJSONModeActive: UserSettingsStore.JSONEditorExpandedSetting, isOpen: true, isPending: false, submitDisabled: false, service, serviceSpec, serviceFormActive: isEdit, // Switch directly to form/json if edit serviceFormErrors: [], serviceJsonActive: false, servicePickerActive: !isEdit, // Switch directly to form/json if edit serviceReviewActive: false, serviceFormHasErrors: false, showAllErrors: false, submitFailed: false, // Tried to submit form and form validation failed }; return newState; } getSecondaryActions() { const { location } = this.props; const { servicePickerActive, serviceReviewActive } = this.state; let label = i18nMark("Back"); if ( servicePickerActive || (this.isLocationEdit(location) && !serviceReviewActive) ) { label = i18nMark("Cancel"); } return [ { className: "button-primary-link button-flush-horizontal", clickHandler: this.handleGoBack, label, }, ]; } render() { const { props } = this; const { hasChangesApplied, isOpen, servicePickerActive, serviceReviewActive, } = this.state; let useGemini = false; if (servicePickerActive || serviceReviewActive) { useGemini = true; } let closeAction = this.handleClose; if (hasChangesApplied) { closeAction = this.handleOpenConfirm; } return ( <FullScreenModal header={this.getHeader()} onClose={closeAction} useGemini={useGemini} open={isOpen} {...Util.omit(props, Object.keys(CreateServiceModal.propTypes))} > {this.getModalContent()} <Confirm closeByBackdropClick={true} header={ <ModalHeading> <Trans render="span">Discard Changes?</Trans> </ModalHeading> } open={this.state.isConfirmOpen} onClose={this.handleCloseConfirmModal} leftButtonText={props.i18n._(t`Cancel`)} leftButtonClassName="button button-primary-link flush-left" leftButtonCallback={this.handleCloseConfirmModal} rightButtonText={props.i18n._(t`Discard`)} rightButtonClassName="button button-danger" rightButtonCallback={this.handleConfirmGoBack} showHeader={true} > <Trans render="p"> Are you sure you want to leave this page? Any data you entered will{" "} be lost. </Trans> </Confirm> </FullScreenModal> ); } } CreateServiceModal.contextTypes = { router: routerShape, }; export default withI18n()(CreateServiceModal);
the_stack
// tslint:disable: no-invalid-template-strings max-func-body-length import * as assert from "assert"; import { getFriendlyExpressionFromJsonString, getFriendlyExpressionFromTleExpression } from "../extension.bundle"; suite("friendly expressions", () => { suite("getFriendlyExpressionFromTleExpression", () => { function createFriendlyExpressionTest( tleExpression: string, // e.g. "'abc'" or "concat('a', 'b')" expected: string | undefined ): void { test(tleExpression, () => { let keepTestNameInClosure = tleExpression; keepTestNameInClosure = keepTestNameInClosure; const actual = getFriendlyExpressionFromTleExpression(tleExpression); assert.deepStrictEqual(actual, expected); }); } suite("Just string literal", () => { createFriendlyExpressionTest("''", ""); createFriendlyExpressionTest("'string'", "string"); createFriendlyExpressionTest("'${a}'", "${a}"); createFriendlyExpressionTest("'variables(\'a\')'", "variables(\'a\')"); }); suite("Just int", () => { createFriendlyExpressionTest("1", '[1]'); }); suite("Expressions with errors - just return original, plus var/par interpolation", () => { createFriendlyExpressionTest("", '[]'); createFriendlyExpressionTest("a", "[a]"); createFriendlyExpressionTest("parameter('a')", `[parameter('a')]`); createFriendlyExpressionTest("parameterss('a')", "[parameterss('a')]"); createFriendlyExpressionTest("(variables('a')+parameters('abc'))", "[(${a}+${abc})]"); createFriendlyExpressionTest("concat(a)", "[concat(a)]"); createFriendlyExpressionTest("concat(a, 1)", "[concat(a, 1)]"); createFriendlyExpressionTest("concat(variables('a'), , 1)", "[concat(${a}, , 1)]"); }); suite("concat", () => { createFriendlyExpressionTest("concat('a')", 'a'); createFriendlyExpressionTest("concat(1)", '[1]'); createFriendlyExpressionTest("concat(1, 2)", '[concat(1, 2)]'); }); suite("just a param or just a var", () => { createFriendlyExpressionTest("parameters('a')", "${a}"); createFriendlyExpressionTest("variables('a')", "${a}"); createFriendlyExpressionTest("PARAMETERS('a')", "${a}"); createFriendlyExpressionTest("VARIABLES('a')", "${a}"); }); suite("If it's not a concat or just a var/param, then return with brackets", () => { createFriendlyExpressionTest("add(1, 2)", "[add(1, 2)]"); createFriendlyExpressionTest("add(1, concat(add(1, 2)))", "[add(1, add(1, 2))]"); }); suite("concat strings", () => { createFriendlyExpressionTest("concat('a', 'b')", 'ab'); createFriendlyExpressionTest("concat(variables('sqlServer'), 'a')", '${sqlServer}a'); createFriendlyExpressionTest("concat(variables('a'),'b',variables('abc'))", '${a}b${abc}'); createFriendlyExpressionTest("concat(variables('sqlServer'), '/', variables('firewallRuleName2'))", '${sqlServer}/${firewallRuleName2}'); }); suite("concat other things", () => { createFriendlyExpressionTest("concat('a', 1)", "[concat('a', 1)]"); createFriendlyExpressionTest("concat(1, 'a')", "[concat(1, 'a')]"); createFriendlyExpressionTest("concat(1, 'a', variables('b'))", "[concat(1, 'a${b}')]"); createFriendlyExpressionTest("concat('a', 'b', 1)", "[concat('ab', 1)]"); createFriendlyExpressionTest("concat('a', 1, 'b', 2)", "[concat('a', 1, 'b', 2)]"); createFriendlyExpressionTest("concat(1, parameters('a'), 'b', 2, 3)", "[concat(1, '${a}b', 2, 3)]"); createFriendlyExpressionTest("concat(1, 2)", "[concat(1, 2)]"); createFriendlyExpressionTest("concat(concat(1, 2), concat(3, 4), 5)", "[concat(concat(1, 2), concat(3, 4), 5)]"); createFriendlyExpressionTest("concat('a', variables('b'))", "a${b}"); createFriendlyExpressionTest("concat(variables('a'), 'b')", "${a}b"); createFriendlyExpressionTest("concat(variables('a'), 'b', 1)", "[concat('${a}b', 1)]"); createFriendlyExpressionTest("concat(variables('a'), 1, 'b')", "[concat(${a}, 1, 'b')]"); createFriendlyExpressionTest("concat(variables('a'), parameters('b'), 'c ')", "${a}${b}c "); createFriendlyExpressionTest("concat(1, 'a')", "[concat(1, 'a')]"); createFriendlyExpressionTest("concat('a', 'b', 1)", "[concat('ab', 1)]"); createFriendlyExpressionTest("concat('a', 1, 'b', 2)", "[concat('a', 1, 'b', 2)]"); }); suite("from nested concat", () => { createFriendlyExpressionTest("concat(concat(variables('a')))", "${a}"); createFriendlyExpressionTest("concat(concat('variables(''a'')'))", 'variables(\'\'a\'\')'); createFriendlyExpressionTest("concat('a', concat('b'), concat('c'))", 'abc'); }); createFriendlyExpressionTest("format('{0}/default/logs', variables('storageAccountName'))", "[format('{0}/default/logs', ${storageAccountName})]"); createFriendlyExpressionTest("concat(parameters('virtualMachineName'),'/', variables('diagnosticsExtensionName'))", "${virtualMachineName}/${diagnosticsExtensionName}"); suite("Shouldn't concat when an expression is an interpolated string with property index", () => { createFriendlyExpressionTest( "concat(parameters('vmProperties').property, 'Another string')", // Should *not* be "${vmProperties}.propertyAnother string" with Deployment tacked on to the expression "[concat(${vmProperties}.property, 'Another string')]" ); createFriendlyExpressionTest( "concat(parameters('vmProperties')[copyIndex()].name,'Deployment')", // Should *not* be "${vmProperties}[copyIndex()].nameDeployment" with Deployment tacked on to the expression "[concat(${vmProperties}[copyIndex()].name, 'Deployment')]" ); }); suite("from child-resources/children-nested.json", () => { createFriendlyExpressionTest("resourceGroup().location", "[resourceGroup().location]"); createFriendlyExpressionTest("uniqueString(resourceGroup().id)", "[uniqueString(resourceGroup().id)]"); }); suite("from 101-sql-logical-server.json", () => { createFriendlyExpressionTest("concat(variables('storageName'), '/Microsoft.Authorization/', variables('uniqueRoleGuid') )", '${storageName}/Microsoft.Authorization/${uniqueRoleGuid}'); createFriendlyExpressionTest("resourceGroup().name", "[resourceGroup().name]"); createFriendlyExpressionTest("tolower(concat('sqlva', variables('uniqueStorage')))", "[tolower('sqlva${uniqueStorage}')]"); }); suite("from copy-in-outputs3.json", () => { createFriendlyExpressionTest("concat(parameters('rgNamePrefix'),'-',parameters('rgEnvList')[copyIndex()])", '${rgNamePrefix}-${rgEnvList}[copyIndex()]'); createFriendlyExpressionTest("concat('nic-', copyIndex())", "[concat('nic-', copyIndex())]"); createFriendlyExpressionTest("array(json('[\"one\",\"two\",\"three\"]'))[copyIndex()]", "[array(json('[\"one\",\"two\",\"three\"]'))[copyIndex()]]"); }); createFriendlyExpressionTest("if(parameters('globalRedundancy'), 'Standard_GRS', 'Standard_LRS')", "[if(${globalRedundancy}, 'Standard_GRS', 'Standard_LRS')]"); createFriendlyExpressionTest("format('{0}/default/logs', variables('storageAccountName'))", "[format('{0}/default/logs', ${storageAccountName})]"); suite("from icons.json", () => { createFriendlyExpressionTest("myFunctions.vmName(parameters('virtualMachineName'),copyindex(1))", "[myFunctions.vmName(${virtualMachineName}, copyindex(1))]"); createFriendlyExpressionTest("myFunctions.diskName(parameters('virtualMachineName'),copyindex(1))", "[myFunctions.diskName(${virtualMachineName}, copyindex(1))]"); createFriendlyExpressionTest("myFunctions.nicName(parameters('virtualMachineName'),copyindex(1))", "[myFunctions.nicName(${virtualMachineName}, copyindex(1))]"); }); suite("from keyvalue-with-param.json", () => { createFriendlyExpressionTest("concat('sql-', uniqueString(resourceGroup().id, 'sql'))", "[concat('sql-', uniqueString(resourceGroup().id, 'sql'))]"); }); createFriendlyExpressionTest("concat(parameters('storagePrefix'), uniqueString(resourceGroup().id))", "[concat(${storagePrefix}, uniqueString(resourceGroup().id))]"); createFriendlyExpressionTest("concat(parameters('storagePrefix'), uniqueString(parameters('secondSubscriptionID'), parameters('secondResourceGroup')))", "[concat(${storagePrefix}, uniqueString(${secondSubscriptionID}, ${secondResourceGroup}))]"); suite("from outofbounds1.json", () => { createFriendlyExpressionTest("parameters('vmNames')[0]", "[${vmNames}[0]]"); createFriendlyExpressionTest("concat(parameters('projectName'),'sqlsrv/',variables('rdsDBName'))", '${projectName}sqlsrv/${rdsDBName}'); }); }); suite("getFriendlyExpressionFromTleExpression", () => { function createFriendlyJsonTest( jsonString: string, // e.g. "abc" or "[concat('a', 'b')]" expected: string | undefined ): void { test(jsonString, () => { let keepTestNameInClosure = jsonString; keepTestNameInClosure = keepTestNameInClosure; const actual = getFriendlyExpressionFromJsonString(jsonString); assert.deepStrictEqual(actual, expected); }); } suite("Plain strings", () => { createFriendlyJsonTest("Microsoft.Storage/storageAccounts/providers/roleAssignments", 'Microsoft.Storage/storageAccounts/providers/roleAssignments'); createFriendlyJsonTest("AllowAllWindowsAzureIps", 'AllowAllWindowsAzureIps'); createFriendlyJsonTest("2019-06-01-preview", '2019-06-01-preview'); createFriendlyJsonTest("[[parameters('subnetName')]", `[[parameters('subnetName')]`); }); suite("expressions", () => { createFriendlyJsonTest("[parameters('a')]", "${a}"); createFriendlyJsonTest("[parameters('vmNames')[0]]", "[${vmNames}[0]]"); }); suite("invalid expressions", () => { createFriendlyJsonTest("[a]", "[a]"); createFriendlyJsonTest("[foo / parameters('vmNames')[0]]", "[foo / ${vmNames}[0]]"); createFriendlyJsonTest("[1 PARAMETERS('a')]", "[1 ${a}]"); createFriendlyJsonTest("[1PARAMETERS('a')]", "[1PARAMETERS('a')]"); createFriendlyJsonTest("[variablesNot('a')]", "[variablesNot('a')]"); }); }); });
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import 'netron/src/view-render.css'; import 'netron/src/view-sidebar.css'; import 'netron/src/view.css'; import 'npm-font-open-sans/open-sans.css'; import { setDebugNodes, setFile, setInputs, setMetadataProps, setModelInputs, setModelOutputs, setNodes, setOutputs, setProperties, setSelectedNode, setShowLeft, setShowRight } from '../../../datastore/actionCreators'; import { ModelProtoSingleton } from '../../../datastore/proto/modelProto'; import IState from '../../../datastore/state'; import './fixed-position-override.css'; import { fileFromPath } from '../../../native/dialog'; import { DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { onOpen } from '../../../native/menu' const browserGlobal = window as any; interface IComponentProperties { // Redux properties file: File, nodes: { [key: string]: any }, setDebugNodes: typeof setDebugNodes, setFile: typeof setFile, setInputs: typeof setInputs, setMetadataProps: typeof setMetadataProps, setModelInputs: typeof setModelInputs, setModelOutputs: typeof setModelOutputs, setNodes: typeof setNodes, setOutputs: typeof setOutputs, setProperties: typeof setProperties, setSelectedNode: typeof setSelectedNode, setShowLeft: typeof setShowLeft, setShowRight: typeof setShowRight, showLeft: boolean, showRight: boolean } interface IComponentState { graph: any, isEdit: boolean, isInit: boolean, isOnnxModel: boolean, metadataProps: { [key: string]: string }, properties: { [key: string]: string }, } class Netron extends React.Component<IComponentProperties, IComponentState> { private proxiesRevoke: Array<() => void> = []; constructor(props: IComponentProperties) { super(props); this.state = { graph: {}, isEdit: true, isInit: true, isOnnxModel: false, metadataProps: {}, properties: {}, } this.props.setShowRight(true); } public componentDidMount() { // Netron must be run after rendering the HTML if (!browserGlobal.host) { const s = document.createElement('script'); s.src = "netron_bundle.js"; s.async = true; s.onload = this.onNetronInitialized; document.body.appendChild(s); } else { this.onNetronInitialized(); } } public componentWillUnmount() { for (const revoke of this.proxiesRevoke) { revoke(); } } public UNSAFE_componentWillReceiveProps(nextProps: IComponentProperties) { if (!browserGlobal.host) { return; } if (nextProps.file && nextProps.file !== this.props.file) { browserGlobal.host._openFile(nextProps.file); } } // public shouldComponentUpdate(nextProps: IComponentProperties, nextState: IComponentState) { // return false; // Netron is a static page and all updates are handled by its JavaScript code // } public render() { const inlineStyle = { color:'lightgray', fontSize:'50px', fontStyle: 'oblique', top: '600px', width: '400px' } return ( // Instead of hardcoding the page, a div with dangerouslySetInnerHTML could be used to include Netron's content <div className='netron-root'> <div id='welcome' className='background' style={{display: 'block'}}> <div className='center logo'> <img className='logo absolute' src='winml_icon.ico' /> <img id='spinner' className='spinner logo absolute' src='spinner.svg' style={{display: 'none'}} /> </div> <button id='open-file-button' className='center' disabled={true}> Open Model...</button> <button id='openFileButton' className='center' style={{top: '200px', width: '100px'}} onClick={onOpen}>Open Model</button> <p className='center' style={inlineStyle}>WinML Dashboard</p> <input type="file" id="openFileButton" style={{display: 'none'}} multiple={false} accept=".onnx, .pb, .meta, .tflite, .keras, .h5, .json, .mlmodel, .caffemodel" /> <div style={{fontWeight: 'normal', color: '#e6e6e6', userSelect: 'none'}}>.</div> <div style={{fontWeight: 600, color: '#e6e6e6', userSelect: 'none'}}>.</div> <div style={{fontWeight: 'bold', color: '#e6e6e6', userSelect: 'none'}}>.</div> </div> <svg id='graph' className='graph' preserveAspectRatio='xMidYMid meet' width='100%' height='100%' /> <div id='toolbar' className='toolbar' style={{position: 'absolute', top: '10px', left: '10px', display: 'none',}}> <button id='model-properties-button' className='xxx' title='Model Properties'/> <DefaultButton id='EditButton' text={'Edit/View'} onClick={this.toggleEditAndView}/> <button id='zoom-in-button' className='icon' title='Zoom In'> <svg viewBox="0 0 100 100" width="24" height="24"> <circle cx="50" cy="50" r="35" strokeWidth="8" stroke="#fff" /> <line x1="50" y1="38" x2="50" y2="62" strokeWidth="8" strokeLinecap="round" stroke="#fff" /> <line x1="38" y1="50" x2="62" y2="50" strokeWidth="8" strokeLinecap="round" stroke="#fff" /> <line x1="78" y1="78" x2="82" y2="82" strokeWidth="12" strokeLinecap="square" stroke="#fff" /> <circle cx="50" cy="50" r="35" strokeWidth="4" /> <line x1="50" y1="38" x2="50" y2="62" strokeWidth="4" strokeLinecap="round" /> <line x1="38" y1="50" x2="62" y2="50" strokeWidth="4" strokeLinecap="round" /> <line x1="78" y1="78" x2="82" y2="82" strokeWidth="8" strokeLinecap="square" /> </svg> </button> <button id='zoom-out-button' className='icon' title='Zoom Out'> <svg viewBox="0 0 100 100" width="24" height="24"> <circle cx="50" cy="50" r="35" strokeWidth="8" stroke="#fff" /> <line x1="38" y1="50" x2="62" y2="50" strokeWidth="8" strokeLinecap="round" stroke="#fff" /> <line x1="78" y1="78" x2="82" y2="82" strokeWidth="12" strokeLinecap="square" stroke="#fff" /> <circle cx="50" cy="50" r="35" strokeWidth="4" /> <line x1="38" y1="50" x2="62" y2="50" strokeWidth="4" strokeLinecap="round" /> <line x1="78" y1="78" x2="82" y2="82" strokeWidth="8" strokeLinecap="square" /> </svg> </button> </div> <div id='sidebar' className='sidebar'> <h1 id='sidebar-title' className='sidebar-title' /> <a href='javascript:void(0)' id='sidebar-closebutton' className='sidebar-closebutton'>&times;</a> <div id='sidebar-content' className='sidebar-content' /> </div> </div> ); } private toggleEditAndView = () => { if(!this.state.isOnnxModel) { const convertDialogOptions = { message: 'Only ONNX model is editable. Convert it first.' } require('electron').remote.dialog.showMessageBox(require('electron').remote.getCurrentWindow(), convertDialogOptions) return; } if(this.state.isEdit) { this.setState({isEdit: false}, () => {document.getElementById('model-properties-button')!.click()}) this.props.setShowLeft(false) this.props.setShowRight(false) } else { browserGlobal.view._sidebar.close(); this.setState({isEdit: true}) this.props.setShowLeft(true) this.props.setShowRight(true) } } private propsToObject(props: any) { return props.reduce((acc: { [key: string]: string }, x: any) => { // metadataProps uses key, while model.properties uses name acc[x.key || x.name] = x.value; return acc; }, {}); } private valueListToObject(values: any) { return values.reduce((acc: { [key: string]: any }, x: any) => { const {name, ...props} = x; acc[name] = props; return acc; }, {}); } private onNetronInitialized = () => { // Open the ONNX file when open with this APP. if(this.state.isInit){ const supportedFileExts = ['onnx', 'pb', 'meta', 'tflite', 'keras', 'h5', 'json', 'mlmodel', 'caffemodel'] if(require('electron').remote.process.argv.length >= 2) { const filePath = require('electron').remote.process.argv[1]; const fileExt = filePath.split('.').pop() if(supportedFileExts.indexOf(fileExt) >= 0) { this.props.setFile(fileFromPath(filePath)); } } this.setState({isInit: false}) } // Reset document overflow property document.documentElement!.style.overflow = 'initial'; this.installProxies(); } private installProxies = () => { // Install proxy on browserGlobal.view.loadBuffer and update the data store const loadBufferHandler = { apply: (target: any, thisArg: any, args: any) => { const [buffer, identifier, callback] = args; // Patch the callback to update our data store first return target.call(thisArg, buffer, identifier, (err: Error, model: any) => { if (!err) { this.updateDataStore(model); } return callback(err, model); }); }, }; const loadBufferProxy = Proxy.revocable(browserGlobal.view.loadBuffer, loadBufferHandler); browserGlobal.view.loadBuffer = loadBufferProxy.proxy; this.proxiesRevoke.push(loadBufferProxy.revoke); const panelOpenHandler = { apply: (target: any, thisArg: any, args: any) => { if (this.props.nodes) { const title = args[1]; if (title === 'Model Properties') { this.props.setSelectedNode(title); if(this.state.isEdit) { return; } } else { this.props.setSelectedNode(undefined); } } return target.apply(thisArg, args); }, }; const panelOpenProxy = Proxy.revocable(browserGlobal.view._sidebar.open, panelOpenHandler); browserGlobal.view._sidebar.open = panelOpenProxy.proxy; this.proxiesRevoke.push(panelOpenProxy.revoke); const panelCloseHandler = { apply: (target: any, thisArg: any, args: any) => { this.props.setSelectedNode(undefined); return target.apply(thisArg, args); }, }; const panelCloseProxy = Proxy.revocable(browserGlobal.view._sidebar.close, panelCloseHandler); browserGlobal.view._sidebar.close = panelCloseProxy.proxy; this.proxiesRevoke.push(panelCloseProxy.revoke); const showNodePropertiesHandler = { apply: (target: any, thisArg: any, args: any) => { if(this.state.isEdit) { const node = args[0]; this.props.setSelectedNode(node.graph.nodes.indexOf(node)); return; } return target.apply(thisArg, args); } } const showNodePropertiesProxy = Proxy.revocable(browserGlobal.view.showNodeProperties, showNodePropertiesHandler); browserGlobal.view.showNodeProperties = showNodePropertiesProxy.proxy; this.proxiesRevoke.push(showNodePropertiesProxy.revoke); } private getModelProperties(modelProto: any) { const opsetImport = (modelProto.opsetImport as Array<{domain: string, version: number}>) .reduce((acc, x) => { const opset = `opsetImport.${x.domain || 'ai.onnx'}`; return { ...acc, [opset]: x.version, }; }, {}); const properties = { ...opsetImport, docString: modelProto.docString, domain: modelProto.domain, irVersion: modelProto.irVersion, modelVersion: modelProto.modelVersion, producerName: modelProto.producerName, producerVersion: modelProto.producerVersion, } Object.entries(properties).forEach(([key, value]) => value || delete properties[key]); // filter empty properties return properties; } private updateDataStore = (model: any) => { const proto = model._model; ModelProtoSingleton.proto = null; // FIXME What to do when model has multiple graphs? const graph = model.graphs[0]; if (graph.constructor.name === 'OnnxGraph') { const getNames = (list: any[]): string[] => list.map((x: any) => x.name); const inputs = getNames(graph.inputs); const outputs = getNames(graph.outputs); this.props.setModelInputs(inputs); this.props.setModelOutputs(outputs); this.props.setInputs(this.valueListToObject(proto.graph.input)); this.props.setOutputs(this.valueListToObject(proto.graph.output)); this.props.setNodes(proto.graph.node.filter((x: any) => x.opType !== 'Constant')); this.props.setMetadataProps(this.propsToObject(proto.metadataProps)); this.props.setProperties(this.getModelProperties(proto)); this.props.setShowLeft(true); this.props.setShowRight(true); this.setState({isOnnxModel: true}); this.setState({isEdit: true}); } else { this.props.setShowLeft(false); this.props.setShowRight(false); this.props.setModelInputs(undefined); this.props.setModelOutputs(undefined); this.props.setNodes(undefined); this.props.setMetadataProps({}); this.props.setProperties({}); this.setState({isOnnxModel: false}); this.setState({isEdit: false}); } this.props.setSelectedNode(undefined); this.props.setDebugNodes({}); ModelProtoSingleton.proto = proto; }; } const mapStateToProps = (state: IState) => ({ file: state.file, nodes: state.nodes, showLeft: state.showLeft, showRight: state.showRight, }); const mapDispatchToProps = { setDebugNodes, setFile, setInputs, setMetadataProps, setModelInputs, setModelOutputs, setNodes, setOutputs, setProperties, setSelectedNode, setShowLeft, setShowRight } export default connect(mapStateToProps, mapDispatchToProps)(Netron);
the_stack
import { Tzip16ContractAbstraction } from '../src/tzip16-contract-abstraction'; import { BigMapMetadataNotFound, UriNotFound } from '../src/tzip16-errors'; describe('Tzip16 contract abstraction test', () => { let mockMetadataProvider: { provideMetadata: jest.Mock<any, any>; }; let mockContractAbstraction: any = {}; let mockSchema: { FindFirstInTopLevelPair: jest.Mock<any, any>; }; let mockContext: any = {}; let mockRpcContractProvider: { getBigMapKeyByID: jest.Mock<any, any>; }; beforeEach(() => { mockMetadataProvider = { provideMetadata: jest.fn() }; mockSchema = { FindFirstInTopLevelPair: jest.fn() }; mockRpcContractProvider = { getBigMapKeyByID: jest.fn() }; mockMetadataProvider.provideMetadata.mockResolvedValue({ uri: 'https://test', metadata: { name: 'Taquito test' } }); mockContext['metadataProvider'] = mockMetadataProvider; mockContext['contract'] = mockRpcContractProvider; mockContractAbstraction['schema'] = mockSchema; mockContractAbstraction['script'] = { script: { code: [], storage: { prim: 'Pair', args: [ { int: '20350' }, [] ] } } }; }); it('Should get the metadata', async (done) => { mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' }); mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue('cafe'); const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); const metadata = await tzip16Abs.getMetadata(); expect(metadata.metadata).toEqual({ name: 'Taquito test' }); done(); }); it('Should fail with BigMapMetadataNotFound', async (done) => { mockSchema.FindFirstInTopLevelPair.mockReturnValue(undefined); const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); try { await tzip16Abs.getMetadata(); } catch (e) { expect(e).toBeInstanceOf(BigMapMetadataNotFound); } done(); }); it('Should fail with UriNotFound', async (done) => { mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' }); mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue(undefined); const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); try { await tzip16Abs.getMetadata(); } catch (e) { expect(e).toBeInstanceOf(UriNotFound); } done(); }); it('Should properly add a valid view to the _metadataViewsObject property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); // Act as we already fetched metadata; it contains one view tzip16Abs['_metadataEnvelope'] = { uri: '', metadata: { views: [ { name: 'multiply-the-nat-in-storage', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [ { prim: 'DUP', args: [], annots: [] }, { prim: 'CDR', args: [], annots: [] }, { prim: 'CAR', args: [], annots: [] }, { prim: 'SWAP', args: [], annots: [] }, { prim: 'CAR', args: [], annots: [] }, { prim: 'MUL', args: [], annots: [] } ] } } ] } ] } }; // Return an object where the key is the view name and the value is a function which return a View instance const metadataView = await tzip16Abs.metadataViews(); expect(Object.keys(metadataView)[0]).toEqual('multiply-the-nat-in-storage'); expect(typeof (Object.values(metadataView)[0])).toBe('function'); expect(tzip16Abs['_metadataViewsObject']).toEqual(metadataView); done(); }); it('The _metadataViewsObject property should be empty when there is no view in metadata', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); // Act as we already fetched metadata; it contains no view tzip16Abs['_metadataEnvelope'] = { uri: '', metadata: { views: [] } }; // Return an empty object const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); expect(tzip16Abs['_metadataViewsObject']).toEqual(metadataView); done(); }); it('The _metadataViewsObject property should be empty when there is no view property in metadata', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); // Act as we already fetched metadata; it contains no view tzip16Abs['_metadataEnvelope'] = { uri: '', metadata: {} }; // Return an empty object const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should ignore view having an unsupported type', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'unknownView', implementations: [ { unknownViewType: { returnType: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] },] } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); expect(tzip16Abs['_metadataViewsObject']).toEqual(metadataView); done(); }); it('Should ignore the unsupported type of view and add the supported one to the _metadataViewsObject property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); // Act as we already fetched metadata; it contains a view having an unsupported type and a valid view (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'unknownView', implementations: [ { unknownViewType: { returnType: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] },] } } ] }, { name: 'multiply-the-nat-in-storage', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [ { prim: 'DUP', args: [], annots: [] }, { prim: 'CDR', args: [], annots: [] }, { prim: 'CAR', args: [], annots: [] }, { prim: 'SWAP', args: [], annots: [] }, { prim: 'CAR', args: [], annots: [] }, { prim: 'MUL', args: [], annots: [] } ] } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(Object.keys(metadataView)[0]).toEqual('multiply-the-nat-in-storage'); expect(Object.keys(metadataView)[1]).toBeUndefined(); expect(tzip16Abs['_metadataViewsObject']).toEqual(metadataView); done(); }); it('Should ignore view having no code property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'invalid-view-no-code', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should ignore view having no returnType property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'invalid-view-no-return-type', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] }] } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should ignore view having no implementation', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'invalid-view', implementations: [] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should ignore view having no implementation property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { name: 'invalid-view' } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should ignore view having no name property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); (tzip16Abs['_metadataEnvelope'] as any) = { uri: '', metadata: { views: [ { implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] }] } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(metadataView).toEqual({}); done(); }); it('Should properly add a valid view to the _metadataViewsObject property', async (done) => { const tzip16Abs = new Tzip16ContractAbstraction(mockContractAbstraction as any, mockContext); // Act as we already fetched metadata; it contains one view tzip16Abs['_metadataEnvelope'] = { uri: '', metadata: { views: [ { name: 'multiply-the-nat-in-storage', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] }] } } ] }, { name: 'multiply-the-nat-in-storage', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [{ prim: 'DUP', args: [], annots: [] }] } } ] }, { name: 'multiply-the-nat-in-storage', implementations: [ { michelsonStorageView: { parameter: { prim: 'nat', args: [], annots: [] }, returnType: { prim: 'nat', args: [], annots: [] }, code: [ { prim: 'DUP', args: [], annots: [] } ] } } ] } ] } }; const metadataView = await tzip16Abs.metadataViews(); expect(Object.keys(metadataView)[0]).toEqual('multiply-the-nat-in-storage'); expect(Object.keys(metadataView)[1]).toEqual('multiply-the-nat-in-storage1'); expect(Object.keys(metadataView)[2]).toEqual('multiply-the-nat-in-storage2'); expect(Object.keys(metadataView)[3]).toBeUndefined(); done(); }); });
the_stack
import React, {CSSProperties} from "react"; import * as DragManager from "./DragManager"; import {GestureState} from "./GestureManager"; export type AbstractPointerEvent = MouseEvent | TouchEvent; interface DragDropDivProps extends React.HTMLAttributes<HTMLDivElement> { getRef?: (ref: HTMLDivElement) => void; onDragStartT?: DragManager.DragHandler; onDragMoveT?: DragManager.DragHandler; onDragEndT?: DragManager.DragHandler; onDragOverT?: DragManager.DragHandler; onDragLeaveT?: DragManager.DragHandler; onDropT?: DragManager.DragHandler; /** * by default onDragStartT will be called on first drag move * but if directDragT is true, onDragStartT will be called as soon as mouse is down */ directDragT?: boolean; useRightButtonDragT?: boolean; onGestureStartT?: (state: GestureState) => boolean; onGestureMoveT?: (state: GestureState) => void; onGestureEndT?: () => void; gestureSensitivity?: number; } export class DragDropDiv extends React.PureComponent<DragDropDivProps, any> { element: HTMLElement; ownerDocument: Document; _getRef = (r: HTMLDivElement) => { if (r === this.element) { return; } let {getRef, onDragOverT} = this.props; if (this.element && onDragOverT) { DragManager.removeHandlers(this.element); } this.element = r; if (r) { this.ownerDocument = r.ownerDocument; } if (getRef) { getRef(r); } if (r && onDragOverT) { DragManager.addHandlers(r, this.props); } }; dragType: DragManager.DragType = null; baseX: number; baseY: number; scaleX: number; scaleY: number; waitingMove = false; listening = false; gesturing = false; baseX2: number; baseY2: number; baseDis: number; baseAng: number; onPointerDown = (e: React.MouseEvent | React.TouchEvent) => { let nativeTarget = e.nativeEvent.target as HTMLElement; if (nativeTarget instanceof HTMLInputElement || nativeTarget instanceof HTMLTextAreaElement || nativeTarget.classList.contains('drag-ignore')) { // ignore drag from input element return; } let {onDragStartT, onGestureStartT, onGestureMoveT, useRightButtonDragT} = this.props; let event = e.nativeEvent; this.cancel(); if (event.type === 'touchstart') { // check single or double fingure touch if ((event as TouchEvent).touches.length === 1) { if (onDragStartT) { this.onDragStart(event); } } else if ((event as TouchEvent).touches.length === 2) { if (onGestureStartT && onGestureMoveT) { this.onGestureStart(event as TouchEvent); } } } else if (onDragStartT) { if ((event as MouseEvent).button === 2 && !useRightButtonDragT) { return; } this.onDragStart(event); } }; onDragStart(event: MouseEvent | TouchEvent) { if (DragManager.isDragging()) { // same pointer event shouldn't trigger 2 drag start return; } let state = new DragManager.DragState(event, this, true); this.baseX = state.pageX; this.baseY = state.pageY; let baseElement = this.element.parentElement; let rect = baseElement.getBoundingClientRect(); this.scaleX = baseElement.offsetWidth / Math.round(rect.width); this.scaleY = baseElement.offsetHeight / Math.round(rect.height); this.addDragListeners(event); if (this.props.directDragT) { this.executeFirstMove(state); } } addDragListeners(event: MouseEvent | TouchEvent) { let {onDragStartT} = this.props; if (event.type === 'touchstart') { this.ownerDocument.addEventListener('touchmove', this.onTouchMove); this.ownerDocument.addEventListener('touchend', this.onDragEnd); this.dragType = 'touch'; } else { this.ownerDocument.addEventListener('mousemove', this.onMouseMove); this.ownerDocument.addEventListener('mouseup', this.onDragEnd); if ((event as MouseEvent).button === 2) { this.dragType = 'right'; } else { this.dragType = 'left'; } } this.waitingMove = true; this.listening = true; } // return true for a valid move checkFirstMove(e: AbstractPointerEvent) { let state = new DragManager.DragState(e, this, true); if (!state.moved()) { // not a move return false; } return this.executeFirstMove(state); } executeFirstMove(state: DragManager.DragState): boolean { let {onDragStartT} = this.props; this.waitingMove = false; onDragStartT(state); if (!DragManager.isDragging()) { this.onDragEnd(); return false; } state._onMove(); this.ownerDocument.addEventListener('keydown', this.onKeyDown); return true; } onMouseMove = (e: MouseEvent) => { let {onDragMoveT} = this.props; if (this.waitingMove) { if (DragManager.isDragging()) { this.onDragEnd(); return; } if (!this.checkFirstMove(e)) { return; } } else { let state = new DragManager.DragState(e, this); state._onMove(); if (onDragMoveT) { onDragMoveT(state); } } e.preventDefault(); }; onTouchMove = (e: TouchEvent) => { let {onDragMoveT} = this.props; if (this.waitingMove) { if (DragManager.isDragging()) { this.onDragEnd(); return; } if (!this.checkFirstMove(e)) { return; } } else if (e.touches.length !== 1) { this.onDragEnd(); } else { let state = new DragManager.DragState(e, this); state._onMove(); if (onDragMoveT) { onDragMoveT(state); } } e.preventDefault(); }; onDragEnd = (e?: TouchEvent | MouseEvent) => { let {onDragEndT} = this.props; let state = new DragManager.DragState(e, this); this.removeListeners(); if (!this.waitingMove) { // e=null means drag is canceled state._onDragEnd(e == null); if (onDragEndT) { onDragEndT(state); } } this.cleanupDrag(state); }; addGestureListeners(event: TouchEvent) { this.ownerDocument.addEventListener('touchmove', this.onGestureMove); this.ownerDocument.addEventListener('touchend', this.onGestureEnd); this.ownerDocument.addEventListener('keydown', this.onKeyDown); this.gesturing = true; this.waitingMove = true; } onGestureStart(event: TouchEvent) { if (!DragManager.isDragging()) { // same pointer event shouldn't trigger 2 drag start return; } let {onGestureStartT} = this.props; this.baseX = event.touches[0].pageX; this.baseY = event.touches[0].pageY; this.baseX2 = event.touches[1].pageX; this.baseY2 = event.touches[1].pageY; let baseElement = this.element.parentElement; let rect = baseElement.getBoundingClientRect(); this.scaleX = baseElement.offsetWidth / Math.round(rect.width); this.scaleY = baseElement.offsetHeight / Math.round(rect.height); this.baseDis = Math.sqrt(Math.pow(this.baseX - this.baseX2, 2) + Math.pow(this.baseY - this.baseY2, 2)); this.baseAng = Math.atan2(this.baseY2 - this.baseY, this.baseX2 - this.baseX); let state = new GestureState(event, this, true); if (onGestureStartT(state)) { this.addGestureListeners(event); event.preventDefault(); } } onGestureMove = (e: TouchEvent) => { let {onGestureMoveT, gestureSensitivity} = this.props; let state = new GestureState(e, this); if (this.waitingMove) { if (!(gestureSensitivity > 0)) { gestureSensitivity = 10; // default sensitivity } if (state.moved() > gestureSensitivity) { this.waitingMove = false; } else { return; } } if (onGestureMoveT) { onGestureMoveT(state); } }; onGestureEnd = (e?: TouchEvent) => { let {onGestureEndT} = this.props; let state = new DragManager.DragState(e, this); this.removeListeners(); if (onGestureEndT) { onGestureEndT(); } }; onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') { this.cancel(); } }; cancel() { if (this.listening) { this.onDragEnd(); } if (this.gesturing) { this.onGestureEnd(); } } removeListeners() { if (this.gesturing) { this.ownerDocument.removeEventListener('touchmove', this.onGestureMove); this.ownerDocument.removeEventListener('touchend', this.onGestureEnd); } else if (this.listening) { if (this.dragType === 'touch') { this.ownerDocument.removeEventListener('touchmove', this.onTouchMove); this.ownerDocument.removeEventListener('touchend', this.onDragEnd); } else { this.ownerDocument.removeEventListener('mousemove', this.onMouseMove); this.ownerDocument.removeEventListener('mouseup', this.onDragEnd); } } this.ownerDocument.removeEventListener('keydown', this.onKeyDown); this.listening = false; this.gesturing = false; } cleanupDrag(state: DragManager.DragState) { this.dragType = null; this.waitingMove = false; } render(): React.ReactNode { let { getRef, children, className, directDragT, onDragStartT, onDragMoveT, onDragEndT, onDragOverT, onDragLeaveT, onDropT, onGestureStartT, onGestureMoveT, onGestureEndT, useRightButtonDragT, ...others } = this.props; let onTouchDown = this.onPointerDown; let onMouseDown = this.onPointerDown; if (!onDragStartT) { onMouseDown = null; if (!onGestureStartT) { onTouchDown = null; } } if (onDragStartT || onGestureStartT) { if (className) { className = `${className} drag-initiator`; } else { className = 'drag-initiator'; } } return ( <div ref={this._getRef} className={className} {...others} onMouseDown={onMouseDown} onTouchStart={onTouchDown}> {children} </div> ); } componentDidUpdate(prevProps: DragDropDivProps) { let {onDragOverT, onDragEndT, onDragLeaveT} = this.props; if (this.element && ( prevProps.onDragOverT !== onDragOverT || prevProps.onDragLeaveT !== onDragLeaveT || prevProps.onDragEndT !== onDragEndT ) ) { if (onDragOverT) { DragManager.addHandlers(this.element, this.props); } else { DragManager.removeHandlers(this.element); } } } componentWillUnmount(): void { let {onDragOverT} = this.props; if (this.element && onDragOverT) { DragManager.removeHandlers(this.element); } this.cancel(); } }
the_stack
import assert = require('assert'); import asyncutil = require('./base/asyncutil'); import collectionutil = require('./base/collectionutil'); import dateutil = require('./base/dateutil'); import err_util = require('./base/err_util'); import event_stream = require('./base/event_stream'); import item_merge = require('./item_merge'); import item_store = require('./item_store'); import key_agent = require('./key_agent'); import logging = require('./base/logging'); import { defer, Deferred } from './base/promise_util'; export class SyncError extends err_util.BaseError { constructor(message: string, sourceErr?: Error) { super(message, sourceErr); } } let syncLog = new logging.BasicLogger('sync'); syncLog.level = logging.Level.Warn; const REMOTE_STORE = 'cloud'; /** Returns true if two date/times from Item.updatedAt should * be considered equal for the purpose of sync. * * This function accounts for the fact that the resolution * of timestamps varies depending on the store - eg. * the Agile Keychain format uses timestamps with only * second-level resolution whereas local_store.Store supports * millisecond-resolution timestamps. */ export function itemUpdateTimesEqual(a: Date, b: Date) { return ( dateutil.unixTimestampFromDate(a) == dateutil.unixTimestampFromDate(b) ); } export enum SyncState { /** Sync is not currently in progress */ Idle, /** Sync is enumerating changed items */ ListingItems, /** Sync is fetching and updating changed items */ SyncingItems, } export interface SyncProgress { state: SyncState; /** Count of items that have been synced. */ updated: number; /** Count of items that failed to sync. */ failed: number; /** Total number of changed items to sync. */ total: number; /** Number of items actively being synced. */ active: number; } enum ItemSyncState { Unchanged, Updated, Deleted, } interface SyncItem { localItem: item_store.ItemState; localState: ItemSyncState; remoteItem: item_store.ItemState; remoteState: ItemSyncState; } /** Interface for syncing encryption keys and items between * a cloud-based store and a local cache. */ export interface Syncer { onProgress: event_stream.EventStream<SyncProgress>; /** Sync encryption keys from the remote store to the local one. * This does not require the remote store to be unlocked. */ syncKeys(): Promise<void>; /** Sync items between the local and remote stores. * Returns a promise which is resolved when the current sync completes. * * Syncing items requires both local and remote stores * to be unlocked first. */ syncItems(): Promise<SyncProgress>; } /** Syncer implementation which syncs changes between an item_store.Store * representing a remote store and a local store. */ export class CloudStoreSyncer implements Syncer { private localStore: item_store.SyncableStore; private cloudStore: item_store.Store; // queue of items left to sync private syncQueue: SyncItem[]; // progress of the current sync private syncProgress: SyncProgress; // promise for the result of the // current sync task or null if no sync // is in progress private currentSync: Deferred<SyncProgress>; onProgress: event_stream.EventStream<SyncProgress>; constructor( localStore: item_store.SyncableStore, cloudStore: item_store.Store ) { this.localStore = localStore; this.cloudStore = cloudStore; this.onProgress = new event_stream.EventStream<SyncProgress>(); this.syncQueue = []; } syncKeys(): Promise<void> { let keys = this.cloudStore.listKeys(); // sync the password hint on a best-effort basis. // If no hint is available, display a placeholder instead. let hint = this.cloudStore .passwordHint() .then(hint => { return hint; }) .catch(err => { return ''; }); return asyncutil.all2([keys, hint]).then(keysAndHint => { var keys = <key_agent.Key[]>keysAndHint[0]; var hint = <string>keysAndHint[1]; return this.localStore.saveKeys(keys, hint); }); } syncItems(): Promise<SyncProgress> { if (this.currentSync) { // if a sync is already in progress, complete the current sync first. // This should queue up a new sync to complete once the current one finishes. return this.currentSync.promise; } syncLog.info('Starting sync'); var result = defer<SyncProgress>(); this.currentSync = result; this.currentSync.promise .then(() => { syncLog.info('Sync completed'); this.currentSync = null; }) .catch(err => { syncLog.error('Sync failed', err.toString()); this.currentSync = null; }); this.syncProgress = { state: SyncState.ListingItems, active: 0, updated: 0, failed: 0, total: 0, }; this.onProgress.listen(() => { if (this.syncProgress.state == SyncState.SyncingItems) { var processed = this.syncProgress.updated + this.syncProgress.failed; syncLog.info({ updated: this.syncProgress.updated, failed: this.syncProgress.failed, total: this.syncProgress.total, }); if (processed == this.syncProgress.total) { this.syncProgress.state = SyncState.Idle; this.notifyProgress(); result.resolve(this.syncProgress); } else { this.syncNextBatch(); } } }, 'sync-progress'); this.notifyProgress(); let localItems = this.localStore.listItemStates(); let remoteItems = this.cloudStore.listItemStates(); let lastSyncRevisions = this.localStore.lastSyncRevisions(REMOTE_STORE); asyncutil .all3([localItems, remoteItems, lastSyncRevisions]) .then(itemLists => { let localItems = <item_store.ItemState[]>itemLists[0]; let remoteItems = <item_store.ItemState[]>itemLists[1]; let lastSyncedRevisions = <Map< string, item_store.RevisionPair >>itemLists[2]; syncLog.info( '%d items in local store, %d in remote store', localItems.length, remoteItems.length ); let allItems: { [index: string]: boolean } = {}; let localItemMap = collectionutil.listToMap( localItems, item => { allItems[item.uuid] = true; return item.uuid; } ); let remoteItemMap = collectionutil.listToMap( remoteItems, item => { allItems[item.uuid] = true; return item.uuid; } ); Object.keys(allItems).forEach(uuid => { let remoteItem = remoteItemMap.get(uuid); let localItem = localItemMap.get(uuid); let lastSyncedRevision = lastSyncedRevisions.get(uuid); this.enqueueItemForSyncIfChanged( localItem, remoteItem, lastSyncedRevision ); }); syncLog.info('found %d items to sync', this.syncQueue.length); this.syncProgress.state = SyncState.SyncingItems; this.notifyProgress(); }) .catch(err => { syncLog.error( 'Failed to list items in local or remote stores', err.stack ); result.reject(err); this.syncProgress.state = SyncState.Idle; this.notifyProgress(); }); this.syncNextBatch(); return this.currentSync.promise; } private enqueueItemForSyncIfChanged( localItem: item_store.ItemState, remoteItem: item_store.ItemState, lastSyncedRevision?: item_store.RevisionPair ) { let uuid = localItem ? localItem.uuid : remoteItem.uuid; let remoteState = ItemSyncState.Unchanged; let localState = ItemSyncState.Unchanged; if (localItem) { if (localItem.deleted) { if (lastSyncedRevision) { localState = ItemSyncState.Deleted; syncLog.info('item %s deleted locally', uuid); } } else if (lastSyncedRevision) { if (localItem.revision !== lastSyncedRevision.local) { localState = ItemSyncState.Updated; syncLog.info('item %s updated locally', uuid); } } else { localState = ItemSyncState.Updated; syncLog.info('item %s added locally'); } } if (remoteItem) { if (remoteItem.deleted) { if (lastSyncedRevision) { remoteState = ItemSyncState.Deleted; syncLog.info('item %s deleted in cloud', uuid); } } else if (lastSyncedRevision) { if (remoteItem.revision !== lastSyncedRevision.external) { remoteState = ItemSyncState.Updated; syncLog.info('item %s updated in cloud', uuid); } } else { remoteState = ItemSyncState.Updated; syncLog.info('item %s added in cloud', uuid); } } if ( localState !== ItemSyncState.Unchanged || remoteState !== ItemSyncState.Unchanged ) { this.syncQueue.push({ localItem: localItem, localState: localState, remoteItem: remoteItem, remoteState: remoteState, }); ++this.syncProgress.total; } } // sync the next batch of items. This adds items // to the queue to sync until the limit of concurrent items // being updated at once reaches a limit. // // When syncing with a store using the Agile Keychain format // and Dropbox, there is one file to fetch per-item so this // batching nicely maps to network requests that we'll need // to make. If we switch to the Cloud Keychain format (or another // format) in future which stores multiple items per file, // the concept of syncing batches of items may no longer // be needed or may need to work differently. private syncNextBatch() { var SYNC_MAX_ACTIVE_ITEMS = 10; while ( this.syncProgress.active < SYNC_MAX_ACTIVE_ITEMS && this.syncQueue.length > 0 ) { var next = this.syncQueue.shift(); this.syncItem(next); } } private notifyProgress() { this.onProgress.publish(this.syncProgress); } // create a tombstone item to represent an item // which has been deleted locally or in the cloud during sync private createTombstone( store: item_store.Store, uuid: string ): item_store.ItemAndContent { let item = new item_store.Item(store, uuid); item.typeName = item_store.ItemTypes.TOMBSTONE; item.updatedAt = new Date(); return { item: item, content: null, }; } private syncItem(item: SyncItem) { ++this.syncProgress.active; var itemDone = (err?: Error) => { --this.syncProgress.active; if (err) { ++this.syncProgress.failed; } else { ++this.syncProgress.updated; } this.notifyProgress(); }; // fetch content for local and remote items and the last-synced // version of the item in order to perform a 3-way merge let uuid = item.localItem ? item.localItem.uuid : item.remoteItem.uuid; syncLog.info(`Beginning sync for item ${uuid}`); let localItemContent: Promise<item_store.ItemAndContent>; let remoteItemContent: Promise<item_store.ItemAndContent>; if (item.localItem) { if (item.localItem.deleted) { localItemContent = Promise.resolve( this.createTombstone(this.localStore, uuid) ); } else { localItemContent = this.localStore.loadItem(uuid); } } if (item.remoteItem) { if (item.remoteItem.deleted) { remoteItemContent = Promise.resolve( this.createTombstone(this.cloudStore, uuid) ); } else { remoteItemContent = this.cloudStore.loadItem(uuid); } } syncLog.info(`Fetching local/remote items for ${uuid}`); let contents = Promise.all([localItemContent, remoteItemContent]); contents .then( ( contents: [ item_store.ItemAndContent, item_store.ItemAndContent ] ) => { syncLog.info(`Merging item changes for ${uuid}`); // merge changes between local/remote store items and update the // last-synced revision let localItem = contents[0]; let remoteItem = contents[1]; this.mergeAndSyncItem( localItem, item.localState, remoteItem, item.remoteState ) .then(() => { syncLog.info('Synced changes for item %s', uuid); itemDone(); }) .catch((err: Error) => { syncLog.error('Syncing item %s failed:', uuid, err); var itemErr = new SyncError( `Failed to save updates for item ${uuid}`, err ); itemDone(itemErr); }); } ) .catch(err => { syncLog.error('Retrieving updates for %s failed:', uuid, err); var itemErr = new SyncError( `Failed to retrieve updated item ${uuid}`, err ); itemDone(itemErr); }); } // returns the item and content for the last-synced version of an item, // or null if the item has not been synced before private getLastSyncedItemRevision( uuid: string ): Promise<item_store.ItemAndContent> { return this.localStore .getLastSyncedRevision(uuid, REMOTE_STORE) .then(revision => { if (revision) { return this.localStore.loadItem(uuid, revision.local); } else { return null; } }); } // given an item from the local and remote stores, one or both of which have changed // since the last sync, and the last-synced version of the item, merge // changes and save the result to the local/remote store as necessary // // When the save completes, the last-synced revision is updated in // the local store private mergeAndSyncItem( localItem: item_store.ItemAndContent, localState: ItemSyncState, remoteItem: item_store.ItemAndContent, remoteState: ItemSyncState ) { assert( localItem || remoteItem, 'neither local nor remote item specified' ); let remoteRevision: string; if (remoteItem && !remoteItem.item.isTombstone()) { remoteRevision = remoteItem.item.revision; assert(remoteRevision, 'item does not have a remote revision'); } let updatedStoreItem: item_store.Item; let saved: Promise<void>; // revision of the item which was saved let newLocalRevision: string; if ( localState === ItemSyncState.Updated && remoteState === ItemSyncState.Updated ) { // item updated both locally and in the cloud, merge changes assert(localItem); assert(remoteItem); syncLog.info( 'merging local and remote changes for item %s', localItem.item.uuid ); let mergedStoreItem: item_store.ItemAndContent; saved = this.getLastSyncedItemRevision(localItem.item.uuid) .then(lastSynced => { mergedStoreItem = item_merge.merge( localItem, remoteItem, lastSynced ); mergedStoreItem.item.updateTimestamps(); let mergedRemoteItem = item_store.cloneItem( mergedStoreItem, mergedStoreItem.item.uuid ); return Promise.all([ this.localStore.saveItem( mergedStoreItem.item, item_store.ChangeSource.Sync ), this.cloudStore.saveItem( mergedRemoteItem.item, item_store.ChangeSource.Sync ), ]); }) .then(() => { assert( mergedStoreItem.item.revision, 'merged local item does not have a revision' ); assert.notEqual( mergedStoreItem.item.revision, localItem.item.revision ); newLocalRevision = mergedStoreItem.item.revision; updatedStoreItem = mergedStoreItem.item; }); } else if (localState !== ItemSyncState.Unchanged) { // item added/updated/removed locally syncLog.info( 'syncing item %s from local -> cloud', localItem.item.uuid ); let clonedItem = item_store.cloneItem( localItem, localItem.item.uuid ).item; newLocalRevision = localItem.item.revision; updatedStoreItem = localItem.item; saved = this.cloudStore .saveItem(clonedItem, item_store.ChangeSource.Sync) .then(() => { remoteRevision = clonedItem.revision; }); } else if (remoteState !== ItemSyncState.Unchanged) { // item added/updated/removed in cloud syncLog.info( 'syncing item %s from cloud -> local', remoteItem.item.uuid ); let clonedItem = item_store.cloneItem( remoteItem, remoteItem.item.uuid ).item; saved = this.localStore .saveItem(clonedItem, item_store.ChangeSource.Sync) .then(() => { assert( clonedItem.revision, 'item cloned from remote store does not have a revision' ); newLocalRevision = clonedItem.revision; updatedStoreItem = clonedItem; }); } return saved.then(() => { syncLog.info( 'setting last synced revisions for %s to %s, %s', updatedStoreItem.uuid, newLocalRevision, remoteRevision ); let revisions: item_store.RevisionPair; if (!updatedStoreItem.isTombstone()) { assert(newLocalRevision, 'saved item does not have a revision'); revisions = { local: newLocalRevision, external: remoteRevision, }; } return this.localStore.setLastSyncedRevision( updatedStoreItem, REMOTE_STORE, revisions ); }); } }
the_stack
* Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */ var Prism; // Private helper vars var lang = /\blang(?:uage)?-(\w+)\b/i; var uniqueId = 0; var _ = Prism = { util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); } else if (_.util.type(tokens) === 'Array') { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]; }, objId: function (obj) { if (!obj['__id']) { Object.defineProperty(obj, '__id', { value: ++uniqueId }); } return obj['__id']; }, // Deep clone a language definition (e.g. to extend it) clone: function (o) { var type = _.util.type(o); switch (type) { case 'Object': var clone = {}; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = _.util.clone(o[key]); } } return clone; case 'Array': // Check for existence for IE8 return o.map && o.map(function(v) { return _.util.clone(v); }); } return o; } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need anobject and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. If not provided, the function appends instead. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; }, // Traverse a language definition with Depth First Search DFS: function(o, callback, type, visited) { visited = visited || {}; for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); if (_.util.type(o[i]) === 'Object' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, null, visited); } else if (_.util.type(o[i]) === 'Array' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, i, visited); } } } } }, plugins: {}, highlightAll: function(async, callback) { var env = { callback: callback, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' }; _.hooks.run("before-highlightall", env); var elements = env.elements || document.querySelectorAll(env.selector); for (var i=0, element; element = elements[i++];) { _.highlightElement(element, async === true, env.callback); } }, highlightElement: function(element, async, callback) { // Find language var language, grammar, parent = element; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (parent.className.match(lang) || [,''])[1].toLowerCase(); grammar = _.languages[language]; } // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; // Set language on the parent, for styling parent = element.parentNode; if (/pre/i.test(parent.nodeName)) { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } var code = element.textContent; var env = { element: element, language: language, grammar: grammar, code: code }; _.hooks.run('before-sanity-check', env); if (!env.code || !env.grammar) { _.hooks.run('complete', env); return; } _.hooks.run('before-highlight', env); if (async && _self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function(evt) { env.highlightedCode = evt.data; _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(env.element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code, immediateClose: true })); } else { env.highlightedCode = _.highlight(env.code, env.grammar, env.language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); } }, highlight: function (text, grammar, language) { var tokens = _.tokenize(text, grammar); return Token.stringify(_.util.encode(tokens), language); }, tokenize: function(text, grammar, language) { var Token = _.Token; var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } tokenloop: for (var token in grammar) { if(!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } var patterns = grammar[token]; patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, greedy = !!pattern.greedy, lookbehindLength = 0, alias = pattern.alias; if (greedy && !pattern.pattern.global) { // Without the global flag, lastIndex won't work var flags = pattern.pattern.toString().match(/[imuy]*$/)[0]; pattern.pattern = RegExp(pattern.pattern.source, flags + "g"); } pattern = pattern.pattern || pattern; // Don’t cache length as it changes during the loop for (var i=0, pos = 0; i<strarr.length; pos += (strarr[i].matchedStr || strarr[i]).length, ++i) { var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! break tokenloop; } if (str instanceof Token) { continue; } pattern.lastIndex = 0; var match = pattern.exec(str), delNum = 1; // Greedy patterns can override/remove up to two previously matched tokens if (!match && greedy && i != strarr.length - 1) { pattern.lastIndex = pos; match = pattern.exec(text); if (!match) { break; } var from = match.index + (lookbehind ? match[1].length : 0), to = match.index + match[0].length, k = i, p = pos; for (var len = strarr.length; k < len && p < to; ++k) { p += (strarr[k].matchedStr || strarr[k]).length; // Move the index i to the element in strarr that is closest to from if (from >= p) { ++i; pos = p; } } /* * If strarr[i] is a Token, then the match starts inside another Token, which is invalid * If strarr[k - 1] is greedy we are in conflict with another greedy pattern */ if (strarr[i] instanceof Token || strarr[k - 1].greedy) { continue; } // Number of tokens to delete and replace with the new match delNum = k - i; str = text.slice(pos, p); match.index -= pos; } if (!match) { continue; } if(lookbehind) { lookbehindLength = match[1].length; } var from = match.index + lookbehindLength, match = match[0].slice(lookbehindLength), to = from + match.length, before = str.slice(0, from), after = str.slice(to); var args = [i, delNum]; if (before) { args.push(before); } var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); } } } return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i=0, callback; callback = callbacks[i++];) { callback(env); } } } }; var Token = _.Token = function(type, content, alias, matchedStr, greedy) { this.type = type; this.content = content; this.alias = alias; // Copy of the full string this token was created from this.matchedStr = matchedStr || null; this.greedy = !!greedy; }; Token.stringify = function(o, language, parent) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function(element) { return Token.stringify(element, language, o); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language, parent), tag: 'span', classes: ['token', o.type], attributes: {}, language: language, parent: parent }; if (env.type == 'comment') { env.attributes['spellcheck'] = 'true'; } if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = ''; for (var name in env.attributes) { attributes += (attributes ? ' ' : '') + name + '="' + (env.attributes[name] || '') + '"'; } return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>'; }; Token.reactify = function(o, language, parent, key) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function(element, i) { return Token.reactify(element, language, o, i); }); } var env = { type: o.type, content: Token.reactify(o.content, language, parent), tag: 'span', classes: [o.type], attributes: {key: key}, language: language, parent: parent }; if (env.type == 'comment') { env.attributes.spellCheck = true; } if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); env.attributes.className = env.classes.join(' '); return React.DOM[env.tag](env.attributes, env.content); }; Prism.languages.markup = { 'comment': /<!--[\w\W]*?-->/, 'prolog': /<\?[\w\W]+?\?>/, 'doctype': /<!DOCTYPE[\w\W]+?>/, 'cdata': /<!\[CDATA\[[\w\W]*?]]>/i, 'tag': { pattern: /<\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i, inside: { 'tag': { pattern: /^<\/?[^\s>\/]+/i, inside: { 'punctuation': /^<\/?/, 'namespace': /^[^\s>\/:]+:/ } }, 'attr-value': { pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i, inside: { 'punctuation': /[=>"']/ } }, 'punctuation': /\/?>/, 'attr-name': { pattern: /[^\s>\/]+/, inside: { 'namespace': /^[^\s>\/:]+:/ } } } }, 'entity': /&#?[\da-z]{1,8};/i }; // Plugin to make entity title show the real entity, idea by Roman Komarov Prism.hooks.add('wrap', function(env) { if (env.type === 'entity') { env.attributes['title'] = env.content.replace(/&amp;/, '&'); } }); ; Prism.languages.clike = { 'comment': [ { pattern: /(^|[^\\])\/\*[\w\W]*?\*\//, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true } ], 'string': /("|')(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, 'class-name': { pattern: /((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i, lookbehind: true, inside: { punctuation: /(\.|\\)/ } }, 'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, 'boolean': /\b(true|false)\b/, 'function': /[a-z0-9_]+(?=\()/i, 'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/, 'operator': /[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|~|\^|%/, 'punctuation': /[{}[\];(),.:]/ }; Prism.languages.javascript = Prism.languages.extend('clike', { 'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/, 'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/, 'function': /(?!\d)[a-z0-9_$]+(?=\()/i }); Prism.languages.insertBefore('javascript', 'keyword', { 'regex': { pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/, lookbehind: true } }); Prism.languages.insertBefore('javascript', 'class-name', { 'template-string': { pattern: /`(?:\\`|\\?[^`])*`/, inside: { 'interpolation': { pattern: /\$\{[^}]+\}/, inside: { 'interpolation-punctuation': { pattern: /^\$\{|\}$/, alias: 'punctuation' }, rest: Prism.languages.javascript } }, 'string': /[\s\S]+/ } } }); if (Prism.languages.markup) { Prism.languages.insertBefore('markup', 'tag', { 'script': { pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/i, inside: { 'tag': { pattern: /<script[\w\W]*?>|<\/script>/i, inside: Prism.languages.markup.tag.inside }, rest: Prism.languages.javascript }, alias: 'language-javascript' } }); } ; (function(Prism) { var javascript = Prism.util.clone(Prism.languages.javascript); Prism.languages.jsx = Prism.languages.extend('markup', javascript); Prism.languages.jsx.tag.pattern= /<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+|(\{[\w\W]*?\})))?\s*)*\/?>/i; Prism.languages.jsx.tag.inside['attr-value'].pattern = /=[^\{](?:('|")[\w\W]*?(\1)|[^\s>]+)/i; Prism.languages.insertBefore('inside', 'attr-value',{ 'script': { pattern: /=(\{[\w\W]*?\})/i, inside: { 'function' : Prism.languages.javascript.function, 'punctuation': /[={}[\];(),.:]/, 'keyword': Prism.languages.javascript.keyword }, 'alias': 'language-javascript' } }, Prism.languages.jsx.tag); }(Prism)); var graphqlComment = { pattern: /#.*/, greedy: true }; var graphqlCommon = { string: { pattern: /"(?:\\.|[^\\"])*"/, greedy: true }, number: /(?:\B-|\b)\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/, boolean: /\b(?:true|false)\b/, variable: { pattern: /\$[a-z_]\w*/i, greedy: true }, operator: /!|=|\.{3}/, punctuation: /[!(){|}[\]:=,]/ }; var graphqlDirective = { pattern: /@[a-z_]\w*(\([\w\W]*?\))?/i, inside: { function: /@[a-z_]\w*/i, args: { pattern: /\([\w\W]*?\)/, inside: { arg: /[a-z_]\w*(?=\s*:)/i, ...graphqlCommon } } } }; Prism.languages.graphql = { comment: graphqlComment, 'schema-def': { pattern: /\bschema\b[^{]*{[^{}]*}/, inside: { comment: graphqlComment, keyword: /\bschema\b|[a-zA-Z_]\w*(?=\s*:)/, 'type-name': { pattern: /(:[\s\[]*)[a-z_]\w*/i, lookbehind: true }, directive: graphqlDirective, punctuation: graphqlCommon.punctuation } }, 'union-def': { pattern: /\bunion\b[^=]+=\s*[a-zA-Z_]\w*(?:\s*\|\s*[a-zA-Z_]\w*)*/, inside: { comment: graphqlComment, keyword: /\bunion\b/, 'type-name': { pattern: /([=|]\s*)[a-z_]\w*/i, lookbehind: true }, directive: graphqlDirective, punctuation: graphqlCommon.punctuation } }, 'type-def': { pattern: /\b(?:type|interface|input|enum)\b[\w\W]+?{(?:[^{}]*|[^{}]*{[^{}]*}[^{}]*|[^{}]*{[^{}]*[^{}]*{[^{}]*}[^{}]*}[^{}]*)}/, inside: { comment: graphqlComment, fields: { pattern: /{(?:[^{}]*|[^{}]*{[^{}]*}[^{}]*|[^{}]*{[^{}]*[^{}]*{[^{}]*}[^{}]*}[^{}]*)}/, inside: { comment: graphqlComment, argDefs: { pattern: /\([\w\W]*?\)/, inside: { comment: graphqlComment, 'attr-name': /[a-z_]\w*(?=\s*:)/i, 'type-name': { pattern: /(:[\s\[]*)[a-z_]\w*/i, lookbehind: true }, directive: graphqlDirective, ...graphqlCommon } }, directive: graphqlDirective, 'attr-name': { pattern: /[a-z_]\w*(?=\s*[:\(])/i, greedy: true, }, 'type-name': { pattern: /(:[\s\[]*)[a-z_]\w*/i, lookbehind: true }, punctuation: /[!{}\[\]:=,]/, } }, keyword: /\b(?:type|interface|implements|input|enum)\b/, directive: graphqlDirective, ...graphqlCommon, // 'type-name': /[a-z_]\w*/i, } }, // string: /"(?:\\.|[^\\"])*"/, // number: /(?:\B-|\b)\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/, // boolean: /\b(?:true|false)\b/, // variable: /\$[a-z_]\w*/i, // directive: { // pattern: /@[a-z_]\w*/i, // alias: 'function' // }, directive: graphqlDirective, 'attr-name': /[a-z_]\w*(?=\s*:)/i, 'keyword': [ { pattern: /(fragment\s+(?!on)[a-z_]\w*\s+|\.\.\.\s*)on\b/, lookbehind: true }, /\b(?:query|mutation|subscription|fragment|extend|scalar)\b/ ], ...graphqlCommon, // 'operator': /!|=|\.{3}/, // 'punctuation': /[!(){}\[\]:=,]/, // comment: /#.*/, // 'enum': /[a-z_]\w*/i }; Prism.languages.json = { 'attr-name': { pattern: /"(?:\\.|[^\\"])*"(?=\s*:)/i, greedy: true }, string: { pattern: /"(?:\\.|[^\\"])*"/, greedy: true }, boolean: /\b(?:true|false)\b/, keyword: /\bnull\b/, number: /(?:\B-|\b)\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/, punctuation: /[{}[\],:]/, }; export default Prism;
the_stack
import * as coreClient from "@azure/core-client"; /** Request to start a conversion */ export interface CreateConversionSettings { /** Conversion settings describe the origin of input files and destination of output files. */ settings: AssetConversionSettings; } /** Conversion settings describe the origin of input files and destination of output files. */ export interface AssetConversionSettings { /** Conversion input settings describe the origin of conversion input. */ inputSettings: AssetConversionInputSettings; /** Conversion output settings describe the destination of conversion output. */ outputSettings: AssetConversionOutputSettings; } /** Conversion input settings describe the origin of conversion input. */ export interface AssetConversionInputSettings { /** The URI of the Azure blob storage container containing the input model. */ storageContainerUrl: string; /** An Azure blob storage container shared access signature giving read and list access to the storage container. Optional. If not provided, the Azure Remote Rendering account needs to be linked with the storage account containing the blob container. See https://docs.microsoft.com/azure/remote-rendering/how-tos/create-an-account#link-storage-accounts for details. For security purposes this field will never be filled out in responses bodies. */ storageContainerReadListSas?: string; /** Only Blobs starting with this prefix will be downloaded to perform the conversion. Optional. If not provided, all Blobs from the container will be downloaded. */ blobPrefix?: string; /** The relative path starting at blobPrefix (or at the container root if blobPrefix is not provided) to the input model. Must point to a file with a supported file format ending. See https://docs.microsoft.com/azure/remote-rendering/how-tos/conversion/model-conversion for details. */ relativeInputAssetPath: string; } /** Conversion output settings describe the destination of conversion output. */ export interface AssetConversionOutputSettings { /** The URI of the Azure blob storage container where the result of the conversion should be written to. */ storageContainerUrl: string; /** An Azure blob storage container shared access signature giving write access to the storage container. Optional. If not provided, the Azure Remote Rendering account needs to be linked with the storage account containing the blob container. See https://docs.microsoft.com/azure/remote-rendering/how-tos/create-an-account#link-storage-accounts for details. For security purposes this field will never be filled out in responses bodies. */ storageContainerWriteSas?: string; /** A prefix which gets prepended in front of all files produced by the conversion process. Will be treated as a virtual folder. Optional. If not provided, output files will be stored at the container root. */ blobPrefix?: string; /** The file name of the output asset. Must end in '.arrAsset'. Optional. If not provided, file name will the same name as the input asset, with '.arrAsset' extension */ outputAssetFilename?: string; } /** The properties of the conversion. */ export interface Conversion { /** The ID of the conversion supplied when the conversion was created. */ conversionId: string; /** Conversion settings describe the origin of input files and destination of output files. */ settings: AssetConversionSettings; /** * Information about the output of a successful conversion. Only present when the status of the conversion is 'Succeeded'. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly output?: AssetConversionOutput; /** The error object containing details about the conversion failure. */ error: RemoteRenderingServiceErrorInternal | null; /** The status of the conversion. Terminal states are 'Cancelled', 'Failed', and 'Succeeded'. */ status: AssetConversionStatus; /** The time when the conversion was created. Date and time in ISO 8601 format. */ createdOn: Date; } /** Information about the output of a successful conversion. Only present when the status of the conversion is 'Succeeded'. */ export interface AssetConversionOutput { /** * URI of the asset generated by the conversion process. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly outputAssetUrl?: string; } /** The error object containing details of why the request failed. */ export interface RemoteRenderingServiceErrorInternal { /** Error code. */ code: string; /** A human-readable representation of the error. */ message: string; /** * An array of details about specific errors that led to this reported error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: RemoteRenderingServiceErrorInternal[]; /** * The target of the particular error (e.g., the name of the property in error). * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * An object containing more specific information than the current object about the error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly innerError?: RemoteRenderingServiceErrorInternal; } /** The error response containing details of why the request failed. */ export interface ErrorResponse { /** The error object containing details of why the request failed. */ error: RemoteRenderingServiceErrorInternal; } /** List of conversions. */ export interface ConversionList { /** The list of conversions. */ conversions: Conversion[]; /** * If more conversions are available this field will contain a URL where the next batch of conversions can be requested. This URL will need the same authentication as all calls to the Azure Remote Rendering API. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Settings of the session to be created. */ export interface RenderingSessionSettings { /** The time in minutes the session will run after reaching the 'Ready' state. It has to be between 0 and 1440. */ maxLeaseTimeInMinutes: number; /** The size of the server used for the rendering session. The size impacts the number of polygons the server can render. Refer to https://docs.microsoft.com/azure/remote-rendering/reference/vm-sizes for details. */ size: RenderingServerSize; } /** The properties of a rendering session. */ export interface SessionProperties { /** The ID of the session supplied when the session was created. */ sessionId: string; /** * The TCP port at which the Azure Remote Rendering Inspector tool is hosted. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly arrInspectorPort?: number; /** * The TCP port used for the handshake when establishing a connection. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly handshakePort?: number; /** * Amount of time in minutes the session is or was in the 'Ready' state. Time is rounded down to a full minute. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly elapsedTimeInMinutes?: number; /** * The hostname under which the rendering session is reachable. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly host?: string; /** * The time in minutes the session will run after reaching the 'Ready' state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxLeaseTimeInMinutes?: number; /** The size of the server used for the rendering session. The size impacts the number of polygons the server can render. Refer to https://docs.microsoft.com/azure/remote-rendering/reference/vm-sizes for details. */ size: RenderingServerSize; /** The status of the rendering session. Terminal states are 'Error', 'Expired', and 'Stopped'. */ status: RenderingSessionStatus; /** * The computational power of the rendering session GPU measured in teraflops. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly teraflops?: number; /** * The error object containing details about the rendering session startup failure. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly error?: RemoteRenderingServiceErrorInternal; /** * The time when the rendering session was created. Date and time in ISO 8601 format. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly createdOn?: Date; } /** Settings used to update the session. */ export interface UpdateSessionSettings { /** Update to the time the session will run after it reached the 'Ready' state. It has to be larger than the current value of maxLeaseTimeMinutes and less than 1440. */ maxLeaseTimeInMinutes: number; } /** The result of a list sessions request. */ export interface SessionsList { /** The list of rendering sessions. Does not include sessions in 'Stopped' state. */ sessions: SessionProperties[]; /** * If more rendering sessions are available this field will contain a URL where the next batch of sessions can be requested. This URL will need the same authentication as all calls to the Azure Remote Rendering API. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Defines headers for RemoteRendering_createConversion operation. */ export interface RemoteRenderingCreateConversionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_createConversion operation. */ export interface RemoteRenderingCreateConversionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_getConversion operation. */ export interface RemoteRenderingGetConversionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Time in seconds when the status of this conversion should be polled again */ retryAfter?: number; } /** Defines headers for RemoteRendering_getConversion operation. */ export interface RemoteRenderingGetConversionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_listConversions operation. */ export interface RemoteRenderingListConversionsHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_listConversions operation. */ export interface RemoteRenderingListConversionsExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting errors to the Azure Remote Rendering team. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_createSession operation. */ export interface RemoteRenderingCreateSessionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_createSession operation. */ export interface RemoteRenderingCreateSessionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_getSession operation. */ export interface RemoteRenderingGetSessionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_updateSession operation. */ export interface RemoteRenderingUpdateSessionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_stopSession operation. */ export interface RemoteRenderingStopSessionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_stopSession operation. */ export interface RemoteRenderingStopSessionExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_listSessions operation. */ export interface RemoteRenderingListSessionsExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_listConversionsNext operation. */ export interface RemoteRenderingListConversionsNextHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; } /** Defines headers for RemoteRendering_listConversionsNext operation. */ export interface RemoteRenderingListConversionsNextExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting errors to the Azure Remote Rendering team. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Defines headers for RemoteRendering_listSessionsNext operation. */ export interface RemoteRenderingListSessionsNextExceptionHeaders { /** Microsoft Correlation Vector. Include this value when reporting issues. */ mscv?: string; /** Describes the error encountered while trying to authenticate the resource. */ wWWAuthenticate?: string; } /** Known values of {@link AssetConversionStatus} that the service accepts. */ export enum KnownAssetConversionStatus { /** The conversion was created but hasn't started. */ NotStarted = "NotStarted", /** The conversion is running. */ Running = "Running", /** The conversion was cancelled. This is a terminal state. */ Cancelled = "Cancelled", /** The conversion has failed. Check the 'error' field for more details. This is a terminal state. */ Failed = "Failed", /** The conversion has succeeded. Check the 'output' field for output asset location. This is a terminal state. */ Succeeded = "Succeeded" } /** * Defines values for AssetConversionStatus. \ * {@link KnownAssetConversionStatus} can be used interchangeably with AssetConversionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NotStarted**: The conversion was created but hasn't started. \ * **Running**: The conversion is running. \ * **Cancelled**: The conversion was cancelled. This is a terminal state. \ * **Failed**: The conversion has failed. Check the 'error' field for more details. This is a terminal state. \ * **Succeeded**: The conversion has succeeded. Check the 'output' field for output asset location. This is a terminal state. */ export type AssetConversionStatus = string; /** Known values of {@link RenderingServerSize} that the service accepts. */ export enum KnownRenderingServerSize { /** Standard rendering session size. */ Standard = "Standard", /** Premium rendering session size. */ Premium = "Premium" } /** * Defines values for RenderingServerSize. \ * {@link KnownRenderingServerSize} can be used interchangeably with RenderingServerSize, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Standard**: Standard rendering session size. \ * **Premium**: Premium rendering session size. */ export type RenderingServerSize = string; /** Known values of {@link RenderingSessionStatus} that the service accepts. */ export enum KnownRenderingSessionStatus { /** The rendering session has encountered an error, and is unusable. This is a terminal state. */ Error = "Error", /** The rendering session enters the 'Expired' state when it has been in the 'Ready' state longer than its lease time. This is a terminal state. */ Expired = "Expired", /** The rendering session is starting, but not accepting incoming connections yet. */ Starting = "Starting", /** The rendering session is ready for incoming connections. */ Ready = "Ready", /** The rendering session has been stopped with the 'Stop Session' operation. This is a terminal state. */ Stopped = "Stopped" } /** * Defines values for RenderingSessionStatus. \ * {@link KnownRenderingSessionStatus} can be used interchangeably with RenderingSessionStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Error**: The rendering session has encountered an error, and is unusable. This is a terminal state. \ * **Expired**: The rendering session enters the 'Expired' state when it has been in the 'Ready' state longer than its lease time. This is a terminal state. \ * **Starting**: The rendering session is starting, but not accepting incoming connections yet. \ * **Ready**: The rendering session is ready for incoming connections. \ * **Stopped**: The rendering session has been stopped with the 'Stop Session' operation. This is a terminal state. */ export type RenderingSessionStatus = string; /** Optional parameters. */ export interface RemoteRenderingCreateConversionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createConversion operation. */ export type RemoteRenderingCreateConversionResponse = RemoteRenderingCreateConversionHeaders & Conversion; /** Optional parameters. */ export interface RemoteRenderingGetConversionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getConversion operation. */ export type RemoteRenderingGetConversionResponse = RemoteRenderingGetConversionHeaders & Conversion; /** Optional parameters. */ export interface RemoteRenderingListConversionsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listConversions operation. */ export type RemoteRenderingListConversionsResponse = RemoteRenderingListConversionsHeaders & ConversionList; /** Optional parameters. */ export interface RemoteRenderingCreateSessionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createSession operation. */ export type RemoteRenderingCreateSessionResponse = SessionProperties; /** Optional parameters. */ export interface RemoteRenderingGetSessionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSession operation. */ export type RemoteRenderingGetSessionResponse = SessionProperties; /** Optional parameters. */ export interface RemoteRenderingUpdateSessionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the updateSession operation. */ export type RemoteRenderingUpdateSessionResponse = SessionProperties; /** Optional parameters. */ export interface RemoteRenderingStopSessionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the stopSession operation. */ export type RemoteRenderingStopSessionResponse = RemoteRenderingStopSessionHeaders; /** Optional parameters. */ export interface RemoteRenderingListSessionsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSessions operation. */ export type RemoteRenderingListSessionsResponse = SessionsList; /** Optional parameters. */ export interface RemoteRenderingListConversionsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listConversionsNext operation. */ export type RemoteRenderingListConversionsNextResponse = RemoteRenderingListConversionsNextHeaders & ConversionList; /** Optional parameters. */ export interface RemoteRenderingListSessionsNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSessionsNext operation. */ export type RemoteRenderingListSessionsNextResponse = SessionsList; /** Optional parameters. */ export interface RemoteRenderingRestClientOptionalParams extends coreClient.ServiceClientOptions { /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import * as I from './internals.js' import { ElemType, Eq, IfElse, Nth, DottedPath, TuplePath, RequireString, Simplify, } from './utils.js' import { Adapt, Apply, Choice, Compose, DisallowTypeChange, ElemUnion, Elems, HKT, Id, Index, PartsOf, Plant, Prop, Optional, SetNth, SetDottedPath, SetTuplePath, Union, } from './hkt.js' export { Apply, Compose, Eq, HKT } export type Removable = true | undefined export interface Params<T extends HKT, R extends Removable = undefined> { readonly _T: T readonly _R: R } export type OpticParams = Params<any, any> export type NextParams< C extends OpticParams, T extends HKT, R extends Removable = undefined > = Params<Compose<C['_T'], T>, R> export type NextComposeParams< C1 extends OpticParams, C2 extends OpticParams > = Params<Compose<C1['_T'], C2['_T']>, C2['_R']> export type OpticFor<S> = Equivalence<S, Params<DisallowTypeChange<S>>, S> export type OpticFor_<S> = Equivalence<S, Params<Id>, S> export interface Equivalence<S, T extends OpticParams, A> { readonly _tag: 'Equivalence' readonly _removable: T['_R'] // Equivalence · Equivalence => Equivalence compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Equivalence<S, NextComposeParams<T, T2>, A2> // Equivalence · Iso => Iso compose<T2 extends OpticParams, A2>( optic: Iso<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> iso<U>( there: (a: A) => U, back: (u: U) => A ): Iso<S, NextParams<T, Adapt<A, U>>, U> indexed(): Iso<S, NextParams<T, Index>, [number, ElemType<A>][]> // Equivalence · Lens => Lens compose<T2 extends OpticParams, A2>( optic: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> prop<K extends keyof A>(key: K): Lens<S, NextParams<T, Prop<A, K>>, A[K]> path<K extends keyof any>( path: K ): Lens<S, NextParams<T, SetDottedPath<A, K>>, DottedPath<A, K>> path<K extends (keyof any)[]>( ...path: K ): Lens<S, NextParams<T, SetTuplePath<A, K>>, TuplePath<A, K>> nth<N extends number>(n: N): Lens<S, NextParams<T, SetNth<A, N>>, Nth<A, N>> pick<K extends keyof A>( keys: K[] ): Lens<S, NextParams<T, Plant<A, K>>, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Lens<S, NextParams<T, Union<A>>, B[]> filter( predicate: (item: ElemType<A>) => boolean ): Lens<S, NextParams<T, Union<A>>, A> valueOr<B>( defaultValue: B ): Lens<S, NextParams<T, Id>, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> reread( read: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> rewrite( write: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> // Equivalence · Prism => Prism compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> optional(): Prism<S, NextParams<T, Optional>, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => Prism<S, NextParams<T, F>, U> guard<U extends A>( g: (a: A) => a is U ): Prism<S, NextParams<T, Choice<A, U>>, U> find( predicate: (item: ElemType<A>) => boolean ): Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> when(predicate: (item: A) => boolean): Prism<S, NextParams<T, Union<A>>, A> at( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > head(): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Equivalence · Traversal => Traversal compose<T2 extends OpticParams, A2>( optic: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> elems(): Traversal<S, NextParams<T, Elems>, ElemType<A>> chars(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > words(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > // Equivalence · Getter => Getter compose<A2>(optic: Getter<A, A2>): Getter<S, A2> to<B>(f: (a: A) => B): Getter<S, B> // Equivalence · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // Equivalence · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> // Equivalence · Setter => Setter compose<T2 extends OpticParams, A2>( optic: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> prependTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> appendTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> } export interface Iso<S, T extends OpticParams, A> { readonly _tag: 'Iso' readonly _removable: T['_R'] // Iso · Equivalence => Iso compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> // Iso · Iso => Iso compose<T2 extends OpticParams, A2>( optic: Iso<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> iso<U>( there: (a: A) => U, back: (u: U) => A ): Iso<S, NextParams<T, Adapt<A, U>>, U> indexed(): Iso<S, NextParams<T, Index>, [number, ElemType<A>][]> // Iso · Lens => Lens compose<T2 extends OpticParams, A2>( optic: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> prop<K extends keyof A>(key: K): Lens<S, NextParams<T, Prop<A, K>>, A[K]> path<K extends keyof any>( path: K ): Lens<S, NextParams<T, SetDottedPath<A, K>>, DottedPath<A, K>> path<K extends (keyof any)[]>( ...path: K ): Lens<S, NextParams<T, SetTuplePath<A, K>>, TuplePath<A, K>> nth<N extends number>(n: N): Lens<S, NextParams<T, SetNth<A, N>>, Nth<A, N>> pick<K extends keyof A>( keys: K[] ): Lens<S, NextParams<T, Plant<A, K>>, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Lens<S, NextParams<T, Union<A>>, B[]> filter( predicate: (item: ElemType<A>) => boolean ): Lens<S, NextParams<T, Union<A>>, A> valueOr<B>( defaultValue: B ): Lens<S, NextParams<T, Id>, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> reread( read: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> rewrite( write: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> // Iso · Prism => Prism compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> optional(): Prism<S, NextParams<T, Optional>, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => Prism<S, NextParams<T, F>, U> guard<U extends A>( g: (a: A) => a is U ): Prism<S, NextParams<T, Choice<A, U>>, U> find( predicate: (item: ElemType<A>) => boolean ): Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> when(predicate: (item: A) => boolean): Prism<S, NextParams<T, Union<A>>, A> at( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > head(): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Iso · Traversal => Traversal compose<T2 extends OpticParams, A2>( optic: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> elems(): Traversal<S, NextParams<T, Elems>, ElemType<A>> chars(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > words(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > // Iso · Getter => Getter compose<A2>(optic: Getter<A, A2>): Getter<S, A2> to<B>(f: (a: A) => B): Getter<S, B> // Iso · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // Iso · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> // Iso · Setter => Setter compose<T2 extends OpticParams, A2>( optic: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> prependTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> appendTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> } export interface Lens<S, T extends OpticParams, A> { readonly _tag: 'Lens' readonly _removable: T['_R'] // Lens · Equivalence => Lens compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Lens · Iso => Lens compose<T2 extends OpticParams, A2>( optic: Iso<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> iso<U>( there: (a: A) => U, back: (u: U) => A ): Lens<S, NextParams<T, Adapt<A, U>>, U> indexed(): Lens<S, NextParams<T, Index>, [number, ElemType<A>][]> // Lens · Lens => Lens compose<T2 extends OpticParams, A2>( optic: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> prop<K extends keyof A>(key: K): Lens<S, NextParams<T, Prop<A, K>>, A[K]> path<K extends keyof any>( path: K ): Lens<S, NextParams<T, SetDottedPath<A, K>>, DottedPath<A, K>> path<K extends (keyof any)[]>( ...path: K ): Lens<S, NextParams<T, SetTuplePath<A, K>>, TuplePath<A, K>> nth<N extends number>(n: N): Lens<S, NextParams<T, SetNth<A, N>>, Nth<A, N>> pick<K extends keyof A>( keys: K[] ): Lens<S, NextParams<T, Plant<A, K>>, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Lens<S, NextParams<T, Union<A>>, B[]> filter( predicate: (item: ElemType<A>) => boolean ): Lens<S, NextParams<T, Union<A>>, A> valueOr<B>( defaultValue: B ): Lens<S, NextParams<T, Id>, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Lens<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> reread( read: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> rewrite( write: (value: A) => A ): Lens<S, NextParams<T, DisallowTypeChange<A>>, A> // Lens · Prism => Prism compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> optional(): Prism<S, NextParams<T, Optional>, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => Prism<S, NextParams<T, F>, U> guard<U extends A>( g: (a: A) => a is U ): Prism<S, NextParams<T, Choice<A, U>>, U> find( predicate: (item: ElemType<A>) => boolean ): Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> when(predicate: (item: A) => boolean): Prism<S, NextParams<T, Union<A>>, A> at( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > head(): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Lens · Traversal => Traversal compose<T2 extends OpticParams, A2>( optic: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> elems(): Traversal<S, NextParams<T, Elems>, ElemType<A>> chars(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > words(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > // Lens · Getter => Getter compose<A2>(optic: Getter<A, A2>): Getter<S, A2> to<B>(f: (a: A) => B): Getter<S, B> // Lens · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // Lens · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> // Lens · Setter => Setter compose<T2 extends OpticParams, A2>( optic: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> prependTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> appendTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> } export interface Prism<S, T extends OpticParams, A> { readonly _tag: 'Prism' readonly _removable: T['_R'] // Prism · Equivalence => Prism compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Prism · Iso => Prism compose<T2 extends OpticParams, A2>( optic: Iso<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> iso<U>( there: (a: A) => U, back: (u: U) => A ): Prism<S, NextParams<T, Adapt<A, U>>, U> indexed(): Prism<S, NextParams<T, Index>, [number, ElemType<A>][]> // Prism · Lens => Prism compose<T2 extends OpticParams, A2>( optic: Lens<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> prop<K extends keyof A>(key: K): Prism<S, NextParams<T, Prop<A, K>>, A[K]> path<K extends keyof any>( path: K ): Prism<S, NextParams<T, SetDottedPath<A, K>>, DottedPath<A, K>> path<K extends (keyof any)[]>( ...path: K ): Prism<S, NextParams<T, SetTuplePath<A, K>>, TuplePath<A, K>> nth<N extends number>(n: N): Prism<S, NextParams<T, SetNth<A, N>>, Nth<A, N>> pick<K extends keyof A>( keys: K[] ): Prism<S, NextParams<T, Plant<A, K>>, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Prism<S, NextParams<T, Union<A>>, B[]> filter( predicate: (item: ElemType<A>) => boolean ): Prism<S, NextParams<T, Union<A>>, A> valueOr<B>( defaultValue: B ): Prism<S, NextParams<T, Id>, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Prism<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Prism<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> reread( read: (value: A) => A ): Prism<S, NextParams<T, DisallowTypeChange<A>>, A> rewrite( write: (value: A) => A ): Prism<S, NextParams<T, DisallowTypeChange<A>>, A> // Prism · Prism => Prism compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> optional(): Prism<S, NextParams<T, Optional>, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => Prism<S, NextParams<T, F>, U> guard<U extends A>( g: (a: A) => a is U ): Prism<S, NextParams<T, Choice<A, U>>, U> find( predicate: (item: ElemType<A>) => boolean ): Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> when(predicate: (item: A) => boolean): Prism<S, NextParams<T, Union<A>>, A> at( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > head(): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse< Eq<A, string>, Prism<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Prism<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Prism · Traversal => Traversal compose<T2 extends OpticParams, A2>( optic: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> elems(): Traversal<S, NextParams<T, Elems>, ElemType<A>> chars(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > words(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > // Prism · Getter => AffineFold compose<A2>(optic: Getter<A, A2>): AffineFold<S, A2> to<B>(f: (a: A) => B): AffineFold<S, B> // Prism · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // Prism · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> // Prism · Setter => Setter compose<T2 extends OpticParams, A2>( optic: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> prependTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> appendTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> } export interface Traversal<S, T extends OpticParams, A> { readonly _tag: 'Traversal' readonly _removable: T['_R'] // Traversal · Equivalence => Traversal compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Iso => Traversal compose<T2 extends OpticParams, A2>( optic: Iso<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> iso<U>( there: (a: A) => U, back: (u: U) => A ): Traversal<S, NextParams<T, Adapt<A, U>>, U> indexed(): Traversal<S, NextParams<T, Index>, [number, ElemType<A>][]> // Traversal · Lens => Traversal compose<T2 extends OpticParams, A2>( optic: Lens<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> prop<K extends keyof A>(key: K): Traversal<S, NextParams<T, Prop<A, K>>, A[K]> path<K extends keyof any>( path: K ): Traversal<S, NextParams<T, SetDottedPath<A, K>>, DottedPath<A, K>> path<K extends (keyof any)[]>( ...path: K ): Traversal<S, NextParams<T, SetTuplePath<A, K>>, TuplePath<A, K>> nth<N extends number>( n: N ): Traversal<S, NextParams<T, SetNth<A, N>>, Nth<A, N>> pick<K extends keyof A>( keys: K[] ): Traversal<S, NextParams<T, Plant<A, K>>, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Traversal<S, NextParams<T, Union<A>>, B[]> filter( predicate: (item: ElemType<A>) => boolean ): Traversal<S, NextParams<T, Union<A>>, A> valueOr<B>( defaultValue: B ): Traversal<S, NextParams<T, Id>, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Traversal<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Traversal<S, NextParams<T, PartsOf<U['_T'], A>>, B[]> reread( read: (value: A) => A ): Traversal<S, NextParams<T, DisallowTypeChange<A>>, A> rewrite( write: (value: A) => A ): Traversal<S, NextParams<T, DisallowTypeChange<A>>, A> // Traversal · Prism => Traversal compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> optional(): Traversal<S, NextParams<T, Optional>, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => Traversal<S, NextParams<T, F>, U> guard<U extends A>( g: (a: A) => a is U ): Traversal<S, NextParams<T, Choice<A, U>>, U> find( predicate: (item: ElemType<A>) => boolean ): Traversal<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> when( predicate: (item: A) => boolean ): Traversal<S, NextParams<T, Union<A>>, A> at( i: number ): IfElse< Eq<A, string>, Traversal<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Traversal<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > head(): IfElse< Eq<A, string>, Traversal<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Traversal<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse< Eq<A, string>, Traversal<S, NextParams<T, DisallowTypeChange<string>, true>, string>, Traversal<S, NextParams<T, ElemUnion<A>, true>, ElemType<A>> > // Traversal · Traversal => Traversal compose<T2 extends OpticParams, A2>( optic: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> elems(): Traversal<S, NextParams<T, Elems>, ElemType<A>> chars(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > words(): RequireString< A, Traversal<S, NextParams<T, DisallowTypeChange<string>>, string> > // Traversal · Getter => Fold compose<A2>(optic: Getter<A, A2>): Fold<S, A2> to<B>(f: (a: A) => B): Fold<S, B> // Traversal · AffineFold => Fold compose<A2>(optic: AffineFold<A, A2>): Fold<S, A2> // Traversal · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> // Traversal · Setter => Setter compose<T2 extends OpticParams, A2>( optic: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> prependTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> appendTo(): Setter<S, NextParams<T, ElemUnion<A>>, ElemType<A>> } export interface Getter<S, A> { readonly _tag: 'Getter' // Getter · Equivalence => Getter compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Getter<S, A2> // Getter · Iso => Getter compose<T2 extends OpticParams, A2>(optic: Iso<A, T2, A2>): Getter<S, A2> iso<U>(there: (a: A) => U, back: (u: U) => A): Getter<S, U> indexed(): Getter<S, [number, ElemType<A>][]> // Getter · Lens => Getter compose<T2 extends OpticParams, A2>(optic: Lens<A, T2, A2>): Getter<S, A2> prop<K extends keyof A>(key: K): Getter<S, A[K]> path<K extends keyof any>(path: K): Getter<S, DottedPath<A, K>> path<K extends (keyof any)[]>(...path: K): Getter<S, TuplePath<A, K>> nth<N extends number>(n: N): Getter<S, Nth<A, N>> pick<K extends keyof A>(keys: K[]): Getter<S, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Getter<S, B[]> filter(predicate: (item: ElemType<A>) => boolean): Getter<S, A> valueOr<B>(defaultValue: B): Getter<S, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): Getter<S, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Getter<S, B[]> reread(read: (value: A) => A): Getter<S, A> rewrite(write: (value: A) => A): Getter<S, A> // Getter · Prism => AffineFold compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): AffineFold<S, A2> optional(): AffineFold<S, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => AffineFold<S, U> guard<U extends A>(g: (a: A) => a is U): AffineFold<S, U> find(predicate: (item: ElemType<A>) => boolean): AffineFold<S, ElemType<A>> when(predicate: (item: A) => boolean): AffineFold<S, A> at( i: number ): IfElse<Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>>> head(): IfElse< Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse<Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>>> // Getter · Traversal => Fold compose<T2 extends OpticParams, A2>(optic: Traversal<A, T2, A2>): Fold<S, A2> elems(): Fold<S, ElemType<A>> chars(): RequireString<A, Fold<S, string>> words(): RequireString<A, Fold<S, string>> // Getter · Getter => Getter compose<A2>(optic: Getter<A, A2>): Getter<S, A2> to<B>(f: (a: A) => B): Getter<S, B> // Getter · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // Getter · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> } export interface AffineFold<S, A> { readonly _tag: 'AffineFold' // AffineFold · Equivalence => AffineFold compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): AffineFold<S, A2> // AffineFold · Iso => AffineFold compose<T2 extends OpticParams, A2>(optic: Iso<A, T2, A2>): AffineFold<S, A2> iso<U>(there: (a: A) => U, back: (u: U) => A): AffineFold<S, U> indexed(): AffineFold<S, [number, ElemType<A>][]> // AffineFold · Lens => AffineFold compose<T2 extends OpticParams, A2>(optic: Lens<A, T2, A2>): AffineFold<S, A2> prop<K extends keyof A>(key: K): AffineFold<S, A[K]> path<K extends keyof any>(path: K): AffineFold<S, DottedPath<A, K>> path<K extends (keyof any)[]>(...path: K): AffineFold<S, TuplePath<A, K>> nth<N extends number>(n: N): AffineFold<S, Nth<A, N>> pick<K extends keyof A>(keys: K[]): AffineFold<S, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): AffineFold<S, B[]> filter(predicate: (item: ElemType<A>) => boolean): AffineFold<S, A> valueOr<B>(defaultValue: B): AffineFold<S, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>( traversal: Traversal<A, U, B> ): AffineFold<S, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): AffineFold<S, B[]> reread(read: (value: A) => A): AffineFold<S, A> rewrite(write: (value: A) => A): AffineFold<S, A> // AffineFold · Prism => AffineFold compose<T2 extends OpticParams, A2>( optic: Prism<A, T2, A2> ): AffineFold<S, A2> optional(): AffineFold<S, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>( g: (a: A) => a is U ) => AffineFold<S, U> guard<U extends A>(g: (a: A) => a is U): AffineFold<S, U> find(predicate: (item: ElemType<A>) => boolean): AffineFold<S, ElemType<A>> when(predicate: (item: A) => boolean): AffineFold<S, A> at( i: number ): IfElse<Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>>> head(): IfElse< Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>> > // Deprecated, use .at() index( i: number ): IfElse<Eq<A, string>, AffineFold<S, string>, AffineFold<S, ElemType<A>>> // AffineFold · Traversal => Fold compose<T2 extends OpticParams, A2>(optic: Traversal<A, T2, A2>): Fold<S, A2> elems(): Fold<S, ElemType<A>> chars(): RequireString<A, Fold<S, string>> words(): RequireString<A, Fold<S, string>> // AffineFold · Getter => AffineFold compose<A2>(optic: Getter<A, A2>): AffineFold<S, A2> to<B>(f: (a: A) => B): AffineFold<S, B> // AffineFold · AffineFold => AffineFold compose<A2>(optic: AffineFold<A, A2>): AffineFold<S, A2> // AffineFold · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> } export interface Fold<S, A> { readonly _tag: 'Fold' // Fold · Equivalence => Fold compose<T2 extends OpticParams, A2>( optic: Equivalence<A, T2, A2> ): Fold<S, A2> // Fold · Iso => Fold compose<T2 extends OpticParams, A2>(optic: Iso<A, T2, A2>): Fold<S, A2> iso<U>(there: (a: A) => U, back: (u: U) => A): Fold<S, U> indexed(): Fold<S, [number, ElemType<A>][]> // Fold · Lens => Fold compose<T2 extends OpticParams, A2>(optic: Lens<A, T2, A2>): Fold<S, A2> prop<K extends keyof A>(key: K): Fold<S, A[K]> path<K extends keyof any>(path: K): Fold<S, DottedPath<A, K>> path<K extends (keyof any)[]>(...path: K): Fold<S, TuplePath<A, K>> nth<N extends number>(n: N): Fold<S, Nth<A, N>> pick<K extends keyof A>(keys: K[]): Fold<S, Pick<A, K>> filter<B extends ElemType<A>>( predicate: (item: ElemType<A>) => item is B ): Fold<S, B[]> filter(predicate: (item: ElemType<A>) => boolean): Fold<S, A> valueOr<B>(defaultValue: B): Fold<S, Exclude<A, undefined> | B> partsOf<U extends OpticParams, B>(traversal: Traversal<A, U, B>): Fold<S, B[]> partsOf<U extends OpticParams, B>( makeTraversal: (o: OpticFor_<A>) => Traversal<A, U, B> ): Fold<S, B[]> reread(read: (value: A) => A): Fold<S, A> rewrite(write: (value: A) => A): Fold<S, A> // Fold · Prism => Fold compose<T2 extends OpticParams, A2>(optic: Prism<A, T2, A2>): Fold<S, A2> optional(): Fold<S, Exclude<A, undefined>> guard_<F extends HKT>(): <U extends A>(g: (a: A) => a is U) => Fold<S, U> guard<U extends A>(g: (a: A) => a is U): Fold<S, U> find(predicate: (item: ElemType<A>) => boolean): Fold<S, ElemType<A>> when(predicate: (item: A) => boolean): Fold<S, A> at(i: number): IfElse<Eq<A, string>, Fold<S, string>, Fold<S, ElemType<A>>> head(): IfElse<Eq<A, string>, Fold<S, string>, Fold<S, ElemType<A>>> // Deprecated, use .at() index(i: number): IfElse<Eq<A, string>, Fold<S, string>, Fold<S, ElemType<A>>> // Fold · Traversal => Fold compose<T2 extends OpticParams, A2>(optic: Traversal<A, T2, A2>): Fold<S, A2> elems(): Fold<S, ElemType<A>> chars(): RequireString<A, Fold<S, string>> words(): RequireString<A, Fold<S, string>> // Fold · Getter => Fold compose<A2>(optic: Getter<A, A2>): Fold<S, A2> to<B>(f: (a: A) => B): Fold<S, B> // Fold · AffineFold => Fold compose<A2>(optic: AffineFold<A, A2>): Fold<S, A2> // Fold · Fold => Fold compose<A2>(optic: Fold<A, A2>): Fold<S, A2> } export interface Setter<S, T extends OpticParams, A> { readonly _tag: 'Setter' readonly _removable: T['_R'] } // Equivalence · Equivalence => Equivalence export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Equivalence<A, T2, A2> ): Equivalence<S, NextComposeParams<T, T2>, A2> // Equivalence · Iso => Iso export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Iso<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> // Equivalence · Lens => Lens export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Equivalence · Prism => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Equivalence · Traversal => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Equivalence · Getter => Getter export function compose<S, T extends OpticParams, A, A2>( optic1: Equivalence<S, T, A>, optic2: Getter<A, A2> ): Getter<S, A2> // Equivalence · AffineFold => AffineFold export function compose<S, T extends OpticParams, A, A2>( optic1: Equivalence<S, T, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // Equivalence · Fold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Equivalence<S, T, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Equivalence · Setter => Setter export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Equivalence<S, T, A>, optic2: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> // Iso · Equivalence => Iso export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Equivalence<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> // Iso · Iso => Iso export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Iso<A, T2, A2> ): Iso<S, NextComposeParams<T, T2>, A2> // Iso · Lens => Lens export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Iso · Prism => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Iso · Traversal => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Iso · Getter => Getter export function compose<S, T extends OpticParams, A, A2>( optic1: Iso<S, T, A>, optic2: Getter<A, A2> ): Getter<S, A2> // Iso · AffineFold => AffineFold export function compose<S, T extends OpticParams, A, A2>( optic1: Iso<S, T, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // Iso · Fold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Iso<S, T, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Iso · Setter => Setter export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Iso<S, T, A>, optic2: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> // Lens · Equivalence => Lens export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Equivalence<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Lens · Iso => Lens export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Iso<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Lens · Lens => Lens export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Lens<A, T2, A2> ): Lens<S, NextComposeParams<T, T2>, A2> // Lens · Prism => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Lens · Traversal => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Lens · Getter => Getter export function compose<S, T extends OpticParams, A, A2>( optic1: Lens<S, T, A>, optic2: Getter<A, A2> ): Getter<S, A2> // Lens · AffineFold => AffineFold export function compose<S, T extends OpticParams, A, A2>( optic1: Lens<S, T, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // Lens · Fold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Lens<S, T, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Lens · Setter => Setter export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Lens<S, T, A>, optic2: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> // Prism · Equivalence => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Equivalence<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Prism · Iso => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Iso<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Prism · Lens => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Lens<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Prism · Prism => Prism export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Prism<A, T2, A2> ): Prism<S, NextComposeParams<T, T2>, A2> // Prism · Traversal => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Prism · Getter => AffineFold export function compose<S, T extends OpticParams, A, A2>( optic1: Prism<S, T, A>, optic2: Getter<A, A2> ): AffineFold<S, A2> // Prism · AffineFold => AffineFold export function compose<S, T extends OpticParams, A, A2>( optic1: Prism<S, T, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // Prism · Fold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Prism<S, T, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Prism · Setter => Setter export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Prism<S, T, A>, optic2: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> // Traversal · Equivalence => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Equivalence<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Iso => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Iso<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Lens => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Lens<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Prism => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Prism<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Traversal => Traversal export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Traversal<A, T2, A2> ): Traversal<S, NextComposeParams<T, T2>, A2> // Traversal · Getter => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Traversal<S, T, A>, optic2: Getter<A, A2> ): Fold<S, A2> // Traversal · AffineFold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Traversal<S, T, A>, optic2: AffineFold<A, A2> ): Fold<S, A2> // Traversal · Fold => Fold export function compose<S, T extends OpticParams, A, A2>( optic1: Traversal<S, T, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Traversal · Setter => Setter export function compose< S, T extends OpticParams, A, T2 extends OpticParams, A2 >( optic1: Traversal<S, T, A>, optic2: Setter<A, T2, A2> ): Setter<S, NextComposeParams<T, T2>, A2> // Getter · Equivalence => Getter export function compose<S, A, T2 extends OpticParams, A2>( optic1: Getter<S, A>, optic2: Equivalence<A, T2, A2> ): Getter<S, A2> // Getter · Iso => Getter export function compose<S, A, T2 extends OpticParams, A2>( optic1: Getter<S, A>, optic2: Iso<A, T2, A2> ): Getter<S, A2> // Getter · Lens => Getter export function compose<S, A, T2 extends OpticParams, A2>( optic1: Getter<S, A>, optic2: Lens<A, T2, A2> ): Getter<S, A2> // Getter · Prism => AffineFold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Getter<S, A>, optic2: Prism<A, T2, A2> ): AffineFold<S, A2> // Getter · Traversal => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Getter<S, A>, optic2: Traversal<A, T2, A2> ): Fold<S, A2> // Getter · Getter => Getter export function compose<S, A, A2>( optic1: Getter<S, A>, optic2: Getter<A, A2> ): Getter<S, A2> // Getter · AffineFold => AffineFold export function compose<S, A, A2>( optic1: Getter<S, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // Getter · Fold => Fold export function compose<S, A, A2>( optic1: Getter<S, A>, optic2: Fold<A, A2> ): Fold<S, A2> // AffineFold · Equivalence => AffineFold export function compose<S, A, T2 extends OpticParams, A2>( optic1: AffineFold<S, A>, optic2: Equivalence<A, T2, A2> ): AffineFold<S, A2> // AffineFold · Iso => AffineFold export function compose<S, A, T2 extends OpticParams, A2>( optic1: AffineFold<S, A>, optic2: Iso<A, T2, A2> ): AffineFold<S, A2> // AffineFold · Lens => AffineFold export function compose<S, A, T2 extends OpticParams, A2>( optic1: AffineFold<S, A>, optic2: Lens<A, T2, A2> ): AffineFold<S, A2> // AffineFold · Prism => AffineFold export function compose<S, A, T2 extends OpticParams, A2>( optic1: AffineFold<S, A>, optic2: Prism<A, T2, A2> ): AffineFold<S, A2> // AffineFold · Traversal => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: AffineFold<S, A>, optic2: Traversal<A, T2, A2> ): Fold<S, A2> // AffineFold · Getter => AffineFold export function compose<S, A, A2>( optic1: AffineFold<S, A>, optic2: Getter<A, A2> ): AffineFold<S, A2> // AffineFold · AffineFold => AffineFold export function compose<S, A, A2>( optic1: AffineFold<S, A>, optic2: AffineFold<A, A2> ): AffineFold<S, A2> // AffineFold · Fold => Fold export function compose<S, A, A2>( optic1: AffineFold<S, A>, optic2: Fold<A, A2> ): Fold<S, A2> // Fold · Equivalence => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Fold<S, A>, optic2: Equivalence<A, T2, A2> ): Fold<S, A2> // Fold · Iso => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Fold<S, A>, optic2: Iso<A, T2, A2> ): Fold<S, A2> // Fold · Lens => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Fold<S, A>, optic2: Lens<A, T2, A2> ): Fold<S, A2> // Fold · Prism => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Fold<S, A>, optic2: Prism<A, T2, A2> ): Fold<S, A2> // Fold · Traversal => Fold export function compose<S, A, T2 extends OpticParams, A2>( optic1: Fold<S, A>, optic2: Traversal<A, T2, A2> ): Fold<S, A2> // Fold · Getter => Fold export function compose<S, A, A2>( optic1: Fold<S, A>, optic2: Getter<A, A2> ): Fold<S, A2> // Fold · AffineFold => Fold export function compose<S, A, A2>( optic1: Fold<S, A>, optic2: AffineFold<A, A2> ): Fold<S, A2> // Fold · Fold => Fold export function compose<S, A, A2>( optic1: Fold<S, A>, optic2: Fold<A, A2> ): Fold<S, A2> export function compose(optic1: any, optic2: any) { return optic1.compose(optic2) } export function optic<S>(): OpticFor<S> { return I.optic as any } export function optic_<S>(): OpticFor_<S> { return I.optic as any } export function get<S, A>( optic: | Equivalence<S, any, A> | Iso<S, any, A> | Lens<S, any, A> | Getter<S, A> ): (source: S) => A { return (source) => I.get((optic as any)._ref, source) } export function preview<S, A>( optic: Prism<S, any, A> | Traversal<S, any, A> | AffineFold<S, A> | Fold<S, A> ): (source: S) => A | undefined { return (source) => I.preview((optic as any)._ref, source) } export function collect<S, A>( optic: Prism<S, any, A> | Traversal<S, any, A> | Fold<S, A> ): (source: S) => A[] { return (source) => I.collect((optic as any)._ref, source) } export function modify<S, T extends OpticParams, A>( optic: | Equivalence<S, T, A> | Iso<S, T, A> | Lens<S, T, A> | Prism<S, T, A> | Traversal<S, T, A> ): <B>(f: (a: A) => B) => (source: S) => Simplify<S, Apply<T['_T'], B>> { return (f) => (source) => I.modify((optic as any)._ref, f, source) } export function set<S, T extends OpticParams, A>( optic: | Equivalence<S, T, A> | Iso<S, T, A> | Lens<S, T, A> | Prism<S, T, A> | Traversal<S, T, A> | Setter<S, T, A> ): <B>(value: B) => (source: S) => Simplify<S, Apply<T['_T'], B>> { return (value) => (source) => I.set((optic as any)._ref, value, source) } export function remove<S>( optic: Prism<S, Params<any, true>, any> | Traversal<S, Params<any, true>, any> ): (source: S) => S { return (source) => I.remove((optic as any)._ref, source) } export { pipe } from './standalone/pipe.js'
the_stack
import * as React from "react"; import { Animated, StyleSheet, View, TouchableOpacity } from "react-native"; import _ from "lodash"; import { useRecoilState } from "recoil"; import { cropSizeState, imageBoundsState, accumulatedPanState } from "./Store"; import { GestureHandlerRootView, PanGestureHandler, PanGestureHandlerGestureEvent, State, } from "react-native-gesture-handler"; import { useContext } from "react"; import { EditorContext } from "./ImageEditor"; const horizontalSections = ["top", "middle", "bottom"]; const verticalSections = ["left", "middle", "right"]; const ImageCropOverlay = () => { // Record which section of the fram window has been pressed // this determines whether it is a translation or scaling gesture const [selectedFrameSection, setSelectedFrameSection] = React.useState(""); // Shared state and bits passed through recoil to avoid prop drilling const [cropSize, setCropSize] = useRecoilState(cropSizeState); const [imageBounds] = useRecoilState(imageBoundsState); const [accumulatedPan, setAccumluatedPan] = useRecoilState( accumulatedPanState ); // Editor context const { fixedAspectRatio, lockAspectRatio, minimumCropDimensions, } = useContext(EditorContext); const [animatedCropSize] = React.useState({ width: new Animated.Value(cropSize.width), height: new Animated.Value(cropSize.height), }); // pan X and Y values to track the current delta of the pan // in both directions - this should be zeroed out on release // and the delta added onto the accumulatedPan state const panX = React.useRef(new Animated.Value(imageBounds.x)); const panY = React.useRef(new Animated.Value(imageBounds.y)); React.useEffect(() => { // Move the pan to the origin and check the bounds so it clicks to // the corner of the image checkCropBounds({ translationX: 0, translationY: 0, }); // When the crop size updates make sure the animated value does too! animatedCropSize.height.setValue(cropSize.height); animatedCropSize.width.setValue(cropSize.width); }, [cropSize]); React.useEffect(() => { // Update the size of the crop window based on the new image bounds let newSize = { width: 0, height: 0 }; const { width, height } = imageBounds; const imageAspectRatio = width / height; // Then check if the cropping aspect ratio is smaller if (fixedAspectRatio < imageAspectRatio) { // If so calculate the size so its not greater than the image width newSize.height = height; newSize.width = height * fixedAspectRatio; } else { // else, calculate the size so its not greater than the image height newSize.width = width; newSize.height = width / fixedAspectRatio; } // Set the size of the crop overlay setCropSize(newSize); }, [imageBounds]); // Function that sets which sections allow for translation when // pressed const isMovingSection = () => { return ( selectedFrameSection == "topmiddle" || selectedFrameSection == "middleleft" || selectedFrameSection == "middleright" || selectedFrameSection == "middlemiddle" || selectedFrameSection == "bottommiddle" ); }; // Check what resizing / translation needs to be performed based on which section was pressed const isLeft = selectedFrameSection.endsWith("left"); const isTop = selectedFrameSection.startsWith("top"); const onOverlayMove = ({ nativeEvent }: PanGestureHandlerGestureEvent) => { if (selectedFrameSection !== "") { // Check if the section pressed is one to translate the crop window or not if (isMovingSection()) { // If it is then use an animated event to directly pass the tranlation // to the pan refs Animated.event( [ { translationX: panX.current, translationY: panY.current, }, ], { useNativeDriver: false } )(nativeEvent); } else { // Else its a scaling operation const { x, y } = getTargetCropFrameBounds(nativeEvent); if (isTop) { panY.current.setValue(-y); } if (isLeft) { panX.current.setValue(-x); } // Finally update the animated width to the values the crop // window has been resized to animatedCropSize.width.setValue(cropSize.width + x); animatedCropSize.height.setValue(cropSize.height + y); } } else { // We need to set which section has been pressed const { x, y } = nativeEvent; const { width: initialWidth, height: initialHeight } = cropSize; let position = ""; // Figure out where we pressed vertically if (y / initialHeight < 0.333) { position = position + "top"; } else if (y / initialHeight < 0.667) { position = position + "middle"; } else { position = position + "bottom"; } // Figure out where we pressed horizontally if (x / initialWidth < 0.333) { position = position + "left"; } else if (x / initialWidth < 0.667) { position = position + "middle"; } else { position = position + "right"; } setSelectedFrameSection(position); } }; const getTargetCropFrameBounds = ({ translationX, translationY, }: Partial<PanGestureHandlerGestureEvent["nativeEvent"]>) => { let x = 0; let y = 0; if (translationX && translationY) { if (translationX < translationY) { x = (isLeft ? -1 : 1) * translationX; if (lockAspectRatio) { y = x / fixedAspectRatio; } else { y = (isTop ? -1 : 1) * translationY; } } else { y = (isTop ? -1 : 1) * translationY; if (lockAspectRatio) { x = y * fixedAspectRatio; } else { x = (isLeft ? -1 : 1) * translationX; } } } return { x, y }; }; const onOverlayRelease = ( nativeEvent: PanGestureHandlerGestureEvent["nativeEvent"] ) => { // Check if the section pressed is one to translate the crop window or not if (isMovingSection()) { // Ensure the cropping overlay has not been moved outside of the allowed bounds checkCropBounds(nativeEvent); } else { // Else its a scaling op - check that the resizing didnt take it out of bounds checkResizeBounds(nativeEvent); } // Disable the pan responder so the section tiles can register being pressed again setSelectedFrameSection(""); }; const onHandlerStateChange = ({ nativeEvent, }: PanGestureHandlerGestureEvent) => { // Handle any state changes from the pan gesture handler // only looking at when the touch ends atm if (nativeEvent.state === State.END) { onOverlayRelease(nativeEvent); } }; const checkCropBounds = ({ translationX, translationY, }: | PanGestureHandlerGestureEvent["nativeEvent"] | { translationX: number; translationY: number }) => { // Check if the pan in the x direction exceeds the bounds let accDx = accumulatedPan.x + translationX; // Is the new x pos less than zero? if (accDx <= imageBounds.x) { // Then set it to be zero and set the pan to zero too accDx = imageBounds.x; } // Is the new x pos plus crop width going to exceed the right hand bound else if (accDx + cropSize.width > imageBounds.width + imageBounds.x) { // Then set the x pos so the crop frame touches the right hand edge let limitedXPos = imageBounds.x + imageBounds.width - cropSize.width; accDx = limitedXPos; } else { // It's somewhere in between - no formatting required } // Check if the pan in the y direction exceeds the bounds let accDy = accumulatedPan.y + translationY; // Is the new y pos less the top edge? if (accDy <= imageBounds.y) { // Then set it to be zero and set the pan to zero too accDy = imageBounds.y; } // Is the new y pos plus crop height going to exceed the bottom bound else if (accDy + cropSize.height > imageBounds.height + imageBounds.y) { // Then set the y pos so the crop frame touches the bottom edge let limitedYPos = imageBounds.y + imageBounds.height - cropSize.height; accDy = limitedYPos; } else { // It's somewhere in between - no formatting required } // Record the accumulated pan and reset the pan refs to zero panX.current.setValue(0); panY.current.setValue(0); setAccumluatedPan({ x: accDx, y: accDy }); }; const checkResizeBounds = ({ translationX, translationY, }: | PanGestureHandlerGestureEvent["nativeEvent"] | { translationX: number; translationY: number }) => { // Check we haven't gone out of bounds when resizing - allow it to be // resized up to the appropriate bounds if so const { width: maxWidth, height: maxHeight } = imageBounds; const { width: minWidth, height: minHeight } = minimumCropDimensions; const { x, y } = getTargetCropFrameBounds({ translationX, translationY }); const animatedWidth = cropSize.width + x; const animatedHeight = cropSize.height + y; let finalHeight = animatedHeight; let finalWidth = animatedWidth; // Ensure the width / height does not exceed the boundaries - // resize to the max it can be if so if (animatedHeight > maxHeight) { finalHeight = maxHeight; if (lockAspectRatio) finalWidth = finalHeight * fixedAspectRatio; } else if (animatedHeight < minHeight) { finalHeight = minHeight; if (lockAspectRatio) finalWidth = finalHeight * fixedAspectRatio; } if (animatedWidth > maxWidth) { finalWidth = maxWidth; if (lockAspectRatio) finalHeight = finalWidth / fixedAspectRatio; } else if (animatedWidth < minWidth) { finalWidth = minWidth; if (lockAspectRatio) finalHeight = finalWidth / fixedAspectRatio; } // Update the accumulated pan with the delta from the pan refs setAccumluatedPan({ x: accumulatedPan.x + (isLeft ? -x : 0), y: accumulatedPan.y + (isTop ? -y : 0), }); // Zero out the pan refs panX.current.setValue(0); panY.current.setValue(0); // Update the crop size to the size after resizing setCropSize({ height: finalHeight, width: finalWidth, }); }; return ( <GestureHandlerRootView style={styles.container}> <PanGestureHandler onGestureEvent={onOverlayMove} onHandlerStateChange={(e) => onHandlerStateChange(e)} > <Animated.View style={[ styles.overlay, animatedCropSize, { transform: [ { translateX: Animated.add(panX.current, accumulatedPan.x) }, { translateY: Animated.add(panY.current, accumulatedPan.y) }, ], }, ]} > { // For reendering out each section of the crop overlay frame horizontalSections.map((hsection) => { return ( <View style={styles.sectionRow} key={hsection}> {verticalSections.map((vsection) => { const key = hsection + vsection; return ( <View style={[styles.defaultSection]} key={key}> { // Add the corner markers to the topleft, // topright, bottomleft and bottomright corners to indicate resizing key == "topleft" || key == "topright" || key == "bottomleft" || key == "bottomright" ? ( <View style={[ styles.cornerMarker, hsection == "top" ? { top: -4, borderTopWidth: 7 } : { bottom: -4, borderBottomWidth: 7 }, vsection == "left" ? { left: -4, borderLeftWidth: 7 } : { right: -4, borderRightWidth: 7 }, ]} /> ) : null } </View> ); })} </View> ); }) } </Animated.View> </PanGestureHandler> </GestureHandlerRootView> ); }; export { ImageCropOverlay }; const styles = StyleSheet.create({ container: { height: "100%", width: "100%", position: "absolute", }, overlay: { height: 40, width: 40, backgroundColor: "#33333355", borderColor: "#ffffff88", borderWidth: 1, }, sectionRow: { flexDirection: "row", flex: 1, }, defaultSection: { flex: 1, borderWidth: 0.5, borderColor: "#ffffff88", justifyContent: "center", alignItems: "center", }, cornerMarker: { position: "absolute", borderColor: "#ffffff", height: 30, width: 30, }, });
the_stack
import { Vector3 } from "three"; import * as dat from "dat.gui"; import { View3d, Volume, VolumeMaker, VolumeLoader, Light, AREA_LIGHT, RENDERMODE_PATHTRACE, RENDERMODE_RAYMARCH, SKY_LIGHT, } from "../src"; import { State } from "./types"; import { getDefaultImageInfo } from "../src/Volume"; let view3D: View3d; const myState: State = { file: "", volume: new Volume(), timeSeriesVolumes: [], numberOfVolumesCached: 0, totalFrames: 0, currentFrame: 0, timerId: 0, density: 12.5, maskAlpha: 1.0, exposure: 0.75, aperture: 0.0, fov: 20, focalDistance: 4.0, lights: [new Light(SKY_LIGHT), new Light(AREA_LIGHT)], skyTopIntensity: 0.3, skyMidIntensity: 0.3, skyBotIntensity: 0.3, skyTopColor: [255, 255, 255], skyMidColor: [255, 255, 255], skyBotColor: [255, 255, 255], lightColor: [255, 255, 255], lightIntensity: 75.0, lightTheta: 14, //deg lightPhi: 54, //deg xmin: 0.0, ymin: 0.0, zmin: 0.0, xmax: 1.0, ymax: 1.0, zmax: 1.0, samplingRate: 0.25, primaryRay: 1.0, secondaryRay: 1.0, isPT: false, isTurntable: false, isAxisShowing: false, isAligned: true, showBoundingBox: false, boundingBoxColor: [255, 255, 0], flipX: 1, flipY: 1, flipZ: 1, channelFolderNames: [], infoObj: getDefaultImageInfo(), channelGui: [], }; // controlPoints is array of [{offset:number, color:cssstring}] // where offset is a value from 0.0 to 1.0, and color is a string encoding a css color value. // first and last control points should be at offsets 0 and 1 // TODO: what if offsets 0 and 1 are not provided? // makeColorGradient([ // {offset:0, color:"black"}, // {offset:0.2, color:"black"}, // {offset:0.25, color:"red"}, // {offset:0.5, color:"orange"} // {offset:1.0, color:"yellow"} //]); /* function makeColorGradient(controlPoints) { const c = document.createElement("canvas"); c.style.height = 1; c.style.width = 256; c.height = 1; c.width = 256; const ctx = c.getContext("2d"); const grd = ctx.createLinearGradient(0, 0, 255, 0); if (!controlPoints.length || controlPoints.length < 1) { console.log("warning: bad control points submitted to makeColorGradient; reverting to linear greyscale gradient"); grd.addColorStop(0, "black"); grd.addColorStop(1, "white"); } else { // what if none at 0 and none at 1? for (let i = 0; i < controlPoints.length; ++i) { grd.addColorStop(controlPoints[i].offset, controlPoints[i].color); } } ctx.fillStyle = grd; ctx.fillRect(0, 0, 256, 1); const imgData = ctx.getImageData(0, 0, 256, 1); // console.log(imgData.data); return imgData.data; } */ function initLights() { myState.lights[0].mColorTop = new Vector3( (myState.skyTopColor[0] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[1] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[2] / 255.0) * myState.skyTopIntensity ); myState.lights[0].mColorMiddle = new Vector3( (myState.skyMidColor[0] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[1] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[2] / 255.0) * myState.skyMidIntensity ); myState.lights[0].mColorBottom = new Vector3( (myState.skyBotColor[0] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[1] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[2] / 255.0) * myState.skyBotIntensity ); myState.lights[1].mTheta = (myState.lightTheta * Math.PI) / 180.0; myState.lights[1].mPhi = (myState.lightPhi * Math.PI) / 180.0; myState.lights[1].mColor = new Vector3( (myState.lightColor[0] / 255.0) * myState.lightIntensity, (myState.lightColor[1] / 255.0) * myState.lightIntensity, (myState.lightColor[2] / 255.0) * myState.lightIntensity ); view3D.updateLights(myState.lights); } let gui: dat.GUI; function setupGui() { gui = new dat.GUI(); //gui = new dat.GUI({autoPlace:false, width:200}); gui .add(myState, "density") .max(100.0) .min(0.0) .step(0.001) .onChange(function(value) { view3D.updateDensity(myState.volume, value / 50.0); }); gui .add(myState, "maskAlpha") .max(1.0) .min(0.0) .step(0.001) .onChange(function(value) { view3D.updateMaskAlpha(myState.volume, value); }); gui .add(myState, "primaryRay") .max(40.0) .min(1.0) .step(0.1) .onChange(function() { view3D.setRayStepSizes(myState.volume, myState.primaryRay, myState.secondaryRay); }); gui .add(myState, "secondaryRay") .max(40.0) .min(1.0) .step(0.1) .onChange(function() { view3D.setRayStepSizes(myState.volume, myState.primaryRay, myState.secondaryRay); }); const cameraGui = gui.addFolder("Camera"); cameraGui .add(myState, "exposure") .max(1.0) .min(0.0) .step(0.001) .onChange(function(value) { view3D.updateExposure(value); }); cameraGui .add(myState, "aperture") .max(0.1) .min(0.0) .step(0.001) .onChange(function() { view3D.updateCamera(myState.fov, myState.focalDistance, myState.aperture); }); cameraGui .add(myState, "focalDistance") .max(5.0) .min(0.1) .step(0.001) .onChange(function() { view3D.updateCamera(myState.fov, myState.focalDistance, myState.aperture); }); cameraGui .add(myState, "fov") .max(90.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateCamera(myState.fov, myState.focalDistance, myState.aperture); }); cameraGui .add(myState, "samplingRate") .max(1.0) .min(0.1) .step(0.001) .onChange(function(value) { view3D.updatePixelSamplingRate(value); }); const clipping = gui.addFolder("Clipping Box"); clipping .add(myState, "xmin") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); clipping .add(myState, "xmax") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); clipping .add(myState, "ymin") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); clipping .add(myState, "ymax") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); clipping .add(myState, "zmin") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); clipping .add(myState, "zmax") .max(1.0) .min(0.0) .step(0.001) .onChange(function() { view3D.updateClipRegion( myState.volume, myState.xmin, myState.xmax, myState.ymin, myState.ymax, myState.zmin, myState.zmax ); }); const lighting = gui.addFolder("Lighting"); lighting .addColor(myState, "skyTopColor") .name("Sky Top") .onChange(function() { myState.lights[0].mColorTop = new Vector3( (myState.skyTopColor[0] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[1] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[2] / 255.0) * myState.skyTopIntensity ); view3D.updateLights(myState.lights); }); lighting .add(myState, "skyTopIntensity") .max(100.0) .min(0.01) .step(0.1) .onChange(function() { myState.lights[0].mColorTop = new Vector3( (myState.skyTopColor[0] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[1] / 255.0) * myState.skyTopIntensity, (myState.skyTopColor[2] / 255.0) * myState.skyTopIntensity ); view3D.updateLights(myState.lights); }); lighting .addColor(myState, "skyMidColor") .name("Sky Mid") .onChange(function() { myState.lights[0].mColorMiddle = new Vector3( (myState.skyMidColor[0] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[1] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[2] / 255.0) * myState.skyMidIntensity ); view3D.updateLights(myState.lights); }); lighting .add(myState, "skyMidIntensity") .max(100.0) .min(0.01) .step(0.1) .onChange(function() { myState.lights[0].mColorMiddle = new Vector3( (myState.skyMidColor[0] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[1] / 255.0) * myState.skyMidIntensity, (myState.skyMidColor[2] / 255.0) * myState.skyMidIntensity ); view3D.updateLights(myState.lights); }); lighting .addColor(myState, "skyBotColor") .name("Sky Bottom") .onChange(function() { myState.lights[0].mColorBottom = new Vector3( (myState.skyBotColor[0] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[1] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[2] / 255.0) * myState.skyBotIntensity ); view3D.updateLights(myState.lights); }); lighting .add(myState, "skyBotIntensity") .max(100.0) .min(0.01) .step(0.1) .onChange(function() { myState.lights[0].mColorBottom = new Vector3( (myState.skyBotColor[0] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[1] / 255.0) * myState.skyBotIntensity, (myState.skyBotColor[2] / 255.0) * myState.skyBotIntensity ); view3D.updateLights(myState.lights); }); lighting .add(myState.lights[1], "mDistance") .max(10.0) .min(0.0) .step(0.1) .onChange(function() { view3D.updateLights(myState.lights); }); lighting .add(myState, "lightTheta") .max(180.0) .min(-180.0) .step(1) .onChange(function(value) { myState.lights[1].mTheta = (value * Math.PI) / 180.0; view3D.updateLights(myState.lights); }); lighting .add(myState, "lightPhi") .max(180.0) .min(0.0) .step(1) .onChange(function(value) { myState.lights[1].mPhi = (value * Math.PI) / 180.0; view3D.updateLights(myState.lights); }); lighting .add(myState.lights[1], "mWidth") .max(100.0) .min(0.01) .step(0.1) .onChange(function(value) { myState.lights[1].mWidth = value; myState.lights[1].mHeight = value; view3D.updateLights(myState.lights); }); lighting .add(myState, "lightIntensity") .max(1000.0) .min(0.01) .step(0.1) .onChange(function() { myState.lights[1].mColor = new Vector3( (myState.lightColor[0] / 255.0) * myState.lightIntensity, (myState.lightColor[1] / 255.0) * myState.lightIntensity, (myState.lightColor[2] / 255.0) * myState.lightIntensity ); view3D.updateLights(myState.lights); }); lighting .addColor(myState, "lightColor") .name("lightColor") .onChange(function() { myState.lights[1].mColor = new Vector3( (myState.lightColor[0] / 255.0) * myState.lightIntensity, (myState.lightColor[1] / 255.0) * myState.lightIntensity, (myState.lightColor[2] / 255.0) * myState.lightIntensity ); view3D.updateLights(myState.lights); }); initLights(); } function removeFolderByName(name: string) { const folder = gui.__folders[name]; if (!folder) { return; } folder.close(); // @ts-expect-error __ul doesn't exist in the type declaration gui.__ul.removeChild(folder.domElement.parentNode); delete gui.__folders[name]; // @ts-expect-error onResize doesn't exist in the type declaration gui.onResize(); } function showChannelUI(volume: Volume) { if (myState && myState.channelFolderNames) { for (let i = 0; i < myState.channelFolderNames.length; ++i) { removeFolderByName(myState.channelFolderNames[i]); } } myState.infoObj = volume.imageInfo; myState.channelGui = []; myState.channelFolderNames = []; for (let i = 0; i < myState.infoObj.channels; ++i) { myState.channelGui.push({ colorD: volume.channel_colors_default[i], colorS: [0, 0, 0], colorE: [0, 0, 0], window: 1.0, level: 0.5, glossiness: 0.0, isovalue: 128, // actual intensity value isosurface: false, // first 3 channels for starters enabled: i < 3, // this doesn't give good results currently but is an example of a per-channel button callback autoIJ: (function(j) { return function() { const lut = volume.getHistogram(j).lutGenerator_auto2(); // TODO: get a proper transfer function editor // const lut = { lut: makeColorGradient([ // {offset:0, color:"black"}, // {offset:0.2, color:"black"}, // {offset:0.25, color:"red"}, // {offset:0.5, color:"orange"}, // {offset:1.0, color:"yellow"}]) // }; volume.setLut(j, lut.lut); view3D.updateLuts(volume); }; })(i), // this doesn't give good results currently but is an example of a per-channel button callback auto0: (function(j) { return function() { const lut = volume.getHistogram(j).lutGenerator_auto(); volume.setLut(j, lut.lut); view3D.updateLuts(volume); }; })(i), // this doesn't give good results currently but is an example of a per-channel button callback bestFit: (function(j) { return function() { const lut = volume.getHistogram(j).lutGenerator_bestFit(); volume.setLut(j, lut.lut); view3D.updateLuts(volume); }; })(i), // eslint-disable-next-line @typescript-eslint/naming-convention pct50_98: (function(j) { return function() { const lut = volume.getHistogram(j).lutGenerator_percentiles(0.5, 0.998); volume.setLut(j, lut.lut); view3D.updateLuts(volume); }; })(i), colorizeEnabled: false, colorize: (function(j) { return function() { const lut = volume.getHistogram(j).lutGenerator_labelColors(); volume.setColorPalette(j, lut.lut); myState.channelGui[j].colorizeEnabled = !myState.channelGui[j].colorizeEnabled; if (myState.channelGui[j].colorizeEnabled) { volume.setColorPaletteAlpha(j, myState.channelGui[j].colorizeAlpha); } else { volume.setColorPaletteAlpha(j, 0); } view3D.updateLuts(volume); }; })(i), colorizeAlpha: 0.0, }); const f = gui.addFolder("Channel " + myState.infoObj.channel_names[i]); myState.channelFolderNames.push("Channel " + myState.infoObj.channel_names[i]); f.add(myState.channelGui[i], "enabled").onChange( (function(j) { return function(value) { view3D.setVolumeChannelEnabled(volume, j, value ? true : false); view3D.updateActiveChannels(volume); }; })(i) ); f.add(myState.channelGui[i], "isosurface").onChange( (function(j) { return function(value) { if (value) { view3D.createIsosurface(volume, j, myState.channelGui[j].isovalue, 1.0); } else { view3D.clearIsosurface(volume, j); } }; })(i) ); f.add(myState.channelGui[i], "isovalue") .max(255) .min(0) .step(1) .onChange( (function(j) { return function(value) { view3D.updateIsosurface(volume, j, value); }; })(i) ); f.addColor(myState.channelGui[i], "colorD") .name("Diffuse") .onChange( (function(j) { return function() { view3D.updateChannelMaterial( volume, j, myState.channelGui[j].colorD, myState.channelGui[j].colorS, myState.channelGui[j].colorE, myState.channelGui[j].glossiness ); view3D.updateMaterial(volume); }; })(i) ); f.addColor(myState.channelGui[i], "colorS") .name("Specular") .onChange( (function(j) { return function() { view3D.updateChannelMaterial( volume, j, myState.channelGui[j].colorD, myState.channelGui[j].colorS, myState.channelGui[j].colorE, myState.channelGui[j].glossiness ); view3D.updateMaterial(volume); }; })(i) ); f.addColor(myState.channelGui[i], "colorE") .name("Emissive") .onChange( (function(j) { return function() { view3D.updateChannelMaterial( volume, j, myState.channelGui[j].colorD, myState.channelGui[j].colorS, myState.channelGui[j].colorE, myState.channelGui[j].glossiness ); view3D.updateMaterial(volume); }; })(i) ); f.add(myState.channelGui[i], "window") .max(1.0) .min(0.0) .step(0.001) .onChange( (function(j) { return function(value) { volume.getChannel(j).lutGenerator_windowLevel(value, myState.channelGui[j].level); view3D.updateLuts(volume); }; })(i) ); f.add(myState.channelGui[i], "level") .max(1.0) .min(0.0) .step(0.001) .onChange( (function(j) { return function(value) { volume.getChannel(j).lutGenerator_windowLevel(myState.channelGui[j].window, value); view3D.updateLuts(volume); }; })(i) ); f.add(myState.channelGui[i], "autoIJ"); f.add(myState.channelGui[i], "auto0"); f.add(myState.channelGui[i], "bestFit"); f.add(myState.channelGui[i], "pct50_98"); f.add(myState.channelGui[i], "colorize"); f.add(myState.channelGui[i], "colorizeAlpha") .max(1.0) .min(0.0) .onChange( (function(j) { return function(value) { if (myState.channelGui[j].colorizeEnabled) { volume.setColorPaletteAlpha(j, value); view3D.updateLuts(volume); } }; })(i) ); f.add(myState.channelGui[i], "glossiness") .max(100.0) .min(0.0) .onChange( (function(j) { return function() { view3D.updateChannelMaterial( volume, j, myState.channelGui[j].colorD, myState.channelGui[j].colorS, myState.channelGui[j].colorE, myState.channelGui[j].glossiness ); view3D.updateMaterial(volume); }; })(i) ); } } function loadVolumeAtlasData(vol, jsonData) { VolumeLoader.loadVolumeAtlasData(vol, jsonData.images, (url, channelIndex) => { vol.channels[channelIndex].lutGenerator_percentiles(0.5, 0.998); if (vol.loaded) { view3D.setVolumeRenderMode(myState.isPT ? RENDERMODE_PATHTRACE : RENDERMODE_RAYMARCH); view3D.removeAllVolumes(); view3D.addVolume(vol); // first 3 channels for starters for (let ch = 0; ch < vol.num_channels; ++ch) { view3D.setVolumeChannelEnabled(vol, ch, ch < 3); } view3D.setVolumeChannelAsMask(vol, jsonData.channel_names.indexOf("SEG_Memb")); view3D.updateActiveChannels(vol); view3D.updateLuts(vol); view3D.updateLights(myState.lights); view3D.updateDensity(vol, myState.density / 100.0); view3D.updateExposure(myState.exposure); // apply a volume transform from an external source: if (jsonData.userData && jsonData.userData.alignTransform) { view3D.setVolumeTranslation(vol, vol.voxelsToWorldSpace(jsonData.userData.alignTransform.translation)); view3D.setVolumeRotation(vol, jsonData.userData.alignTransform.rotation); } } }); } function loadImageData(jsonData, volumeData?) { const vol = new Volume(jsonData); myState.volume = vol; // tell the viewer about the image AFTER it's loaded //view3D.removeAllVolumes(); //view3D.addVolume(vol); // get data into the image if (volumeData) { for (let i = 0; i < volumeData.length; ++i) { // where each volumeData element is a flat Uint8Array of xyz data // according to jsonData.tile_width*jsonData.tile_height*jsonData.tiles // (first row of first plane is the first data in // the layout, then second row of first plane, etc) vol.setChannelDataFromVolume(i, volumeData[i]); view3D.setVolumeRenderMode(myState.isPT ? RENDERMODE_PATHTRACE : RENDERMODE_RAYMARCH); view3D.removeAllVolumes(); view3D.addVolume(vol); // first 3 channels for starters for (let ch = 0; ch < vol.num_channels; ++ch) { view3D.setVolumeChannelEnabled(vol, ch, ch < 3); } const maskChannelIndex = jsonData.channel_names.indexOf("SEG_Memb"); view3D.setVolumeChannelAsMask(vol, maskChannelIndex); view3D.updateActiveChannels(vol); view3D.updateLuts(vol); view3D.updateLights(myState.lights); view3D.updateDensity(vol, myState.density / 100.0); view3D.updateExposure(myState.exposure); } } else { loadVolumeAtlasData(vol, jsonData); } showChannelUI(vol); return vol; } function cacheTimeSeriesImageData(jsonData, frameNumber) { const vol = new Volume(jsonData); myState.timeSeriesVolumes[frameNumber] = vol; return vol; } function fetchImage(url, isTimeSeries = false, frameNumber = 0) { fetch(url) .then(function(response) { return response.json(); }) .then(function(myJson) { if (isTimeSeries) { // if you need to adjust image paths prior to download, // now is the time to do it: myJson.images.forEach(function(element) { element.name = "http://dev-aics-dtp-001.corp.alleninstitute.org/dan-data/" + element.name; }); const currentVol = cacheTimeSeriesImageData(myJson, frameNumber); if (frameNumber === 0) { // create the main volume and add to view (this is the only place) myState.volume = new Volume(myJson); // TODO: this can go in the Volume and Channel constructors! // preallocate some memory to be filled in later for (let i = 0; i < myState.volume.num_channels; ++i) { myState.volume.channels[i].imgData = { data: new Uint8ClampedArray(myJson.atlas_width * myJson.atlas_height), width: myJson.atlas_width, height: myJson.atlas_height, }; myState.volume.channels[i].volumeData = new Uint8Array( myJson.tile_width * myJson.tile_height * myJson.tiles ); // TODO also preallocate the Fused data texture } view3D.removeAllVolumes(); view3D.addVolume(myState.volume); view3D.setVolumeRenderMode(myState.isPT ? RENDERMODE_PATHTRACE : RENDERMODE_RAYMARCH); // first 3 channels for starters for (let ch = 0; ch < myState.volume.num_channels; ++ch) { view3D.setVolumeChannelEnabled(myState.volume, ch, ch < 3); } view3D.setVolumeChannelAsMask(myState.volume, myJson.channel_names.indexOf("SEG_Memb")); view3D.updateActiveChannels(myState.volume); view3D.updateLuts(myState.volume); view3D.updateLights(myState.lights); view3D.updateDensity(myState.volume, myState.density / 100.0); view3D.updateExposure(myState.exposure); // apply a volume transform from an external source: if (myJson.userData && myJson.userData.alignTransform) { view3D.setVolumeTranslation( myState.volume, myState.volume.voxelsToWorldSpace(myJson.userData.alignTransform.translation) ); view3D.setVolumeRotation(myState.volume, myJson.userData.alignTransform.rotation); } myState.currentFrame = 0; showChannelUI(myState.volume); } VolumeLoader.loadVolumeAtlasData(currentVol, myJson.images, (url, channelIndex) => { currentVol.channels[channelIndex].lutGenerator_percentiles(0.5, 0.998); if (currentVol.isLoaded()) { console.log("currentVol with name" + currentVol.name + " is loaded"); myState.numberOfVolumesCached++; if (myState.numberOfVolumesCached >= myState.totalFrames) { console.log("ALL FRAMES RECEIVED"); } if (frameNumber === 0) { copyVolumeToVolume(currentVol, myState.volume); // has assumption that only 3 channels view3D.onVolumeData(myState.volume, [0, 1, 2]); view3D.updateActiveChannels(myState.volume); view3D.updateLuts(myState.volume); myState.volume.setIsLoaded(true); } } }); } else { loadImageData(myJson); } }); } function fetchTimeSeries(urlStart, urlEnd, t0, tf, interval = 1) { let frameNumber = 0; for (let t = t0; t <= tf; t += interval) { fetchImage(urlStart + t + urlEnd, true, frameNumber); frameNumber++; } myState.totalFrames = frameNumber; console.log(`${frameNumber} frames requested`); } function copyVolumeToVolume(src, dest) { // assumes volumes already have identical dimensions!!! // grab references to data from each channel and put it in myState.volume for (let i = 0; i < src.num_channels; ++i) { // dest.channels[i].imgData.data.set(src.channels[i].imgData.data); // dest.channels[i].volumeData.set(src.channels[i].volumeData); // dest.channels[i].lut.set(src.channels[i].lut); dest.channels[i].imgData = { data: src.channels[i].imgData.data, width: src.channels[i].imgData.width, height: src.channels[i].imgData.height, }; dest.channels[i].volumeData = src.channels[i].volumeData; dest.channels[i].lut = src.channels[i].lut; // danger: not a copy! dest.channels[i].histogram = src.channels[i].histogram; dest.channels[i].loaded = true; } } function updateViewForNewVolume() { view3D.onVolumeData(myState.volume, [0, 1, 2]); myState.volume.setIsLoaded(true); if (myState.isPT) { view3D.updateActiveChannels(myState.volume); } else { view3D.updateLuts(myState.volume); } for (let i = 0; i < myState.volume.num_channels; ++i) { view3D.updateIsosurface(myState.volume, i, myState.channelGui[i].isovalue); } } function playTimeSeries() { const loadNextFrame = () => { if (myState.currentFrame >= myState.totalFrames - 1) { clearInterval(myState.timerId); console.log("Reached end of sequence"); return; } const nextFrame = myState.currentFrame + 1; const nextFrameVolume = myState.timeSeriesVolumes[nextFrame]; //console.log("loadNextFrame at " + nextFrame); copyVolumeToVolume(nextFrameVolume, myState.volume); updateViewForNewVolume(); myState.currentFrame = nextFrame; }; myState.timerId = window.setInterval(loadNextFrame, 1); } function goToFrame(targetFrame) { console.log("going to Frame " + targetFrame); const outOfBounds = targetFrame > myState.totalFrames - 1 || targetFrame < 0; if (outOfBounds) { console.log("frame out of bounds"); return; } const targetFrameVolume = myState.timeSeriesVolumes[targetFrame]; copyVolumeToVolume(targetFrameVolume, myState.volume); updateViewForNewVolume(); myState.currentFrame = targetFrame; } function createTestVolume() { const imgData = { // width := original full size image width width: 64, // height := original full size image height height: 64, channels: 3, channel_names: ["DRAQ5", "EGFP", "SEG_Memb"], rows: 8, cols: 8, // tiles <= rows*cols, tiles is number of z slices tiles: 64, tile_width: 64, tile_height: 64, // These dimensions are used to prepare the raw volume arrays for rendering as tiled texture atlases // for webgl reasons, it is best for atlas_width and atlas_height to be <= 2048 // and ideally a power of 2. (adjust other dimensions accordingly) // atlas_width === cols*tile_width atlas_width: 512, // atlas_height === rows*tile_height atlas_height: 512, pixel_size_x: 1, pixel_size_y: 1, pixel_size_z: 1, name: "AICS-10_5_5", status: "OK", version: "0.0.0", aicsImageVersion: "0.3.0", }; // generate some raw volume data const channelVolumes = [ VolumeMaker.createSphere(imgData.tile_width, imgData.tile_height, imgData.tiles, 24), VolumeMaker.createTorus(imgData.tile_width, imgData.tile_height, imgData.tiles, 24, 8), VolumeMaker.createCone(imgData.tile_width, imgData.tile_height, imgData.tiles, 24, 24), ]; return { imgData: imgData, volumeData: channelVolumes, }; } function main() { const el = document.getElementById("volume-viewer"); if (!el) { return; } view3D = new View3d(el); const xBtn = document.getElementById("X"); xBtn?.addEventListener("click", () => { view3D.setCameraMode("X"); }); const yBtn = document.getElementById("Y"); yBtn?.addEventListener("click", () => { view3D.setCameraMode("Y"); }); const zBtn = document.getElementById("Z"); zBtn?.addEventListener("click", () => { view3D.setCameraMode("Z"); }); const d3Btn = document.getElementById("3D"); d3Btn?.addEventListener("click", () => { view3D.setCameraMode("3D"); }); const rotBtn = document.getElementById("rotBtn"); rotBtn?.addEventListener("click", () => { myState.isTurntable = !myState.isTurntable; view3D.setAutoRotate(myState.isTurntable); }); const axisBtn = document.getElementById("axisBtn"); axisBtn?.addEventListener("click", () => { myState.isAxisShowing = !myState.isAxisShowing; view3D.setShowAxis(myState.isAxisShowing); }); const showBoundsBtn = document.getElementById("showBoundingBox"); showBoundsBtn?.addEventListener("click", () => { myState.showBoundingBox = !myState.showBoundingBox; view3D.setShowBoundingBox(myState.volume, myState.showBoundingBox); }); const boundsColorBtn = document.getElementById("boundingBoxColor"); boundsColorBtn?.addEventListener("change", (event: Event) => { // convert value to rgb array function hexToRgb(hex, last: [number, number, number]): [number, number, number] { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [parseInt(result[1], 16) / 255.0, parseInt(result[2], 16) / 255.0, parseInt(result[3], 16) / 255.0] : last; } myState.boundingBoxColor = hexToRgb((event.target as HTMLInputElement)?.value, myState.boundingBoxColor); view3D.setBoundingBoxColor(myState.volume, myState.boundingBoxColor); }); const flipXBtn = document.getElementById("flipXBtn"); flipXBtn?.addEventListener("click", () => { myState.flipX *= -1; view3D.setFlipVolume(myState.volume, myState.flipX, myState.flipY, myState.flipZ); }); const flipYBtn = document.getElementById("flipYBtn"); flipYBtn?.addEventListener("click", () => { myState.flipY *= -1; view3D.setFlipVolume(myState.volume, myState.flipX, myState.flipY, myState.flipZ); }); const flipZBtn = document.getElementById("flipZBtn"); flipZBtn?.addEventListener("click", () => { myState.flipZ *= -1; view3D.setFlipVolume(myState.volume, myState.flipX, myState.flipY, myState.flipZ); }); const playBtn = document.getElementById("playBtn"); playBtn?.addEventListener("click", () => { if (myState.currentFrame >= myState.totalFrames - 1) { myState.currentFrame = -1; } playTimeSeries(); }); const pauseBtn = document.getElementById("pauseBtn"); pauseBtn?.addEventListener("click", () => { clearInterval(myState.timerId); }); const forwardBtn = document.getElementById("forwardBtn"); forwardBtn?.addEventListener("click", () => { goToFrame(myState.currentFrame + 1); }); const backBtn = document.getElementById("backBtn"); backBtn?.addEventListener("click", () => { goToFrame(myState.currentFrame - 1); }); const alignBtn = document.getElementById("xfBtn"); alignBtn?.addEventListener("click", () => { myState.isAligned = !myState.isAligned; view3D.setVolumeTranslation(myState.volume, myState.isAligned ? myState.volume.getTranslation() : [0, 0, 0]); view3D.setVolumeRotation(myState.volume, myState.isAligned ? myState.volume.getRotation() : [0, 0, 0]); }); const resetCamBtn = document.getElementById("resetCamBtn"); resetCamBtn?.addEventListener("click", () => { view3D.resetCamera(); }); const counterSpan = document.getElementById("counter"); if (counterSpan) { view3D.setRenderUpdateListener(count => { counterSpan.innerHTML = "" + count; }); } if (view3D.hasWebGL2()) { const ptBtn = document.getElementById("ptBtn") as HTMLButtonElement; ptBtn.disabled = false; ptBtn.addEventListener("click", () => { myState.isPT = !myState.isPT; view3D.setVolumeRenderMode(myState.isPT ? RENDERMODE_PATHTRACE : RENDERMODE_RAYMARCH); view3D.updateLights(myState.lights); }); } const screenshotBtn = document.getElementById("screenshotBtn"); screenshotBtn?.addEventListener("click", () => { view3D.capture(dataUrl => { const anchor = document.createElement("a"); anchor.href = dataUrl; anchor.download = "screenshot.png"; anchor.click(); }); }); setupGui(); const loadTimeSeries = false; const loadTestData = true; if (loadTimeSeries) { fetchTimeSeries( "http://dev-aics-dtp-001.corp.alleninstitute.org/dan-data/test_parent_T49.ome_", "_atlas.json", 0, 46 ); } else if (loadTestData) { fetchImage("AICS-12_881_atlas.json"); } else { const volumeInfo = createTestVolume(); loadImageData(volumeInfo.imgData, volumeInfo.volumeData); } console.log(myState.timeSeriesVolumes); } document.body.onload = () => { main(); };
the_stack
import * as fs from 'fs'; import * as ts from 'typescript'; import * as vm from 'vm'; import { transpileSource, virtualCompilerHost, virtualTsConfigHost } from './test-utils/transpile'; const mockFs = { readFile: jest.fn(fs.readFile), readFileSync: jest.fn(fs.readFileSync), writeFileSync: jest.fn(fs.writeFileSync), }; jest.doMock('fs', () => mockFs); import { applyTypes, getTypeCollectorSnippet, IApplyTypesOptions, IInstrumentOptions, instrument } from './index'; function typeWiz(input: string, typeCheck = false, options?: IApplyTypesOptions) { // setup options to allow using the TypeChecker if (options && options.tsConfig) { options.tsCompilerHost = virtualCompilerHost(input, 'c:/test.ts'); options.tsConfigHost = virtualTsConfigHost({ compilerOptions: { noImplicitThis: true, target: 'es2015', }, include: ['test.ts'], }); } // Step 1: instrument the source const instrumented = instrument(input, 'c:\\test.ts', { instrumentCallExpressions: true, instrumentImplicitThis: true, ...options, } as IInstrumentOptions); // Step 2: compile + add the type collector const compiled = typeCheck ? transpileSource(instrumented, 'test.ts') : ts.transpile(instrumented, { target: ts.ScriptTarget.ES2015, }); // Step 3: evaluate the code, and collect the runtime type information const collectedTypes = vm.runInNewContext(getTypeCollectorSnippet() + compiled + ';$_$twiz.get();'); // Step 4: put the collected types into the code mockFs.readFileSync.mockReturnValue(input); mockFs.writeFileSync.mockImplementationOnce(() => 0); applyTypes(collectedTypes, options); if (options && options.tsConfig) { expect(options.tsConfigHost!.readFile).toHaveBeenCalledWith(options.tsConfig); } if (mockFs.writeFileSync.mock.calls.length) { expect(mockFs.writeFileSync).toHaveBeenCalledTimes(1); expect(mockFs.writeFileSync).toHaveBeenCalledWith('c:/test.ts', expect.any(String)); return mockFs.writeFileSync.mock.calls[0][1]; } else { return null; } } beforeEach(() => { mockFs.readFileSync.mockImplementation(fs.readFileSync); jest.clearAllMocks(); }); describe('function parameters', () => { it('should add `this` type', () => { const input = ` class Greeter { text = "Hello World"; sayGreeting = greet; } function greet() { return this.text; } const greeter = new Greeter(); greeter.sayGreeting(); `; expect(typeWiz(input, true, { tsConfig: 'tsconfig.integration.json' })).toBe(` class Greeter { text = "Hello World"; sayGreeting = greet; } function greet(this: Greeter) { return this.text; } const greeter = new Greeter(); greeter.sayGreeting(); `); }); it('should add `this` type before parameter', () => { const input = ` class Greeter { text = "Hello World: "; sayGreeting = greet; } function greet(name) { return this.text + name; } const greeter = new Greeter(); greeter.sayGreeting('user'); `; expect(typeWiz(input, true, { tsConfig: 'tsconfig.integration.json' })).toBe(` class Greeter { text = "Hello World: "; sayGreeting = greet; } function greet(this: Greeter, name: string) { return this.text + name; } const greeter = new Greeter(); greeter.sayGreeting('user'); `); }); it('should not add `this` type when it can be inferred', () => { const input = ` class Greeter { text; constructor(){ this.text = "Hello World"; } sayGreeting() { return this.text; } } const greeter = new Greeter(); greeter.sayGreeting(); `; expect(typeWiz(input, true, { tsConfig: 'tsconfig.integration.json' })).toBe(` class Greeter { text: string; constructor(){ this.text = "Hello World"; } sayGreeting() { return this.text; } } const greeter = new Greeter(); greeter.sayGreeting(); `); }); it('should infer `string` type for a simple function', () => { const input = ` function greet(c) { return 'Hello ' + c; } greet('World'); `; expect(typeWiz(input, true)).toBe(` function greet(c: string) { return 'Hello ' + c; } greet('World'); `); }); it('should find argument types for arrow functions', () => { const input = `((x) => { return x + 5; })(10)`; expect(typeWiz(input)).toBe(`((x: number) => { return x + 5; })(10)`); }); it('should find argument types for arrow function expressions', () => { const input = `((x)=>x+5)(10)`; expect(typeWiz(input)).toBe(`((x: number)=>x+5)(10)`); }); it('should correcly handle arrow functions without parenthesis around the argument names', () => { const input = `(async x=>x+5)(10)`; expect(typeWiz(input)).toBe(`(async (x: number)=>x+5)(10)`); }); it('should correctly transform arrow functions that return arrow functions', () => { const input = `(x=>y=>x+y)(10)(5)`; expect(typeWiz(input)).toBe(`((x: number)=>(y: number)=>x+y)(10)(5)`); }); it('should infer `string` type for class method', () => { const input = ` class Greeter { greet(who) { return 'Hello, ' + who; } } new Greeter().greet('World'); `; expect(typeWiz(input)).toBe(` class Greeter { greet(who: string) { return 'Hello, ' + who; } } new Greeter().greet('World'); `); }); it('should infer `string` type for object literal method', () => { const input = ` const greeter = { greet(who) { return 'Hello, ' + who; } } greeter.greet('World'); `; expect(typeWiz(input)).toBe(` const greeter = { greet(who: string) { return 'Hello, ' + who; } } greeter.greet('World'); `); }); it('should infer type for object literal regular expression', () => { const input = ` const greeter = { greet(regex) { return regex; } } greeter.greet(/goodness squad/i); `; expect(typeWiz(input)).toBe(` const greeter = { greet(regex: RegExp) { return regex; } } greeter.greet(/goodness squad/i); `); }); it('should correctly handle optional parameters', () => { const input = ` function calculate(a, b?) { return a + (b || 0); } calculate(5, 6); `; expect(typeWiz(input)).toBe(` function calculate(a: number, b?: number) { return a + (b || 0); } calculate(5, 6); `); }); it('should keep unused functions as is', () => { const input = ` function unused(foo, bar) { } `; expect(typeWiz(input)).toBe(null); // null means we haven't updated the input file }); it('should support union types', () => { const input = ` function commas(item) { return Array.from(item).join(', '); } commas('Lavender'); commas(['Apples', 'Oranges']); `; expect(typeWiz(input)).toBe(` function commas(item: string|string[]) { return Array.from(item).join(', '); } commas('Lavender'); commas(['Apples', 'Oranges']); `); }); it('should should not append `undefined` type to optional parameters', () => { const input = ` function optional(b?, c?) { return b || 0; } optional() + optional(10); `; expect(typeWiz(input)).toBe(` function optional(b?: number, c?) { return b || 0; } optional() + optional(10); `); }); it('should use TypeScript inference to find argument types', () => { const input = ` function f(a) { } const arr: string[] = []; f(arr); `; expect(typeWiz(input, false, { tsConfig: 'tsconfig.integration.json' })).toBe(` function f(a: string[]) { } const arr: string[] = []; f(arr); `); }); it('should discover generic types using Type Inference', () => { const input = ` function f(a) { return a; } const promise = Promise.resolve(15); f(promise); `; expect(typeWiz(input, true, { tsConfig: 'tsconfig.integration.json' })).toBe(` function f(a: Promise<number>) { return a; } const promise = Promise.resolve(15); f(promise); `); }); it('should not add `any` type if this was the inferred type for an argument', () => { const input = ` function f(a) { return a; } let val: any = {}; f(val); `; expect(typeWiz(input, true, { tsConfig: 'tsconfig.integration.json' })).toBe(` function f(a: {}) { return a; } let val: any = {}; f(val); `); }); }); describe('class fields', () => { it('should detect `boolean` type for class field', () => { const input = ` class Test { passed; } new Test().passed = true; `; expect(typeWiz(input)).toBe(` class Test { passed: boolean; } new Test().passed = true; `); }); it('should detect types for private class fields', () => { const input = ` class Test { private passed; constructor() { this.passed = true; } } new Test(); `; expect(typeWiz(input)).toBe(` class Test { private passed: boolean; constructor() { this.passed = true; } } new Test(); `); }); it('should detect types for optional class fields, and not add undefined as a type option', () => { const input = ` class Foo { someValue?; } const foo = new Foo(); foo.someValue = 5; foo.someValue = ''; foo.someValue = undefined; `; expect(typeWiz(input)).toBe(` class Foo { someValue?: number|string; } const foo = new Foo(); foo.someValue = 5; foo.someValue = ''; foo.someValue = undefined; `); }); it('should detect types for readonly class fields', () => { const input = ` class Foo { readonly someValue; constructor() { this.someValue = 15; } } const foo = new Foo(); `; expect(typeWiz(input, true)).toBe(` class Foo { readonly someValue: number; constructor() { this.someValue = 15; } } const foo = new Foo(); `); }); }); describe('object types', () => { it('should infer parameters whose types are objects', () => { const input = ` function foo(obj) { return obj; } foo({hello: 'world', 'foo-bar': 42}); `; expect(typeWiz(input)).toBe(` function foo(obj: { "foo-bar": number, hello: string }) { return obj; } foo({hello: 'world', 'foo-bar': 42}); `); }); it('should not fail when given an object with a circular references', () => { const input = ` let a = {}; a.a = a; function foo(obj) { return obj; } foo(a); `; expect(typeWiz(input)).toBe(null); // null means we haven't updated the input file }); }); describe('regression tests', () => { it('issue #66: endless recursion in getTypeName()', () => { const input = ` function log(o) { console.log(o); } function f(o) { return o.someVal; } const obj = { get someVal() { log(this); return 5; } }; f(obj); `; expect(typeWiz(input)).toBe(` function log(o: { someVal: number }) { console.log(o); } function f(o: { someVal: number }) { return o.someVal; } const obj = { get someVal() { log(this); return 5; } }; f(obj); `); }); it('issue #75: fails typescript parsing when having nested arrow functions', () => { const input = ` function doTheThing(cb) { cb([1,2,3]); } doTheThing((results) => { results.forEach((result) => console.log(result)); }); `; expect(typeWiz(input)).toBe(` function doTheThing(cb: (results: any) => any) { cb([1,2,3]); } doTheThing((results: number[]) => { results.forEach((result: number) => console.log(result)); }); `); }); it('issue #83: invalid code produced for parameter destructuring with default values', () => { const input = ` function greet({ who = "" }) { return 'Hello, ' + who; } greet({who: 'world'}); `; expect(typeWiz(input)).toBe(` function greet({ who = "" }: { who: string }) { return 'Hello, ' + who; } greet({who: 'world'}); `); }); it('issue #93: invalid code produced for nested destructuring with default values', () => { const input = `const fn = ({ foo: { bar = '' }}) => 0;`; expect(typeWiz(input)).toBe(null); }); }); describe('apply-types options', () => { describe('prefix', () => { it('should add the given prefix in front of the detected types', () => { const input = ` function greet(c) { return 'Hello ' + c; } greet('World'); `; expect(typeWiz(input, false, { prefix: '/*auto*/' })).toBe(` function greet(c: /*auto*/string) { return 'Hello ' + c; } greet('World'); `); }); }); });
the_stack
import * as coreClient from "@azure/core-client"; /** Data Lake Analytics account list information. */ export interface DataLakeAnalyticsAccountListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: DataLakeAnalyticsAccountBasic[]; /** * The current number of data lake analytics accounts under this subscription. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly count?: number; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The basic account specific properties that are associated with an underlying Data Lake Analytics account. */ export interface DataLakeAnalyticsAccountPropertiesBasic { /** * The unique identifier associated with this Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accountId?: string; /** * The provisioning status of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: DataLakeAnalyticsAccountStatus; /** * The state of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: DataLakeAnalyticsAccountState; /** * The account creation time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly creationTime?: Date; /** * The account last modified time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedTime?: Date; /** * The full CName endpoint for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly endpoint?: string; } /** The resource model definition. */ export interface Resource { /** * The resource identifier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The resource location. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly location?: string; /** * The resource tags. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly tags?: { [propertyName: string]: string }; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } /** The error detail. */ export interface ErrorDetail { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorDetail[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** The parameters to use for creating a Data Lake Analytics account. */ export interface CreateDataLakeAnalyticsAccountParameters { /** The resource location. */ location: string; /** The resource tags. */ tags?: { [propertyName: string]: string }; /** The default Data Lake Store account associated with this account. */ defaultDataLakeStoreAccount: string; /** The list of Data Lake Store accounts associated with this account. */ dataLakeStoreAccounts: AddDataLakeStoreWithAccountParameters[]; /** The list of Azure Blob Storage accounts associated with this account. */ storageAccounts?: AddStorageAccountWithAccountParameters[]; /** The list of compute policies associated with this account. */ computePolicies?: CreateComputePolicyWithAccountParameters[]; /** The list of firewall rules associated with this account. */ firewallRules?: CreateFirewallRuleWithAccountParameters[]; /** The current state of the IP address firewall for this account. */ firewallState?: FirewallState; /** The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. */ firewallAllowAzureIps?: FirewallAllowAzureIpsState; /** The commitment tier for the next month. */ newTier?: TierType; /** The maximum supported jobs running under the account at the same time. */ maxJobCount?: number; /** The maximum supported degree of parallelism for this account. */ maxDegreeOfParallelism?: number; /** The maximum supported degree of parallelism per job for this account. */ maxDegreeOfParallelismPerJob?: number; /** The minimum supported priority per job for this account. */ minPriorityPerJob?: number; /** The number of days that job metadata is retained. */ queryStoreRetention?: number; } /** The parameters used to add a new Data Lake Store account while creating a new Data Lake Analytics account. */ export interface AddDataLakeStoreWithAccountParameters { /** The unique name of the Data Lake Store account to add. */ name: string; /** The optional suffix for the Data Lake Store account. */ suffix?: string; } /** The parameters used to add a new Azure Storage account while creating a new Data Lake Analytics account. */ export interface AddStorageAccountWithAccountParameters { /** The unique name of the Azure Storage account to add. */ name: string; /** The access key associated with this Azure Storage account that will be used to connect to it. */ accessKey: string; /** The optional suffix for the storage account. */ suffix?: string; } /** The parameters used to create a new compute policy while creating a new Data Lake Analytics account. */ export interface CreateComputePolicyWithAccountParameters { /** The unique name of the compute policy to create. */ name: string; /** The AAD object identifier for the entity to create a policy for. */ objectId: string; /** The type of AAD object the object identifier refers to. */ objectType: AADObjectType; /** The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. */ maxDegreeOfParallelismPerJob?: number; /** The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. */ minPriorityPerJob?: number; } /** The parameters used to create a new firewall rule while creating a new Data Lake Analytics account. */ export interface CreateFirewallRuleWithAccountParameters { /** The unique name of the firewall rule to create. */ name: string; /** The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ startIpAddress: string; /** The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ endIpAddress: string; } /** The resource model definition for a nested resource. */ export interface SubResource { /** * The resource identifier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * The resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; } /** The parameters that can be used to update an existing Data Lake Analytics account. */ export interface UpdateDataLakeAnalyticsAccountParameters { /** The resource tags. */ tags?: { [propertyName: string]: string }; /** The list of Data Lake Store accounts associated with this account. */ dataLakeStoreAccounts?: UpdateDataLakeStoreWithAccountParameters[]; /** The list of Azure Blob storage accounts associated with this account. */ storageAccounts?: UpdateStorageAccountWithAccountParameters[]; /** The list of compute policies associated with this account. */ computePolicies?: UpdateComputePolicyWithAccountParameters[]; /** The list of firewall rules associated with this account. */ firewallRules?: UpdateFirewallRuleWithAccountParameters[]; /** The current state of the IP address firewall for this account. Disabling the firewall does not remove existing rules, they will just be ignored until the firewall is re-enabled. */ firewallState?: FirewallState; /** The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. */ firewallAllowAzureIps?: FirewallAllowAzureIpsState; /** The commitment tier to use for next month. */ newTier?: TierType; /** The maximum supported jobs running under the account at the same time. */ maxJobCount?: number; /** The maximum supported degree of parallelism for this account. */ maxDegreeOfParallelism?: number; /** The maximum supported degree of parallelism per job for this account. */ maxDegreeOfParallelismPerJob?: number; /** The minimum supported priority per job for this account. */ minPriorityPerJob?: number; /** The number of days that job metadata is retained. */ queryStoreRetention?: number; } /** The parameters used to update a Data Lake Store account while updating a Data Lake Analytics account. */ export interface UpdateDataLakeStoreWithAccountParameters { /** The unique name of the Data Lake Store account to update. */ name: string; /** The optional suffix for the Data Lake Store account. */ suffix?: string; } /** The parameters used to update an Azure Storage account while updating a Data Lake Analytics account. */ export interface UpdateStorageAccountWithAccountParameters { /** The unique name of the Azure Storage account to update. */ name: string; /** The updated access key associated with this Azure Storage account that will be used to connect to it. */ accessKey?: string; /** The optional suffix for the storage account. */ suffix?: string; } /** The parameters used to update a compute policy while updating a Data Lake Analytics account. */ export interface UpdateComputePolicyWithAccountParameters { /** The unique name of the compute policy to update. */ name: string; /** The AAD object identifier for the entity to create a policy for. */ objectId?: string; /** The type of AAD object the object identifier refers to. */ objectType?: AADObjectType; /** The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. */ maxDegreeOfParallelismPerJob?: number; /** The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. */ minPriorityPerJob?: number; } /** The parameters used to update a firewall rule while updating a Data Lake Analytics account. */ export interface UpdateFirewallRuleWithAccountParameters { /** The unique name of the firewall rule to update. */ name: string; /** The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ startIpAddress?: string; /** The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ endIpAddress?: string; } /** Data Lake Store account list information. */ export interface DataLakeStoreAccountInformationListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: DataLakeStoreAccountInformation[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The parameters used to add a new Data Lake Store account. */ export interface AddDataLakeStoreParameters { /** The optional suffix for the Data Lake Store account. */ suffix?: string; } /** Azure Storage account list information. */ export interface StorageAccountInformationListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: StorageAccountInformation[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The parameters used to add a new Azure Storage account. */ export interface AddStorageAccountParameters { /** The access key associated with this Azure Storage account that will be used to connect to it. */ accessKey: string; /** The optional suffix for the storage account. */ suffix?: string; } /** The parameters used to update an Azure Storage account. */ export interface UpdateStorageAccountParameters { /** The updated access key associated with this Azure Storage account that will be used to connect to it. */ accessKey?: string; /** The optional suffix for the storage account. */ suffix?: string; } /** The list of blob containers associated with the storage account attached to the Data Lake Analytics account. */ export interface StorageContainerListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: StorageContainer[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The SAS response that contains the storage account, container and associated SAS token for connection use. */ export interface SasTokenInformationListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: SasTokenInformation[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** SAS token information. */ export interface SasTokenInformation { /** * The access token for the associated Azure Storage Container. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accessToken?: string; } /** The list of compute policies in the account. */ export interface ComputePolicyListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: ComputePolicy[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The parameters used to create a new compute policy. */ export interface CreateOrUpdateComputePolicyParameters { /** The AAD object identifier for the entity to create a policy for. */ objectId: string; /** The type of AAD object the object identifier refers to. */ objectType: AADObjectType; /** The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. */ maxDegreeOfParallelismPerJob?: number; /** The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. */ minPriorityPerJob?: number; } /** The parameters used to update a compute policy. */ export interface UpdateComputePolicyParameters { /** The AAD object identifier for the entity to create a policy for. */ objectId?: string; /** The type of AAD object the object identifier refers to. */ objectType?: AADObjectType; /** The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. */ maxDegreeOfParallelismPerJob?: number; /** The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. */ minPriorityPerJob?: number; } /** Data Lake Analytics firewall rule list information. */ export interface FirewallRuleListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: FirewallRule[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The parameters used to create a new firewall rule. */ export interface CreateOrUpdateFirewallRuleParameters { /** The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ startIpAddress: string; /** The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ endIpAddress: string; } /** The parameters used to update a firewall rule. */ export interface UpdateFirewallRuleParameters { /** The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ startIpAddress?: string; /** The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. */ endIpAddress?: string; } /** The list of available operations for Data Lake Analytics. */ export interface OperationListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Operation[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** An available operation for Data Lake Analytics. */ export interface Operation { /** * The name of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * The display information for the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly display?: OperationDisplay; /** * The OperationMetaPropertyInfo for the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly properties?: OperationMetaPropertyInfo; /** * The intended executor of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly origin?: OperationOrigin; } /** The display information for a particular operation. */ export interface OperationDisplay { /** * The resource provider of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; /** * The resource type of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * A friendly name of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; /** * A friendly description of the operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; } export interface OperationMetaPropertyInfo { /** The operations OperationMetaServiceSpecification. */ serviceSpecification?: OperationMetaServiceSpecification; } export interface OperationMetaServiceSpecification { /** The metricSpecifications for OperationMetaServiceSpecification. */ metricSpecifications?: OperationMetaMetricSpecification[]; /** The logSpecifications for OperationMetaServiceSpecification. */ logSpecifications?: OperationMetaLogSpecification[]; } export interface OperationMetaMetricSpecification { /** The name for OperationMetaMetricSpecification. */ name?: string; /** The displayName for OperationMetaMetricSpecification. */ displayDescription?: string; /** The displayName for OperationMetaMetricSpecification. */ displayName?: string; /** The unit for OperationMetaMetricSpecification. */ unit?: string; /** The aggregationType for OperationMetaMetricSpecification. */ aggregationType?: string; /** The availabilities for OperationMetaMetricSpecification. */ availabilities?: OperationMetaMetricAvailabilitiesSpecification[]; } export interface OperationMetaMetricAvailabilitiesSpecification { /** The timegrain for OperationMetaMetricAvailabilitiesSpecification. */ timeGrain?: string; /** The blobDuration for OperationMetaMetricAvailabilitiesSpecification. */ blobDuration?: string; } export interface OperationMetaLogSpecification { /** The name for OperationMetaLogSpecification. */ name?: string; /** The displayName for OperationMetaLogSpecification. */ displayName?: string; /** The blobDuration for OperationMetaLogSpecification. */ blobDuration?: string; } /** Subscription-level properties and limits for Data Lake Analytics. */ export interface CapabilityInformation { /** * The subscription credentials that uniquely identifies the subscription. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly subscriptionId?: string; /** * The subscription state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: SubscriptionState; /** * The maximum supported number of accounts under this subscription. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxAccountCount?: number; /** * The current number of accounts under this subscription. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accountCount?: number; /** * The Boolean value of true or false to indicate the maintenance state. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly migrationState?: boolean; } /** Data Lake Analytics account name availability check parameters. */ export interface CheckNameAvailabilityParameters { /** The Data Lake Analytics name to check availability for. */ name: string; /** The resource type. Note: This should not be set by the user, as the constant value is Microsoft.DataLakeAnalytics/accounts */ type: "Microsoft.DataLakeAnalytics/accounts"; } /** Data Lake Analytics account name availability result information. */ export interface NameAvailabilityInformation { /** * The Boolean value of true or false to indicate whether the Data Lake Analytics account name is available or not. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nameAvailable?: boolean; /** * The reason why the Data Lake Analytics account name is not available, if nameAvailable is false. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly reason?: string; /** * The message describing why the Data Lake Analytics account name is not available, if nameAvailable is false. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Data Lake Analytics VirtualNetwork rule list information. */ export interface VirtualNetworkRuleListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: VirtualNetworkRule[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Data Lake Analytics HiveMetastore list information. */ export interface HiveMetastoreListResult { /** * The results of the list operation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: HiveMetastore[]; /** * The link (url) to the next page of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** The account specific properties that are associated with an underlying Data Lake Analytics account. Returned only when retrieving a specific account. */ export type DataLakeAnalyticsAccountProperties = DataLakeAnalyticsAccountPropertiesBasic & { /** * The type of the default Data Lake Store account associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly defaultDataLakeStoreAccountType?: string; /** * The default Data Lake Store account associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly defaultDataLakeStoreAccount?: string; /** * The list of Data Lake Store accounts associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dataLakeStoreAccounts?: DataLakeStoreAccountInformation[]; /** The list of Data Lake Store accounts associated with this account. */ publicDataLakeStoreAccounts?: DataLakeStoreAccountInformation[]; /** * The list of Azure Blob Storage accounts associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly storageAccounts?: StorageAccountInformation[]; /** * The list of compute policies associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly computePolicies?: ComputePolicy[]; /** * The list of hiveMetastores associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hiveMetastores?: HiveMetastore[]; /** * The list of virtualNetwork rules associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly virtualNetworkRules?: VirtualNetworkRule[]; /** * The list of firewall rules associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly firewallRules?: FirewallRule[]; /** The current state of the IP address firewall for this account. */ firewallState?: FirewallState; /** The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. */ firewallAllowAzureIps?: FirewallAllowAzureIpsState; /** The commitment tier for the next month. */ newTier?: TierType; /** * The commitment tier in use for the current month. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly currentTier?: TierType; /** The maximum supported jobs running under the account at the same time. */ maxJobCount?: number; /** * The maximum supported active jobs under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxActiveJobCountPerUser?: number; /** * The maximum supported jobs queued under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxQueuedJobCountPerUser?: number; /** * The maximum supported active jobs under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxJobRunningTimeInMin?: number; /** * The system defined maximum supported jobs running under the account at the same time, which restricts the maximum number of running jobs the user can set for the account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemMaxJobCount?: number; /** The maximum supported degree of parallelism for this account. */ maxDegreeOfParallelism?: number; /** * The system defined maximum supported degree of parallelism for this account, which restricts the maximum value of parallelism the user can set for the account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemMaxDegreeOfParallelism?: number; /** The maximum supported degree of parallelism per job for this account. */ maxDegreeOfParallelismPerJob?: number; /** * The minimum supported priority per job for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly minPriorityPerJob?: number; /** The number of days that job metadata is retained. */ queryStoreRetention?: number; /** * The current state of the DebugDataAccessLevel for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly debugDataAccessLevel?: DebugDataAccessLevel; }; /** A Data Lake Analytics account object, containing all information associated with the named Data Lake Analytics account. */ export type DataLakeAnalyticsAccountBasic = Resource & { /** * The unique identifier associated with this Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accountId?: string; /** * The provisioning status of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: DataLakeAnalyticsAccountStatus; /** * The state of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: DataLakeAnalyticsAccountState; /** * The account creation time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly creationTime?: Date; /** * The account last modified time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedTime?: Date; /** * The full CName endpoint for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly endpoint?: string; }; /** A Data Lake Analytics account object, containing all information associated with the named Data Lake Analytics account. */ export type DataLakeAnalyticsAccount = Resource & { /** * The unique identifier associated with this Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly accountId?: string; /** * The provisioning status of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: DataLakeAnalyticsAccountStatus; /** * The state of the Data Lake Analytics account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: DataLakeAnalyticsAccountState; /** * The account creation time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly creationTime?: Date; /** * The account last modified time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedTime?: Date; /** * The full CName endpoint for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly endpoint?: string; /** * The type of the default Data Lake Store account associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly defaultDataLakeStoreAccountType?: string; /** * The default Data Lake Store account associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly defaultDataLakeStoreAccount?: string; /** * The list of Data Lake Store accounts associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly dataLakeStoreAccounts?: DataLakeStoreAccountInformation[]; /** The list of Data Lake Store accounts associated with this account. */ publicDataLakeStoreAccounts?: DataLakeStoreAccountInformation[]; /** * The list of Azure Blob Storage accounts associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly storageAccounts?: StorageAccountInformation[]; /** * The list of compute policies associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly computePolicies?: ComputePolicy[]; /** * The list of hiveMetastores associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hiveMetastores?: HiveMetastore[]; /** * The list of virtualNetwork rules associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly virtualNetworkRules?: VirtualNetworkRule[]; /** * The list of firewall rules associated with this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly firewallRules?: FirewallRule[]; /** The current state of the IP address firewall for this account. */ firewallState?: FirewallState; /** The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. */ firewallAllowAzureIps?: FirewallAllowAzureIpsState; /** The commitment tier for the next month. */ newTier?: TierType; /** * The commitment tier in use for the current month. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly currentTier?: TierType; /** The maximum supported jobs running under the account at the same time. */ maxJobCount?: number; /** * The maximum supported active jobs under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxActiveJobCountPerUser?: number; /** * The maximum supported jobs queued under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxQueuedJobCountPerUser?: number; /** * The maximum supported active jobs under the account at the same time. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxJobRunningTimeInMin?: number; /** * The system defined maximum supported jobs running under the account at the same time, which restricts the maximum number of running jobs the user can set for the account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemMaxJobCount?: number; /** The maximum supported degree of parallelism for this account. */ maxDegreeOfParallelism?: number; /** * The system defined maximum supported degree of parallelism for this account, which restricts the maximum value of parallelism the user can set for the account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemMaxDegreeOfParallelism?: number; /** The maximum supported degree of parallelism per job for this account. */ maxDegreeOfParallelismPerJob?: number; /** * The minimum supported priority per job for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly minPriorityPerJob?: number; /** The number of days that job metadata is retained. */ queryStoreRetention?: number; /** * The current state of the DebugDataAccessLevel for this account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly debugDataAccessLevel?: DebugDataAccessLevel; }; /** Data Lake Store account information. */ export type DataLakeStoreAccountInformation = SubResource & { /** * The optional suffix for the Data Lake Store account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly suffix?: string; }; /** Azure Storage account information. */ export type StorageAccountInformation = SubResource & { /** * The optional suffix for the storage account. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly suffix?: string; }; /** Data Lake Analytics compute policy information. */ export type ComputePolicy = SubResource & { /** * The AAD object identifier for the entity to create a policy for. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectId?: string; /** * The type of AAD object the object identifier refers to. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly objectType?: AADObjectType; /** * The maximum degree of parallelism per job this user can use to submit jobs. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly maxDegreeOfParallelismPerJob?: number; /** * The minimum priority per job this user can use to submit jobs. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly minPriorityPerJob?: number; }; export type HiveMetastore = SubResource & { /** * The serverUri for the Hive MetaStore * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly serverUri?: string; /** * The databaseName for the Hive MetaStore * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly databaseName?: string; /** * The runtimeVersion for the Hive MetaStore * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly runtimeVersion?: string; /** * The userName for the Hive MetaStore * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly userName?: string; /** * The password for the Hive MetaStore * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly password?: string; /** * The current state of the NestedResource * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nestedResourceProvisioningState?: NestedResourceProvisioningState; }; /** Data Lake Analytics VirtualNetwork Rule information. */ export type VirtualNetworkRule = SubResource & { /** * The resource identifier for the subnet * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly subnetId?: string; /** * The current state of the VirtualNetwork Rule * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly virtualNetworkRuleState?: VirtualNetworkRuleState; }; /** Data Lake Analytics firewall rule information. */ export type FirewallRule = SubResource & { /** * The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly startIpAddress?: string; /** * The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly endIpAddress?: string; }; /** Azure Storage blob container information. */ export type StorageContainer = SubResource & { /** * The last modified time of the blob container. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastModifiedTime?: Date; }; /** Known values of {@link AADObjectType} that the service accepts. */ export enum KnownAADObjectType { User = "User", Group = "Group", ServicePrincipal = "ServicePrincipal" } /** * Defines values for AADObjectType. \ * {@link KnownAADObjectType} can be used interchangeably with AADObjectType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Group** \ * **ServicePrincipal** */ export type AADObjectType = string; /** Known values of {@link OperationOrigin} that the service accepts. */ export enum KnownOperationOrigin { User = "user", System = "system", UserSystem = "user,system" } /** * Defines values for OperationOrigin. \ * {@link KnownOperationOrigin} can be used interchangeably with OperationOrigin, * this enum contains the known values that the service supports. * ### Known values supported by the service * **user** \ * **system** \ * **user,system** */ export type OperationOrigin = string; /** Known values of {@link SubscriptionState} that the service accepts. */ export enum KnownSubscriptionState { Registered = "Registered", Suspended = "Suspended", Deleted = "Deleted", Unregistered = "Unregistered", Warned = "Warned" } /** * Defines values for SubscriptionState. \ * {@link KnownSubscriptionState} can be used interchangeably with SubscriptionState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Registered** \ * **Suspended** \ * **Deleted** \ * **Unregistered** \ * **Warned** */ export type SubscriptionState = string; /** Defines values for DataLakeAnalyticsAccountStatus. */ export type DataLakeAnalyticsAccountStatus = | "Failed" | "Creating" | "Running" | "Succeeded" | "Patching" | "Suspending" | "Resuming" | "Deleting" | "Deleted" | "Undeleting" | "Canceled"; /** Defines values for DataLakeAnalyticsAccountState. */ export type DataLakeAnalyticsAccountState = "Active" | "Suspended"; /** Defines values for FirewallState. */ export type FirewallState = "Enabled" | "Disabled"; /** Defines values for FirewallAllowAzureIpsState. */ export type FirewallAllowAzureIpsState = "Enabled" | "Disabled"; /** Defines values for TierType. */ export type TierType = | "Consumption" | "Commitment_100AUHours" | "Commitment_500AUHours" | "Commitment_1000AUHours" | "Commitment_5000AUHours" | "Commitment_10000AUHours" | "Commitment_50000AUHours" | "Commitment_100000AUHours" | "Commitment_500000AUHours"; /** Defines values for NestedResourceProvisioningState. */ export type NestedResourceProvisioningState = | "Succeeded" | "Canceled" | "Failed"; /** Defines values for VirtualNetworkRuleState. */ export type VirtualNetworkRuleState = | "Active" | "NetworkSourceDeleted" | "Failed"; /** Defines values for DebugDataAccessLevel. */ export type DebugDataAccessLevel = "All" | "Customer" | "None"; /** Optional parameters. */ export interface AccountsListOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the list operation. */ export type AccountsListResponse = DataLakeAnalyticsAccountListResult; /** Optional parameters. */ export interface AccountsListByResourceGroupOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByResourceGroup operation. */ export type AccountsListByResourceGroupResponse = DataLakeAnalyticsAccountListResult; /** Optional parameters. */ export interface AccountsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type AccountsCreateResponse = DataLakeAnalyticsAccount; /** Optional parameters. */ export interface AccountsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AccountsGetResponse = DataLakeAnalyticsAccount; /** Optional parameters. */ export interface AccountsUpdateOptionalParams extends coreClient.OperationOptions { /** Parameters supplied to the update Data Lake Analytics account operation. */ parameters?: UpdateDataLakeAnalyticsAccountParameters; /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type AccountsUpdateResponse = DataLakeAnalyticsAccount; /** Optional parameters. */ export interface AccountsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AccountsCheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type AccountsCheckNameAvailabilityResponse = NameAvailabilityInformation; /** Optional parameters. */ export interface AccountsListNextOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listNext operation. */ export type AccountsListNextResponse = DataLakeAnalyticsAccountListResult; /** Optional parameters. */ export interface AccountsListByResourceGroupNextOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByResourceGroupNext operation. */ export type AccountsListByResourceGroupNextResponse = DataLakeAnalyticsAccountListResult; /** Optional parameters. */ export interface DataLakeStoreAccountsListByAccountOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByAccount operation. */ export type DataLakeStoreAccountsListByAccountResponse = DataLakeStoreAccountInformationListResult; /** Optional parameters. */ export interface DataLakeStoreAccountsAddOptionalParams extends coreClient.OperationOptions { /** The details of the Data Lake Store account. */ parameters?: AddDataLakeStoreParameters; } /** Optional parameters. */ export interface DataLakeStoreAccountsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type DataLakeStoreAccountsGetResponse = DataLakeStoreAccountInformation; /** Optional parameters. */ export interface DataLakeStoreAccountsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DataLakeStoreAccountsListByAccountNextOptionalParams extends coreClient.OperationOptions { /** OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByAccountNext operation. */ export type DataLakeStoreAccountsListByAccountNextResponse = DataLakeStoreAccountInformationListResult; /** Optional parameters. */ export interface StorageAccountsListByAccountOptionalParams extends coreClient.OperationOptions { /** The OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByAccount operation. */ export type StorageAccountsListByAccountResponse = StorageAccountInformationListResult; /** Optional parameters. */ export interface StorageAccountsAddOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface StorageAccountsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type StorageAccountsGetResponse = StorageAccountInformation; /** Optional parameters. */ export interface StorageAccountsUpdateOptionalParams extends coreClient.OperationOptions { /** The parameters containing the access key and suffix to update the storage account with, if any. Passing nothing results in no change. */ parameters?: UpdateStorageAccountParameters; } /** Optional parameters. */ export interface StorageAccountsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface StorageAccountsListStorageContainersOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listStorageContainers operation. */ export type StorageAccountsListStorageContainersResponse = StorageContainerListResult; /** Optional parameters. */ export interface StorageAccountsGetStorageContainerOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getStorageContainer operation. */ export type StorageAccountsGetStorageContainerResponse = StorageContainer; /** Optional parameters. */ export interface StorageAccountsListSasTokensOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSasTokens operation. */ export type StorageAccountsListSasTokensResponse = SasTokenInformationListResult; /** Optional parameters. */ export interface StorageAccountsListByAccountNextOptionalParams extends coreClient.OperationOptions { /** The OData filter. Optional. */ filter?: string; /** The number of items to return. Optional. */ top?: number; /** The number of items to skip over before returning elements. Optional. */ skip?: number; /** OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. */ select?: string; /** OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional. */ orderby?: string; /** The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional. */ count?: boolean; } /** Contains response data for the listByAccountNext operation. */ export type StorageAccountsListByAccountNextResponse = StorageAccountInformationListResult; /** Optional parameters. */ export interface StorageAccountsListStorageContainersNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listStorageContainersNext operation. */ export type StorageAccountsListStorageContainersNextResponse = StorageContainerListResult; /** Optional parameters. */ export interface StorageAccountsListSasTokensNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSasTokensNext operation. */ export type StorageAccountsListSasTokensNextResponse = SasTokenInformationListResult; /** Optional parameters. */ export interface ComputePoliciesListByAccountOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByAccount operation. */ export type ComputePoliciesListByAccountResponse = ComputePolicyListResult; /** Optional parameters. */ export interface ComputePoliciesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type ComputePoliciesCreateOrUpdateResponse = ComputePolicy; /** Optional parameters. */ export interface ComputePoliciesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ComputePoliciesGetResponse = ComputePolicy; /** Optional parameters. */ export interface ComputePoliciesUpdateOptionalParams extends coreClient.OperationOptions { /** Parameters supplied to update the compute policy. */ parameters?: UpdateComputePolicyParameters; } /** Contains response data for the update operation. */ export type ComputePoliciesUpdateResponse = ComputePolicy; /** Optional parameters. */ export interface ComputePoliciesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface ComputePoliciesListByAccountNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByAccountNext operation. */ export type ComputePoliciesListByAccountNextResponse = ComputePolicyListResult; /** Optional parameters. */ export interface FirewallRulesListByAccountOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByAccount operation. */ export type FirewallRulesListByAccountResponse = FirewallRuleListResult; /** Optional parameters. */ export interface FirewallRulesCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type FirewallRulesCreateOrUpdateResponse = FirewallRule; /** Optional parameters. */ export interface FirewallRulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type FirewallRulesGetResponse = FirewallRule; /** Optional parameters. */ export interface FirewallRulesUpdateOptionalParams extends coreClient.OperationOptions { /** Parameters supplied to update the firewall rule. */ parameters?: UpdateFirewallRuleParameters; } /** Contains response data for the update operation. */ export type FirewallRulesUpdateResponse = FirewallRule; /** Optional parameters. */ export interface FirewallRulesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface FirewallRulesListByAccountNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByAccountNext operation. */ export type FirewallRulesListByAccountNextResponse = FirewallRuleListResult; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult; /** Optional parameters. */ export interface LocationsGetCapabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getCapability operation. */ export type LocationsGetCapabilityResponse = CapabilityInformation; /** Optional parameters. */ export interface DataLakeAnalyticsAccountManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_contractlinescheduleofvalue_Project_Information { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab_GeneralTab_Sections { GeneralSection: DevKit.Controls.Section; InvoiceSection: DevKit.Controls.Section; } interface tab_GeneralTab extends DevKit.Controls.ITab { Section: tab_GeneralTab_Sections; } interface Tabs { GeneralTab: tab_GeneralTab; } interface Body { Tab: Tabs; /** Enter the value of the milestone. */ msdyn_amount: DevKit.Controls.Money; msdyn_amount_after_tax: DevKit.Controls.Money; /** Select the project contract associated with this milestone. */ msdyn_contract: DevKit.Controls.Lookup; /** Enter a description of the project contract line that has this milestone. */ msdyn_ContractLineDescription: DevKit.Controls.String; /** Unique identifier for Project Contract Line associated with Project Contract Line Invoice Schedule. */ msdyn_ContractLineId: DevKit.Controls.Lookup; /** Enter the date of which this milestone should be achieved */ msdyn_Invoicedate: DevKit.Controls.Date; /** Select the status of invoicing of this milestone */ msdyn_Invoicestatus: DevKit.Controls.OptionSet; /** Type the name of the milestone. */ msdyn_name: DevKit.Controls.String; /** Select the project work breakdown structure (WBS) task that is tracking the work for this milestone. */ msdyn_projecttask: DevKit.Controls.Lookup; msdyn_tax: DevKit.Controls.Money; } } class Formmsdyn_contractlinescheduleofvalue_Project_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_contractlinescheduleofvalue_Project_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_contractlinescheduleofvalue_Project_Information */ Body: DevKit.Formmsdyn_contractlinescheduleofvalue_Project_Information.Body; /** The Header section of form msdyn_contractlinescheduleofvalue_Project_Information */ Header: DevKit.Formmsdyn_contractlinescheduleofvalue_Project_Information.Header; } namespace Formmsdyn_contractlinescheduleofvalue_Project_Quick_Create { interface tab_tab_1_Sections { AmountSection: DevKit.Controls.Section; GeneralSection: DevKit.Controls.Section; InvoiceSection: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Enter the value of the milestone. */ msdyn_amount: DevKit.Controls.Money; /** Select the project contract associated with this milestone. */ msdyn_contract: DevKit.Controls.Lookup; /** Unique identifier for Project Contract Line associated with Project Contract Line Invoice Schedule. */ msdyn_ContractLineId: DevKit.Controls.Lookup; /** Enter the date of which this milestone should be achieved */ msdyn_Invoicedate: DevKit.Controls.Date; /** Select the status of invoicing of this milestone */ msdyn_Invoicestatus: DevKit.Controls.OptionSet; /** Type the name of the milestone. */ msdyn_name: DevKit.Controls.String; /** Select the project work breakdown structure (WBS) task that is tracking the work for this milestone. */ msdyn_projecttask: DevKit.Controls.Lookup; msdyn_tax: DevKit.Controls.Money; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class Formmsdyn_contractlinescheduleofvalue_Project_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_contractlinescheduleofvalue_Project_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_contractlinescheduleofvalue_Project_Quick_Create */ Body: DevKit.Formmsdyn_contractlinescheduleofvalue_Project_Quick_Create.Body; } class msdyn_contractlinescheduleofvalueApi { /** * DynamicsCrm.DevKit msdyn_contractlinescheduleofvalueApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enter the value of the milestone. */ msdyn_amount: DevKit.WebApi.MoneyValue; msdyn_amount_after_tax: DevKit.WebApi.MoneyValueReadonly; /** Value of the amount_after_tax in base currency. */ msdyn_amount_after_tax_Base: DevKit.WebApi.MoneyValueReadonly; /** Value of the Amount in base currency. */ msdyn_amount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the project contract associated with this milestone. */ msdyn_contract: DevKit.WebApi.LookupValue; /** (Deprecated) Shows the project contract line that has this milestone */ msdyn_ContractLine: DevKit.WebApi.StringValue; /** Enter a description of the project contract line that has this milestone. */ msdyn_ContractLineDescription: DevKit.WebApi.StringValue; /** Unique identifier for Project Contract Line associated with Project Contract Line Invoice Schedule. */ msdyn_ContractLineId: DevKit.WebApi.LookupValue; /** Unique identifier for entity instances */ msdyn_contractlinescheduleofvalueId: DevKit.WebApi.GuidValue; /** Type a description of the milestone. */ msdyn_description: DevKit.WebApi.StringValue; /** Description of the project contract line milestone */ msdyn_externaldescription: DevKit.WebApi.StringValue; /** Enter the date of which this milestone should be achieved */ msdyn_Invoicedate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Select the status of invoicing of this milestone */ msdyn_Invoicestatus: DevKit.WebApi.OptionSetValue; /** Type the name of the milestone. */ msdyn_name: DevKit.WebApi.StringValue; /** Enter the price of the transaction. */ msdyn_price: DevKit.WebApi.MoneyValue; /** Value of the Price in base currency. */ msdyn_price_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the project that is tracking the work required to achieve this milestone. */ msdyn_project: DevKit.WebApi.LookupValue; /** Select the project work breakdown structure (WBS) task that is tracking the work for this milestone. */ msdyn_projecttask: DevKit.WebApi.LookupValue; /** Date of project contract line milestone */ msdyn_startdatetime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_tax: DevKit.WebApi.MoneyValue; /** Value of the tax in base currency. */ msdyn_tax_Base: DevKit.WebApi.MoneyValueReadonly; /** Transaction classification of the project contract line milestone */ msdyn_TransactionClassification: DevKit.WebApi.OptionSetValue; /** Transaction type of the project contract line milestone */ msdyn_TransactionTypeCode: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the project contract line milestone. */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the project contract line milestone. */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_contractlinescheduleofvalue { enum msdyn_Invoicestatus { /** 192350002 */ Customer_invoice_created, /** 192350003 */ Customer_invoice_posted, /** 192350000 */ Not_Ready_for_invoicing, /** 192350001 */ Ready_for_invoicing } enum msdyn_TransactionClassification { /** 690970001 */ Additional, /** 690970000 */ Commission, /** 192350001 */ Expense, /** 192350004 */ Fee, /** 192350002 */ Material, /** 192350003 */ Milestone, /** 690970002 */ Tax, /** 192350000 */ Time } enum msdyn_TransactionTypeCode { /** 192350006 */ Billed_Sales, /** 192350000 */ Cost, /** 192350008 */ Inter_Organizational_Sales, /** 192350004 */ Project_Contract, /** 192350007 */ Resourcing_Unit_Cost, /** 192350005 */ Unbilled_Sales } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Project Information','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import nanoid from 'nanoid' import produce, {applyPatches, Patch, enablePatches, Draft} from 'immer' enablePatches() export const enum NodeStatus { Ready = 'Ready', Success = 'Success', Failure = 'Failure', Running = 'Running', } export const enum NodeType { Action = 'Action', Condition = 'Condition', Decorator = 'Decorator', Invert = 'Invert', Parallel = 'Parallel', Portal = 'Portal', Root = 'Root', Selector = 'Selector', Sequence = 'Sequence', State = 'State', } export const enum _StoreKey { Patches = '$patches', SequenceIndex = '$sequenceIndex', Status = '$status', Count = '$count', WasRun = '$wasRun', } export interface INodeState { [_StoreKey.Count]: number [_StoreKey.Status]: NodeStatus } export interface INodeTarget { addEventListener: ( type: 'tickstart' | 'tickend', listener: () => void ) => void removeEventListener: ( type: 'tickstart' | 'tickend', listener: () => void ) => void dispatchEvent: (event: CustomEvent) => boolean } export interface IRootNode<State, Props> extends IWithNodeState, INodeTarget { id: string name: string type: NodeType.Root state: State children: ICompositeNode<State, Props> tick: (props?: Props) => NodeStatus | undefined } export interface IConditionNode<State, Props> extends IWithNodeState { id: string name: string type: NodeType.Condition parent?: IAnyNode<State, Props> exec( args: { state: State node: IConditionNode<State, Props> root: IRootNode<State, Props> }, props: Props ): any } export interface IActionNode<State, Props> extends IWithNodeState { id: string name: string type: NodeType.Action fn: (state: State, props: Props) => void | Promise<void> parent?: IAnyNode<State, Props> } export interface IStateNode<State, Props> extends IWithNodeState { id: string type: NodeType.State parent?: IAnyNode<State, Props> children: IAnyChildNode<State, Props> state: any } export interface IPortalNode<State, Props> extends IWithNodeState { id: string type: NodeType.Portal parent?: IAnyNode<State, Props> children: Array<ICompositeNode<State, Props>> clear: () => IPortalNode<State, Props> mount: (children: ICompositeNode<State, Props>) => IPortalNode<State, Props> unmount: (children: ICompositeNode<State, Props>) => IPortalNode<State, Props> } export interface ISequenceNode<State, Props> extends IWithNodeState { id: string type: NodeType.Sequence parent?: IAnyNode<State, Props> children: IAnyChildNode<State, Props>[] } export interface IParallelNode<State, Props> extends IWithNodeState { id: string type: NodeType.Parallel parent?: IAnyNode<State, Props> children: IAnyChildNode<State, Props>[] } export interface ISelectorNode<State, Props> extends IWithNodeState { id: string type: NodeType.Selector parent?: IAnyNode<State, Props> children: IAnyChildNode<State, Props>[] } export interface IDecoratorNode<State, Props> extends IWithNodeState { id: string type: NodeType.Decorator parent?: IAnyNode<State, Props> decorator: (status: NodeStatus) => NodeStatus children: ILeafNode<State, Props> } export interface IInvertNode<State, Props> extends IWithNodeState { id: string type: NodeType.Invert parent?: IAnyNode<State, Props> children: IAnyChildNode<State, Props> } export type ICompositeNode<State, Props> = | ISelectorNode<State, Props> | ISequenceNode<State, Props> | IParallelNode<State, Props> | IDecoratorNode<State, Props> | IInvertNode<State, Props> | IPortalNode<State, Props> | IStateNode<State, Props> export type ILeafNode<State, Props> = | IActionNode<State, Props> | IConditionNode<State, Props> export type IAnyChildNode<State, Props> = | ICompositeNode<State, Props> | ILeafNode<State, Props> export type IAnyNode<State, Props> = | IRootNode<State, Props> | IAnyChildNode<State, Props> export interface IWithNodeState { $nodeState: INodeState /** * Get value form node state */ getValue: <T>(key: string, defaultValue?: T) => T /** * Set value in node state */ setValue: (key: string, value: any) => any } export type IOptions<Props> = { props?: Props setState: any } export const nodes = { root: function<State, Props>( name: string, childrenFactory: () => ICompositeNode<State, Props> ) { return ( initialState: State, options: IOptions<Props> = { props: {} as Props, setState: () => {}, } ): IRootNode<State, Props> => { const registrations: { [key: string]: Array<(event: CustomEvent) => void> } = {} const getListeners = function(type: string) { if (!(type in registrations)) registrations[type] = [] return registrations[type] } const root: IRootNode<State, Props> = { id: nanoid(), name, type: NodeType.Root, children: childrenFactory(), state: initialState, tick: function tick(props?: Props) { if (typeof window === 'undefined') { return undefined } this.dispatchEvent(new CustomEvent('tickstart')) const nodeStatus = _interpret(this.children, this, { ...options, props, }) _resetFinalStates(this.children, this) this.dispatchEvent(new CustomEvent('tickend')) return nodeStatus }, addEventListener: ( type: 'tickstart' | 'tickend', listener: () => void ) => { const listeners = getListeners(type) const index = listeners.indexOf(listener) if (index === -1) registrations[type].push(listener) }, removeEventListener: ( type: 'tickstart' | 'tickend', listener: () => void ) => { const listeners = getListeners(type) const index = listeners.indexOf(listener) if (index !== -1) registrations[type].splice(index, 1) }, dispatchEvent: (event: CustomEvent) => { var listeners = getListeners(event.type).slice() for (var i = 0; i < listeners.length; i++) listeners[i].call(this, event) return !event.defaultPrevented }, ...createNodeState(), } root.addEventListener = root.addEventListener.bind(root) root.removeEventListener = root.removeEventListener.bind(root) root.dispatchEvent = root.dispatchEvent.bind(root) root.tick = root.tick.bind(root) return root } }, /** * Runs child nodes in sequence until it finds one that succeeds. Succeeds when it finds the first child that succeeds. For child nodes that fail, it moves forward to the next child node. While a child is running it stays on that child node without moving forward. */ selector: function<State, Props>( children: IAnyChildNode<State, Props>[] ): ISelectorNode<State, Props> { return { id: nanoid(), type: NodeType.Selector, children, ...createNodeState(), } }, /** * Runs each child node one by one. Fails for the first child node that fails. Moves to the next child when the current running child succeeds. Stays on the current child node while it returns running. Succeeds when all child nodes have succeeded. */ sequence: function<State, Props>( children: IAnyChildNode<State, Props>[] ): ISequenceNode<State, Props> { return { id: nanoid(), type: NodeType.Sequence, children, ...createNodeState({ [_StoreKey.SequenceIndex]: 0, }), } }, /** * Runs all child nodes in parallel. Continues to run until a required number of child nodes have either failed or succeeded. */ parallel: function<State, Props>( children: IAnyChildNode<State, Props>[] ): IParallelNode<State, Props> { return { id: nanoid(), type: NodeType.Parallel, children, ...createNodeState(), } }, condition: function<State, Props>( name: string, fn?: (state: State, props: Props) => any ): IConditionNode<State, Props> { return { id: nanoid(), name, type: NodeType.Condition, exec: (args, props) => { if (typeof fn === 'function') { return fn(args.state, props) } else { return true } }, ...createNodeState(), } }, portal: function<State, Props>(): IPortalNode<State, Props> { return { id: nanoid(), type: NodeType.Portal, children: [], ...createNodeState(), clear: function() { this.children.splice(0, this.children.length) return this }, mount: function(children: ICompositeNode<State, Props>) { if (this.children.find(item => item.id === children.id)) return this this.children.push(children) return this }, unmount: function(children: ICompositeNode<State, Props>) { const index = this.children.findIndex(item => item.id === children.id) this.children.splice(index, 1) return this }, } }, state: function<State, Props>( state: any, children: IAnyChildNode<State, Props> ): IStateNode<State, Props> { return { id: nanoid(), type: NodeType.State, children, state, ...createNodeState(), } }, invert: function<State, Props>( children: IAnyChildNode<State, Props> ): IInvertNode<State, Props> { return { id: nanoid(), type: NodeType.Invert, children, ...createNodeState(), } }, action: function<State, Props>( name: string, fn: (state: State, props: Props) => void ): IActionNode<State, Props> { return { id: nanoid(), name, type: NodeType.Action, fn, ...createNodeState(), } }, } function _resetFinalStates<State, Props>( node: IAnyNode<State, Props>, root: IRootNode<State, Props> ) { switch (node.type) { case NodeType.Action: if (!node.getValue(_StoreKey.WasRun)) { node.setValue(_StoreKey.Status, NodeStatus.Ready) } break case NodeType.Portal: case NodeType.Invert: case NodeType.Parallel: case NodeType.Sequence: case NodeType.Selector: { // TODO: Clean up this logic const children = Array.isArray(node.children) ? node.children : [node.children] const hasRunningChildren = children.some( item => item.getValue(_StoreKey.Status) === NodeStatus.Running ) const isSequence = node.type === NodeType.Sequence const hasSequenceFinished = isSequence ? node.getValue<number>(_StoreKey.SequenceIndex) + 1 === children.length || node.getValue(_StoreKey.WasRun) === false : true if (!hasRunningChildren && hasSequenceFinished) { node.setValue(_StoreKey.Status, NodeStatus.Ready) if (node.type === NodeType.Sequence) { node.setValue(_StoreKey.SequenceIndex, 0) } children.forEach(item => { item.setValue(_StoreKey.Status, NodeStatus.Ready) }) } for (let i = 0; i < children.length; i++) { _resetFinalStates(children[i], root) } break } default: break } node.setValue(_StoreKey.WasRun, false) } function _interpret<State, Props>( node: IAnyNode<State, Props>, root: IRootNode<State, Props>, options: IOptions<Props> = { props: {} as Props, setState: () => {}, } ): NodeStatus { const {state} = root node.setValue(_StoreKey.WasRun, true) switch (node.type) { case NodeType.Action: { const status = node.getValue<NodeStatus>(_StoreKey.Status) // This is an async action if (status === NodeStatus.Running) { const patches = node.getValue<Patch[]>(_StoreKey.Patches) // If patches is not undefined then action has resolved and we can apply it's result to current state if (patches) { // Apply patches to current state const nextState = applyPatches(state, patches) // Reset patches array node.setValue(_StoreKey.Patches, undefined) node.setValue(_StoreKey.Status, NodeStatus.Success) root.state = nextState options.setState?.(nextState) root.tick(options.props) return NodeStatus.Success } return status } bump(node) const nextState = produce( state, draft => node.fn(draft as State, options.props || ({} as Props)), patches => { node.setValue(_StoreKey.Patches, patches) if (isPromise(nextState)) { root.tick() } } ) if (isPromise(nextState)) { node.setValue(_StoreKey.Status, NodeStatus.Running) return NodeStatus.Running } // TODO: Handle errors(failure status) root.state = nextState as State options.setState?.(nextState) node.setValue(_StoreKey.Status, NodeStatus.Success) return NodeStatus.Success } case NodeType.Condition: { bump(node) node.setValue(_StoreKey.Status, NodeStatus.Running) if ( node.exec( { state, node, root, }, options.props || ({} as Props) ) ) { node.setValue(_StoreKey.Status, NodeStatus.Success) return NodeStatus.Success } else { node.setValue(_StoreKey.Status, NodeStatus.Failure) return NodeStatus.Failure } } case NodeType.Invert: { bump(node) node.setValue(_StoreKey.Status, NodeStatus.Running) const status = _interpret(node.children, root, options) if (status === NodeStatus.Failure) { node.setValue(_StoreKey.Status, NodeStatus.Success) return NodeStatus.Success } if (status === NodeStatus.Success) { node.setValue(_StoreKey.Status, NodeStatus.Failure) return NodeStatus.Failure } return status } case NodeType.State: { bump(node) return _interpret(node.children, root, options) } case NodeType.Decorator: { bump(node) return node.decorator(_interpret(node.children, root, options)) } case NodeType.Portal: case NodeType.Parallel: { bump(node) node.setValue(_StoreKey.Status, NodeStatus.Running) let states = [] for (let i = 0; i < node.children.length; i++) { node.children[i].parent = node states[i] = _interpret(node.children[i], root, options) } // TODO: Make this a prop const nSuccess = states.filter(status => status === NodeStatus.Success) .length // TODO: Make this a prop const nFailure = states.filter(status => status === NodeStatus.Failure) .length if (nSuccess === node.children.length) { node.setValue(_StoreKey.Status, NodeStatus.Success) return NodeStatus.Success } else if (nFailure === node.children.length) { node.setValue(_StoreKey.Status, NodeStatus.Failure) return NodeStatus.Failure } node.setValue(_StoreKey.Status, NodeStatus.Running) return NodeStatus.Running } case NodeType.Sequence: { bump(node) node.setValue(_StoreKey.Status, NodeStatus.Running) let index = node.getValue<number>(_StoreKey.SequenceIndex, 0) while (index < node.children.length) { const child = node.children[index] child.parent = node const status = _interpret(child, root, options) if (status === NodeStatus.Success) { node.setValue(_StoreKey.SequenceIndex, ++index) continue } else if (status === NodeStatus.Running) { node.setValue(_StoreKey.Status, NodeStatus.Running) return NodeStatus.Running } else if (status === NodeStatus.Failure) { node.setValue(_StoreKey.SequenceIndex, 0) node.setValue(_StoreKey.Status, NodeStatus.Failure) return NodeStatus.Failure } } node.setValue(_StoreKey.SequenceIndex, 0) node.setValue(_StoreKey.Status, NodeStatus.Success) return NodeStatus.Success } case NodeType.Selector: { bump(node) node.setValue(_StoreKey.Status, NodeStatus.Running) for (const child of node.children) { child.parent = node const status = _interpret(child, root, options) if (status === NodeStatus.Success || status === NodeStatus.Running) { node.setValue(_StoreKey.Status, status) return status } } node.setValue(_StoreKey.Status, NodeStatus.Failure) return NodeStatus.Failure } default: throw new Error('Invalid node type!') } } function bump(node: IAnyNode<any, any>) { const currentValue = node.getValue<number>(_StoreKey.Count, 0) node.setValue(_StoreKey.Count, currentValue + 1) } function createNodeState(customState?: any) { return { $nodeState: { [_StoreKey.Count]: 0, [_StoreKey.WasRun]: false, [_StoreKey.Status]: NodeStatus.Ready, ...customState, }, setValue(key: string, value: any) { this['$nodeState'][key] = value }, getValue<Value>(key: string, defaultValue?: any): Value { if (this['$nodeState'] === undefined) { return defaultValue === undefined ? undefined : defaultValue } return this['$nodeState'][key] === undefined ? defaultValue : this['$nodeState'][key] }, } } function isPromise(item: any): boolean { return item && typeof item.then === 'function' }
the_stack
import ccxt from "ccxt.pro"; import { Logger } from "tslog"; import { findPurchasedTokens, markPurchasedTokensAsInTrading } from "../coin-analysis/coin-analysis.service"; import { calculateServertimeDrift } from "../timesync/timesync.controller"; import { getWalletBalanceForERC20Token } from "../wallet/wallet.controller"; import { changeTokenStatus, findTokensByStatus, importTradeableToken /*sendToBinance*/ } from "./trading.service"; // import { getGasPrice } from "../apis/gasNow"; import isAfter from "date-fns/isAfter"; import sub from "date-fns/sub"; import { TradeableToken } from "./schemas/tradeable-token.schema"; import { LeanDocument } from "mongoose"; import { promisify } from "util"; const sleep = promisify(setTimeout); const log: Logger = new Logger(); const BINANCE_API_KEY = process.env.BINANCE_API_KEY || null; const BINANCE_API_SECRETKEY = process.env.BINANCE_API_SECRETKEY || null; // const BINANCE_WALLET_ADDRESS = process.env.BINANCE_WALLET_ADDRESS || null; const MY_ETHEREUM_ADDRESS = process.env.MY_ETHEREUM_ADDRESS || null; const TIME_TO_WAIT_BEFORE_SELLING = +process.env.TIME_TO_WAIT_BEFORE_SELLING || 1100; // const SEND_TO_BINANCE_GAS_MULTIPLIER = +process.env.SEND_TO_BINANCE_GAS_MULTIPLIER || 1.5; const TIME_TO_LEAVE_LIMIT_ORDER_ACTIVE = +process.env.TIME_TO_LEAVE_LIMIT_ORDER_ACTIVE || 150; const AMOUNT_OF_TOP_PRICES_TO_DISCARD = +process.env.AMOUNT_OF_TOP_PRICES_TO_DISCARD || 5; const exchangeClass = ccxt["binance"]; export const setupBinanceMarket = (): ccxt.binance => { const exchange = new exchangeClass({ apiKey: BINANCE_API_KEY, secret: BINANCE_API_SECRETKEY, timeout: 30000, enableRateLimit: true, newUpdates: true, }); // exchange.verbose = true; return exchange; }; export const processPurchasedTokens = async (): Promise<void | TradeableToken[]> => { const purchasedTokenList = await findPurchasedTokens(); if (purchasedTokenList.length === 0) { return Promise.resolve(); } //Immediately mark the purchased tokens as locked for further trading so they cannot be imported again await Promise.all( purchasedTokenList.map(async (token) => { return markPurchasedTokensAsInTrading(token.tokenCode); }) ); log.debug("Completed trading lock"); await Promise.all( purchasedTokenList.map(async (token) => { const walletBalanceInWei = await getWalletBalanceForERC20Token(token.tokenContract); if (walletBalanceInWei.eq(0) || !walletBalanceInWei) { log.error("Balance for erc20 token was 0"); return; } log.info(`Balance for erc20 token is ${walletBalanceInWei}`); return importTradeableToken({ tokenCode: token.tokenCode.toUpperCase(), tokenContract: token.tokenContract, tokenPairs: token.tokenPairs.map((pair) => pair.toUpperCase()), tradingStartDate: token.tradingStartDate, tokenAmountInWei: walletBalanceInWei, purchasePriceInWei: token.priceInWei, sellPriceInUSD: token.priceInWei.dividedBy(100000000).times(0.00000038).toNumber(), }); }) ); log.debug("Completed importing token to trading"); }; export const moveOwnedTokensToBinance = async (): Promise<void | LeanDocument<TradeableToken>[]> => { const ownedTokenList = await findTokensByStatus("purchased"); if (ownedTokenList.length === 0) { return Promise.resolve(); } await Promise.all( ownedTokenList.map((token) => { return changeTokenStatus(token.tokenCode, "sendingToBinance"); }) ); // const currentGasPrice = (await getGasPrice()).times(SEND_TO_BINANCE_GAS_MULTIPLIER); return Promise.all( ownedTokenList.map(async (token) => { try { // await sendToBinance({ // gasPrice: currentGasPrice, // myAddress: MY_ETHEREUM_ADDRESS, // binanceAddress: BINANCE_WALLET_ADDRESS, // tokenContract: token.tokenContract, // }); log.info("Tokens will manually be sent to binance"); return changeTokenStatus(token.tokenCode, "sentToBinance"); } catch (error) { log.error("Tokens transfer to binance failed. Reverting status to `purchased`"); log.trace(error); await changeTokenStatus(token.tokenCode, "purchased"); throw new Error(error); } }) ); }; export const checkIfBalanceIsAvailable = async (): Promise<void | (void | LeanDocument<TradeableToken>)[]> => { const tokenList = await findTokensByStatus("sentToBinance"); if (tokenList.length === 0) { // log.debug("No new tokens marked as pending arrival"); return Promise.resolve(); } const exchange = setupBinanceMarket(); const balances = await exchange.fetchBalance(); return Promise.all( tokenList.map(async (token) => { // log.debug(token); const availableBalance = balances.free[token.tokenCode]; if (availableBalance && availableBalance > 0) { log.info( `Balance of ${availableBalance} $${token.tokenCode} have been detected on Binance. Marking as Available.` ); return changeTokenStatus(token.tokenCode, "availableOnBinance"); } log.debug(`Waiting for ${token.tokenCode} to arrive on binance`); return Promise.resolve(); }) ); }; export const waitForTradingStartDate = async (): Promise<(void | LeanDocument<TradeableToken>)[]> => { const tokenList = await findTokensByStatus("availableOnBinance"); if (tokenList.length === 0) { return; } return Promise.all( tokenList.map(async (token) => { const triggerDate = sub(new Date(token.tradingStartDate), { minutes: 5, }); if (isAfter(new Date(), triggerDate)) { log.debug(`Trigger date: ${triggerDate.toISOString()}`); log.debug(`Current date: ${new Date().toISOString()}`); log.info("Trading is starting soon. Marking as ready for trading"); return changeTokenStatus(token.tokenCode, "readyForTrading"); } log.info("Waiting for trading to begin...."); return Promise.resolve(); }) ); }; export const initiateTrade = async (): Promise<void[]> => { const tokenList = await findTokensByStatus("readyForTrading"); if (tokenList.length === 0) { Promise.resolve(); } //Immediately mark the purchased as locked for further trading so it cannot be imported again await Promise.all( tokenList.map((token) => { return changeTokenStatus(token.tokenCode, "inTrading"); }) ); return Promise.all( tokenList.map(async (token) => { const tradingPairs = []; const busdPair = token.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("busd"); }); if (busdPair && busdPair[0]) { tradingPairs.push(busdPair[0]); } const usdtPair = token.tokenPairs.filter((tokenPair) => { return tokenPair.toLowerCase().includes("usdt"); }); if (usdtPair && usdtPair[0]) { tradingPairs.push(usdtPair[0]); } return sellAvailableTokens(token.tokenCode, tradingPairs); }) ); }; export const moveFundsBackToWallet = async (): Promise<void[]> => { const soldTokenList = await findTokensByStatus("soldOnBinance"); if (soldTokenList.length === 0) { return; } await Promise.all( soldTokenList.map(async (token) => { return changeTokenStatus(token.tokenCode, "convertingOnBinance"); }) ); return Promise.all( soldTokenList.map(async (token) => { const exchange = setupBinanceMarket(); const markets = await exchange.loadMarkets(); const balances = await exchange.fetchBalance(); try { const availableBusd = balances.free["BUSD"]; log.info(`Available BUSD: ${availableBusd}`); log.info(`Minimum amount for ETH/BUSD pair is ${markets["ETH/BUSD"].limits.amount.min}`); const MinimumOrderSize = markets["ETH/BUSD"].limits.amount.min; const BusdEthPrice = (await exchange.fetchTicker("ETH/BUSD")).bid; const BusdEthAmount = (availableBusd / BusdEthPrice / 100) * 99.8; if (MinimumOrderSize > BusdEthAmount) { log.debug("Not enough BUSD available to purchase ETH"); } else { log.info(`Ethereum price: ${BusdEthPrice}, attempting to buy ${BusdEthAmount} ETH`); const BustSwapForEthOrder = await exchange.createMarketOrder("ETH/BUSD", "buy", BusdEthAmount); log.debug(BustSwapForEthOrder); } } catch (error) { log.error(error); } try { const availableUsdt = balances.free["USDT"]; log.info(`Available USDT: ${availableUsdt}`); log.info(`Minimum amount for ETH/USDT pair is ${markets["ETH/USDT"].limits.amount.min}`); const MinimumOrderSize = markets["ETH/USDT"].limits.amount.min; const UsdtEthPrice = (await exchange.fetchTicker("ETH/USDT")).bid; const UsdtEthAmount = (availableUsdt / UsdtEthPrice / 100) * 99.8; if (MinimumOrderSize > UsdtEthAmount) { log.debug("Not enough USDT available to purchase ETH"); } else { log.info(`Ethereum price: ${UsdtEthAmount}, attempting to buy ${UsdtEthAmount} ETH`); const UsdtSwapForEthOrder = await exchange.createMarketOrder("ETH/USDT", "buy", UsdtEthAmount); log.debug(UsdtSwapForEthOrder); } } catch (error) { log.error(error); } await changeTokenStatus(token.tokenCode, "convertedOnBinance"); const EthBalances = await exchange.fetchBalance(); const availableEth = EthBalances.free["ETH"]; log.info(`Available ETH: ${availableEth}`); log.info(`Eth balance available: ${availableEth}`); if (MY_ETHEREUM_ADDRESS) { log.info(`Waiting 70 seconds to withdraw`); await sleep(70000); log.debug("Withdrawing..."); try { const withdrawOrder = await exchange.withdraw("ETH", availableEth, MY_ETHEREUM_ADDRESS); log.debug(withdrawOrder); } catch (error) { log.error(error); } } await changeTokenStatus(token.tokenCode, "withdrawnFromBinance"); }) ); }; //watch stream for random period beteween 1.1 and 1.2 seconds //get highest price from this period const sellAvailableTokens = async (tokenCode: string, tradingPairs: string[]): Promise<void> => { log.debug(tokenCode); log.debug(tradingPairs); const exchange = setupBinanceMarket(); await exchange.loadMarkets(); let timeToSell: number; const pricesPerPair = {}; let sold = false; let sellLock = false; let firstTrade = true; let marketsPromise; const balances = await exchange.fetchBalance(); const availableBalanceToSell = balances.free[tokenCode]; log.debug(`Available for sale: ${availableBalanceToSell}`); log.debug("Measuring server latency..."); const serverTimeDrift = await calculateServertimeDrift(); log.debug(serverTimeDrift); log.debug(`Waiting for events from Binance Websocket...`); let priceLog = ""; await Promise.all( tradingPairs.map((tradingPair) => (async () => { while (!sold && !sellLock) { try { // log.debug(`Trading pair to execute against is: ${tradingPair}`); const newTrades = await exchange.watchTrades(tradingPair); newTrades.forEach(async (trade) => { if (!pricesPerPair[tradingPair]) { pricesPerPair[tradingPair] = []; } if (sellLock) { return; } if (!trade?.price || !trade?.timestamp) { return; } if (!timeToSell) { timeToSell = calculateTimeToSell(trade.timestamp, serverTimeDrift); } if (firstTrade) { firstTrade = false; marketsPromise = exchange.loadMarkets(true); } pricesPerPair[tradingPair].push(trade.price); priceLog += `New price price for ${tradingPair}: ${trade.price}\n`; if (trade.timestamp >= timeToSell) { if (sold || sellLock) { return; } sellLock = true; log.debug(`Initiating sale of ${tokenCode}`); let highestPriceOfAll = 0; let tradingPairWithHighestPrice; for (const pair in pricesPerPair) { const uniquePairPrices = [...new Set(pricesPerPair[pair])]; const currentHighestPrice = uniquePairPrices .sort((a: number, b: number) => b - a) .splice( uniquePairPrices.length > AMOUNT_OF_TOP_PRICES_TO_DISCARD ? AMOUNT_OF_TOP_PRICES_TO_DISCARD : 0 )[0] as number; if (highestPriceOfAll < currentHighestPrice) { highestPriceOfAll = currentHighestPrice; tradingPairWithHighestPrice = pair; } if (!currentHighestPrice) { console.warn(`${uniquePairPrices}`); throw new Error(`currentHighestPrice is invalid, ${currentHighestPrice}`); } log.info(`Highest price on ${pair} was ${currentHighestPrice}`); } log.info( `Highest price of all was ${highestPriceOfAll} on ${tradingPairWithHighestPrice}` ); await changeTokenStatus(tokenCode, "sellingInProgress"); await marketsPromise; log.warn("markets loaded"); await sellItAll( exchange, tradingPairWithHighestPrice, availableBalanceToSell, highestPriceOfAll, tokenCode ); await changeTokenStatus(tokenCode, "soldOnBinance"); log.debug(`Sale of ${tokenCode} complete`); log.info(priceLog); sold = true; } }); } catch (e) { log.error(tradingPair, e); // do nothing and retry on next loop iteration } } })() ) ); log.debug("Sale process complete"); return Promise.resolve(); }; const sellItAll = async (exchange: ccxt.binance, tokenPair, amount, price, tokenCode): Promise<boolean> => { log.debug(`Limit Sell order arguments:`); log.debug({ tokenPair, amount, price }); //set a limit order for the current highest price let limitOrder; try { limitOrder = await exchange.createLimitOrder(tokenPair, "sell", amount, 74); } catch (error) { console.error(error.code); if (error && error.code && error.code && error.code !== -1013) { throw new Error(error); } log.warn("Not enough balance to execute limit order"); } await sleep(TIME_TO_LEAVE_LIMIT_ORDER_ACTIVE); log.debug(`Limit Sell order:`); log.debug(limitOrder); // If we still have unsold tokens, cancel limit order and market sell try { if (limitOrder?.remaining > 0) { await exchange.cancelOrder(limitOrder.id, tokenPair); const marketSellOrder = await exchange.createMarketOrder(tokenPair, "sell", limitOrder.remaining); await sleep(100); log.debug(`Market Sell order:`); log.debug(marketSellOrder); if (marketSellOrder.status === "closed") { return true; } throw new Error("Market Sell order not in correct state"); } await exchange.createMarketOrder(tokenPair, "sell", limitOrder.remaining); return true; } catch (error) { const markets = await exchange.loadMarkets(); const minimumTradeableToken = markets[tokenPair]?.limits?.amount?.min; const balances = await exchange.fetchBalance(); const availableBalance = balances.free[tokenCode]; log.warn(`Available: ${availableBalance} , minimum: ${minimumTradeableToken}`); log.trace(error); } }; //determine how long to wait before selling const calculateTimeToSell = (firstTradeTimestamp, driftData): number => { const { latency } = driftData; const timeToSell = firstTradeTimestamp + TIME_TO_WAIT_BEFORE_SELLING - latency; return timeToSell; };
the_stack
import { Injectable, InjectionToken, Inject, Optional } from '@angular/core'; import { StripeCaller } from './stripe-caller'; import type { StripeConstructor, StripeConstructorOptions, StripeError, PaymentIntent, PaymentMethod, PaymentRequest, PaymentRequestOptions, SetupIntent, Token, TokenCreateParams, Source, RedirectToCheckoutOptions, ConfirmAlipayPaymentData, ConfirmAlipayPaymentOptions, ConfirmAuBecsDebitPaymentData, ConfirmBancontactPaymentData, ConfirmBancontactPaymentOptions, ConfirmCardPaymentData, ConfirmCardPaymentOptions, ConfirmEpsPaymentData, ConfirmEpsPaymentOptions, ConfirmFpxPaymentData, ConfirmFpxPaymentOptions, ConfirmGiropayPaymentData, ConfirmGiropayPaymentOptions, ConfirmIdealPaymentData, ConfirmIdealPaymentOptions, ConfirmP24PaymentData, ConfirmP24PaymentOptions, ConfirmSepaDebitPaymentData, CreatePaymentMethodData, ConfirmAuBecsDebitSetupData, ConfirmBacsDebitSetupData, ConfirmCardSetupData, ConfirmCardSetupOptions, ConfirmSepaDebitSetupData, StripeIbanElement, CreateTokenIbanData, StripeCardElement, StripeCardNumberElement, CreateTokenCardData, CreateTokenPiiData, CreateTokenBankAccountData, StripeCardCvcElement, StripeElement, CreateSourceData, RetrieveSourceParam } from '@stripe/stripe-js'; /** Stripe Public Key token */ export const STRIPE_PUBLIC_KEY = new InjectionToken<string>('wizdm.stripe.public-key'); /** Stripe Options token */ export const STRIPE_OPTIONS = new InjectionToken<StripeConstructorOptions>('wizdm.stripe.options'); /** Stripe constructor token */ export const STRIPEJS = new InjectionToken<Promise<StripeConstructor>>('wizdm.stripe.constructor'); /** Stripe.js Injectale proxy service for Angular */ /** @dynamic - tells ngc to ignore the error on potentially unknown types generated by strictEmitMetadata: true */ @Injectable() export class StripeService extends StripeCaller { ///////////////////////////// /// Checkout /// /// https://stripe.com/docs/js/checkout ///////////////////////////// /** * Use `stripe.redirectToCheckout` to redirect your customers to [Checkout](https://stripe.com/docs/payments/checkout), a Stripe-hosted page to securely collect payment information. * When the customer completes their purchase, they are redirected back to your website. */ public redirectToCheckout(options: RedirectToCheckoutOptions): Promise<never | {error: StripeError}> { return this.callStripe('redirectToCheckout', arguments); } ///////////////////////////// /// Payment Intents /// /// https://stripe.com/docs/js/payment_intents ///////////////////////////// /** * Use `stripe.confirmAlipayPayment` in the [Alipay Payments](https://stripe.com/docs/payments/alipay) with Payment Methods flow when the customer submits your payment form. * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide, and it will automatically redirect the customer to authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new PaymentMethod for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment */ public confirmAlipayPayment(clientSecret: string, data?: ConfirmAlipayPaymentData, options?: ConfirmAlipayPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmAlipayPayment', arguments); } /** * Requires beta access: * Contact [Stripe support](https://support.stripe.com/) for more information. * * Use `stripe.confirmAuBecsDebitPayment` in the [BECS Direct Debit Payments](https://stripe.com/docs/payments/payment-methods/au-becs-debit) with Payment Methods flow when the customer submits your payment form. * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. * Note that there are some additional requirements to this flow that are not covered in this reference. * Refer to our [integration guide](https://stripe.com/docs/payments/payment-methods/au-becs-debit-quickstart-payment-intents) for more details. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new PaymentMethod for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_au_becs_debit_payment */ public confirmAuBecsDebitPayment(clientSecret: string, data?: ConfirmAuBecsDebitPaymentData): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmAuBecsDebitPayment', arguments); } /** * Use `stripe.confirmBancontactPayment` in the [Bancontact Payments with Payment Methods](https://stripe.com/docs/payments/bancontact#web) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_bancontact_payment */ public confirmBancontactPayment(clientSecret: string, data?: ConfirmBancontactPaymentData, options?: ConfirmBancontactPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmBancontactPayment', arguments); } /** * Use `stripe.confirmCardPayment` when the customer submits your payment form. * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide and carry out 3DS or other next actions if they are required. * * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * It can also be called with an existing `PaymentMethod`, or if you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment */ public confirmCardPayment(clientSecret: string, data?: ConfirmCardPaymentData, options?: ConfirmCardPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmCardPayment', arguments); }; /** * Use `stripe.confirmEpsPayment` in the [EPS Payments with Payment Methods](https://stripe.com/docs/payments/eps#web) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_eps_payment */ public confirmEpsPayment(clientSecret: string, data?: ConfirmEpsPaymentData, options?: ConfirmEpsPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmEpsPayment', arguments); } /** * Use `stripe.confirmFpxPayment` in the [FPX Payments with Payment Methods](https://stripe.com/docs/payments/fpx#web) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_fpx_payment */ public confirmFpxPayment(clientSecret: string, data?: ConfirmFpxPaymentData, options?: ConfirmFpxPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmFpxPayment', arguments); } /** * Use `stripe.confirmGiropayPayment` in the [giropay Payments with Payment Methods](https://stripe.com/docs/payments/giropay#web) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_giropay_payment */ public confirmGiropayPayment(clientSecret: string, data?: ConfirmGiropayPaymentData, options?: ConfirmGiropayPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmGiropayPayment', arguments); } /** * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment */ public confirmIdealPayment(clientSecret: string, data?: ConfirmIdealPaymentData, options?: ConfirmIdealPaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmGiropayPayment', arguments); } /** * Use `stripe.confirmP24Payment` in the [Przelewy24 Payments with Payment Methods](https://stripe.com/docs/payments/p24#web) flow when the customer submits your payment form. * When called, it will confirm the `PaymentIntent` with `data` you provide, and it will automatically redirect the customer to the authorize the transaction. * Once authorization is complete, the customer will be redirected back to your specified `return_url`. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_p24_payment */ public confirmP24Payment(clientSecret: string, data?: ConfirmP24PaymentData, options?: ConfirmP24PaymentOptions): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmP24Payment', arguments); } /** * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit) with Payment Methods flow when the customer submits your payment form. * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. * Note that there are some additional requirements to this flow that are not covered in this reference. * Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit) for more details. * * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new PaymentMethod for you. * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment */ public confirmSepaDebitPayment(clientSecret: string, data?: ConfirmSepaDebitPaymentData): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('confirmSepaDebitPayment', arguments); } /** * Use `stripe.handleCardAction` in the Payment Intents API [manual confirmation](https://stripe.com/docs/payments/payment-intents/web-manual) flow to handle a [PaymentIntent](https://stripe.com/docs/api/payment_intents) with the `requires_action` status. * It will throw an error if the `PaymentIntent` has a different status. * * Note that `stripe.handleCardAction` may take several seconds to complete. * During that time, you should disable your form from being resubmitted and show a waiting indicator like a spinner. * If you receive an error result, you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator. * * Additionally, `stripe.handleCardAction` may trigger a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication challenge. * The authentication challenge requires a context switch that can be hard to follow on a screen-reader. * Ensure that your form is accessible by ensuring that success or error messages are clearly read out. * * @docs https://stripe.com/docs/js/payment_intents/handle_card_action */ public handleCardAction(clientSecret: string): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('handleCardAction', arguments); } /** * Use stripe.createPaymentMethod to convert payment information collected by elements into a [PaymentMethod](https://stripe.com/docs/api/payment_methods) object that you safely pass to your server to use in an API call. * * @docs https://stripe.com/docs/js/payment_intents/create_payment_method */ public createPaymentMethod(paymentMethodData: CreatePaymentMethodData): Promise<{paymentMethod?: PaymentMethod; error?: StripeError}> { return this.callStripe('createPaymentMethod', arguments); } /** * Retrieve a [PaymentIntent](https://stripe.com/docs/api/payment_intents) using its [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret). * * @docs https://stripe.com/docs/js/payment_intents/retrieve_payment_intent */ public retrievePaymentIntent(clientSecret: string): Promise<{paymentIntent?: PaymentIntent; error?: StripeError}> { return this.callStripe('retrievePaymentIntent', arguments); } ///////////////////////////// /// Setup Intents /// /// https://stripe.com/docs/js/setup_intents ///////////////////////////// /** * Requires beta access: * Contact [Stripe support](https://support.stripe.com/) for more information. * * Use `stripe.confirmAuBecsDebitSetup` in the [BECS Direct Debit with Setup Intents](https://stripe.com/docs/payments/payment-methods/au-becs-debit-quickstart-setup-intents) flow when the customer submits your payment form. * When called, it will confirm the `SetupIntent` with `data` you provide. * Note that there are some additional requirements to this flow that are not covered in this reference. * Refer to our [integration guide](https://stripe.com/docs/payments/payment-methods/au-becs-debit-quickstart-setup-intents) for more details. * * When you confirm a `SetupIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `SetupIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * It can also be called with an existing `PaymentMethod`, or if you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/setup_intents/confirm_au_becs_debit_setup */ public confirmAuBecsDebitSetup(clientSecret: string, data?: ConfirmAuBecsDebitSetupData): Promise<{setupIntent?: SetupIntent; error?: StripeError}> { return this.callStripe('confirmAuBecsDebitSetup', arguments); } /** * Use `stripe.confirmBacsDebitSetup` in the [Bacs Direct Debit Payments](https://stripe.com/docs/payments/payment-methods/bacs-debit) flow when the customer submits your payment form. * When called, it will confirm the [SetupIntent](https://stripe.com/docs/api/setup_intents) with `data` you provide. * Note that there are some additional requirements to this flow that are not covered in this reference. * Refer to our [integration guide](https://stripe.com/docs/payments/payment-methods/bacs-debit) for more details. * * When you confirm a `SetupIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `SetupIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * It can also be called with an existing `PaymentMethod`, or if you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * These use cases are detailed in the sections that follow. * * @docs https://stripe.com/docs/js/setup_intents/confirm_bacs_debit_setup */ public confirmBacsDebitSetup(clientSecret: string, data?: ConfirmBacsDebitSetupData): Promise<{setupIntent?: SetupIntent; error?: StripeError}> { return this.callStripe('confirmBacsDebitSetup', arguments); } /** * Use `stripe.confirmCardSetup` in the [Setup Intents API flow](https://stripe.com/docs/payments/save-and-reuse) when the customer submits your payment form. * When called, it will confirm the [SetupIntent](https://stripe.com/docs/api/setup_intents) with `data` you provide and carry out 3DS or other next actions if they are required. * * When you confirm a `SetupIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `SetupIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * It can also be called with an existing `PaymentMethod`, or if you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/setup_intents/confirm_card_setup */ public confirmCardSetup(clientSecret: string, data?: ConfirmCardSetupData, options?: ConfirmCardSetupOptions): Promise<{setupIntent?: SetupIntent; error?: StripeError}> { return this.callStripe('confirmCardSetup', arguments); } /** * Use `stripe.confirmSepaDebitSetup` in the [SEPA Direct Debit with Setup Intents](https://stripe.com/docs/payments/sepa-debit-setup-intents) flow when the customer submits your payment form. * When called, it will confirm the `SetupIntent` with `data` you provide. * Note that there are some additional requirements to this flow that are not covered in this reference. * Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit-setup-intents) for more details. * * When you confirm a `SetupIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods). * In addition to confirming the `SetupIntent`, this method can automatically create and attach a new `PaymentMethod` for you. * It can also be called with an existing `PaymentMethod`, or if you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data. * * @docs https://stripe.com/docs/js/setup_intents/confirm_sepa_debit_setup */ public confirmSepaDebitSetup(clientSecret: string, data?: ConfirmSepaDebitSetupData): Promise<{setupIntent?: SetupIntent; error?: StripeError}> { return this.callStripe('confirmSepaDebitSetup', arguments); } /** * Retrieve a [SetupIntent](https://stripe.com/docs/api/setup_intents) using its client secret. * * @docs https://stripe.com/docs/js/setup_intents/retrieve_setup_intent */ public retrieveSetupIntent(clientSecret: string): Promise<{setupIntent?: SetupIntent; error?: StripeError}> { return this.callStripe('retrieveSetupIntent', arguments); } ///////////////////////////// /// Payment Request /// /// https://stripe.com/docs/js/payment_request ///////////////////////////// /** * Use `stripe.paymentRequest` to create a `PaymentRequest` object. * Creating a `PaymentRequest` requires that you configure it with an `options` object. * * In Safari, `stripe.paymentRequest` uses Apple Pay, and in other browsers it uses the [Payment Request API standard](https://www.w3.org/TR/payment-request/). */ public paymentRequest(options: PaymentRequestOptions): Promise<PaymentRequest> { return this.callStripe('paymentRequest', arguments); } ///////////////////////////// /// Token and Sources /// /// https://stripe.com/docs/js/tokens_sources ///////////////////////////// /** * Use `stripe.createToken` to convert information collected by an `IbanElement` into a single-use [Token](https://stripe.com/docs/api#tokens) that you safely pass to your server to use in an API call. * * @docs https://stripe.com/docs/js/tokens_sources/create_token?type=ibanElement */ public createToken(tokenType: StripeIbanElement, data: CreateTokenIbanData): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to convert information collected by card elements into a single-use [Token](https://stripe.com/docs/api#tokens) that you safely pass to your server to use in an API call. * * @docs https://stripe.com/docs/js/tokens_sources/create_token?type=cardElement */ public createToken(tokenType: StripeCardElement | StripeCardNumberElement, data?: CreateTokenCardData): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to convert personally identifiable information (PII) into a single-use [Token](https://stripe.com/docs/api#tokens) for account identity verification. * * @docs https://stripe.com/docs/js/tokens_sources/create_token?type=pii */ public createToken(tokenType: 'pii', data: CreateTokenPiiData): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to convert bank account information into a single-use token that you safely pass to your server to use in an API call. * * @docs https://stripe.com/docs/js/tokens_sources/create_token?type=bank_account */ public createToken(tokenType: 'bank_account', data: CreateTokenBankAccountData): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to tokenize the recollected CVC for a saved card. * First, include the `cvc_update_beta_1` flag when creating an instance of the Stripe object. * Next, render an `CardCvcElement` to collect the data. * Then pass the `CardCvcElement` to `stripe.createToken` to tokenize the collected data. * * @docs https://stripe.com/docs/js/tokens_sources/create_token?type=bank_account */ public createToken(tokenType: 'cvc_update', element?: StripeCardCvcElement): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to create a single-use token that wraps a user’s legal entity information. * Use this when creating or updating a Connect account. * See the [account tokens documentation](https://stripe.com/docs/connect/account-tokens) to learn more. */ public createToken(tokenType: 'account', data: TokenCreateParams.Account): Promise<{token?: Token; error?: StripeError}>; /** * Use `stripe.createToken` to create a single-use token that represents the details for a person. * Use this when creating or updating persons associated with a Connect account. * See the [documentation](https://stripe.com/docs/connect/account-tokens) to learn more. */ public createToken(tokenType: 'person', data: TokenCreateParams.Person): Promise<{token?: Token; error?: StripeError}>; // createToken function implementation public createToken() { return this.callStripe('createToken', arguments); } /** * Use `stripe.createSource` to convert payment information collected by elements into a `Source` object that you safely pass to your server to use in an API call. * See the [Sources documentation](https://stripe.com/docs/sources) for more information about sources. */ public createSource(element: StripeElement, sourceData: CreateSourceData): Promise<{source?: Source; error?: StripeError}>; /** * Use `stripe.createSource` to convert raw payment information into a `Source` object that you safely pass to your server to use in an API call. * See the [Sources documentation](https://stripe.com/docs/sources) for more information about sources. */ public createSource(sourceData: CreateSourceData): Promise<{source?: Source; error?: StripeError}>; // createSource function implementation public createSource() { return this.callStripe('createSource', arguments); } /** * Retrieve a [Source](https://stripe.com/docs/api#sources) using its unique ID and client secret. * * @docs https://stripe.com/docs/js/tokens_sources/retrieve_source */ public retrieveSource(source: RetrieveSourceParam): Promise<{source?: Source; error?: StripeError}> { return this.callStripe('retrieveSource', arguments); } // Extends the StripeCaller base class enabling Stripe sdk proxy capabilities constructor(@Inject(STRIPEJS) stripejs: Promise<StripeConstructor>, @Inject(STRIPE_PUBLIC_KEY) publicKey: string, @Optional() @Inject(STRIPE_OPTIONS) options: StripeConstructorOptions) { super(stripejs, publicKey, options); } }
the_stack
'use strict'; var Analytics = require('../build').constructor; var analytics = require('../build'); var assert = require('proclaim'); var sinon = require('sinon'); var cookie = Analytics.cookie; var group = analytics.group(); var Group = group.Group; var memory = Analytics.memory; var store = Analytics.store; describe('group', function() { var cookieKey = group._options.cookie.key; var localStorageKey = group._options.localStorage.key; beforeEach(function() { group = new Group(); group.reset(); }); afterEach(function() { group.reset(); cookie.remove(cookieKey); store.remove(cookieKey); store.remove(localStorageKey); group.protocol = location.protocol; }); describe('()', function() { beforeEach(function() { cookie.set(cookieKey, 'gid'); store.set(localStorageKey, { trait: true }); }); it('should not reset group id and traits', function() { var group = new Group(); assert(group.id() === 'gid'); assert(group.traits().trait === true); }); it('id() should fallback to localStorage', function() { var group = new Group(); group.id('gid'); // delete the cookie. cookie.remove(cookieKey); // verify cookie is deleted. assert.equal(cookie.get(cookieKey), null); // verify id() returns the id even when cookie is deleted. assert.equal(group.id(), 'gid'); // verify cookie value is retored from localStorage. assert.equal(cookie.get(cookieKey), 'gid'); }); it('id() should not fallback to localStorage when localStorage fallback is disabled', function() { var group = new Group(); group.options({ localStorageFallbackDisabled: true }); group.id('gid'); // delete the cookie. cookie.remove(cookieKey); // verify cookie is deleted. assert.equal(cookie.get(cookieKey), null); // verify id() does not return the id when cookie is deleted. assert.equal(group.id(), null); }); }); describe('#id', function() { describe('when cookies are disabled', function() { beforeEach(function() { sinon.stub(cookie, 'get', function() {}); group = new Group(); }); afterEach(function() { cookie.get.restore(); }); it('should get an id from store', function() { store.set(cookieKey, 'id'); assert(group.id() === 'id'); }); it('should get an id when not persisting', function() { group.options({ persist: false }); group._id = 'id'; assert(group.id() === 'id'); }); it('should set an id to the store', function() { group.id('id'); assert(store.get(cookieKey) === 'id'); }); it('should set the id when not persisting', function() { group.options({ persist: false }); group.id('id'); assert(group._id === 'id'); }); it('should be null by default', function() { assert(group.id() === null); }); }); describe('when cookies and localStorage are disabled', function() { beforeEach(function() { sinon.stub(cookie, 'get', function() {}); store.enabled = false; group = new Group(); }); afterEach(function() { store.enabled = true; cookie.get.restore(); }); it('should get an id from the store', function() { memory.set(cookieKey, 'id'); assert(group.id() === 'id'); }); it('should get an id when not persisting', function() { group.options({ persist: false }); group._id = 'id'; assert(group.id() === 'id'); }); it('should set an id to the store', function() { group.id('id'); assert(memory.get(cookieKey) === 'id'); }); it('should set the id when not persisting', function() { group.options({ persist: false }); group.id('id'); assert(group._id === 'id'); }); it('should be null by default', function() { assert(group.id() === null); }); }); describe('when cookies are enabled', function() { it('should get an id from the cookie', function() { cookie.set(cookieKey, 'id'); assert(group.id() === 'id'); }); it('should get an id when not persisting', function() { group.options({ persist: false }); group._id = 'id'; assert(group.id() === 'id'); }); it('should set an id to the cookie', function() { group.id('id'); assert(cookie.get(cookieKey) === 'id'); }); it('should set the id when not persisting', function() { group.options({ persist: false }); group.id('id'); assert(group._id === 'id'); }); it('should be null by default', function() { assert(group.id() === null); }); }); }); describe('#properties', function() { it('should get properties', function() { store.set(localStorageKey, { property: true }); assert.deepEqual(group.properties(), { property: true }); }); it('should get a copy of properties', function() { store.set(localStorageKey, { property: true }); assert(group._traits !== group.properties()); }); it('should get properties when not persisting', function() { group.options({ persist: false }); group._traits = { property: true }; assert.deepEqual(group.properties(), { property: true }); }); it('should get a copy of properties when not persisting', function() { group.options({ persist: false }); group._traits = { property: true }; assert(group._traits !== group.properties()); }); it('should set properties', function() { group.properties({ property: true }); assert.deepEqual(store.get(localStorageKey), { property: true }); }); it('should set the id when not persisting', function() { group.options({ persist: false }); group.properties({ property: true }); assert.deepEqual(group._traits, { property: true }); }); it('should default properties to an empty object', function() { group.properties(null); assert.deepEqual(store.get(localStorageKey), {}); }); it('should default properties to an empty object when not persisting', function() { group.options({ persist: false }); group.properties(null); assert.deepEqual(group._traits, {}); }); it('should be an empty object by default', function() { assert.deepEqual(group.properties(), {}); }); }); describe('#options', function() { it('should get options', function() { var options = group.options(); assert(options === group._options); }); it('should set options with defaults', function() { group.options({ option: true }); assert.deepEqual(group._options, { option: true, persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }); }); }); describe('#save', function() { it('should save an id to a cookie', function() { group.id('id'); group.save(); assert(cookie.get(cookieKey) === 'id'); }); it('should save an id to localStorage', function() { group.id('id'); group.save(); assert(store.get(cookieKey) === 'id'); }); it('should not save an id to localStorage when localStorage fallback is disabled', function() { group.options({ localStorageFallbackDisabled: true }); group.id('id'); group.save(); assert.equal(store.get(cookieKey), null); }); it('should save properties to local storage', function() { group.properties({ property: true }); group.save(); assert.deepEqual(store.get(localStorageKey), { property: true }); }); it('shouldnt save if persist is false', function() { group.options({ persist: false }); group.id('id'); group.save(); assert(cookie.get(cookieKey) === null); }); }); describe('#logout', function() { it('should reset an id and properties', function() { group.id('id'); group.properties({ property: true }); group.logout(); assert(group.id() === null); assert.deepEqual(group.properties(), {}); }); it('should clear id in cookie', function() { group.id('id'); group.save(); group.logout(); assert(cookie.get(cookieKey) === null); }); it('should clear id in localStorage', function() { group.id('id'); group.save(); group.logout(); assert(store.get(cookieKey) === undefined); }); it('should clear traits in local storage', function() { group.properties({ property: true }); group.save(); group.logout(); assert(store.get(localStorageKey) === undefined); }); }); describe('#identify', function() { it('should save an id', function() { group.identify('id'); assert(group.id() === 'id'); assert(cookie.get(cookieKey) === 'id'); }); it('should save properties', function() { group.identify(null, { property: true }); assert(group.properties(), { property: true }); assert(store.get(localStorageKey), { property: true }); }); it('should save an id and properties', function() { group.identify('id', { property: true }); assert(group.id() === 'id'); assert.deepEqual(group.properties(), { property: true }); assert(cookie.get(cookieKey) === 'id'); assert.deepEqual(store.get(localStorageKey), { property: true }); }); it('should extend existing properties', function() { group.properties({ one: 1 }); group.identify('id', { two: 2 }); assert.deepEqual(group.properties(), { one: 1, two: 2 }); assert.deepEqual(store.get(localStorageKey), { one: 1, two: 2 }); }); it('shouldnt extend existing properties for a new id', function() { group.id('id'); group.properties({ one: 1 }); group.identify('new', { two: 2 }); assert.deepEqual(group.properties(), { two: 2 }); assert.deepEqual(store.get(localStorageKey), { two: 2 }); }); it('should reset properties for a new id', function() { group.id('id'); group.properties({ one: 1 }); group.identify('new'); assert.deepEqual(group.properties(), {}); assert.deepEqual(store.get(localStorageKey), {}); }); }); describe('#load', function() { it('should load an empty group', function() { group.load(); assert(group.id() === null); assert.deepEqual(group.properties(), {}); }); it('should load an id from a cookie', function() { cookie.set(cookieKey, 'id'); group.load(); assert(group.id() === 'id'); }); it('should load properties from local storage', function() { store.set(localStorageKey, { property: true }); group.load(); assert.deepEqual(group.properties(), { property: true }); }); }); });
the_stack
import { pipe } from 'rxjs'; import { pairwise, startWith, tap } from 'rxjs/operators'; import { ICompiledComponent } from '../engine/render'; import { IArrayChildRenderElement } from '../engine/render/Array'; import { IHTMLRenderElement, isHTMLRenderElement, } from '../engine/render/Static'; import { isArray } from '../helpers/isArray'; export function updateDomChildNodesPipe(target: Element) { const initialState = []; return pipe( startWith(initialState), pairwise(), tap( ([prevChildren, currChildren]: [ ICompiledComponent[], ICompiledComponent[], ]) => { const elementsThatMount: IHTMLRenderElement[] = []; // intial render // creates a fragment and appends the fragment to parent if (!prevChildren || !prevChildren.length) { const fragment = window.document.createDocumentFragment(); for (let currChild of currChildren) { if (currChild) { if (isArray(currChild)) { currChild.forEach((entry) => { if (entry) { fragment.appendChild( entry.renderElement.htmlElement, ); if (entry.renderElement.element$) { elementsThatMount.push( entry.renderElement, ); } } }); } else { fragment.appendChild(currChild.htmlElement); if (isHTMLRenderElement(currChild)) { elementsThatMount.push(currChild); } } } } target.appendChild(fragment); } else { // smart comparison and DOM update let insertBeforeNode: Element | Text = null; for (let i = currChildren.length - 1; i >= 0; i--) { const prevChild = prevChildren[i]; const currChild = currChildren[i]; if (prevChild == currChild) { if (!isArray(currChild)) { insertBeforeNode = currChild.htmlElement; } else if ( currChild.length && currChild[0].renderElement.htmlElement ) { insertBeforeNode = currChild[0].renderElement.htmlElement; } continue; } if (!isArray(prevChild) && !isArray(currChild)) { if (prevChild.htmlElement) { if (currChild.htmlElement) { target.replaceChild( currChild.htmlElement, prevChild.htmlElement, ); if (isHTMLRenderElement(currChild)) { elementsThatMount.push(currChild); } insertBeforeNode = currChild.htmlElement; } else { target.removeChild(prevChild.htmlElement); } continue; } if (currChild) { target.insertBefore( currChild.htmlElement, insertBeforeNode, ); insertBeforeNode = currChild.htmlElement; continue; } continue; } // array updates (-_-) // prevChild is array // remove all prev array elements, and add current child if (isArray(prevChild) && !isArray(currChild)) { prevChild.forEach((entry) => { target.removeChild( entry.renderElement.htmlElement, ); }); target.insertBefore( currChild.htmlElement, insertBeforeNode, ); insertBeforeNode = currChild.htmlElement; continue; } // currChild is array // remove prev element, and add array elements if (!isArray(prevChild) && isArray(currChild)) { target.removeChild(prevChild.htmlElement); if (!currChild.length) { continue; } const documentFragment = window.document.createDocumentFragment(); for (let j = 0; j < currChild.length; j++) { documentFragment.appendChild( currChild[j].renderElement.htmlElement, ); if ( isHTMLRenderElement( currChild[j].renderElement, ) ) { elementsThatMount.push( currChild[j].renderElement, ); } } target.insertBefore( documentFragment, insertBeforeNode, ); insertBeforeNode = currChild[0].renderElement.htmlElement; continue; } // array to array update // console.warn('suboptimal array update'); if (isArray(prevChild) && isArray(currChild)) { // store current array keys const currKeys = new Array(currChild.length).fill( void 0, ); // Try early exit if all elements are equal if (prevChild.length == currChild.length) { let arraysAreEqual = true; for ( let j = currChild.length - 1; j >= 0; j-- ) { if ( arraysAreEqual && (currChild[j].key !== prevChild[j].key || currChild[j].renderElement .htmlElement !== prevChild[j].renderElement .htmlElement) ) { arraysAreEqual = false; } // store current array keys currKeys[j] = currChild[j].key; } // early exit here if (arraysAreEqual) { continue; } } else { // store current array keys for ( let j = currChild.length - 1; j >= 0; j-- ) { currKeys[j] = currChild[j].key; } } const entriesThatStay: IArrayChildRenderElement[] = []; for (let j = prevChild.length - 1; j >= 0; j--) { if (!currKeys.includes(prevChild[j].key)) { target.removeChild( prevChild[j].renderElement.htmlElement, ); } else { entriesThatStay.unshift(prevChild[j]); } } let k = entriesThatStay.length - 1; for (let j = currChild.length - 1; j >= 0; j--) { if ( k >= 0 && currChild[j].key == entriesThatStay[k].key ) { if ( currChild[j].renderElement .htmlElement !== entriesThatStay[k].renderElement .htmlElement ) { target.replaceChild( currChild[j].renderElement .htmlElement, entriesThatStay[k].renderElement .htmlElement, ); if ( isHTMLRenderElement( currChild[j].renderElement, ) ) { elementsThatMount.push( currChild[j].renderElement, ); } } insertBeforeNode = currChild[j].renderElement.htmlElement; k--; continue; } try { target.insertBefore( currChild[j].renderElement.htmlElement, insertBeforeNode, ); if ( isHTMLRenderElement( currChild[j].renderElement, ) ) { elementsThatMount.push( currChild[j].renderElement, ); } } catch (e) { // TODO: atm there are cases when prev node // is absent on the DOM // possible reasons: // - it was replaced or wasnt added at all // - a key occures two or more times in the array console.error(e); } insertBeforeNode = currChild[j].renderElement.htmlElement; } for (; k >= 0; k--) { target.removeChild( entriesThatStay[k].renderElement .htmlElement, ); if ( isHTMLRenderElement( entriesThatStay[k].renderElement, ) ) { elementsThatMount.push( entriesThatStay[k].renderElement, ); } } continue; } } } elementsThatMount.forEach((el) => el.element$.next(el.htmlElement), ); }, ), ); }
the_stack
import React, { cloneElement, CSSProperties, MouseEvent, KeyboardEvent, TransitionEvent, Key, ReactNode, useContext, useEffect, useRef, useState, memo, useCallback } from 'react'; import classnames from 'classnames'; import ResizeObserver from 'resize-observer-polyfill'; import _ from 'lodash'; import { setTransform, isTransform3dSupported, getStyle, isVertical } from './utils'; import RefContext, { GetRef } from './RefContext'; import { Panes, TabBarPosition } from './shared'; import { prefixCls } from './style'; const noop = () => undefined; const warning = (skip: boolean, msg: string) => !skip && console.warn(msg); interface TabBarTabsNodeProps { activeKey: Key | null; panes: Panes; tabBarGutter?: number; tabBarPosition: TabBarPosition; direction: string; onTabClick: (activeKey: Key) => void; } const TabBarTabsNode = ({ activeKey, panes, tabBarGutter, tabBarPosition, direction, onTabClick = noop }: TabBarTabsNodeProps) => { const { saveRef } = useContext(RefContext); const rst: ReactNode[] = []; panes.forEach((pane, index) => { if (!pane) return; const key = pane.key; const paneProps = pane.pane.props; const className = classnames({ [`${prefixCls}-tab`]: 1, [`${prefixCls}-tab-active`]: activeKey === key, [`${prefixCls}-tab-disabled`]: paneProps.disabled }); const gutter = tabBarGutter && index === panes.length - 1 ? 0 : tabBarGutter; const marginProperty = direction === 'rtl' ? 'marginLeft' : 'marginRight'; const style = { [isVertical(tabBarPosition) ? 'marginBottom' : marginProperty]: gutter }; warning('tab' in paneProps, 'There must be `tab` property on children of Tabs.'); const node = ( <div className={className} key={key} style={style} {...(activeKey === key ? { ref: saveRef('activeTab') } : {})} {...(paneProps.disabled ? {} : { onClick: onTabClick.bind(this, key) })} > {paneProps.tab} </div> ); rst.push(node); }); return <div ref={saveRef('navTabsContainer')}>{rst}</div>; }; interface TabBarRootNodeInterface { className?: string; style?: CSSProperties; tabBarPosition?: TabBarPosition; children: ReactNode; extraContent?: ReactNode; onKeyDown?: (e: KeyboardEvent) => void; styleType: string; } const TabBarRootNode = ({ tabBarPosition = 'top', children, extraContent, onKeyDown = noop, styleType }: TabBarRootNodeInterface) => { const { saveRef = () => null } = useContext(RefContext); const cls = classnames( `${prefixCls}-bar`, `${prefixCls}-${tabBarPosition}-bar`, `${prefixCls}-styletype-${styleType}-bar` ); const topOrBottom = isVertical(tabBarPosition); const tabBarExtraContentStyle = topOrBottom ? { float: 'right' } : {}; const extraContentStyle = extraContent && React.isValidElement(extraContent) ? extraContent.props.style : {}; let newChildren = children; if (extraContent) { if (React.isValidElement(extraContent)) { extraContent = cloneElement(extraContent, { key: 'extra', style: { ...tabBarExtraContentStyle, ...extraContentStyle } }); } newChildren = topOrBottom ? ( <> {extraContent} {children} </> ) : ( <> {children} {extraContent} </> ); } return ( <div role="tablist" className={cls} tabIndex={0} ref={saveRef('root')} onKeyDown={onKeyDown}> {newChildren} </div> ); }; interface InkTabBarNodeProps { inkBarAnimated?: boolean; direction: string; tabBarPosition: TabBarPosition; styles?: { inkBar?: CSSProperties; }; panes: Panes; activeKey: Key | null; } function scrollInkBar(props: Pick<BarContext, 'getRef' | 'direction' | 'tabBarPosition'>) { const { getRef, direction, tabBarPosition } = props; const rootNode = getRef('root'); const wrapNode = getRef('nav') || rootNode; const inkBarNode = getRef('inkBar'); const activeTab = getRef('activeTab'); if (!inkBarNode || !wrapNode || !rootNode) return; const inkBarNodeStyle = inkBarNode.style; const display = !!activeTab; inkBarNodeStyle.display = display ? 'block' : 'none'; if (!display) return; if (activeTab) { const tabNode = activeTab; const transformSupported = isTransform3dSupported(inkBarNodeStyle); // Reset current style setTransform(inkBarNodeStyle, ''); inkBarNodeStyle.width = ''; inkBarNodeStyle.height = ''; inkBarNodeStyle.left = ''; inkBarNodeStyle.top = ''; inkBarNodeStyle.bottom = ''; inkBarNodeStyle.right = ''; if (isVertical(tabBarPosition)) { const top = tabNode.offsetTop; const height = tabNode.offsetHeight; if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`); inkBarNodeStyle.top = '0'; } else { inkBarNodeStyle.top = `${top}px`; } inkBarNodeStyle.height = `${height}px`; } else { let left = tabNode.offsetLeft; let width = tabNode.offsetWidth; // If tabNode width equal to wrapNode width when tabBarPosition is top or bottom // It means no css working, then ink bar should not have width until css is loaded // Fix https://github.com/ant-design/ant-design/issues/7564 if (width === rootNode.offsetWidth) { width = 0; } if (direction === 'rtl') { left = getStyle(tabNode, 'margin-left') - left; } // use 3d gpu to optimize render if (transformSupported) { setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`); } else { inkBarNodeStyle.left = `${left}px`; } inkBarNodeStyle.width = `${width}px`; } } } const InkTabBarNode = ({ panes, activeKey, tabBarPosition, inkBarAnimated = true, direction }: InkTabBarNodeProps) => { const { saveRef, getRef } = useContext(RefContext); const onResize = useCallback(() => { scrollInkBar({ getRef, tabBarPosition, direction }); }, [direction, getRef, tabBarPosition]); useEffect(() => { onResize(); }, [panes, activeKey, onResize]); useEffect(() => { const resizeObserver = new ResizeObserver(onResize); const containerNode = getRef('container'); if (containerNode) resizeObserver.observe(containerNode); return () => { if (resizeObserver) { resizeObserver.disconnect(); } }; }, [getRef, onResize]); const className = `${prefixCls}-ink-bar`; const classes = classnames(className, inkBarAnimated ? `${className}-animated` : `${className}-no-animated`); return <div className={classes} key="inkBar" ref={saveRef('inkBar')} />; }; const getOffsetWH = (node: HTMLElement | null, tabBarPosition: TabBarPosition) => { if (!node) return 0; if (isVertical(tabBarPosition)) { return node.offsetHeight; } return node.offsetWidth; }; const getScrollWH = (node: HTMLElement | null, tabBarPosition: TabBarPosition) => { if (!node) return 0; if (isVertical(tabBarPosition)) { return node.scrollHeight; } return node.scrollWidth; }; const getOffsetLT = (node: HTMLElement | null, tabBarPosition: TabBarPosition) => { if (!node) return 0; if (isVertical(tabBarPosition)) { return node.offsetTop; } return node.offsetLeft; }; interface BarContext { getCurrentOffset: () => number; setCurrentOffset: (offset: number) => void; currentOffset: number; tabBarPosition: TabBarPosition; direction?: string; getRef: GetRef; next: boolean; prev: boolean; } const setNavOffset = ( offset: number, context: Pick<BarContext, 'getRef' | 'currentOffset' | 'tabBarPosition' | 'direction'> ) => { const { currentOffset, getRef, tabBarPosition, direction } = context; const navNode = getRef('nav'); const navTabsContainer = getRef('navTabsContainer'); const navNodeWH = getScrollWH(navTabsContainer || navNode, tabBarPosition); // Add 1px to fix `offsetWidth` with decimal in Chrome not correct handle // https://github.com/ant-design/ant-design/issues/13423 const containerWH = getOffsetWH(getRef('container'), tabBarPosition) + 1; const navWrapNodeWH = getOffsetWH(getRef('navWrap'), tabBarPosition); const minOffset = containerWH - navNodeWH; if (offset > 0) offset = 0; if (minOffset >= 0) { offset = 0; } else if (minOffset >= offset) { const realOffset = navWrapNodeWH - navNodeWH; offset = realOffset; } if (currentOffset !== offset) { let navOffset: { value?: string; name?: 'top' | 'left'; } = {}; const navNode = getRef('nav'); if (!navNode) return currentOffset; const navStyle = navNode.style; const transformSupported = isTransform3dSupported(navStyle); if (isVertical(tabBarPosition)) { if (transformSupported) { navOffset = { value: `translate3d(0,${offset}px,0)` }; } else { navOffset = { name: 'top', value: `${offset}px` }; } } else { if (transformSupported) { if (direction === 'rtl') { offset = -offset; } navOffset = { value: `translate3d(${offset}px,0,0)` }; } else { navOffset = { name: 'left', value: `${offset}px` }; } } if (navOffset.value) { if (transformSupported) { setTransform(navStyle, navOffset.value); } else if (navOffset.name) { navStyle[navOffset.name] = navOffset.value; } } } return offset; }; const getNextPrev = ({ getRef, tabBarPosition, currentOffset }: Pick<BarContext, 'getRef' | 'tabBarPosition' | 'currentOffset'>) => { const navNode = getRef('nav'); const navTabsContainer = getRef('navTabsContainer'); const navNodeWH = getScrollWH(navTabsContainer || navNode, tabBarPosition); // Add 1px to fix `offsetWidth` with decimal in Chrome not correct handle // https://github.com/ant-design/ant-design/issues/13423 const containerWH = getOffsetWH(getRef('container'), tabBarPosition) + 1; const minOffset = containerWH - navNodeWH; let next, prev; if (minOffset >= 0) { next = false; } else if (minOffset < currentOffset) { next = true; } else { next = false; } if (currentOffset < 0) { prev = true; } else { prev = false; } return { next, prev }; }; const getOffsetOfActive = (context: { getRef: GetRef; next: boolean; prev: boolean; tabBarPosition: TabBarPosition; currentOffset: number; }) => { const { getRef, next, prev, tabBarPosition, currentOffset } = context; const activeTab = getRef('activeTab'); const navWrap = getRef('navWrap'); if (!activeTab) return; // when not scrollable or enter scrollable first time, don't emit scrolling const needToScroll = next || prev; if (!needToScroll) return; const activeTabWH = getScrollWH(activeTab, tabBarPosition); const wrapWH = getOffsetWH(navWrap, tabBarPosition); const activeTabOffset = getOffsetLT(activeTab, tabBarPosition); if (-currentOffset < activeTabOffset + activeTabWH - wrapWH) { return -(activeTabOffset + activeTabWH - wrapWH); } else if (-currentOffset > activeTabOffset) { return -activeTabOffset; } }; interface ScrollableTabBarNodeProps { tabBarPosition: TabBarPosition; scrollAnimated?: boolean; onPrevClick?: (e: MouseEvent) => void; onNextClick?: (e: MouseEvent) => void; prevIcon?: ReactNode; nextIcon?: ReactNode; children?: ReactNode; direction?: string; activeKey: Key | null; } const ScrollableTabBarNode = ({ tabBarPosition, scrollAnimated = true, onPrevClick = noop, onNextClick = noop, prevIcon, nextIcon, children, direction, activeKey }: ScrollableTabBarNodeProps) => { const offsetRef = useRef(0); const [next, setNext] = useState(false); const [prev, setPrev] = useState(false); const showNextPrev = prev || next; const { saveRef, getRef } = useContext(RefContext); // update next/prev icon const setNextPrev = useCallback(() => { const { next, prev } = getNextPrev({ getRef, currentOffset: offsetRef.current, tabBarPosition }); setNext(next); setPrev(prev); }, [getRef, tabBarPosition]); // set nav offset const setOffset = useCallback( (offset: number) => { const newOffset = setNavOffset(offset, { currentOffset: offsetRef.current, direction, tabBarPosition, getRef }); offsetRef.current = newOffset; }, [direction, getRef, tabBarPosition] ); // scroll bar to active tab const scrollToActiveTab = useCallback(() => { const offset = getOffsetOfActive({ getRef, next, prev, tabBarPosition, currentOffset: offsetRef.current }); if (offset != null) setOffset(offset); }, [getRef, next, prev, setOffset, tabBarPosition]); const prevTransitionEnd = useCallback( (e: TransitionEvent) => { if (e.propertyName !== 'opacity') return; scrollToActiveTab(); setNextPrev(); }, [scrollToActiveTab, setNextPrev] ); const onPrev = useCallback( (e: MouseEvent) => { onPrevClick?.(e); const navWrapNode = getRef('navWrap'); const navWrapNodeWH = getOffsetWH(navWrapNode, tabBarPosition); setOffset(offsetRef.current + navWrapNodeWH); setNextPrev(); }, [getRef, onPrevClick, setNextPrev, setOffset, tabBarPosition] ); const onNext = useCallback( (e: MouseEvent) => { onNextClick?.(e); const navWrapNode = getRef('navWrap'); const navWrapNodeWH = getOffsetWH(navWrapNode, tabBarPosition); setOffset(offsetRef.current - navWrapNodeWH); setNextPrev(); }, [getRef, onNextClick, setNextPrev, setOffset, tabBarPosition] ); // reset offset when tabBarPosition change useEffect(() => { setOffset(0); // eslint-disable-next-line react-hooks/exhaustive-deps }, [tabBarPosition]); // scroll to active when initial and activeKey changed useEffect(() => { scrollToActiveTab(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeKey, tabBarPosition]); useEffect(() => { setNextPrev(); }, [children, setNextPrev, tabBarPosition]); // set next/prev when size change useEffect(() => { const debouncedResize = _.debounce(() => { setNextPrev(); }, 200); const resizeObserver = new ResizeObserver(debouncedResize); const containerNode = getRef('container'); if (containerNode) resizeObserver.observe(containerNode); return () => { if (resizeObserver) { resizeObserver.disconnect(); } if (debouncedResize.cancel) { debouncedResize.cancel(); } }; }, [getRef, setNextPrev]); const prevButton = ( <span onClick={onPrev} unselectable="on" className={classnames({ [`${prefixCls}-tab-prev`]: 1, [`${prefixCls}-tab-btn-disabled`]: !prev, [`${prefixCls}-tab-arrow-show`]: showNextPrev })} onTransitionEnd={prevTransitionEnd} > {prevIcon || <span className={`${prefixCls}-tab-prev-icon`} />} </span> ); const nextButton = ( <span onClick={onNext} unselectable="on" className={classnames({ [`${prefixCls}-tab-next`]: 1, [`${prefixCls}-tab-btn-disabled`]: !next, [`${prefixCls}-tab-arrow-show`]: showNextPrev })} > {nextIcon || <span className={`${prefixCls}-tab-next-icon`} />} </span> ); const navClassName = `${prefixCls}-nav`; const navClasses = classnames( navClassName, scrollAnimated ? `${navClassName}-animated` : `${navClassName}-no-animated` ); return ( <div className={classnames({ [`${prefixCls}-nav-container`]: 1, [`${prefixCls}-nav-container-scrolling`]: showNextPrev })} ref={saveRef('container')} > {prevButton} {nextButton} <div className={`${prefixCls}-nav-wrap`} ref={saveRef('navWrap')}> <div className={`${prefixCls}-nav-scroll`}> <div className={navClasses} ref={saveRef('nav')}> {children} </div> </div> </div> </div> ); }; interface TabBarProps { onKeyDown: (e: KeyboardEvent) => void; tabBarPosition: TabBarPosition; onTabClick: (activeKey: Key) => void; panes: Panes; activeKey: Key | null; direction: string; styleType: string; } const TabBar = (props: TabBarProps) => { const refs = useRef<Record<string, HTMLElement | null>>({}); const getRef = useCallback((name: string) => refs.current[name], []); const saveRef = useCallback( (name: string) => (node: HTMLElement | null) => { if (!node) return; refs.current[name] = node; }, [] ); const { styleType } = props; return ( <RefContext.Provider value={{ getRef, saveRef }}> <TabBarRootNode {...props}> <ScrollableTabBarNode {...props}> <TabBarTabsNode {...props} /> {styleType === 'ink' ? <InkTabBarNode {...props} /> : null} </ScrollableTabBarNode> </TabBarRootNode> </RefContext.Provider> ); }; export default memo(TabBar);
the_stack
import React, { useState, useEffect, useCallback, useMemo } from 'react'; import sumBy from 'lodash/sumBy' import { registerComponent, Components, getFragment } from '../../lib/vulcan-lib'; import { useUpdate } from '../../lib/crud/withUpdate'; import { updateEachQueryResultOfType, handleUpdateMutation } from '../../lib/crud/cacheUpdates'; import { useMulti } from '../../lib/crud/withMulti'; import { useMutation, gql } from '@apollo/client'; import { useCurrentUser } from '../common/withUser'; import classNames from 'classnames'; import * as _ from "underscore" import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward' import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward' import { Link } from '../../lib/reactRouterWrapper'; import { AnalyticsContext, useTracking } from '../../lib/analyticsEvents' import seedrandom from '../../lib/seedrandom'; import { getCostData, getReviewPhase, REVIEW_YEAR } from '../../lib/reviewUtils'; import { annualReviewAnnouncementPostPathSetting } from '../../lib/publicSettings'; import { forumTypeSetting } from '../../lib/instanceSettings'; import Select from '@material-ui/core/Select'; import MenuItem from '@material-ui/core/MenuItem'; import Card from '@material-ui/core/Card'; import { DEFAULT_QUALITATIVE_VOTE } from '../../lib/collections/reviewVotes/schema'; import { randomId } from '../../lib/random'; const isEAForum = forumTypeSetting.get() === 'EAForum' const userVotesAreQuadraticField: keyof DbUser = "reviewVotesQuadratic2020"; const styles = (theme: ThemeType): JssStyles => ({ grid: { display: 'grid', gridTemplateColumns: ` minmax(10px, 0.5fr) minmax(100px, 740px) minmax(30px, 0.5fr) minmax(300px, 740px) minmax(30px, 0.5fr) `, gridTemplateAreas: ` "... leftColumn ... rightColumn ..." `, paddingBottom: 175, alignItems: "start", [theme.breakpoints.down('sm')]: { display: "block" } }, instructions: { padding: 16, marginBottom: 24, background: theme.palette.panelBackground.default, boxShadow: theme.palette.boxShadow.default, [theme.breakpoints.down('sm')]: { display: "none" } }, leftColumn: { gridArea: "leftColumn", position: "sticky", top: 72, height: "90vh", overflow: "scroll", paddingLeft: 24, paddingRight: 36, [theme.breakpoints.down('sm')]: { gridArea: "unset", paddingLeft: 0, paddingRight: 0, overflow: "unset", height: "unset", position: "unset" } }, rightColumn: { gridArea: "rightColumn", [theme.breakpoints.down('sm')]: { gridArea: "unset" }, }, result: { ...theme.typography.smallText, ...theme.typography.commentStyle, lineHeight: "1.3rem", marginBottom: 10, position: "relative" }, votingBox: { maxWidth: 700 }, expandedInfo: { maxWidth: 600, marginBottom: 175, }, widget: { marginBottom: 32 }, menu: { position: "sticky", top:0, display: "flex", alignItems: "center", justifyContent: "space-between", backgroundColor: theme.palette.panelBackground.default, zIndex: theme.zIndexes.reviewVotingMenu, padding: theme.spacing.unit, background: theme.palette.grey[310], borderBottom: theme.palette.border.slightlyFaint, flexWrap: "wrap" }, menuIcon: { marginLeft: theme.spacing.unit }, returnToBasicIcon: { transform: "rotate(180deg)", marginRight: theme.spacing.unit }, expandedInfoWrapper: { position: "fixed", top: 100, overflowY: "auto", height: "100vh", paddingRight: 8 }, header: { ...theme.typography.display3, ...theme.typography.commentStyle, marginTop: 6, }, postHeader: { ...theme.typography.display1, ...theme.typography.postStyle, marginTop: 0, }, comments: { }, costTotal: { ...theme.typography.commentStyle, marginLeft: 10, color: theme.palette.grey[600], marginRight: "auto", whiteSpace: "pre" }, excessVotes: { color: theme.palette.error.main, // border: `solid 1px ${theme.palette.error.light}`, // paddingLeft: 12, // paddingRight: 12, // paddingTop: 6, // paddingBottom: 6, // borderRadius: 3, // '&:hover': { // opacity: .5 // } }, message: { width: "100%", textAlign: "center", paddingTop: 50, ...theme.typography.body2, ...theme.typography.commentStyle, }, hideOnDesktop: { [theme.breakpoints.up('md')]: { display: "none" } }, warning: { color: theme.palette.error.main }, voteAverage: { cursor: 'pointer', }, faqCard: { width: 400, padding: 16, }, faqQuestion: { color: theme.palette.primary.main }, postCount: { ...theme.typography.commentStyle, marginLeft: 10, color: theme.palette.grey[600], marginRight: "auto", whiteSpace: "pre" }, reviewedCount: { color: theme.palette.primary.main, cursor: "pointer", marginRight: 8 }, sortingOptions: { whiteSpace: "pre", display: "flex", [theme.breakpoints.down('xs')]: { paddingTop: 12, paddingLeft: 4 } }, postsLoading: { opacity: .4, }, sortBy: { color: theme.palette.grey[600], marginRight: 3 }, sortArrow: { cursor: "pointer", padding: 4, borderRadius: 3, marginRight: 6, border: theme.palette.border.normal, "&:hover": { background: theme.palette.panelBackground.darken20, } }, votingTitle: { ...theme.typography.display2, ...theme.typography.postStyle, [theme.breakpoints.up('md')]: { display: "none" } }, postList: { boxShadow: `0 1px 5px 0px ${theme.palette.boxShadowColor(0.2)}`, background: theme.palette.panelBackground.default, [theme.breakpoints.down('sm')]: { boxShadow: "unset" } } }); export type SyntheticReviewVote = {postId: string, score: number, type: 'QUALITATIVE' | 'QUADRATIC'} export type SyntheticQualitativeVote = {_id: string, postId: string, score: number, type: 'QUALITATIVE'} export type SyntheticQuadraticVote = {postId: string, score: number, type: 'QUADRATIC'} const generatePermutation = (count: number, user: UsersCurrent|null): Array<number> => { const seed = user?._id || ""; const rng = seedrandom(seed); let remaining = _.range(count); let result: Array<number> = []; while(remaining.length > 0) { let idx = Math.floor(rng() * remaining.length); result.push(remaining[idx]); remaining.splice(idx, 1); } return result; } const ReviewVotingPage = ({classes}: { classes: ClassesType, }) => { const currentUser = useCurrentUser() const { captureEvent } = useTracking({eventType: "reviewVotingEvent"}) const { results, loading: postsLoading, error: postsError } = useMulti({ terms: { view: getReviewPhase() === "VOTING" ? "reviewFinalVoting" : "reviewVoting", before: `${REVIEW_YEAR+1}-01-01`, ...(isEAForum ? {} : {after: `${REVIEW_YEAR}-01-01`}), limit: 600, }, collectionName: "Posts", fragmentName: 'PostsReviewVotingList', fetchPolicy: 'cache-and-network', }); // useMulti is incorrectly typed const postsResults = results as PostsListWithVotes[] | null; const [submitVote] = useMutation(gql` mutation submitReviewVote($postId: String, $qualitativeScore: Int, $quadraticChange: Int, $newQuadraticScore: Int, $comment: String, $year: String, $dummy: Boolean) { submitReviewVote(postId: $postId, qualitativeScore: $qualitativeScore, quadraticChange: $quadraticChange, comment: $comment, newQuadraticScore: $newQuadraticScore, year: $year, dummy: $dummy) { ...PostsReviewVotingList } } ${getFragment("PostsReviewVotingList")} `); const [sortedPosts, setSortedPosts] = useState(postsResults) const [loading, setLoading] = useState(false) const [sortReviews, setSortReviews ] = useState<string>("new") const [expandedPost, setExpandedPost] = useState<PostsListWithVotes|null>(null) const [showKarmaVotes] = useState<any>(true) const [postsHaveBeenSorted, setPostsHaveBeenSorted] = useState(false) if (postsError) { // eslint-disable-next-line no-console console.error('Error loading posts', postsError); } function getCostTotal (posts) { return posts?.map(post=>getCostData({})[post.currentUserReviewVote?.qualitativeScore || 0].cost).reduce((a,b)=>a+b, 0) } const [costTotal, setCostTotal] = useState<number>(getCostTotal(postsResults)) let defaultSort = "" if (getReviewPhase() === "REVIEWS") { defaultSort = "needsReview" } if (getReviewPhase() === "VOTING") { defaultSort = "needsFinalVote"} const [sortPosts, setSortPosts] = useState(defaultSort) const [sortReversed, setSortReversed] = useState(false) const dispatchQualitativeVote = useCallback(async ({_id, postId, score}: SyntheticQualitativeVote) => { const post = postsResults?.find(post => post._id === postId) const newPost = { __typename: "Post", ...post, currentUserReviewVote: { __typename: "ReviewVote", _id: _id || randomId(), qualitativeScore: score } } return await submitVote({ variables: {postId, qualitativeScore: score, year: REVIEW_YEAR+"", dummy: false}, optimisticResponse: { submitReviewVote: newPost } }) }, [submitVote, postsResults]); const { LWTooltip, Loading, ReviewVotingExpandedPost, ReviewVoteTableRow, SectionTitle, RecentComments, FrontpageReviewWidget, ContentStyles } = Components const canInitialResort = !!postsResults const reSortPosts = useCallback((sortPosts, sortReversed) => { if (!postsResults) return const randomPermutation = generatePermutation(postsResults.length, currentUser) const newlySortedPosts = postsResults .map((post, i) => ([post, randomPermutation[i]] as const)) .sort(([inputPost1, permuted1], [inputPost2, permuted2]) => { const post1 = sortReversed ? inputPost2 : inputPost1 const post2 = sortReversed ? inputPost1 : inputPost2 const post1Score = post1.currentUserReviewVote?.qualitativeScore || 0 const post2Score = post2.currentUserReviewVote?.qualitativeScore || 0 if (sortPosts === "needsReview") { // This prioritizes posts with no reviews, which you highly upvoted const post1NeedsReview = post1.reviewCount === 0 && post1.reviewVoteScoreHighKarma > 4 const post2NeedsReview = post2.reviewCount === 0 && post2.reviewVoteScoreHighKarma > 4 const post1isCurrentUsers = post1.userId === currentUser?._id const post2isCurrentUsers = post2.userId === currentUser?._id if (post1NeedsReview && !post2NeedsReview) return -1 if (post2NeedsReview && !post1NeedsReview) return 1 if (post1isCurrentUsers && !post2isCurrentUsers) return -1 if (post2isCurrentUsers && !post1isCurrentUsers) return 1 if (post1Score > post2Score) return -1 if (post1Score < post2Score) return 1 } if (sortPosts === "needsFinalVote") { const post1NotReviewVoted = post1.currentUserReviewVote === null && post1.userId !== currentUser?._id const post2NotReviewVoted = post2.currentUserReviewVote === null && post2.userId !== currentUser?._id const post1NotKarmaVoted = post1.currentUserVote === null const post2NotKarmaVoted = post2.currentUserVote === null if (post1NotReviewVoted && !post2NotReviewVoted) return -1 if (post2NotReviewVoted && !post1NotReviewVoted) return 1 if (post1Score < post2Score) return 1 if (post1Score > post2Score) return -1 if (post1NotKarmaVoted && !post2NotKarmaVoted) return 1 if (post2NotKarmaVoted && !post1NotKarmaVoted) return -1 if (permuted1 < permuted2) return -1; if (permuted1 > permuted2) return 1; } if (sortPosts === "yourVote") { if (post1Score < post2Score) return 1 if (post1Score > post2Score) return -1 } if (post1[sortPosts] > post2[sortPosts]) return -1 if (post1[sortPosts] < post2[sortPosts]) return 1 if (post1.reviewVoteScoreHighKarma > post2.reviewVoteScoreHighKarma ) return -1 if (post1.reviewVoteScoreHighKarma < post2.reviewVoteScoreHighKarma ) return 1 // TODO: figure out why commenting this out makes it sort correctly. const reviewedNotVoted1 = post1.reviewCount > 0 && !post1Score const reviewedNotVoted2 = post2.reviewCount > 0 && !post2Score if (reviewedNotVoted1 && !reviewedNotVoted2) return -1 if (!reviewedNotVoted1 && reviewedNotVoted2) return 1 if (post1Score < post2Score) return 1 if (post1Score > post2Score) return -1 if (permuted1 < permuted2) return -1; if (permuted1 > permuted2) return 1; return 0 }) .map(([post, _]) => post) setSortedPosts(newlySortedPosts) setPostsHaveBeenSorted(true) captureEvent(undefined, {eventSubType: "postsResorted"}) // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentUser, captureEvent, canInitialResort]) useEffect(() => { setCostTotal(getCostTotal(postsResults)) }, [canInitialResort, postsResults]) useEffect(() => { reSortPosts(sortPosts, sortReversed) }, [canInitialResort, reSortPosts, sortPosts, sortReversed]) const FaqCard = ({linkText, children}) => ( <LWTooltip tooltip={false} title={ <Card className={classes.faqCard}> <ContentStyles contentType="comment"> {children} </ContentStyles> </Card>} > {linkText} </LWTooltip> ) const instructions = isEAForum ? <ContentStyles contentType="comment" className={classes.instructions}> <p>This is the Final Voting phase. During this phase, you'll read reviews, reconsider posts in the context of today, and cast or update your votes. At the end we'll have a final ordering of the Forum's favorite EA writings of all time.</p> <p><b>FAQ</b></p> <p className={classes.faqQuestion}> <FaqCard linkText="How exactly do the votes work?"> <p>If you intuitively sort posts into "good", "important", "crucial", etc., you'll probably do fine. But here are some details on how it works under the hood:</p> <p>Each of the voting buttons corresponds to a relative strength: 1x, 4x, or 9x. One of your "9" votes is 9x as powerful as one of your "1" votes. However, voting power is normalized so that everyone ends up with roughly the same amount of influence. If you mark every post you like as a "9", your "9" votes will end up weaker than those of someone who used them more sparingly. On the "backend", we use a quadratic voting system, giving you a fixed number of points and attempting to allocate them to match the relative strengths of your votes.</p> </FaqCard> </p> <p className={classes.faqQuestion}> <FaqCard linkText="Submitting reviews"> <p>The Review phase involves writing reviews of posts, with the advantage of hindsight. They can be brief or very detailed. You can write multiple reviews if your thoughts evolve over the course of the event.</p> </FaqCard> </p> <p>If you have any trouble, please <Link to="/contact">contact the Forum team</Link>, or leave a comment on <Link to={annualReviewAnnouncementPostPathSetting.get()}>this post</Link>.</p> </ContentStyles> : <ContentStyles contentType="comment" className={classes.instructions}> {getReviewPhase() === "NOMINATIONS" && <><p>During the <em>Preliminary Voting Phase</em>, eligible users are encouraged to:</p> <ul> <li> Vote on posts that represent important intellectual progress. </li> <li>Write short reviews that explain why those posts seem important</li> </ul> <p>Posts with at least one positive vote will appear on this page, to the right. Posts with at least one review are sorted to the top, to make them easier to vote on.</p> <p>At the end of the Preliminary Voting phase, the LessWrong team will publish a ranked list of the results. This will help inform how to spend attention during <em>the Review Phase</em>. High-ranking, undervalued or controversial posts can get additional focus.</p></>} {getReviewPhase() === "REVIEWS" && <><p><b>Posts need at least 1 Review to enter the Final Voting Phase</b></p> <p>This is the Review Phase. Posts with one nomation will appear in the public list to the right. Please write reviews of whatever posts you have opinions about.</p> <p>If you wish to adjust your votes, you can sort posts into seven categories (roughly "super strong downvote" to "super strong upvote"). During the Final Voting phase, you'll have the opportunity to fine-tune those votes using our quadratic voting system; see <a href="https://lesswrong.com/posts/qQ7oJwnH9kkmKm2dC/feedback-request-quadratic-voting-for-the-2018-review">this LessWrong post</a> for details.</p></>} <p><b>FAQ</b></p> <p className={classes.faqQuestion}> <FaqCard linkText="How exactly do Preliminary Votes work?"> <p>If you intuitively sort posts into "good", "important", "crucial", you'll probably do fine. But here are some details on how it works under-the-hood:</p> <p>Each vote-button corresponds to a relative strength: 1x, 4x, or 9x. Your "9" votes are 9x as powerful as your "1" votes. But, voting power is normalized so that everyone ends up with roughly the same amount of influence. If you mark every post you like as a "9", your "9" votes will end up weaker than someone who used them more sparingly.</p> <p>On the "backend" the system uses our <Link to="/posts/qQ7oJwnH9kkmKm2dC/feedback-request-quadratic-voting-for-the-2018-review">quadratic voting system</Link>, giving you a 500 points and allocating them to match the relative strengths of your vote-choices. A 4x vote costs 10 points, a 9x costs 45.</p> <p>You can change your votes during the Final Voting Phase.</p> </FaqCard> </p> <p className={classes.faqQuestion}> <FaqCard linkText="Who is eligible?"> <ul> <li>Any user registered before {REVIEW_YEAR} can vote on posts.</li> <li>Votes by users with 1000+ karma will be weighted more highly by the moderation team when assembling the final sequence, books or prizes.</li> <li>Any user can write reviews.</li> </ul> </FaqCard> </p> </ContentStyles> const reviewedPosts = sortedPosts?.filter(post=>post.reviewCount > 0) const costTotalTooltip = costTotal > 500 ? <div>You have spent more than 500 points. Your vote strength will be reduced to account for this.</div> : <div>You have {500 - costTotal} points remaining before your vote-weight begins to reduce.</div> return ( <AnalyticsContext pageContext="ReviewVotingPage"> <div> <div className={classes.grid}> <div className={classes.leftColumn}> {!expandedPost && <div> <div className={classes.widget}> <FrontpageReviewWidget showFrontpageItems={false}/> </div> {instructions} <SectionTitle title="Reviews"> <Select value={sortReviews} onChange={(e)=>setSortReviews(e.target.value)} disableUnderline > <MenuItem value={'top'}>Sorted by Top</MenuItem> <MenuItem value={'new'}>Sorted by New</MenuItem> <MenuItem value={'groupByPost'}>Grouped by Post</MenuItem> </Select> </SectionTitle> <RecentComments terms={{ view: "reviews", reviewYear: REVIEW_YEAR, sortBy: sortReviews}} truncated/> </div>} <ReviewVotingExpandedPost key={expandedPost?._id} post={expandedPost}/> </div> <div className={classes.rightColumn}> <div className={classes.votingTitle}>Voting</div> <div className={classes.menu}> {/* TODO: Remove this if we haven't seen the error in awhile. I think I've fixed it but... model uncertainty */} {!postsResults && !postsLoading && <div className={classes.postCount}>ERROR: Please Refresh</div>} {sortedPosts && <div className={classes.postCount}> <LWTooltip title="Posts need at least 1 review to enter the Final Voting Phase"> <span className={classes.reviewedCount}> {reviewedPosts?.length || 0} Reviewed Posts </span> </LWTooltip> {getReviewPhase() !== "VOTING" && <>({sortedPosts.length} Nominated)</>} </div> } {(postsLoading || loading) && <Loading/>} {!isEAForum && (costTotal !== null) && <div className={classNames(classes.costTotal, {[classes.excessVotes]: costTotal > 500})}> <LWTooltip title={costTotalTooltip}> {costTotal}/500 </LWTooltip> </div>} <div className={classes.sortingOptions}> <LWTooltip title={`Sorted by ${sortReversed ? "Ascending" : "Descending"}`}> <div onClick={() => { setSortReversed(!sortReversed); }}> {sortReversed ? <ArrowUpwardIcon className={classes.sortArrow} /> : <ArrowDownwardIcon className={classes.sortArrow} /> } </div> </LWTooltip> <Select value={sortPosts} onChange={(e)=>{setSortPosts(e.target.value)}} disableUnderline > <MenuItem value={'lastCommentedAt'}> <span className={classes.sortBy}>Sort by</span> Last Commented </MenuItem> <MenuItem value={'reviewVoteScoreHighKarma'}> <span className={classes.sortBy}>Sort by</span> Vote Total (1000+ Karma Users) </MenuItem> <MenuItem value={'reviewVoteScoreAllKarma'}> <span className={classes.sortBy}>Sort by</span> Vote Total (All Users) </MenuItem> {!isEAForum && <MenuItem value={'reviewVoteScoreAF'}> <span className={classes.sortBy}>Sort by</span> Vote Total (Alignment Forum Users) </MenuItem>} <MenuItem value={'yourVote'}> <span className={classes.sortBy}>Sort by</span> Your Vote </MenuItem> <MenuItem value={'reviewCount'}> <span className={classes.sortBy}>Sort by</span> Review Count </MenuItem> {getReviewPhase() === "REVIEWS" && <MenuItem value={'needsReview'}> <span className={classes.sortBy}>Sort by</span> Needs Review </MenuItem>} {getReviewPhase() === "VOTING" && <MenuItem value={'needsFinalVote'}> <span className={classes.sortBy}>Sort by</span> Needs Vote </MenuItem>} </Select> </div> </div> <div className={classNames({[classes.postList]: getReviewPhase() !== "VOTING", [classes.postLoading]: postsLoading || loading})}> {postsHaveBeenSorted && sortedPosts?.map((post) => { const currentVote = post.currentUserReviewVote !== null ? { _id: post.currentUserReviewVote._id, postId: post._id, score: post.currentUserReviewVote.qualitativeScore, type: "QUALITATIVE" as const } : null return <div key={post._id} onClick={()=>{ setExpandedPost(post) captureEvent(undefined, {eventSubType: "voteTableRowClicked", postId: post._id})}} > <ReviewVoteTableRow post={post} costTotal={costTotal} showKarmaVotes={showKarmaVotes} dispatch={dispatchQualitativeVote} currentVote={currentVote} expandedPostId={expandedPost?._id} /> </div> })} </div> </div> </div> </div> </AnalyticsContext> ); } const ReviewVotingPageComponent = registerComponent('ReviewVotingPage', ReviewVotingPage, {styles}); declare global { interface ComponentTypes { ReviewVotingPage: typeof ReviewVotingPageComponent } }
the_stack
import React from 'react'; import { connect } from 'react-redux'; import { TweenLite } from 'gsap/dist/gsap'; import Link from 'next/link'; import styles from './style-old.module.scss'; // import { TProps, TState } from "./home"; interface TProps { theme: { color: string; fontFamily: string; }; } interface TState { currentPage: number; activeSlide: number; canScroll: boolean; } class Home extends React.Component<TProps, TState> { constructor(props: TProps) { super(props); this.state = { currentPage: 0, activeSlide: 1, canScroll: true, }; this.prev = 0; this.bgImage = null; this.slide1Box = null; this.slide2Text = null; this.slide3All = null; this.slide3Img = null; this.slide3Text = null; this.myTween = null; this.touchYStart = 0; } prev: number; touchYStart: number; bgImage: HTMLDivElement | null; slide1Box: HTMLDivElement | null; slide2Text: HTMLDivElement | null; slide3All: HTMLDivElement | null; slide3Img: HTMLDivElement | null; slide3Text: HTMLDivElement | null; myTween: ReturnType<typeof TweenLite.to> | null; componentDidMount() { this.prev = window.scrollY; window.addEventListener('scroll', this.handleScroll); window.addEventListener('keyup', this._handleKeyDown); window.addEventListener('touchstart', this._touchStartHandle, false); window.addEventListener('touchend', this._touchEndHandle, false); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); window.removeEventListener('keyup', this._handleKeyDown); window.removeEventListener('touchstart', this._touchStartHandle, false); window.removeEventListener('touchend', this._touchEndHandle, false); } _canScroll = (status: boolean, time = 0) => { setTimeout(() => { this.setState({ canScroll: status, }); }, time); }; _animeDown1to2 = () => { this.myTween = TweenLite.to(this.slide1Box, 0.3, { y: 300, opacity: 0 }); this.myTween = TweenLite.to(this.bgImage, 0.5, { transform: 'scale(1.8)', top: '45vh', left: '400px', filter: 'brightness(1)' }); this.myTween = TweenLite.to(this.slide2Text, 0.6, { bottom: '35%', opacity: 1 }); this._canScroll(true, 600); }; _animeDown2to3 = () => { this.myTween = TweenLite.to(this.bgImage, 0.5, { top: '-100%', left: '400px', opacity: 0 }); this.myTween = TweenLite.to(this.slide2Text, 0.5, { bottom: '100%', opacity: 0 }); // this.myTween = TweenLite.to(this.slide3All, .5, {top: '25%', opacity: 1}); this.myTween = TweenLite.to(this.slide3Text, 0.7, { bottom: '50%', opacity: 1 }); this.myTween = TweenLite.to(this.slide3Img, 0.5, { bottom: '0%', opacity: 1 }); this._canScroll(true, 600); }; _animeUp2to1 = () => { this.myTween = TweenLite.to(this.bgImage, 0.4, { transform: 'scale(1)', top: '15vh', left: '0px', filter: 'brightness(0.7)' }); this.myTween = TweenLite.to(this.slide1Box, 0.5, { y: 0, opacity: 1 }); this.myTween = TweenLite.to(this.slide2Text, 0.4, { bottom: '-30%', opacity: 0 }); this._canScroll(true, 500); }; _animeUp3to2 = () => { this.myTween = TweenLite.to(this.bgImage, 0.5, { top: '45vh', left: '400px', opacity: 1 }); this.myTween = TweenLite.to(this.slide2Text, 0.5, { bottom: '35%', opacity: 1 }); // this.myTween = TweenLite.to(this.slide3All, .5, {top: '100%', opacity: 0}); this.myTween = TweenLite.to(this.slide3Text, 0.5, { bottom: '-100%', opacity: 0 }); this.myTween = TweenLite.to(this.slide3Img, 0.5, { bottom: '-100%', opacity: 0 }); this._canScroll(true, 600); }; handleScroll = () => { // if (this.prev > window.scrollY) { // console.log("scrolling up"); // this._animeSmall(); // } // else if (this.prev < window.scrollY) { // console.log("scrolling down"); // this._animeBig() // } // this.prev = window.scrollY; }; _startAnimationDown = () => { const { activeSlide } = this.state; console.log('down', activeSlide); if (activeSlide === 2) { this._animeDown1to2(); } else if (activeSlide === 3) { this._animeDown2to3(); } }; _startAnimationUp = () => { const { activeSlide } = this.state; console.log('up', activeSlide); if (activeSlide === 1) { this._animeUp2to1(); } else if (activeSlide === 2) { this._animeUp3to2(); } }; _animationUpChecking = () => { const { activeSlide } = this.state; if (activeSlide > 1) { this.setState( { canScroll: false, activeSlide: activeSlide - 1 < 1 ? 1 : activeSlide - 1, }, () => { this._startAnimationUp(); } ); } }; _animationDownChecking = () => { const { activeSlide } = this.state; if (activeSlide < 3) { this.setState( { canScroll: false, activeSlide: activeSlide + 1, }, () => { this._startAnimationDown(); } ); } }; _handleWheel = (e: any) => { const { canScroll } = this.state; if (!canScroll) { return; } if (e.deltaY < 0) { this._animationUpChecking(); } else { this._animationDownChecking(); } }; _handleKeyDown = (e: any) => { const { canScroll } = this.state; if (!canScroll) { return; } if (e.keyCode === 38) { this._animationUpChecking(); } else if (e.keyCode === 40) { this._animationDownChecking(); } }; _scrollDown = () => { const { canScroll } = this.state; if (!canScroll) { return; } this._animationDownChecking(); }; _touchStartHandle = (e: any) => { e.preventDefault(); this.touchYStart = e.changedTouches[0].pageY; }; _touchEndHandle = (e: any) => { const { canScroll } = this.state; const endTouchY = e.changedTouches[0].pageY; if (!canScroll) { return; } if (this.touchYStart > endTouchY) { this._animationDownChecking(); } else { this._animationUpChecking(); } }; render() { return ( <div className={styles.homePage}> <nav className={styles.nav}> <div className={styles.insideNav}> <div className={styles.navLeft}> <img src="/images/logo1.png" alt="wtfresume logo (resume builder)" /> </div> <div className={styles.navRight}> <div className={styles.navItem}> <Link href="/resume-builder">Create My Resume</Link> </div> <div className={styles.navItem}>EN</div> <div className={styles.navItem}> <a href="https://github.com/sramezani/resume-builder" target="_blank" rel="noopener noreferrer"> github </a> </div> </div> </div> </nav> {/* <div className={styles.xxxxx}> </div> */} <div className={[styles.slide, styles.slide1].join(' ')} onWheel={(e) => this._handleWheel(e)}> <div className={styles.container}> <div ref={(e) => (this.bgImage = e)} className={styles.firstImg}> <img src="/images/bg.png" alt="first slide image home page" /> </div> <div className={styles.slide1Box} ref={(e) => (this.slide1Box = e)}> <div className={styles.slide1Text}> <h1>Who cares who you are</h1> <p>design your resume and prove yourself</p> </div> <div className={styles.slide1crBtn}> <div className={styles.crBtn}> <Link href="/resume-builder">Build My Resume</Link> </div> </div> <div className={styles.slide1scrollDown}> <div className={styles.scrollDown} onClick={() => this._scrollDown()}> <i className="material-icons">arrow_downward</i> </div> </div> </div> <div className={[styles.slide2].join(' ')} ref={(e) => (this.slide2Text = e)}> <h2>why trying us?</h2> <p>It&lsquo;s 100% free</p> <p>It&lsquo;s easy to use</p> <p>It makes a minute</p> <p>No need register</p> <p>real time design</p> <div className={styles.slide1scrollDown}> <div className={styles.scrollDown} onClick={() => this._scrollDown()}> <i className="material-icons">arrow_downward</i> </div> </div> </div> <div className={[styles.slide3].join(' ')} ref={(e) => (this.slide3All = e)}> <div className={styles.slide3ImgBox} ref={(e) => (this.slide3Img = e)}> {/* <img src="/images/resume-pic.jpg" alt="resume image" /> */} <video autoPlay loop poster="/images/resume-pic.jpg" controls> <source src="video/resume.mp4" type="video/mp4" /> <source src="video/resume.webm" type="video/webm" /> </video> </div> <div ref={(e) => (this.slide3Text = e)} className={styles.slide3text}> <p>You can save your data and use in the future. what do you think! its amazing?</p> <div className={styles.crBtn}> <Link href="/resume-builder">WTF! Show me how</Link> </div> </div> </div> </div> </div> </div> ); } } const mapStateToProps = (store: any) => ({ theme: store.theme, }); const mapDispatchToProps = () => ({}); export default connect(mapStateToProps, mapDispatchToProps)(Home);
the_stack
import { chimeeLog } from 'chimee-helper-log'; import { cloneDeep, isBoolean, isError, isFunction, isInteger, isPlainObject, isString } from 'lodash'; import { accessor, applyDecorators, frozen } from 'toxic-decorators'; import { isEmpty, isPromise } from 'toxic-predicate-functions'; import { bind } from 'toxic-utils'; import VideoConfig from '../config/video'; import { IFriendlyDom } from '../dispatcher/dom'; import Dispatcher, { IFriendlyDispatcher } from '../dispatcher/index'; import VideoWrapper from '../dispatcher/video-wrapper'; import { ComputedMap, PluginConfig, PluginEvents, PluginMethods, PluginOption } from '../typings/base'; export type IChimeePluginConstructor = new(...args: any[]) => ChimeePlugin; /** * <pre> * Plugin is the class for plugin developer. * When we use a plugin, we will generate an instance of plugin. * Developer can do most of things base on this plugin * </pre> */ export default class ChimeePlugin extends VideoWrapper { get $autoFocus(): boolean { return this.autoFocusValue; } set $autoFocus(val: boolean) { this.autoFocusValue = val; // It's a work around for the friendly class in https://github.com/Microsoft/TypeScript/issues/7692#issuecomment-341115350 const dom: IFriendlyDom = (this.dispatcher.dom as any); dom.autoFocusToVideo(this.$dom, !val); } /** * the z-index level, higher when you set higher * @type {boolean} */ set $level(val: number) { if (!isInteger(val)) { return; } this.levelValue = val; const dispatcher: IFriendlyDispatcher = (this.dispatcher as any); dispatcher.sortZIndex(); } get $level(): number { return this.levelValue; } /** * to tell us if the plugin can be operable, can be dynamic change * @type {boolean} */ set $operable(val: boolean) { if (!isBoolean(val)) { return; } this.$dom.style.pointerEvents = val ? 'auto' : 'none'; this.operableValue = val; } get $operable(): boolean { return this.operableValue; } public $config: PluginOption; public $dom: HTMLElement; public $inner: boolean; public $penetrate: boolean; public $videoConfig: VideoConfig; public destroyed: boolean = false; public ready: Promise<this>; public readySync: boolean; public VERSION: string = process.env.PLAYER_VERSION; private autoFocusValue: boolean = false; private levelValue: number = 0; private operableValue: boolean = true; /** * <pre> * to create a plugin, we need three parameter * 1. the config of a plugin * 2. the dispatcher * 3. this option for plugin to read * this is the plugin base class, which you can get on Chimee * You can just extends it and then install * But in that way you must remember to pass the arguments to super() * </pre> * @param {string} PluginConfig.id camelize from plugin's name or class name. * @param {string} PluginConfig.name plugin's name or class name * @param {Number} PluginConfig.level the level of z-index * @param {Boolean} PluginConfig.operable to tell if the plugin can be operable, if not, we will add pointer-events: none on it. * @param {Function} PluginConfig.create the create function which we will called when plugin is used. sth like constructor in object style. * @param {Function} PluginConfig.destroy function to be called when we destroy a plugin * @param {Object} PluginConfig.events You can set some events handler in this object, we will bind it once you use the plugin. * @param {Object} PluginConfig.data dataset we will bind on data in object style * @param {Object<{get: Function, set: Function}} PluginConfig.computed dataset we will handle by getter and setter * @param {Object<Function>} PluginConfig.methods some function we will bind on plugin * @param {string|HTMLElment} PluginConfig.el can be string or HTMLElement, we will use this to create the dom for plugin * @param {boolean} PluginConfig.penetrate boolean to let us do we need to forward the dom events for this plugin. * @param {Dispatcher} dispatcher referrence of dispatcher * @param {Object} option PluginOption that will pass to the plugin * @return {Plugin} plugin instance */ constructor( { id, name, level = 0, operable = true, beforeCreate, create, init, inited, destroy, events = {}, data = {}, computed = {}, methods = {}, el, penetrate = false, inner = true, autoFocus, className, }: PluginConfig, dispatcher: Dispatcher, option: PluginOption = { name }) { super({ dispatcher, id }); if (!dispatcher) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { chimeeLog.error('Dispatcher.plugin', 'lack of dispatcher. Do you forget to pass arguments to super in plugin?'); } throw new TypeError('lack of dispatcher'); } if (!isString(id)) { throw new TypeError('id of PluginConfig must be string'); } this.id = id; this.$videoConfig = this.dispatcher.videoConfig; this.wrapAsVideo(this.$videoConfig); this.beforeCreate = this.beforeCreate || beforeCreate; try { if (isFunction(this.beforeCreate)) { this.beforeCreate({ computed, data, events, methods, }, option); } } catch (error) { this.$throwError(error); } // bind plugin methods into instance if (!isEmpty(methods) && isPlainObject(methods)) { Object.keys(methods).forEach((key) => { const fn = methods[key]; if (!isFunction(fn)) { throw new TypeError('plugins methods must be Function'); } Object.defineProperty(this, key, { configurable: true, enumerable: false, value: bind(fn, this), writable: true, }); }); } // hook plugin events on bus if (!isEmpty(events) && isPlainObject(events)) { Object.keys(events) .forEach((key) => { if (!isFunction(events[key])) { throw new TypeError('plugins events hook must bind with Function'); } this.$on(key, events[key]); }); } // bind data into plugin instance if (!isEmpty(data) && isPlainObject(data)) { Object.assign(this, cloneDeep(data)); } // set the computed member by getter and setter if (!isEmpty(computed) && isPlainObject(computed)) { const props = Object.keys(computed) .reduce((props: { [x: string]: (...args: any[]) => any }, key) => { const val = computed[key]; if (isFunction(val)) { props[key] = accessor({ get: val }); return props; } if (isPlainObject(val) && (isFunction(val.get) || isFunction(val.set))) { props[key] = accessor(val); return props; } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { chimeeLog.warn('Dispatcher.plugin', `Wrong computed member '${key}' defination in Plugin ${name}`); } return props; }, {}); applyDecorators(this, props, { self: true }); } /** * the create Function of plugin * @type {Function} */ this.create = this.create || create; /** * this init Function of plugin * which will be called when we start to create the video player * the plugin can handle some config here * @type {Function} */ this.init = this.init || init; /** * this inited Function of plugin * which will be called when we have created the video player * @type {Function} */ this.inited = this.inited || inited; /** * the destroy Function of plugin * @type {Function} */ this.destroy = this.destroy || destroy; /** * the dom node of whole plugin * @type {HTMLElement} */ this.$dom = this.dispatcher.dom.insertPlugin(this.id, el, { penetrate, inner, className }); this.$autoFocus = isBoolean(autoFocus) ? autoFocus : inner; // now we can frozen inner, autoFocus and penetrate this.$inner = inner; this.$penetrate = penetrate; applyDecorators(this, { $inner: frozen, $penetrate: frozen, }, { self: true }); /** * to tell us if the plugin can be operable, can be dynamic change * @type {boolean} */ this.$operable = isBoolean(option.operable) ? option.operable : operable; this.levelValue = isInteger(option.level) ? option.level : level; /** * pluginOption, so it's easy for plugin developer to check the config * @type {Object} */ this.$config = option; try { if (isFunction(this.create)) { this.create(); } } catch (error) { this.$throwError(error); } } /** * set the plugin to be the top of all plugins */ public $bumpToTop() { const dispatcher: IFriendlyDispatcher = (this.dispatcher as any); const topLevel = dispatcher.getTopLevel(this.$inner); this.$level = topLevel + 1; } /** * officail destroy function for plugin * we will call user destory function in this method */ public $destroy() { if (this.destroyed) { return; } if (isFunction(this.destroy)) { this.destroy(); } super.destroyVideoWrapper(); this.dispatcher.dom.removePlugin(this.id); delete this.dispatcher; delete this.$dom; this.destroyed = true; } public $throwError(error: Error | string) { this.dispatcher.throwError(error); } public beforeCreate?(obj: { computed: ComputedMap, data: any, events: PluginEvents, methods: PluginMethods }, option: PluginOption): void; public create?(): void; public destroy?(): void; public init?(config: VideoConfig): void; public inited?(): void | Promise<void>; /** * call for inited lifecycle hook, which just to tell the plugin we have inited. */ public runInitedHook(): Promise<this> | this { let result; try { result = isFunction(this.inited) && this.inited(); } catch (error) { this.$throwError(error); } const promiseResult = isPromise(result) && result; this.readySync = !promiseResult; this.ready = promiseResult ? promiseResult .then(() => { this.readySync = true; return this; }) .catch((error: Error) => { if (isError(error)) { this.$throwError(error); } return Promise.reject(error); }) : Promise.resolve(this); return this.readySync ? this : this.ready; } /** * call for init lifecycle hook, which mainly handle the original config of video and kernel. * @param {VideoConfig} videoConfig the original config of the videoElement or Kernel */ public runInitHook(videoConfig: VideoConfig) { try { if (isFunction(this.init)) { this.init(videoConfig); } } catch (error) { this.$throwError(error); } } }
the_stack
import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { StylesheetContext } from "./LessParser"; import { StatementContext } from "./LessParser"; import { MediaContext } from "./LessParser"; import { MediaQueryListContext } from "./LessParser"; import { MediaQueryContext } from "./LessParser"; import { MediaTypeContext } from "./LessParser"; import { MediaExpressionContext } from "./LessParser"; import { MediaFeatureContext } from "./LessParser"; import { VariableNameContext } from "./LessParser"; import { CommandStatementContext } from "./LessParser"; import { MathCharacterContext } from "./LessParser"; import { MathStatementContext } from "./LessParser"; import { ExpressionContext } from "./LessParser"; import { FuncContext } from "./LessParser"; import { ConditionsContext } from "./LessParser"; import { ConditionContext } from "./LessParser"; import { ConditionStatementContext } from "./LessParser"; import { VariableDeclarationContext } from "./LessParser"; import { ImportDeclarationContext } from "./LessParser"; import { ImportOptionContext } from "./LessParser"; import { ReferenceUrlContext } from "./LessParser"; import { MediaTypesContext } from "./LessParser"; import { RulesetContext } from "./LessParser"; import { BlockContext } from "./LessParser"; import { BlockItemContext } from "./LessParser"; import { MixinDefinitionContext } from "./LessParser"; import { MixinGuardContext } from "./LessParser"; import { MixinDefinitionParamContext } from "./LessParser"; import { MixinReferenceContext } from "./LessParser"; import { SelectorsContext } from "./LessParser"; import { SelectorContext } from "./LessParser"; import { AttribContext } from "./LessParser"; import { NegationContext } from "./LessParser"; import { PseudoContext } from "./LessParser"; import { ElementContext } from "./LessParser"; import { SelectorPrefixContext } from "./LessParser"; import { AttribRelateContext } from "./LessParser"; import { IdentifierContext } from "./LessParser"; import { IdentifierPartContext } from "./LessParser"; import { IdentifierVariableNameContext } from "./LessParser"; import { PropertyContext } from "./LessParser"; import { ValuesContext } from "./LessParser"; import { UrlContext } from "./LessParser"; import { MeasurementContext } from "./LessParser"; /** * This interface defines a complete listener for a parse tree produced by * `LessParser`. */ export interface LessParserListener extends ParseTreeListener { /** * Enter a parse tree produced by `LessParser.stylesheet`. * @param ctx the parse tree */ enterStylesheet?: (ctx: StylesheetContext) => void; /** * Exit a parse tree produced by `LessParser.stylesheet`. * @param ctx the parse tree */ exitStylesheet?: (ctx: StylesheetContext) => void; /** * Enter a parse tree produced by `LessParser.statement`. * @param ctx the parse tree */ enterStatement?: (ctx: StatementContext) => void; /** * Exit a parse tree produced by `LessParser.statement`. * @param ctx the parse tree */ exitStatement?: (ctx: StatementContext) => void; /** * Enter a parse tree produced by `LessParser.media`. * @param ctx the parse tree */ enterMedia?: (ctx: MediaContext) => void; /** * Exit a parse tree produced by `LessParser.media`. * @param ctx the parse tree */ exitMedia?: (ctx: MediaContext) => void; /** * Enter a parse tree produced by `LessParser.mediaQueryList`. * @param ctx the parse tree */ enterMediaQueryList?: (ctx: MediaQueryListContext) => void; /** * Exit a parse tree produced by `LessParser.mediaQueryList`. * @param ctx the parse tree */ exitMediaQueryList?: (ctx: MediaQueryListContext) => void; /** * Enter a parse tree produced by `LessParser.mediaQuery`. * @param ctx the parse tree */ enterMediaQuery?: (ctx: MediaQueryContext) => void; /** * Exit a parse tree produced by `LessParser.mediaQuery`. * @param ctx the parse tree */ exitMediaQuery?: (ctx: MediaQueryContext) => void; /** * Enter a parse tree produced by `LessParser.mediaType`. * @param ctx the parse tree */ enterMediaType?: (ctx: MediaTypeContext) => void; /** * Exit a parse tree produced by `LessParser.mediaType`. * @param ctx the parse tree */ exitMediaType?: (ctx: MediaTypeContext) => void; /** * Enter a parse tree produced by `LessParser.mediaExpression`. * @param ctx the parse tree */ enterMediaExpression?: (ctx: MediaExpressionContext) => void; /** * Exit a parse tree produced by `LessParser.mediaExpression`. * @param ctx the parse tree */ exitMediaExpression?: (ctx: MediaExpressionContext) => void; /** * Enter a parse tree produced by `LessParser.mediaFeature`. * @param ctx the parse tree */ enterMediaFeature?: (ctx: MediaFeatureContext) => void; /** * Exit a parse tree produced by `LessParser.mediaFeature`. * @param ctx the parse tree */ exitMediaFeature?: (ctx: MediaFeatureContext) => void; /** * Enter a parse tree produced by `LessParser.variableName`. * @param ctx the parse tree */ enterVariableName?: (ctx: VariableNameContext) => void; /** * Exit a parse tree produced by `LessParser.variableName`. * @param ctx the parse tree */ exitVariableName?: (ctx: VariableNameContext) => void; /** * Enter a parse tree produced by `LessParser.commandStatement`. * @param ctx the parse tree */ enterCommandStatement?: (ctx: CommandStatementContext) => void; /** * Exit a parse tree produced by `LessParser.commandStatement`. * @param ctx the parse tree */ exitCommandStatement?: (ctx: CommandStatementContext) => void; /** * Enter a parse tree produced by `LessParser.mathCharacter`. * @param ctx the parse tree */ enterMathCharacter?: (ctx: MathCharacterContext) => void; /** * Exit a parse tree produced by `LessParser.mathCharacter`. * @param ctx the parse tree */ exitMathCharacter?: (ctx: MathCharacterContext) => void; /** * Enter a parse tree produced by `LessParser.mathStatement`. * @param ctx the parse tree */ enterMathStatement?: (ctx: MathStatementContext) => void; /** * Exit a parse tree produced by `LessParser.mathStatement`. * @param ctx the parse tree */ exitMathStatement?: (ctx: MathStatementContext) => void; /** * Enter a parse tree produced by `LessParser.expression`. * @param ctx the parse tree */ enterExpression?: (ctx: ExpressionContext) => void; /** * Exit a parse tree produced by `LessParser.expression`. * @param ctx the parse tree */ exitExpression?: (ctx: ExpressionContext) => void; /** * Enter a parse tree produced by `LessParser.func`. * @param ctx the parse tree */ enterFunc?: (ctx: FuncContext) => void; /** * Exit a parse tree produced by `LessParser.func`. * @param ctx the parse tree */ exitFunc?: (ctx: FuncContext) => void; /** * Enter a parse tree produced by `LessParser.conditions`. * @param ctx the parse tree */ enterConditions?: (ctx: ConditionsContext) => void; /** * Exit a parse tree produced by `LessParser.conditions`. * @param ctx the parse tree */ exitConditions?: (ctx: ConditionsContext) => void; /** * Enter a parse tree produced by `LessParser.condition`. * @param ctx the parse tree */ enterCondition?: (ctx: ConditionContext) => void; /** * Exit a parse tree produced by `LessParser.condition`. * @param ctx the parse tree */ exitCondition?: (ctx: ConditionContext) => void; /** * Enter a parse tree produced by `LessParser.conditionStatement`. * @param ctx the parse tree */ enterConditionStatement?: (ctx: ConditionStatementContext) => void; /** * Exit a parse tree produced by `LessParser.conditionStatement`. * @param ctx the parse tree */ exitConditionStatement?: (ctx: ConditionStatementContext) => void; /** * Enter a parse tree produced by `LessParser.variableDeclaration`. * @param ctx the parse tree */ enterVariableDeclaration?: (ctx: VariableDeclarationContext) => void; /** * Exit a parse tree produced by `LessParser.variableDeclaration`. * @param ctx the parse tree */ exitVariableDeclaration?: (ctx: VariableDeclarationContext) => void; /** * Enter a parse tree produced by `LessParser.importDeclaration`. * @param ctx the parse tree */ enterImportDeclaration?: (ctx: ImportDeclarationContext) => void; /** * Exit a parse tree produced by `LessParser.importDeclaration`. * @param ctx the parse tree */ exitImportDeclaration?: (ctx: ImportDeclarationContext) => void; /** * Enter a parse tree produced by `LessParser.importOption`. * @param ctx the parse tree */ enterImportOption?: (ctx: ImportOptionContext) => void; /** * Exit a parse tree produced by `LessParser.importOption`. * @param ctx the parse tree */ exitImportOption?: (ctx: ImportOptionContext) => void; /** * Enter a parse tree produced by `LessParser.referenceUrl`. * @param ctx the parse tree */ enterReferenceUrl?: (ctx: ReferenceUrlContext) => void; /** * Exit a parse tree produced by `LessParser.referenceUrl`. * @param ctx the parse tree */ exitReferenceUrl?: (ctx: ReferenceUrlContext) => void; /** * Enter a parse tree produced by `LessParser.mediaTypes`. * @param ctx the parse tree */ enterMediaTypes?: (ctx: MediaTypesContext) => void; /** * Exit a parse tree produced by `LessParser.mediaTypes`. * @param ctx the parse tree */ exitMediaTypes?: (ctx: MediaTypesContext) => void; /** * Enter a parse tree produced by `LessParser.ruleset`. * @param ctx the parse tree */ enterRuleset?: (ctx: RulesetContext) => void; /** * Exit a parse tree produced by `LessParser.ruleset`. * @param ctx the parse tree */ exitRuleset?: (ctx: RulesetContext) => void; /** * Enter a parse tree produced by `LessParser.block`. * @param ctx the parse tree */ enterBlock?: (ctx: BlockContext) => void; /** * Exit a parse tree produced by `LessParser.block`. * @param ctx the parse tree */ exitBlock?: (ctx: BlockContext) => void; /** * Enter a parse tree produced by `LessParser.blockItem`. * @param ctx the parse tree */ enterBlockItem?: (ctx: BlockItemContext) => void; /** * Exit a parse tree produced by `LessParser.blockItem`. * @param ctx the parse tree */ exitBlockItem?: (ctx: BlockItemContext) => void; /** * Enter a parse tree produced by `LessParser.mixinDefinition`. * @param ctx the parse tree */ enterMixinDefinition?: (ctx: MixinDefinitionContext) => void; /** * Exit a parse tree produced by `LessParser.mixinDefinition`. * @param ctx the parse tree */ exitMixinDefinition?: (ctx: MixinDefinitionContext) => void; /** * Enter a parse tree produced by `LessParser.mixinGuard`. * @param ctx the parse tree */ enterMixinGuard?: (ctx: MixinGuardContext) => void; /** * Exit a parse tree produced by `LessParser.mixinGuard`. * @param ctx the parse tree */ exitMixinGuard?: (ctx: MixinGuardContext) => void; /** * Enter a parse tree produced by `LessParser.mixinDefinitionParam`. * @param ctx the parse tree */ enterMixinDefinitionParam?: (ctx: MixinDefinitionParamContext) => void; /** * Exit a parse tree produced by `LessParser.mixinDefinitionParam`. * @param ctx the parse tree */ exitMixinDefinitionParam?: (ctx: MixinDefinitionParamContext) => void; /** * Enter a parse tree produced by `LessParser.mixinReference`. * @param ctx the parse tree */ enterMixinReference?: (ctx: MixinReferenceContext) => void; /** * Exit a parse tree produced by `LessParser.mixinReference`. * @param ctx the parse tree */ exitMixinReference?: (ctx: MixinReferenceContext) => void; /** * Enter a parse tree produced by `LessParser.selectors`. * @param ctx the parse tree */ enterSelectors?: (ctx: SelectorsContext) => void; /** * Exit a parse tree produced by `LessParser.selectors`. * @param ctx the parse tree */ exitSelectors?: (ctx: SelectorsContext) => void; /** * Enter a parse tree produced by `LessParser.selector`. * @param ctx the parse tree */ enterSelector?: (ctx: SelectorContext) => void; /** * Exit a parse tree produced by `LessParser.selector`. * @param ctx the parse tree */ exitSelector?: (ctx: SelectorContext) => void; /** * Enter a parse tree produced by `LessParser.attrib`. * @param ctx the parse tree */ enterAttrib?: (ctx: AttribContext) => void; /** * Exit a parse tree produced by `LessParser.attrib`. * @param ctx the parse tree */ exitAttrib?: (ctx: AttribContext) => void; /** * Enter a parse tree produced by `LessParser.negation`. * @param ctx the parse tree */ enterNegation?: (ctx: NegationContext) => void; /** * Exit a parse tree produced by `LessParser.negation`. * @param ctx the parse tree */ exitNegation?: (ctx: NegationContext) => void; /** * Enter a parse tree produced by `LessParser.pseudo`. * @param ctx the parse tree */ enterPseudo?: (ctx: PseudoContext) => void; /** * Exit a parse tree produced by `LessParser.pseudo`. * @param ctx the parse tree */ exitPseudo?: (ctx: PseudoContext) => void; /** * Enter a parse tree produced by `LessParser.element`. * @param ctx the parse tree */ enterElement?: (ctx: ElementContext) => void; /** * Exit a parse tree produced by `LessParser.element`. * @param ctx the parse tree */ exitElement?: (ctx: ElementContext) => void; /** * Enter a parse tree produced by `LessParser.selectorPrefix`. * @param ctx the parse tree */ enterSelectorPrefix?: (ctx: SelectorPrefixContext) => void; /** * Exit a parse tree produced by `LessParser.selectorPrefix`. * @param ctx the parse tree */ exitSelectorPrefix?: (ctx: SelectorPrefixContext) => void; /** * Enter a parse tree produced by `LessParser.attribRelate`. * @param ctx the parse tree */ enterAttribRelate?: (ctx: AttribRelateContext) => void; /** * Exit a parse tree produced by `LessParser.attribRelate`. * @param ctx the parse tree */ exitAttribRelate?: (ctx: AttribRelateContext) => void; /** * Enter a parse tree produced by `LessParser.identifier`. * @param ctx the parse tree */ enterIdentifier?: (ctx: IdentifierContext) => void; /** * Exit a parse tree produced by `LessParser.identifier`. * @param ctx the parse tree */ exitIdentifier?: (ctx: IdentifierContext) => void; /** * Enter a parse tree produced by `LessParser.identifierPart`. * @param ctx the parse tree */ enterIdentifierPart?: (ctx: IdentifierPartContext) => void; /** * Exit a parse tree produced by `LessParser.identifierPart`. * @param ctx the parse tree */ exitIdentifierPart?: (ctx: IdentifierPartContext) => void; /** * Enter a parse tree produced by `LessParser.identifierVariableName`. * @param ctx the parse tree */ enterIdentifierVariableName?: (ctx: IdentifierVariableNameContext) => void; /** * Exit a parse tree produced by `LessParser.identifierVariableName`. * @param ctx the parse tree */ exitIdentifierVariableName?: (ctx: IdentifierVariableNameContext) => void; /** * Enter a parse tree produced by `LessParser.property`. * @param ctx the parse tree */ enterProperty?: (ctx: PropertyContext) => void; /** * Exit a parse tree produced by `LessParser.property`. * @param ctx the parse tree */ exitProperty?: (ctx: PropertyContext) => void; /** * Enter a parse tree produced by `LessParser.values`. * @param ctx the parse tree */ enterValues?: (ctx: ValuesContext) => void; /** * Exit a parse tree produced by `LessParser.values`. * @param ctx the parse tree */ exitValues?: (ctx: ValuesContext) => void; /** * Enter a parse tree produced by `LessParser.url`. * @param ctx the parse tree */ enterUrl?: (ctx: UrlContext) => void; /** * Exit a parse tree produced by `LessParser.url`. * @param ctx the parse tree */ exitUrl?: (ctx: UrlContext) => void; /** * Enter a parse tree produced by `LessParser.measurement`. * @param ctx the parse tree */ enterMeasurement?: (ctx: MeasurementContext) => void; /** * Exit a parse tree produced by `LessParser.measurement`. * @param ctx the parse tree */ exitMeasurement?: (ctx: MeasurementContext) => void; }
the_stack
import { TableFeature } from '../core/instance' import { OnChangeFn, TableGenerics, TableInstance, Row, RowModel, Updater, } from '../types' import { makeStateUpdater, memo } from '../utils' export type RowSelectionState = Record<string, boolean> export type RowSelectionTableState = { rowSelection: RowSelectionState } export type RowSelectionOptions<TGenerics extends TableGenerics> = { enableRowSelection?: boolean | ((row: Row<TGenerics>) => boolean) enableMultiRowSelection?: boolean | ((row: Row<TGenerics>) => boolean) enableSubRowSelection?: boolean | ((row: Row<TGenerics>) => boolean) onRowSelectionChange?: OnChangeFn<RowSelectionState> // enableGroupingRowSelection?: // | boolean // | (( // row: Row<TGenerics> // ) => boolean) // isAdditiveSelectEvent?: (e: unknown) => boolean // isInclusiveSelectEvent?: (e: unknown) => boolean // selectRowsFn?: ( // instance: TableInstance< // TData, // TValue, // TFilterFns, // TSortingFns, // TAggregationFns // >, // rowModel: RowModel<TGenerics> // ) => RowModel<TGenerics> } export type RowSelectionRow = { getIsSelected: () => boolean getIsSomeSelected: () => boolean getCanSelect: () => boolean getCanMultiSelect: () => boolean getCanSelectSubRows: () => boolean toggleSelected: (value?: boolean) => void getToggleSelectedHandler: () => (event: unknown) => void } export type RowSelectionInstance<TGenerics extends TableGenerics> = { getToggleAllRowsSelectedHandler: () => (event: unknown) => void getToggleAllPageRowsSelectedHandler: () => (event: unknown) => void setRowSelection: (updater: Updater<RowSelectionState>) => void resetRowSelection: (defaultState?: boolean) => void getIsAllRowsSelected: () => boolean getIsAllPageRowsSelected: () => boolean getIsSomeRowsSelected: () => boolean getIsSomePageRowsSelected: () => boolean toggleAllRowsSelected: (value?: boolean) => void toggleAllPageRowsSelected: (value?: boolean) => void getPreSelectedRowModel: () => RowModel<TGenerics> getSelectedRowModel: () => RowModel<TGenerics> getFilteredSelectedRowModel: () => RowModel<TGenerics> getGroupedSelectedRowModel: () => RowModel<TGenerics> } // export const RowSelection: TableFeature = { getInitialState: (state): RowSelectionTableState => { return { rowSelection: {}, ...state, } }, getDefaultOptions: <TGenerics extends TableGenerics>( instance: TableInstance<TGenerics> ): RowSelectionOptions<TGenerics> => { return { onRowSelectionChange: makeStateUpdater('rowSelection', instance), enableRowSelection: true, enableMultiRowSelection: true, enableSubRowSelection: true, // enableGroupingRowSelection: false, // isAdditiveSelectEvent: (e: unknown) => !!e.metaKey, // isInclusiveSelectEvent: (e: unknown) => !!e.shiftKey, } }, createInstance: <TGenerics extends TableGenerics>( instance: TableInstance<TGenerics> ): RowSelectionInstance<TGenerics> => { return { setRowSelection: updater => instance.options.onRowSelectionChange?.(updater), resetRowSelection: defaultState => instance.setRowSelection( defaultState ? {} : instance.initialState.rowSelection ?? {} ), toggleAllRowsSelected: value => { instance.setRowSelection(old => { value = typeof value !== 'undefined' ? value : !instance.getIsAllRowsSelected() const rowSelection = { ...old } const preGroupedFlatRows = instance.getPreGroupedRowModel().flatRows // We don't use `mutateRowIsSelected` here for performance reasons. // All of the rows are flat already, so it wouldn't be worth it if (value) { preGroupedFlatRows.forEach(row => { rowSelection[row.id] = true }) } else { preGroupedFlatRows.forEach(row => { delete rowSelection[row.id] }) } return rowSelection }) }, toggleAllPageRowsSelected: value => instance.setRowSelection(old => { const resolvedValue = typeof value !== 'undefined' ? value : !instance.getIsAllPageRowsSelected() const rowSelection: RowSelectionState = { ...old } instance.getRowModel().rows.forEach(row => { mutateRowIsSelected(rowSelection, row.id, resolvedValue, instance) }) return rowSelection }), // addRowSelectionRange: rowId => { // const { // rows, // rowsById, // options: { selectGroupingRows, selectSubRows }, // } = instance // const findSelectedRow = (rows: Row[]) => { // let found // rows.find(d => { // if (d.getIsSelected()) { // found = d // return true // } // const subFound = findSelectedRow(d.subRows || []) // if (subFound) { // found = subFound // return true // } // return false // }) // return found // } // const firstRow = findSelectedRow(rows) || rows[0] // const lastRow = rowsById[rowId] // let include = false // const selectedRowIds = {} // const addRow = (row: Row) => { // mutateRowIsSelected(selectedRowIds, row.id, true, { // rowsById, // selectGroupingRows: selectGroupingRows!, // selectSubRows: selectSubRows!, // }) // } // instance.rows.forEach(row => { // const isFirstRow = row.id === firstRow.id // const isLastRow = row.id === lastRow.id // if (isFirstRow || isLastRow) { // if (!include) { // include = true // } else if (include) { // addRow(row) // include = false // } // } // if (include) { // addRow(row) // } // }) // instance.setRowSelection(selectedRowIds) // }, getPreSelectedRowModel: () => instance.getCoreRowModel(), getSelectedRowModel: memo( () => [instance.getState().rowSelection, instance.getCoreRowModel()], (rowSelection, rowModel) => { if (!Object.keys(rowSelection).length) { return { rows: [], flatRows: [], rowsById: {}, } } return selectRowsFn(instance, rowModel) }, { key: process.env.NODE_ENV === 'development' && 'getSelectedRowModel', debug: () => instance.options.debugAll ?? instance.options.debugTable, } ), getFilteredSelectedRowModel: memo( () => [ instance.getState().rowSelection, instance.getFilteredRowModel(), ], (rowSelection, rowModel) => { if (!Object.keys(rowSelection).length) { return { rows: [], flatRows: [], rowsById: {}, } } return selectRowsFn(instance, rowModel) }, { key: process.env.NODE_ENV === 'production' && 'getFilteredSelectedRowModel', debug: () => instance.options.debugAll ?? instance.options.debugTable, } ), getGroupedSelectedRowModel: memo( () => [instance.getState().rowSelection, instance.getSortedRowModel()], (rowSelection, rowModel) => { if (!Object.keys(rowSelection).length) { return { rows: [], flatRows: [], rowsById: {}, } } return selectRowsFn(instance, rowModel) }, { key: process.env.NODE_ENV === 'production' && 'getGroupedSelectedRowModel', debug: () => instance.options.debugAll ?? instance.options.debugTable, } ), /// // getGroupingRowCanSelect: rowId => { // const row = instance.getRow(rowId) // if (!row) { // throw new Error() // } // if (typeof instance.options.enableGroupingRowSelection === 'function') { // return instance.options.enableGroupingRowSelection(row) // } // return instance.options.enableGroupingRowSelection ?? false // }, getIsAllRowsSelected: () => { const preFilteredFlatRows = instance.getPreFilteredRowModel().flatRows const { rowSelection } = instance.getState() let isAllRowsSelected = Boolean( preFilteredFlatRows.length && Object.keys(rowSelection).length ) if (isAllRowsSelected) { if (preFilteredFlatRows.some(row => !rowSelection[row.id])) { isAllRowsSelected = false } } return isAllRowsSelected }, getIsAllPageRowsSelected: () => { const paginationFlatRows = instance.getPaginationRowModel().flatRows const { rowSelection } = instance.getState() let isAllPageRowsSelected = !!paginationFlatRows.length if ( isAllPageRowsSelected && paginationFlatRows.some(row => !rowSelection[row.id]) ) { isAllPageRowsSelected = false } return isAllPageRowsSelected }, getIsSomeRowsSelected: () => { return ( !instance.getIsAllRowsSelected() && !!Object.keys(instance.getState().rowSelection ?? {}).length ) }, getIsSomePageRowsSelected: () => { const paginationFlatRows = instance.getPaginationRowModel().flatRows return instance.getIsAllPageRowsSelected() ? false : paginationFlatRows.some( d => d.getIsSelected() || d.getIsSomeSelected() ) }, getToggleAllRowsSelectedHandler: () => { return (e: unknown) => { instance.toggleAllRowsSelected( ((e as MouseEvent).target as HTMLInputElement).checked ) } }, getToggleAllPageRowsSelectedHandler: () => { return (e: unknown) => { instance.toggleAllPageRowsSelected( ((e as MouseEvent).target as HTMLInputElement).checked ) } }, } }, createRow: <TGenerics extends TableGenerics>( row: Row<TGenerics>, instance: TableInstance<TGenerics> ): RowSelectionRow => { return { toggleSelected: value => { const isSelected = row.getIsSelected() instance.setRowSelection(old => { value = typeof value !== 'undefined' ? value : !isSelected if (isSelected === value) { return old } const selectedRowIds = { ...old } mutateRowIsSelected(selectedRowIds, row.id, value, instance) return selectedRowIds }) }, getIsSelected: () => { const { rowSelection } = instance.getState() return isRowSelected(row, rowSelection, instance) === true }, getIsSomeSelected: () => { const { rowSelection } = instance.getState() return isRowSelected(row, rowSelection, instance) === 'some' }, getCanSelect: () => { if (typeof instance.options.enableRowSelection === 'function') { return instance.options.enableRowSelection(row) } return instance.options.enableRowSelection ?? true }, getCanSelectSubRows: () => { if (typeof instance.options.enableSubRowSelection === 'function') { return instance.options.enableSubRowSelection(row) } return instance.options.enableSubRowSelection ?? true }, getCanMultiSelect: () => { if (typeof instance.options.enableMultiRowSelection === 'function') { return instance.options.enableMultiRowSelection(row) } return instance.options.enableMultiRowSelection ?? true }, getToggleSelectedHandler: () => { const canSelect = row.getCanSelect() return (e: unknown) => { if (!canSelect) return row.toggleSelected( ((e as MouseEvent).target as HTMLInputElement)?.checked ) } }, } }, } const mutateRowIsSelected = <TGenerics extends TableGenerics>( selectedRowIds: Record<string, boolean>, id: string, value: boolean, instance: TableInstance<TGenerics> ) => { const row = instance.getRow(id) const isGrouped = row.getIsGrouped() // if ( // TODO: enforce grouping row selection rules // !isGrouped || // (isGrouped && instance.options.enableGroupingRowSelection) // ) { if (value) { selectedRowIds[id] = true } else { delete selectedRowIds[id] } // } if (row.subRows?.length && row.getCanSelectSubRows()) { row.subRows.forEach(row => mutateRowIsSelected(selectedRowIds, row.id, value, instance) ) } } export function selectRowsFn<TGenerics extends TableGenerics>( instance: TableInstance<TGenerics>, rowModel: RowModel<TGenerics> ): RowModel<TGenerics> { const rowSelection = instance.getState().rowSelection const newSelectedFlatRows: Row<TGenerics>[] = [] const newSelectedRowsById: Record<string, Row<TGenerics>> = {} // Filters top level and nested rows const recurseRows = (rows: Row<TGenerics>[], depth = 0): Row<TGenerics>[] => { return rows .map(row => { const isSelected = isRowSelected(row, rowSelection, instance) === true if (isSelected) { newSelectedFlatRows.push(row) newSelectedRowsById[row.id] = row } if (row.subRows?.length) { row = { ...row, subRows: recurseRows(row.subRows, depth + 1), } } if (isSelected) { return row } }) .filter(Boolean) as Row<TGenerics>[] } return { rows: recurseRows(rowModel.rows), flatRows: newSelectedFlatRows, rowsById: newSelectedRowsById, } } export function isRowSelected<TGenerics extends TableGenerics>( row: Row<TGenerics>, selection: Record<string, boolean>, instance: TableInstance<TGenerics> ): boolean | 'some' { if (selection[row.id]) { return true } if (row.subRows && row.subRows.length) { let allChildrenSelected = true let someSelected = false row.subRows.forEach(subRow => { // Bail out early if we know both of these if (someSelected && !allChildrenSelected) { return } if (isRowSelected(subRow, selection, instance)) { someSelected = true } else { allChildrenSelected = false } }) return allChildrenSelected ? true : someSelected ? 'some' : false } return false }
the_stack
import { async, TestBed } from '@angular/core/testing'; // App import { NovoTabbedGroupPickerElement, TabbedGroupPickerTab, TabbedGroupPickerQuickSelect } from './TabbedGroupPicker'; import { NovoTabbedGroupPickerModule } from './TabbedGroupPicker.module'; import { ComponentUtils } from '../../utils/component-utils/ComponentUtils'; import { NovoLabelService } from '../../services/novo-label-service'; describe('Elements: NovoTabbedGroupPickerElement', () => { let fixture; let component: NovoTabbedGroupPickerElement; const getChickenTab = (): TabbedGroupPickerTab => ({ typeName: 'chickens', typeLabel: 'Chickens', valueField: 'chickenId', labelField: 'bwaack', data: [ ({ chickenId: 3, bwaack: 'bwock?' } as unknown) as { selected?: boolean }, ({ chickenId: 4, bwaack: 'baa bock' } as unknown) as { selected?: boolean }, ], }); beforeEach(async(() => { TestBed.configureTestingModule({ providers: [{ provide: ComponentUtils, useClass: ComponentUtils }, NovoLabelService], imports: [NovoTabbedGroupPickerModule], }).compileComponents(); fixture = TestBed.createComponent(NovoTabbedGroupPickerElement); component = fixture.debugElement.componentInstance; })); it('should initialize correctly', () => { expect(component).toBeTruthy(); }); describe('function: ngOnInit', () => { const firstTab = { typeName: 'firstTypeName', typeLabel: 'firstTypeLabel', valueField: 'firstValueField', labelField: 'firstLabelField', data: [], }; beforeEach(() => { component.tabs = [ firstTab, { typeName: 'secondTypeName', typeLabel: 'secondTypeLabel', valueField: 'secondValueField', labelField: 'secondLabelField', data: [], }, ]; }); it('should activate the first item in the input tabs array', () => { component.ngOnInit(); expect(component.displayTab).toEqual(firstTab); // these should be identical but should NOT be the same object or else the filter function // will permanently remove data from the component (for the life of the component at least). expect(component.displayTab).not.toBe(firstTab); }); it('should stop loading', () => { component.ngOnInit(); expect(component.loading).toEqual(false); }); }); describe('function: filter', () => { const getLetter = (n: number) => String.fromCharCode((n % 26) + 65); const turnNumbersIntoLetters = (val: string): string => Array.from(val) .map((n) => parseInt(n, 10)) .map(getLetter) .join(''); const buildBigDataset = (): Partial<TabbedGroupPickerTab>[] => { const names: string[] = Array(200) .fill(0) .map((e, i) => String(Math.pow(1000 + i, 5))); // make a bunch of ~16 character strings const tabNames = names.slice(0, 100); const labelFieldNames = names.splice(0, 100); const tabs = tabNames.map((typeName, i) => ({ typeName, labelField: labelFieldNames[i], // search/filter only looks at labelField })); tabs.forEach((tab) => { const { labelField } = tab; tab['data'] = Array(1000) .fill(0) .map((n, i) => ({ [labelField]: turnNumbersIntoLetters(`${labelField}${i}`), })); }); return tabs; }; it('should filter large datasets in a reasonable amount of time', () => { const amountOfTimeInMillisecondsThatIndicatesAGrosslyInefficientAlgorithm = 1000; component.tabs = buildBigDataset() as TabbedGroupPickerTab[]; component.ngOnInit(); const start = performance.now(); component.filter('asdfasdf'); const timeItTakesToSearchAMillionItems = performance.now() - start; expect(timeItTakesToSearchAMillionItems).toBeLessThan(amountOfTimeInMillisecondsThatIndicatesAGrosslyInefficientAlgorithm); }); }); describe('function: createChildrenReferences', () => { it('should make it so that children of data list items are references to other data list items', () => { const dinosaurs = [ { id: 5, name: 'Allosaurus', children: [{ chickenId: 3, bwaack: 'bwock?' }, { chickenId: 4, bwaack: 'tweeet' }], }, ]; component.tabs = [ getChickenTab(), { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: dinosaurs, }, ]; const chicken = component.tabs[0].data[0]; let childOfAllosaurus = component.tabs[1].data[0]['children'][0]; expect(childOfAllosaurus).not.toBe(chicken); component.createChildrenReferences(); childOfAllosaurus = component.tabs[1].data[0]['children'][0]; expect(childOfAllosaurus).toBe(chicken); }); }); describe('function: updateParentsAndQuickSelect', () => { it('should set parents to selected if their only child is selected', () => { component.tabs = [ getChickenTab(), { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: [ ({ id: 5, name: 'Allosaurus', children: [({ chickenId: 3, bwaack: 'bwock?' } as unknown) as { selected?: boolean }], } as unknown) as { selected?: boolean }, ], }, ]; component.createChildrenReferences(); component.tabs[0].data[0].selected = true; const parent = component.tabs[1].data[0]; expect(parent.selected).toEqual(undefined); component.updateParentsAndQuickSelect(); expect(parent.selected).toEqual(true); }); it('should set parents to unselected if none of their children are selected', () => { component.tabs = [ getChickenTab(), { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: [ ({ selected: true, id: 5, name: 'Allosaurus', children: [...getChickenTab().data], } as unknown) as { selected?: boolean }, ], }, ]; component.createChildrenReferences(); const parent = component.tabs[1].data[0]; expect(parent.selected).toEqual(true); component.updateParentsAndQuickSelect(); expect(parent.selected).toEqual(undefined); }); it('should set parents to indeterminate if one of their many children is selected', () => { const dinosaurTab = { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: [ ({ selected: true, id: 5, name: 'Allosaurus', children: [...getChickenTab().data], } as unknown) as { selected?: boolean; indeterminate?: boolean }, ], }; component.tabs = [ { ...getChickenTab(), data: [...getChickenTab().data], }, dinosaurTab, ]; component.tabs[0].data[0].selected = true; component.createChildrenReferences(); const parent = dinosaurTab.data[0]; expect(parent.selected).toEqual(true); component.updateParentsAndQuickSelect(); expect(parent.selected).toEqual(undefined); expect(parent.indeterminate).toEqual(true); }); }); describe('function: getSelectedValue', () => { it('should return indeterminate if one value is selected', () => { const childArray = [{ id: 1, name: 'Scout', selected: true }, { id: 2, name: 'Atticus' }]; const result = component.getSelectedState(childArray); expect(result).toEqual('indeterminate'); }); it('should return selected if every element of the child array is selected', () => { const childArray = [{ id: 1, name: 'Scout', selected: true }, { id: 2, name: 'Atticus', selected: true }]; const result = component.getSelectedState(childArray); expect(result).toEqual('selected'); }); it('should return undefined if none of the items in the child array are selected', () => { const childArray = [{ id: 1, name: 'Scout' }, { id: 2, name: 'Atticus' }]; const result = component.getSelectedState(childArray as any); expect(result).toEqual(undefined); }); }); describe('function: updateParentsAndQuickSelect', () => { it('should select each item in the quick select group', () => { const data = [{ id: 1, name: 'chicken', selected: true }, { id: 2, name: 'goldfish' }]; const quickSelectItem: TabbedGroupPickerQuickSelect = { childTypeName: 'animals', children: [1], label: 'chicken' }; component.quickSelectConfig = { label: 'Quick Select', items: [quickSelectItem], }; component.tabs = [ { typeName: 'animals', typeLabel: 'Animalz', valueField: 'id', labelField: 'name', data, }, ]; component.createChildrenReferences(); expect(quickSelectItem.selected).toEqual(undefined); component.updateParentsAndQuickSelect(); expect(quickSelectItem.selected).toEqual(true); }); }); describe('function: onItemToggled', () => { it('should use an algorithm more efficient than O(MxN^2)', () => { // this dataset takes about 3 orders of magnitude longer for MxN^2 vs MxN const amountOfTimeInMillisecondsThatIndicatesAGrosslyInefficientAlgorithm = 500; const children: TabbedGroupPickerTab['data'] = Array(10000) .fill(0) .map((n, i) => ({ value: i, label: `child #${i}`, selected: true, })); const childTab: TabbedGroupPickerTab = { typeLabel: 'child', typeName: 'child', valueField: 'value', labelField: 'label', data: children, }; const parentTabs: TabbedGroupPickerTab[] = Array(10) .fill(0) .map( (n, i): TabbedGroupPickerTab => ({ typeLabel: 'parent', typeName: `parent${i}`, labelField: `label${i}`, valueField: `value${i}`, childTypeName: 'child', data: Array(10) .fill(0) .map((nn, ii) => ({ [`value${i}`]: i, [`label${i}`]: i, children, })), }), ); component.tabs = [...parentTabs, childTab]; const firstParent = parentTabs[0].data[0]; firstParent.selected = true; const start = performance.now(); component.onItemToggled(firstParent); const end = performance.now(); expect(end - start).toBeLessThan(amountOfTimeInMillisecondsThatIndicatesAGrosslyInefficientAlgorithm); const allAreSelected = component.tabs.every((tab) => tab.data.every((datum) => datum.selected)); expect(allAreSelected).toBe(true); }); it('should select each item in the quick select group', () => { const data = [{ id: 1, name: 'chicken', selected: false }, { id: 2, name: 'goldfish', selected: false }]; const quickSelectItem: TabbedGroupPickerQuickSelect = { childTypeName: 'animals', children: [data[0]], label: 'chicken', selected: true, }; component.quickSelectConfig = { label: 'Quick Select', items: [quickSelectItem], }; component.tabs = [{ typeName: 'animals', typeLabel: 'Animalz', valueField: 'id', labelField: 'name', data }]; const chicken = component.tabs[0].data[0]; const goldfish = component.tabs[0].data[1]; expect(chicken.selected).toBeFalsy(); component.onItemToggled(quickSelectItem as any); expect(chicken.selected).toEqual(true); expect(goldfish.selected).toEqual(false); }); it('should unselect each item in the quick select group', () => { const data = [{ id: 1, name: 'chicken', selected: true }, { id: 2, name: 'goldfish' }]; const quickSelectItem: TabbedGroupPickerQuickSelect = { childTypeName: 'animals', children: [data[0]], label: 'chicken', selected: false, }; component.quickSelectConfig = { label: 'Quick Select', items: [quickSelectItem], }; component.tabs = [ { typeName: 'animals', typeLabel: 'Animalz', valueField: 'id', labelField: 'name', data, }, ]; const chicken = component.tabs[0].data[0]; expect(chicken.selected).toEqual(true); component.onItemToggled(quickSelectItem as any); expect(chicken.selected).toEqual(undefined); }); it('should update the selected status on the tab as well as the display data', () => { component.tabs = [getChickenTab()]; component.ngOnInit(); const chicken = component.tabs[0].data[0]; chicken.selected = true; component.onItemToggled(chicken); const selectedItem = component.tabs[0].data[0]; const displayReference = component.displayTabs.find(({ typeName }) => typeName === 'chickens').data[0]; expect(selectedItem.selected).toEqual(true); expect(displayReference.selected).toEqual(true); expect(selectedItem).toEqual(displayReference); }); it('should update the selected status of a group to indeterminate if an item in the group is selected but others are not', () => { const dinosaurs = [ { id: 5, name: 'Allosaurus', children: [{ chickenId: 3, bwaack: 'bwock?' }, { chickenId: 4, bwaack: 'tweeet' }], }, ]; component.tabs = [ getChickenTab(), { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: dinosaurs, }, ]; const chicken = component.tabs[0].data[0]; chicken.selected = true; component.createChildrenReferences(); component.onItemToggled(chicken); const selectedItem = component.tabs[0].data[0]; expect(selectedItem.selected).toEqual(true); const indeterminateGroup = component.tabs[1].data[0]; expect(indeterminateGroup.selected).toBeFalsy(); expect(indeterminateGroup['indeterminate']).toEqual(true); }); it('should update the selected status of a group if the only item in the group is selected', () => { const chickenTab = getChickenTab(); const dinosaur = { id: '1', name: 'Tyrannosaurus', children: [chickenTab.data[0]] }; component.tabs = [ chickenTab, { typeName: 'dinosaurs', typeLabel: 'Dinosaurs', valueField: 'id', labelField: 'name', childTypeName: 'chickens', data: [dinosaur], }, ]; const chicken = component.tabs[0].data[0]; chicken.selected = true; const tRex = component.tabs[1].data[0]; component.onItemToggled(chicken); expect(tRex.selected).toEqual(true); }); }); });
the_stack
import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { QuizExercise, QuizStatus } from 'app/entities/quiz/quiz-exercise.model'; import { createRequestOption } from 'app/shared/util/request-util'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; import { QuizQuestion } from 'app/entities/quiz/quiz-question.model'; import { downloadFile } from 'app/shared/util/download.util'; export type EntityResponseType = HttpResponse<QuizExercise>; export type EntityArrayResponseType = HttpResponse<QuizExercise[]>; @Injectable({ providedIn: 'root' }) export class QuizExerciseService { private resourceUrl = SERVER_API_URL + 'api/quiz-exercises'; constructor(private http: HttpClient, private exerciseService: ExerciseService) {} /** * Create the given quiz exercise * @param quizExercise the quiz exercise that should be created */ create(quizExercise: QuizExercise): Observable<EntityResponseType> { const copy = this.exerciseService.convertDateFromClient(quizExercise); copy.categories = this.exerciseService.stringifyExerciseCategories(copy); return this.http.post<QuizExercise>(this.resourceUrl, copy, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Update the given quiz exercise * @param quizExercise the quiz exercise that should be updated * @param req Additional parameters that should be passed to the server when updating the exercise */ update(quizExercise: QuizExercise, req?: any): Observable<EntityResponseType> { const options = createRequestOption(req); const copy = this.exerciseService.convertDateFromClient(quizExercise); copy.categories = this.exerciseService.stringifyExerciseCategories(copy); return this.http.put<QuizExercise>(this.resourceUrl, copy, { params: options, observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Find the quiz exercise with the given id * @param quizExerciseId the id of the quiz exercise that should be found */ find(quizExerciseId: number): Observable<EntityResponseType> { return this.http.get<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}`, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Recalculate the statistics for a given quiz exercise * @param quizExerciseId the id of the quiz exercise for which the statistics should be recalculated */ recalculate(quizExerciseId: number): Observable<EntityResponseType> { return this.http.get<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}/recalculate-statistics`, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Note: the exercises in the response do not contain participations and do not contain the course to save network bandwidth * They also do not contain questions * * @param courseId the course for which the quiz exercises should be returned */ findForCourse(courseId: number): Observable<EntityArrayResponseType> { return this.http.get<QuizExercise[]>(`api/courses/${courseId}/quiz-exercises`, { observe: 'response' }).pipe( map((res: EntityArrayResponseType) => this.exerciseService.convertDateArrayFromServer(res)), map((res: EntityArrayResponseType) => this.exerciseService.convertExerciseCategoryArrayFromServer(res)), ); } /** * Note: the exercises in the response do not contain participations, the course and also not the exerciseGroup to save network bandwidth * They also do not contain questions * * @param examId the exam for which the quiz exercises should be returned */ findForExam(examId: number): Observable<EntityArrayResponseType> { return this.http.get<QuizExercise[]>(`api/${examId}/quiz-exercises`, { observe: 'response' }).pipe( map((res: EntityArrayResponseType) => this.exerciseService.convertDateArrayFromServer(res)), map((res: EntityArrayResponseType) => this.exerciseService.convertExerciseCategoryArrayFromServer(res)), ); } /** * Find the quiz exercise with the given id, with information filtered for students * @param quizExerciseId the id of the quiz exercise that should be loaded */ findForStudent(quizExerciseId: number): Observable<EntityResponseType> { return this.http.get<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}/for-student`, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Open a quiz exercise for practice * @param quizExerciseId the id of the quiz exercise that should be opened for practice */ openForPractice(quizExerciseId: number): Observable<EntityResponseType> { return this.http.put<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}/open-for-practice`, null, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Start a quiz exercise * @param quizExerciseId the id of the quiz exercise that should be started */ start(quizExerciseId: number): Observable<EntityResponseType> { return this.http.put<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}/start-now`, null, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Set a quiz exercise visible * @param quizExerciseId the id of the quiz exercise that should be set visible */ setVisible(quizExerciseId: number): Observable<EntityResponseType> { return this.http.put<QuizExercise>(`${this.resourceUrl}/${quizExerciseId}/set-visible`, null, { observe: 'response' }).pipe( map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)), map((res: EntityResponseType) => this.exerciseService.convertExerciseCategoriesFromServer(res)), ); } /** * Load all quiz exercises */ query(): Observable<EntityArrayResponseType> { return this.http.get<QuizExercise[]>(this.resourceUrl, { observe: 'response' }).pipe( map((res: EntityArrayResponseType) => this.exerciseService.convertDateArrayFromServer(res)), map((res: EntityArrayResponseType) => this.exerciseService.convertExerciseCategoryArrayFromServer(res)), ); } /** * Delete a quiz exercise * @param quizExerciseId the id of the quiz exercise that should be deleted */ delete(quizExerciseId: number): Observable<HttpResponse<{}>> { return this.http.delete(`${this.resourceUrl}/${quizExerciseId}`, { observe: 'response' }); } /** * Reset a quiz exercise * @param quizExerciseId the id of the quiz exercise that should be reset */ reset(quizExerciseId: number): Observable<HttpResponse<{}>> { return this.http.delete(`${SERVER_API_URL + 'api/exercises'}/${quizExerciseId}/reset`, { observe: 'response' }); } /** * Exports given quiz questions into json file * @param quizQuestions Quiz questions we want to export * @param exportAll If true exports all questions, else exports only those whose export flag is true * @param fileName Name (without ending) of the resulting file, defaults to 'quiz' */ exportQuiz(quizQuestions?: QuizQuestion[], exportAll?: boolean, fileName?: string) { // Make list of questions which we need to export, const questions: QuizQuestion[] = []; quizQuestions!.forEach((question) => { if (exportAll === true || question.exportQuiz) { question.quizQuestionStatistic = undefined; question.exercise = undefined; questions.push(question); } }); if (questions.length === 0) { return; } // Make blob from the list of questions and download the file, const quizJson = JSON.stringify(questions); const blob = new Blob([quizJson], { type: 'application/json' }); downloadFile(blob, (fileName ?? 'quiz') + '.json'); } /** * Evaluates the QuizStatus for a given quiz * * @param quizExercise the quiz exercise to get the status of * @return the status of the quiz */ getStatus(quizExercise: QuizExercise) { if (quizExercise.isPlannedToStart && quizExercise.remainingTime != undefined) { if (quizExercise.remainingTime <= 0) { // the quiz is over return quizExercise.isOpenForPractice ? QuizStatus.OPEN_FOR_PRACTICE : QuizStatus.CLOSED; } else { return QuizStatus.ACTIVE; } } // the quiz hasn't started yet return quizExercise.isVisibleBeforeStart ? QuizStatus.VISIBLE : QuizStatus.HIDDEN; } }
the_stack
import 'slickgrid/plugins/slick.rowdetailview'; import 'slickgrid/plugins/slick.rowselectionmodel'; import { ApplicationRef, ComponentRef, Injectable, Type, ViewContainerRef } from '@angular/core'; import { addToArrayWhenNotExists, castObservableToPromise, Column, RowDetailViewExtension as UniversalRowDetailViewExtension, RxJsFacade, SharedService, SlickEventHandler, SlickGrid, SlickNamespace, SlickRowDetailView, } from '@slickgrid-universal/common'; import { EventPubSubService } from '@slickgrid-universal/event-pub-sub'; import { Observable, Subject, Subscription } from 'rxjs'; import * as DOMPurify_ from 'dompurify'; const DOMPurify = DOMPurify_; // patch to fix rollup to work import { GridOption, RowDetailView } from '../models/index'; import { AngularUtilService } from '../services/angularUtil.service'; import { unsubscribeAllObservables } from '../services/utilities'; // using external non-typed js libraries declare const Slick: SlickNamespace; const ROW_DETAIL_CONTAINER_PREFIX = 'container_'; const PRELOAD_CONTAINER_PREFIX = 'container_loading'; export interface CreatedView { id: string | number; dataContext: any; componentRef?: ComponentRef<any>; } @Injectable() export class RowDetailViewExtension implements UniversalRowDetailViewExtension { rowDetailContainer!: ViewContainerRef; private _addon: any; private _addonOptions!: RowDetailView | null; private _eventHandler: SlickEventHandler; private _preloadComponent: Type<object> | undefined; private _views: CreatedView[] = []; private _viewComponent!: Type<object>; private _subscriptions: Subscription[] = []; private _userProcessFn!: (item: any) => Promise<any> | Observable<any> | Subject<any>; constructor( private readonly angularUtilService: AngularUtilService, private readonly appRef: ApplicationRef, private readonly eventPubSubService: EventPubSubService, private readonly sharedService: SharedService, private rxjs?: RxJsFacade, ) { this._eventHandler = new Slick.EventHandler(); } private get datasetIdPropName(): string { return this.gridOptions.datasetIdPropertyName || 'id'; } get eventHandler(): SlickEventHandler { return this._eventHandler; } get gridOptions(): GridOption { return (this.sharedService?.gridOptions ?? {}) as GridOption; } get rowDetailViewOptions(): RowDetailView | undefined { return this.gridOptions.rowDetailView; } addRxJsResource(rxjs: RxJsFacade) { this.rxjs = rxjs; } /** Dispose of the RowDetailView Extension */ dispose() { // unsubscribe all SlickGrid events this._eventHandler.unsubscribeAll(); if (this._addon && this._addon.destroy) { this._addon.destroy(); } this._addonOptions = null; // also unsubscribe all RxJS subscriptions this._subscriptions = unsubscribeAllObservables(this._subscriptions); this.disposeAllViewComponents(); } /** Dispose of all the opened Row Detail Panels Angular View Components */ disposeAllViewComponents() { this._views.forEach((compRef) => this.disposeViewComponent(compRef)); this._views = []; } /** * Create the plugin before the Grid creation, else it will behave oddly. * Mostly because the column definitions might change after the grid creation */ create(columnDefinitions: Column[], gridOptions: GridOption): SlickRowDetailView | null { if (columnDefinitions && gridOptions) { if (!gridOptions.rowDetailView) { throw new Error('The Row Detail View requires options to be passed via the "rowDetailView" property of the Grid Options'); } if (gridOptions?.rowDetailView) { if (!this._addon) { if (typeof gridOptions.rowDetailView.process === 'function') { // we need to keep the user "process" method and replace it with our own execution method // we do this because when we get the item detail, we need to call "onAsyncResponse.notify" for the plugin to work this._userProcessFn = gridOptions.rowDetailView.process as (item: any) => Observable<any>; // keep user's process method gridOptions.rowDetailView.process = (item) => this.onProcessing(item); // replace process method & run our internal one } else { throw new Error('You need to provide a "process" function for the Row Detail Extension to work properly'); } // load the Preload & RowDetail Templates (could be straight HTML or Angular View/ViewModel) // when those are Angular View/ViewModel, we need to create View Component & provide the html containers to the Plugin (preTemplate/postTemplate methods) if (!gridOptions.rowDetailView.preTemplate) { this._preloadComponent = gridOptions?.rowDetailView?.preloadComponent; gridOptions.rowDetailView.preTemplate = () => DOMPurify.sanitize(`<div class="${PRELOAD_CONTAINER_PREFIX}"></div>`); } if (!gridOptions.rowDetailView.postTemplate) { this._viewComponent = gridOptions?.rowDetailView?.viewComponent; gridOptions.rowDetailView.postTemplate = (itemDetail: any) => DOMPurify.sanitize(`<div class="${ROW_DETAIL_CONTAINER_PREFIX}${itemDetail[this.datasetIdPropName]}"></div>`); } // finally register the Row Detail View Plugin this._addonOptions = gridOptions.rowDetailView; this._addon = new Slick.Plugins.RowDetailView(this._addonOptions); } const iconColumn: Column = this._addon.getColumnDefinition(); if (typeof iconColumn === 'object') { iconColumn.excludeFromExport = true; iconColumn.excludeFromColumnPicker = true; iconColumn.excludeFromGridMenu = true; iconColumn.excludeFromQuery = true; iconColumn.excludeFromHeaderMenu = true; // column index position in the grid const columnPosition = gridOptions && gridOptions.rowDetailView && gridOptions.rowDetailView.columnIndexPosition || 0; if (columnPosition > 0) { columnDefinitions.splice(columnPosition, 0, iconColumn); } else { columnDefinitions.unshift(iconColumn); } } } return this._addon; } return null; } /** Get the instance of the SlickGrid addon (control or plugin). */ getAddonInstance() { return this._addon; } register(rowSelectionPlugin?: any) { if (this.sharedService?.slickGrid && this.sharedService.gridOptions) { // the plugin has to be created BEFORE the grid (else it behaves oddly), but we can only watch grid events AFTER the grid is created this.sharedService.slickGrid.registerPlugin(this._addon); // this also requires the Row Selection Model to be registered as well if (!rowSelectionPlugin || !this.sharedService.slickGrid.getSelectionModel()) { rowSelectionPlugin = new Slick.RowSelectionModel(this.sharedService.gridOptions.rowSelectionOptions || { selectActiveRow: true }); this.sharedService.slickGrid.setSelectionModel(rowSelectionPlugin); } // hook all events if (this.sharedService.slickGrid && this.rowDetailViewOptions) { if (this.rowDetailViewOptions.onExtensionRegistered) { this.rowDetailViewOptions.onExtensionRegistered(this._addon); } this._eventHandler.subscribe(this._addon.onAsyncResponse, (e: any, args: { item: any; detailView: RowDetailView }) => { if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAsyncResponse === 'function') { this.rowDetailViewOptions.onAsyncResponse(e, args); } }); this._eventHandler.subscribe(this._addon.onAsyncEndUpdate, (e: any, args: { grid: SlickGrid; item: any; }) => { // triggers after backend called "onAsyncResponse.notify()" this.renderViewModel(args && args.item); if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAsyncEndUpdate === 'function') { this.rowDetailViewOptions.onAsyncEndUpdate(e, args); } }); this._eventHandler.subscribe(this._addon.onAfterRowDetailToggle, (e: any, args: { grid: SlickGrid; item: any; expandedRows: number[]; }) => { // display preload template & re-render all the other Detail Views after toggling // the preload View will eventually go away once the data gets loaded after the "onAsyncEndUpdate" event this.renderPreloadView(); this.renderAllViewComponents(); if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onAfterRowDetailToggle === 'function') { this.rowDetailViewOptions.onAfterRowDetailToggle(e, args); } }); this._eventHandler.subscribe(this._addon.onBeforeRowDetailToggle, (e: any, args: { grid: SlickGrid; item: any; }) => { // before toggling row detail, we need to create View Component if it doesn't exist this.onBeforeRowDetailToggle(e, args); if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onBeforeRowDetailToggle === 'function') { this.rowDetailViewOptions.onBeforeRowDetailToggle(e, args); } }); this._eventHandler.subscribe(this._addon.onRowBackToViewportRange, (e: any, args: { grid: SlickGrid; item: any; rowId: number; rowIndex: number; expandedRows: any[]; rowIdsOutOfViewport: number[]; }) => { // when row is back to viewport range, we will re-render the View Component(s) this.onRowBackToViewportRange(e, args); if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onRowBackToViewportRange === 'function') { this.rowDetailViewOptions.onRowBackToViewportRange(e, args); } }); this._eventHandler.subscribe(this._addon.onRowOutOfViewportRange, (e: any, args: { grid: SlickGrid; item: any; rowId: number; rowIndex: number; expandedRows: any[]; rowIdsOutOfViewport: number[]; }) => { if (this.rowDetailViewOptions && typeof this.rowDetailViewOptions.onRowOutOfViewportRange === 'function') { this.rowDetailViewOptions.onRowOutOfViewportRange(e, args); } }); // -- // hook some events needed by the Plugin itself // we need to redraw the open detail views if we change column position (column reorder) this._eventHandler.subscribe(this.sharedService.slickGrid.onColumnsReordered, this.redrawAllViewComponents.bind(this)); // on row selection changed, we also need to redraw if (this.gridOptions.enableRowSelection || this.gridOptions.enableCheckboxSelector) { this._eventHandler.subscribe(this.sharedService.slickGrid.onSelectedRowsChanged, this.redrawAllViewComponents.bind(this)); } // on sort, all row detail are collapsed so we can dispose of all the Views as well this._eventHandler.subscribe(this.sharedService.slickGrid.onSort, this.disposeAllViewComponents.bind(this)); // on filter changed, we need to re-render all Views this._subscriptions.push( this.eventPubSubService.subscribe('onFilterChanged', this.redrawAllViewComponents.bind(this)) ); } return this._addon; } return null; } /** Redraw (re-render) all the expanded row detail View Components */ redrawAllViewComponents() { this._views.forEach((compRef) => { this.redrawViewComponent(compRef); }); } /** Render all the expanded row detail View Components */ renderAllViewComponents() { this._views.forEach((view) => { if (view && view.dataContext) { this.renderViewModel(view.dataContext); } }); } /** Redraw the necessary View Component */ redrawViewComponent(createdView: CreatedView) { const containerElements = document.getElementsByClassName(`${ROW_DETAIL_CONTAINER_PREFIX}${createdView.id}`); if (containerElements && containerElements.length >= 0) { this.renderViewModel(createdView.dataContext); } } /** Render (or re-render) the View Component (Row Detail) */ renderPreloadView() { const containerElements = document.getElementsByClassName(`${PRELOAD_CONTAINER_PREFIX}`); if (containerElements && containerElements.length >= 0) { this.angularUtilService.createAngularComponentAppendToDom(this._preloadComponent, containerElements[containerElements.length - 1], true); } } /** Render (or re-render) the View Component (Row Detail) */ renderViewModel(item: any): CreatedView | undefined { const containerElements = document.getElementsByClassName(`${ROW_DETAIL_CONTAINER_PREFIX}${item[this.datasetIdPropName]}`); if (containerElements && containerElements.length > 0) { const componentOutput = this.angularUtilService.createAngularComponentAppendToDom(this._viewComponent, containerElements[containerElements.length - 1], true); if (componentOutput && componentOutput.componentRef && componentOutput.componentRef.instance) { // pass a few properties to the Row Detail template component Object.assign(componentOutput.componentRef.instance, { model: item, addon: this._addon, grid: this.sharedService.slickGrid, dataView: this.sharedService.dataView, parent: this.rowDetailViewOptions && this.rowDetailViewOptions.parent, }); const viewObj = this._views.find(obj => obj.id === item[this.datasetIdPropName]); if (viewObj) { viewObj.componentRef = componentOutput.componentRef; } return viewObj; } } return undefined; } // -- // private functions // ------------------ private disposeViewComponent(expandedView: CreatedView) { const compRef = expandedView?.componentRef; if (compRef) { this.appRef.detachView(compRef.hostView); if (compRef?.destroy) { compRef.destroy(); } return expandedView; } return null; } /** * notify the onAsyncResponse with the "args.item" (required property) * the plugin will then use item to populate the row detail panel with the "postTemplate" * @param item */ private notifyTemplate(item: any) { if (this._addon) { this._addon.onAsyncResponse.notify({ item }, undefined, this); } } /** * On Processing, we will notify the plugin with the new item detail once backend server call completes * @param item */ private async onProcessing(item: any) { if (item && typeof this._userProcessFn === 'function') { let awaitedItemDetail: any; const userProcessFn = this._userProcessFn(item); // wait for the "userProcessFn", once resolved we will save it into the "collection" const response: any | any[] = await userProcessFn; if (response.hasOwnProperty(this.datasetIdPropName)) { awaitedItemDetail = response; // from Promise } else if (response && response instanceof Observable || response instanceof Promise) { awaitedItemDetail = await castObservableToPromise(this.rxjs as RxJsFacade, response); // from Angular-http-client } if (!awaitedItemDetail || !awaitedItemDetail.hasOwnProperty(this.datasetIdPropName)) { throw new Error(`[Angular-Slickgrid] could not process the Row Detail, you must make sure that your "process" callback (a Promise or an HttpClient call returning an Observable) returns an item object that has an "${this.datasetIdPropName}" property`); } // notify the plugin with the new item details this.notifyTemplate(awaitedItemDetail || {}); } } /** * Just before the row get expanded or collapsed we will do the following * First determine if the row is expanding or collapsing, * if it's expanding we will add it to our View Components reference array if we don't already have it * or if it's collapsing we will remove it from our View Components reference array */ private onBeforeRowDetailToggle(e: Event, args: { grid: SlickGrid; item: any; }) { // expanding if (args && args.item && args.item.__collapsed) { // expanding row detail const viewInfo: CreatedView = { id: args.item[this.datasetIdPropName], dataContext: args.item }; const idPropName = this.gridOptions.datasetIdPropertyName || 'id'; addToArrayWhenNotExists(this._views, viewInfo, idPropName); } else { // collapsing, so dispose of the View/Component const foundViewIndex = this._views.findIndex((view: CreatedView) => view.id === args.item[this.datasetIdPropName]); if (foundViewIndex >= 0 && this._views.hasOwnProperty(foundViewIndex)) { const compRef = this._views[foundViewIndex].componentRef; if (compRef) { this.appRef.detachView(compRef.hostView); compRef.destroy(); } this._views.splice(foundViewIndex, 1); } } } /** When Row comes back to Viewport Range, we need to redraw the View */ private onRowBackToViewportRange(e: Event, args: { grid: SlickGrid; item: any; rowId: number; rowIndex: number; expandedRows: any[]; rowIdsOutOfViewport: number[]; }) { if (args && args.item) { this._views.forEach((view) => { if (view.id === args.item[this.datasetIdPropName]) { this.redrawViewComponent(view); } }); } } }
the_stack
import * as ko from "knockout"; import { Question, SurveyModel } from "survey-core"; import { IPage, SurveyElement } from "survey-core"; import { Page, Panel } from "./kopage"; import { PageModel } from "survey-core"; import { surveyCss } from "survey-core"; import { koTemplate, SurveyTemplateText } from "./templateText"; import { CustomWidgetCollection } from "survey-core"; import { LocalizableString } from "survey-core"; import { ItemValue } from "survey-core"; import { ImplementorBase } from "./kobase"; import { StylesManager } from "survey-core"; import { doKey2ClickDown, doKey2ClickUp } from "../utils/utils"; CustomWidgetCollection.Instance.onCustomWidgetAdded.add(customWidget => { if (customWidget.widgetJson.isDefaultRender) return; if (!customWidget.htmlTemplate) customWidget.htmlTemplate = "<div>'htmlTemplate' attribute is missed.</div>"; new SurveyTemplateText().replaceText( customWidget.htmlTemplate, "widget", customWidget.name ); }); export class Survey extends SurveyModel { public static get cssType(): string { return surveyCss.currentType; } public static set cssType(value: string) { StylesManager.applyTheme(value); } private renderedElement: HTMLElement; private isFirstRender: boolean = true; private mouseDownPage: any = null; koCurrentPage: any; koIsFirstPage: any; koIsLastPage: any; dummyObservable: any; koState: any; koAfterRenderPage: any; koAfterRenderHeader: any; koCompletedState: any; koCompletedStateText: any; koCompletedStateCss: any; koTimerInfoText: any; koTitleTemplate: any = <any>ko.observable("survey-header"); public getDataValueCore(valuesHash: any, key: string) { if (!!this.editingObj) return super.getDataValueCore(valuesHash, key); if (valuesHash[key] === undefined) { valuesHash[key] = ko.observable(); } return ko.unwrap(valuesHash[key]); } public setDataValueCore(valuesHash: any, key: string, value: any) { if (!!this.editingObj) { super.setDataValueCore(valuesHash, key, value); return; } if (ko.isWriteableObservable(valuesHash[key])) { valuesHash[key](value); } else { valuesHash[key] = ko.observable(value); } } public deleteDataValueCore(valuesHash: any, key: string) { if (!!this.editingObj) { super.deleteDataValueCore(valuesHash, key); return; } if (ko.isWriteableObservable(valuesHash[key])) { valuesHash[key](undefined); } else { delete valuesHash[key]; } } constructor( jsonObj: any = null, renderedElement: any = null, css: any = null ) { super(jsonObj); if (typeof ko === "undefined") throw new Error("knockoutjs library is not loaded."); if (css) { this.css = css; } if (renderedElement) { this.renderedElement = renderedElement; } this.render(renderedElement); } protected onBaseCreating() { super.onBaseCreating(); new ImplementorBase(this); } public nextPageUIClick() { if (!!this.mouseDownPage && this.mouseDownPage !== this.currentPage) return; this.mouseDownPage = null; this.nextPage(); } public nextPageMouseDown() { this.mouseDownPage = this.currentPage; return this.navigationMouseDown(); } public render(element: any = null) { this.updateKoCurrentPage(); this.updateCustomWidgets(this.currentPage); this.updateElementCss(false); const self = this; if (element && typeof element === "string") { element = document.getElementById(element); } if (element) { this.renderedElement = element; } element = this.renderedElement; self.startTimerFromUI(); if (!element) return; self.applyBinding(); } public clear(clearData: boolean = true, gotoFirstPage: boolean = true) { super.clear(clearData, gotoFirstPage); this.render(); } public localeChanged() { super.localeChanged(); this.render(); } public koEventAfterRender(element: any, survey: any) { survey.afterRenderSurvey(element); } public loadSurveyFromService( surveyId: string = null, clientId: string = null, renderedElement: any = null ) { if (renderedElement) { this.renderedElement = renderedElement; } super.loadSurveyFromService(surveyId, clientId); } public setCompleted() { super.setCompleted(); this.updateKoCurrentPage(); } public start(): boolean { var res = super.start(); this.updateKoCurrentPage(); return res; } public createNewPage(name: string): PageModel { return new Page(name); } protected getHtmlTemplate(): string { return koTemplate; } protected onBeforeCreating() { this.dummyObservable = ko.observable(0); this.koCurrentPage = ko.observable(this.currentPage); this.isCurrentPageEmpty = ko.computed( () => !!this.koCurrentPage() && this.getRows(this.koCurrentPage()).length === 0 ); this.koIsFirstPage = ko.computed(() => { this.dummyObservable(); return this.isFirstPage; }); this.koIsLastPage = ko.computed(() => { this.dummyObservable(); return this.isLastPage; }); this.koState = ko.observable(this.state); this.koCompletedState = ko.observable(""); this.koCompletedStateText = ko.observable(""); this.koCompletedStateCss = ko.observable(""); this.koTimerInfoText = ko.observable(this.timerInfoText); this.koAfterRenderPage = (elements: any, con: any) => { var el = SurveyElement.GetFirstNonTextElement(elements); if (!el) return; setTimeout(() => { !!ko.tasks && ko.tasks.runEarly(); this.afterRenderPage(el); }, 0); }; this.koAfterRenderHeader = (elements: any, con: any) => { var el = SurveyElement.GetFirstNonTextElement(elements); if (el) this.afterRenderHeader(el); }; } protected currentPageChanged(newValue: PageModel, oldValue: PageModel) { this.updateKoCurrentPage(); super.currentPageChanged(newValue, oldValue); if (!this.isDesignMode) this.scrollToTopOnPageChange(); } pageVisibilityChanged(page: IPage, newValue: boolean) { super.pageVisibilityChanged(page, newValue); this.updateKoCurrentPage(); } protected onLoadSurveyFromService() { this.render(); } protected onLoadingSurveyFromService() { this.render(); } protected setCompletedState(value: string, text: string) { super.setCompletedState(value, text); this.koCompletedState(this.completedState); this.koCompletedStateText(this.completedStateText); this.koCompletedStateCss( this.completedState !== "" ? this.css.saveData[this.completedState] : "" ); } protected doTimer() { super.doTimer(); this.koTimerInfoText(this.timerInfoText); } private applyBinding() { if (!this.renderedElement) return; this.updateKoCurrentPage(); ko.cleanNode(this.renderedElement); if (!this.isFirstRender) { this.updateCurrentPageQuestions(); } this.isFirstRender = false; ko.renderTemplate( "survey-content", this, { afterRender: this.koEventAfterRender }, this.renderedElement ); } private updateKoCurrentPage() { if (this.isLoadingFromJson || this.isDisposed) return; this.dummyObservable(this.dummyObservable() + 1); if (this.currentPage !== this.koCurrentPage()) { this.koCurrentPage(this.currentPage); } this.koState(this.state); } private getRows(pnl: any): Array<any> { return !!pnl["koRows"] ? pnl["koRows"]() : pnl.rows; } private updateCurrentPageQuestions() { if (this.isDisposed) return; var questions = this.currentPage ? this.currentPage.questions : []; for (var i = 0; i < questions.length; i++) { var q = questions[i]; if (q.visible) q["updateQuestion"](); } } public updateSurvey(newProps: any, oldProps?: any) { for (var key in newProps) { if (key == "model" || key == "children") continue; if (key == "css") { this.mergeValues(newProps.css, this.getCss()); this.updateElementCss(); continue; } if (key.indexOf("on") == 0 && this[key] && this[key].add) { let funcBody = newProps[key]; let func = function (sender: any, options: any) { funcBody(sender, options); }; this[key].add(func); } else { this[key] = newProps[key]; } } if (newProps && newProps.data) this.onValueChanged.add((sender, options) => { newProps.data[options.name] = options.value; }); } public dispose() { super.dispose(); if (!!this.renderedElement) { ko.cleanNode(this.renderedElement); this.renderedElement.innerHTML = ""; } this.koAfterRenderPage = undefined; this.koAfterRenderHeader = undefined; this.isCurrentPageEmpty.dispose(); this.koIsFirstPage.dispose(); this.koIsLastPage.dispose(); this.iteratePropertiesHash((hash, key) => { delete hash[key]; }); this.koCurrentPage(undefined); } } LocalizableString.prototype["onCreating"] = function () { // var self = this; // this.koReRender = ko.observable(0); this.koHasHtml = ko.observable(this.hasHtml); this.koRenderedHtml = ko.observable(this.renderedHtml); // Object.defineProperty(self, "koHasHtml", { // get: () => { // self.koReRender(); // return self.hasHtml; // }, // }); // this.koRenderedHtml = ko.pureComputed(function() { // self.koReRender(); // return self.renderedHtml; // }); }; ItemValue.prototype["onCreating"] = function () { new ImplementorBase(this); }; LocalizableString.prototype["onChanged"] = function () { // this.koReRender(this.koReRender() + 1); const hasHtml = this.hasHtml; this.koHasHtml(hasHtml); this.koRenderedHtml(hasHtml ? this.getHtmlValue() : this.calculatedText); }; ko.components.register("survey", { viewModel: { createViewModel: function (params: any, componentInfo: any) { var survey: Survey = ko.unwrap(params.survey); setTimeout(() => { var surveyRoot = document.createElement("div"); componentInfo.element.appendChild(surveyRoot); survey.render(surveyRoot); }, 1); // !!ko.tasks && ko.tasks.runEarly(); return params.survey; }, }, template: koTemplate, }); ko.bindingHandlers["surveyProp"] = { update: function (element: any, valueAccessor: any, allBindingsAccessor: any) { var value = ko.utils.unwrapObservable(valueAccessor()) || {}; for (var propName in value) { if (typeof propName == "string") { var propValue = ko.utils.unwrapObservable(value[propName]); element[propName] = propValue; } } }, }; SurveyModel.platform = "knockout"; export var registerTemplateEngine = (ko: any, platform: string) => { (<any>ko).surveyTemplateEngine = function () { }; (<any>ko).surveyTemplateEngine.prototype = new ko.nativeTemplateEngine(); (<any>ko).surveyTemplateEngine.prototype.makeTemplateSource = function ( template: any, templateDocument: any ) { if (typeof template === "string") { templateDocument = templateDocument || document; var templateElementRoot = templateDocument.getElementById( "survey-content-" + platform ); if (!templateElementRoot) { templateElementRoot = document.createElement("div"); templateElementRoot.id = "survey-content-" + SurveyModel.platform; templateElementRoot.style.display = "none"; templateElementRoot.innerHTML = koTemplate; document.body.appendChild(templateElementRoot); } var elem; for (var i = 0; i < templateElementRoot.children.length; i++) { if (templateElementRoot.children[i].id === template) { elem = templateElementRoot.children[i]; break; } } if (!elem) { elem = templateDocument.getElementById(template); } if (!elem) { return new ko.nativeTemplateEngine().makeTemplateSource( template, templateDocument ); } return new ko.templateSources.domElement(elem); } else if (template.nodeType === 1 || template.nodeType === 8) { return new ko.templateSources.anonymousTemplate(template); } else { throw new Error("Unknown template type: " + template); } }; // (<any>ko).surveyTemplateEngine.prototype.renderTemplateSource = function (templateSource: any, bindingContext: any, options: any, templateDocument: any) { // var useNodesIfAvailable = !((<any>ko.utils).ieVersion < 9), // templateNodesFunc = useNodesIfAvailable ? templateSource["nodes"] : null, // templateNodes = templateNodesFunc ? templateSource["nodes"]() : null; // if (templateNodes) { // return (<any>ko.utils).makeArray(templateNodes.cloneNode(true).childNodes); // } else { // var templateText = templateSource["text"](); // return (<any>ko.utils).parseHtmlFragment(templateText, templateDocument); // } // }; var surveyTemplateEngineInstance = new (<any>ko).surveyTemplateEngine(); ko.setTemplateEngine(surveyTemplateEngineInstance); }; ko.bindingHandlers["key2click"] = { init: function (element: HTMLElement, valueAccessor, allBindingsAccessor, viewModel: any) { const options = valueAccessor() || { processEsc: true }; if (viewModel.disableTabStop) { element.tabIndex = -1; return; } element.tabIndex = 0; element.onkeyup = (evt: any) => { evt.preventDefault(); evt.stopPropagation(); doKey2ClickUp(evt, options); return false; }; element.onkeydown = (evt: any) => doKey2ClickDown(evt, options); }, };
the_stack
import * as Models from './models'; import * as Parameters from './parameters'; import { Client } from '../clients'; import { Callback } from '../callback'; import { RequestConfig } from '../requestConfig'; export class WorkflowSchemes { constructor(private client: Client) {} /** * Returns a [paginated](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#pagination) list of all * workflow schemes, not including draft workflow schemes. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getAllWorkflowSchemes<T = Models.PageWorkflowScheme>( parameters: Parameters.GetAllWorkflowSchemes | undefined, callback: Callback<T> ): Promise<void>; /** * Returns a [paginated](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#pagination) list of all * workflow schemes, not including draft workflow schemes. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getAllWorkflowSchemes<T = Models.PageWorkflowScheme>( parameters?: Parameters.GetAllWorkflowSchemes, callback?: never ): Promise<T>; async getAllWorkflowSchemes<T = Models.PageWorkflowScheme>( parameters?: Parameters.GetAllWorkflowSchemes, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: '/rest/api/2/workflowscheme', method: 'GET', params: { startAt: parameters?.startAt, maxResults: parameters?.maxResults, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.getAllWorkflowSchemes' }); } /** * Creates a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async createWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.CreateWorkflowScheme | undefined, callback: Callback<T> ): Promise<void>; /** * Creates a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async createWorkflowScheme<T = Models.WorkflowScheme>( parameters?: Parameters.CreateWorkflowScheme, callback?: never ): Promise<T>; async createWorkflowScheme<T = Models.WorkflowScheme>( parameters?: Parameters.CreateWorkflowScheme, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: '/rest/api/2/workflowscheme', method: 'POST', data: { id: parameters?.id, name: parameters?.name, description: parameters?.description, defaultWorkflow: parameters?.defaultWorkflow, issueTypeMappings: parameters?.issueTypeMappings, originalDefaultWorkflow: parameters?.originalDefaultWorkflow, originalIssueTypeMappings: parameters?.originalIssueTypeMappings, draft: parameters?.draft, lastModifiedUser: parameters?.lastModifiedUser, lastModified: parameters?.lastModified, self: parameters?.self, updateDraftIfNeeded: parameters?.updateDraftIfNeeded, issueTypes: parameters?.issueTypes, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.createWorkflowScheme' }); } /** * Returns a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.GetWorkflowScheme, callback: Callback<T> ): Promise<void>; /** * Returns a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.GetWorkflowScheme, callback?: never ): Promise<T>; async getWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.GetWorkflowScheme, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}`, method: 'GET', params: { returnDraftIfExists: parameters.returnDraftIfExists, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.getWorkflowScheme' }); } /** * Updates a workflow scheme, including the name, default workflow, issue type to project mappings, and more. If the * workflow scheme is active (that is, being used by at least one project), then a draft workflow scheme is created or * updated instead, provided that `updateDraftIfNeeded` is set to `true`. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowScheme, callback: Callback<T> ): Promise<void>; /** * Updates a workflow scheme, including the name, default workflow, issue type to project mappings, and more. If the * workflow scheme is active (that is, being used by at least one project), then a draft workflow scheme is created or * updated instead, provided that `updateDraftIfNeeded` is set to `true`. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowScheme, callback?: never ): Promise<T>; async updateWorkflowScheme<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowScheme, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}`, method: 'PUT', data: { name: parameters.name, description: parameters.description, defaultWorkflow: parameters.defaultWorkflow, issueTypeMappings: parameters.issueTypeMappings, updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.updateWorkflowScheme' }); } /** * Deletes a workflow scheme. Note that a workflow scheme cannot be deleted if it is active (that is, being used by at * least one project). * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowScheme<T = void>( parameters: Parameters.DeleteWorkflowScheme, callback: Callback<T> ): Promise<void>; /** * Deletes a workflow scheme. Note that a workflow scheme cannot be deleted if it is active (that is, being used by at * least one project). * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowScheme<T = void>(parameters: Parameters.DeleteWorkflowScheme, callback?: never): Promise<T>; async deleteWorkflowScheme<T = void>( parameters: Parameters.DeleteWorkflowScheme, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}`, method: 'DELETE', }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.deleteWorkflowScheme' }); } /** * Returns the default workflow for a workflow scheme. The default workflow is the workflow that is assigned any issue * types that have not been mapped to any other workflow. The default workflow has *All Unassigned Issue Types* listed * in its issue types for the workflow scheme in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getDefaultWorkflow<T = Models.DefaultWorkflow>( parameters: Parameters.GetDefaultWorkflow, callback: Callback<T> ): Promise<void>; /** * Returns the default workflow for a workflow scheme. The default workflow is the workflow that is assigned any issue * types that have not been mapped to any other workflow. The default workflow has *All Unassigned Issue Types* listed * in its issue types for the workflow scheme in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getDefaultWorkflow<T = Models.DefaultWorkflow>( parameters: Parameters.GetDefaultWorkflow, callback?: never ): Promise<T>; async getDefaultWorkflow<T = Models.DefaultWorkflow>( parameters: Parameters.GetDefaultWorkflow, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/default`, method: 'GET', params: { returnDraftIfExists: parameters.returnDraftIfExists, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.getDefaultWorkflow' }); } /** * Sets the default workflow for a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request object and a draft workflow scheme is created or updated with the new default workflow. The * draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.UpdateDefaultWorkflow, callback: Callback<T> ): Promise<void>; /** * Sets the default workflow for a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request object and a draft workflow scheme is created or updated with the new default workflow. The * draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.UpdateDefaultWorkflow, callback?: never ): Promise<T>; async updateDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.UpdateDefaultWorkflow, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/default`, method: 'PUT', data: { workflow: parameters.workflow, updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.updateDefaultWorkflow' }); } /** * Resets the default workflow for a workflow scheme. That is, the default workflow is set to Jira's system workflow * (the *jira* workflow). * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the default workflow reset. The draft workflow scheme * can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.DeleteDefaultWorkflow, callback: Callback<T> ): Promise<void>; /** * Resets the default workflow for a workflow scheme. That is, the default workflow is set to Jira's system workflow * (the *jira* workflow). * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the default workflow reset. The draft workflow scheme * can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.DeleteDefaultWorkflow, callback?: never ): Promise<T>; async deleteDefaultWorkflow<T = Models.WorkflowScheme>( parameters: Parameters.DeleteDefaultWorkflow, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/default`, method: 'DELETE', params: { updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.deleteDefaultWorkflow' }); } /** * Returns the issue type-workflow mapping for an issue type in a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflowSchemeIssueType<T = Models.IssueTypeWorkflowMapping>( parameters: Parameters.GetWorkflowSchemeIssueType, callback: Callback<T> ): Promise<void>; /** * Returns the issue type-workflow mapping for an issue type in a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflowSchemeIssueType<T = Models.IssueTypeWorkflowMapping>( parameters: Parameters.GetWorkflowSchemeIssueType, callback?: never ): Promise<T>; async getWorkflowSchemeIssueType<T = Models.IssueTypeWorkflowMapping>( parameters: Parameters.GetWorkflowSchemeIssueType, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/issuetype/${parameters.issueType}`, method: 'GET', params: { returnDraftIfExists: parameters.returnDraftIfExists, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.getWorkflowSchemeIssueType', }); } /** * Sets the workflow for an issue type in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request body and a draft workflow scheme is created or updated with the new issue type-workflow * mapping. The draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async setWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.SetWorkflowSchemeIssueType, callback: Callback<T> ): Promise<void>; /** * Sets the workflow for an issue type in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request body and a draft workflow scheme is created or updated with the new issue type-workflow * mapping. The draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async setWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.SetWorkflowSchemeIssueType, callback?: never ): Promise<T>; async setWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.SetWorkflowSchemeIssueType, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/issuetype/${parameters.issueType}`, method: 'PUT', data: parameters.body, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.setWorkflowSchemeIssueType', }); } /** * Deletes the issue type-workflow mapping for an issue type in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the issue type-workflow mapping deleted. The draft * workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.DeleteWorkflowSchemeIssueType, callback: Callback<T> ): Promise<void>; /** * Deletes the issue type-workflow mapping for an issue type in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the issue type-workflow mapping deleted. The draft * workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.DeleteWorkflowSchemeIssueType, callback?: never ): Promise<T>; async deleteWorkflowSchemeIssueType<T = Models.WorkflowScheme>( parameters: Parameters.DeleteWorkflowSchemeIssueType, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/issuetype/${parameters.issueType}`, method: 'DELETE', params: { updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.deleteWorkflowSchemeIssueType', }); } /** * Returns the workflow-issue type mappings for a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflow<T = Models.IssueTypesWorkflowMapping>( parameters: Parameters.GetWorkflow, callback: Callback<T> ): Promise<void>; /** * Returns the workflow-issue type mappings for a workflow scheme. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async getWorkflow<T = Models.IssueTypesWorkflowMapping>( parameters: Parameters.GetWorkflow, callback?: never ): Promise<T>; async getWorkflow<T = Models.IssueTypesWorkflowMapping>( parameters: Parameters.GetWorkflow, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/workflow`, method: 'GET', params: { workflowName: parameters.workflowName, returnDraftIfExists: parameters.returnDraftIfExists, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.getWorkflow' }); } /** * Sets the issue types for a workflow in a workflow scheme. The workflow can also be set as the default workflow for * the workflow scheme. Unmapped issues types are mapped to the default workflow. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request body and a draft workflow scheme is created or updated with the new workflow-issue types * mappings. The draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateWorkflowMapping<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowMapping, callback: Callback<T> ): Promise<void>; /** * Sets the issue types for a workflow in a workflow scheme. The workflow can also be set as the default workflow for * the workflow scheme. Unmapped issues types are mapped to the default workflow. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` in the request body and a draft workflow scheme is created or updated with the new workflow-issue types * mappings. The draft workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async updateWorkflowMapping<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowMapping, callback?: never ): Promise<T>; async updateWorkflowMapping<T = Models.WorkflowScheme>( parameters: Parameters.UpdateWorkflowMapping, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/workflow`, method: 'PUT', params: { workflowName: parameters.workflowName, }, data: { workflow: parameters.workflow, issueTypes: parameters.issueTypes, defaultMapping: parameters.defaultMapping, updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.updateWorkflowMapping' }); } /** * Deletes the workflow-issue type mapping for a workflow in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the workflow-issue type mapping deleted. The draft * workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowMapping<T = unknown>( parameters: Parameters.DeleteWorkflowMapping, callback: Callback<T> ): Promise<void>; /** * Deletes the workflow-issue type mapping for a workflow in a workflow scheme. * * Note that active workflow schemes cannot be edited. If the workflow scheme is active, set `updateDraftIfNeeded` to * `true` and a draft workflow scheme is created or updated with the workflow-issue type mapping deleted. The draft * workflow scheme can be published in Jira. * * **[Permissions](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/#permissions) required:** * *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg). */ async deleteWorkflowMapping<T = unknown>(parameters: Parameters.DeleteWorkflowMapping, callback?: never): Promise<T>; async deleteWorkflowMapping<T = unknown>( parameters: Parameters.DeleteWorkflowMapping, callback?: Callback<T>, ): Promise<void | T> { const config: RequestConfig = { url: `/rest/api/2/workflowscheme/${parameters.id}/workflow`, method: 'DELETE', params: { workflowName: parameters.workflowName, updateDraftIfNeeded: parameters.updateDraftIfNeeded, }, }; return this.client.sendRequest(config, callback, { methodName: 'version2.workflowSchemes.deleteWorkflowMapping' }); } }
the_stack
import { CroNetwork } from '@crypto-org-chain/chain-jslib/lib/dist/core/cro'; export const APP_DB_NAMESPACE = 'data-store'; export const MARKET_API_BASE_URL = 'https://crypto.org/api'; export const COINBASE_TICKER_API_BASE_URL = 'https://api.coinbase.com/v2/'; export const CRYPTO_COM_PRICE_API_BASE_URL = { V1: 'https://price-api.crypto.com/price/v1/', V2: 'https://price-api.crypto.com/price/v2/', }; export const NV_GRAPHQL_API_ENDPOINT = 'https://crypto.com/nft-api/graphql'; export const IPFS_MIDDLEWARE_SERVER_UPLOAD_ENDPOINT = 'https://crypto.org/ipfs-middleware-server/uploads'; export const DEFAULT_CLIENT_MEMO = 'client:chain-desktop-app'; export const CLOUDFLARE_TRACE_URI = 'https://www.cloudflare.com/cdn-cgi/trace'; // This constant value is used when actual values are not known yet // For instance : export const NOT_KNOWN_YET_VALUE = 'TO_BE_DECIDED'; export const MODERATION_CONFIG_FILE_URL = 'https://raw.githubusercontent.com/crypto-com/chain-desktop-wallet/dev/config/app.moderation.json'; export const UNBLOCKING_PERIOD_IN_DAYS = { UNDELEGATION: { MAINNET: '28', OTHERS: '28', }, REDELEGATION: { MAINNET: '28', OTHERS: '28', }, }; // Reference: Google Sheet : Foris Markets Table - 4 October 2021 export const COUNTRY_CODES_TO_BLOCK = [ // Afghanistan 'AF', 'AFG', // Burma(Myanmar) 'MM', 'MMR', // Burundi 'BI', 'BDI', // Central African Republic 'CF', 'CAF', // Congo, Dem. Rep. 'CD', 'COD', // Cuba 'CU', 'CUB', // Eritrea 'ER', 'ERI', // Guinea-Bissau 'GW', 'GNB', // Guinea, Republic of 'GN', 'GIN', // Iran 'IR', 'IRN', // Iraq 'IQ', 'IRQ', // North Korea 'KP', 'PRK', // Lebanon 'LB', 'LBN', // Libya 'LY', 'LBY', // Mali 'ML', 'MLI', // Somalia 'SO', 'SOM', // South Sudan 'SS', 'SSD', // Sudan 'SD', 'SDN', // Syria 'SY', 'SYR', // Venezuela 'VE', 'VEN', // Yemen 'YE', 'YEM', // Zimbabwe 'ZW', 'ZWE', // Unidentified Countries NOT_KNOWN_YET_VALUE, ]; export const GEO_BLOCK_TIMEOUT = 4_000; export const NodePorts = { EVM: ':8545', Tendermint: ':26657', Cosmos: ':1317', }; // maximum in ledger: 2147483647 export const LedgerWalletMaximum = 2147483647; export const CUMULATIVE_SHARE_PERCENTAGE_THRESHOLD = 33.3; // 1 year = 60sec * 60 * 24 * 365 = 31536000 sec export const SECONDS_OF_YEAR = 31536000; // Max Incorrect Attempts allowed export const MAX_INCORRECT_ATTEMPTS_ALLOWED = 10; export const SHOW_WARNING_INCORRECT_ATTEMPTS = 5; export const DEFAULT_LANGUAGE_CODE = 'enUS'; export const SUPPORTED_LANGUAGE = [ { value: 'enUS', label: 'English' }, { value: 'zhHK', label: '繁體中文' }, { value: 'zhCN', label: '简体中文' }, { value: 'koKR', label: '한국어' }, ]; export interface SupportedCurrency { value: string; symbol: string; label: string; } export const CRC20_TOKEN_ICON_URL = { "VVS": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/61711b671ef47000c5ac9f78/VVS_Finance_Logo_Token_Symbol-White.png", "BIFI": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5f979dd0acbd0e009941cbf0/BIFI_8.png", "DOGE": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5c1248835568a4017c20a9a6/dogecoin.png", "ATOM": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5cc8dba7d436cf008a5ad9cd/cosmos.png", "SWAPP": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/610b8b87d07aba00c6590f3b/SWAPP_cronos_4.png", "CRONA": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/619de338a4396a00c5b30250/CRONA_4.png", "USDT": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5c12487f5568a4017c20a999/tether.png", "USDC": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5c1251c25afb9500ec2d2ff3/coin_log_usd-coin.png", "ELK": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/619de4423363e600c5f22dbc/ELK_4.png", "SMOL": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/61a4da089a45a100c53b189f/SMOL_4.png", "SHIB": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5f979d61acbd0e009941ca04/SHIBxxxhdpi.png", "WCRO": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5c1248c15568a4017c20aa87/cro.png", "DAI": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5e01c4cd49cde700adb27b0d/DAIxxxhdpi.png", "WETH": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5fc4d2ba3deadb00995dbfc5/WETH-xxxhdpi.png", "WBTC": "https://s3-ap-southeast-1.amazonaws.com/monaco-cointrack-production/uploads/coin/colorful_logo/5eb427298eadfb009885d309/WBTC_4x.png" } export const SUPPORTED_CURRENCY = new Map<string, SupportedCurrency>(); SUPPORTED_CURRENCY.set('USD', { value: 'USD', label: 'USD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('GBP', { value: 'GBP', label: 'GBP - £', symbol: '£' }); SUPPORTED_CURRENCY.set('EUR', { value: 'EUR', label: 'EUR - €', symbol: '€' }); SUPPORTED_CURRENCY.set('SGD', { value: 'SGD', label: 'SGD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('CAD', { value: 'CAD', label: 'CAD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('AUD', { value: 'AUD', label: 'AUD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('NZD', { value: 'NZD', label: 'NZD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('HKD', { value: 'HKD', label: 'HKD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('TWD', { value: 'TWD', label: 'TWD - $', symbol: '$' }); SUPPORTED_CURRENCY.set('NOK', { value: 'NOK', label: 'NOK - kr', symbol: 'kr' }); SUPPORTED_CURRENCY.set('SEK', { value: 'SEK', label: 'SEK - kr', symbol: 'kr' }); SUPPORTED_CURRENCY.set('DKK', { value: 'DKK', label: 'DKK - kr', symbol: 'kr' }); SUPPORTED_CURRENCY.set('CHF', { value: 'CHF', label: 'CHF - CHF', symbol: 'CHF' }); SUPPORTED_CURRENCY.set('PLN', { value: 'PLN', label: 'PLN - zł', symbol: 'zł' }); SUPPORTED_CURRENCY.set('ZAR', { value: 'ZAR', label: 'ZAR - R', symbol: 'R' }); SUPPORTED_CURRENCY.set('KES', { value: 'KES', label: 'KES - KSh', symbol: 'KSh' }); SUPPORTED_CURRENCY.set('RUB', { value: 'RUB', label: 'RUB - ₽', symbol: '₽' }); SUPPORTED_CURRENCY.set('BGN', { value: 'BGN', label: 'BGN - Лв.', symbol: 'Лв.' }); SUPPORTED_CURRENCY.set('RON', { value: 'RON', label: 'RON - lei', symbol: 'lei' }); SUPPORTED_CURRENCY.set('ILS', { value: 'ILS', label: 'ILS - ₪', symbol: '₪' }); SUPPORTED_CURRENCY.set('SAR', { value: 'SAR', label: 'SAR - ر.س', symbol: 'ر.س' }); SUPPORTED_CURRENCY.set('AED', { value: 'AED', label: 'AED - د.إ', symbol: 'د.إ' }); SUPPORTED_CURRENCY.set('HUF', { value: 'HUF', label: 'HUF - Ft', symbol: 'Ft' }); SUPPORTED_CURRENCY.set('CZK', { value: 'CZK', label: 'CZK - Kč', symbol: 'Kč' }); SUPPORTED_CURRENCY.set('BRL', { value: 'BRL', label: 'BRL - R$', symbol: 'R$' }); SUPPORTED_CURRENCY.set('TRY', { value: 'TRY', label: 'TRY - ₺', symbol: '₺' }); export enum SupportedChainName { CRYPTO_ORG = 'Crypto.org Chain', CRONOS = 'Cronos Chain', } export interface SupportedBridge { value: string; label: string; } export const SUPPORTED_BRIDGE = new Map<string, SupportedBridge>(); SUPPORTED_BRIDGE.set('CRONOS', { value: 'CRONOS', label: SupportedChainName.CRONOS }); SUPPORTED_BRIDGE.set('CRYPTO_ORG', { value: 'CRYPTO_ORG', label: SupportedChainName.CRYPTO_ORG, }); export const SUPPORTED_BRIDGES_ASSETS = ['CRO']; export type WalletConfig = { enabled: boolean; name: string; explorer: any; explorerUrl: string; nodeUrl: string; indexingUrl: string; derivationPath: string; network: Network; disableDefaultClientMemo: boolean; // When enabled all settings update will be propagated to all wallets of the same network. // E.g: User updates nodeURL in one mainnet wallet, all other mainnet wallets will have the new nodeURL enableGeneralSettings: boolean; analyticsDisabled: boolean; fee: { gasLimit: string; networkFee: string; }; }; export const FIXED_DEFAULT_FEE = String(10_000); export const FIXED_DEFAULT_GAS_LIMIT = String(300_000); export const DEFAULT_IBC_TRANSFER_TIMEOUT = 3_600_000; export const EVM_MINIMUM_GAS_PRICE = String(42_000_000_000); export const EVM_MINIMUM_GAS_LIMIT = String(42_000); export const NFT_IMAGE_DENOM_SCHEMA = { title: 'Asset Metadata', type: 'Object', properties: { description: { type: 'string', description: 'Describes the asset to which this NFT represents', }, name: { type: 'string', description: 'Identifies the asset to which this NFT represents', }, image: { type: 'string', description: 'A URI pointing to a resource with mime type image', }, mimeType: { type: 'string', description: 'Describes the type of represented NFT media', }, }, }; export const NFT_VIDEO_DENOM_SCHEMA = { title: 'Asset Metadata', type: 'Object', properties: { description: { type: 'string', description: 'Describes the asset to which this NFT represents', }, name: { type: 'string', description: 'Identifies the asset to which this NFT represents', }, image: { type: 'string', description: 'A URI pointing to a resource with mime type image', }, animation_url: { type: 'string', description: 'A URI pointing to a resource with mime type video', }, mimeType: { type: 'string', description: 'Describes the type of represented NFT media', }, }, }; export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; export const MAX_VIDEO_SIZE = 20 * 1024 * 1024; const TestNetConfig: WalletConfig = { enabled: true, name: 'TESTNET', derivationPath: "m/44'/1'/0'/0/0", explorer: { baseUrl: 'https://crypto.org/explorer/croeseid', tx: 'https://crypto.org/explorer/croeseid/tx', address: 'https://crypto.org/explorer/croeseid/account', validator: 'https://crypto.org/explorer/croeseid/validator', }, explorerUrl: 'https://crypto.org/explorer/croeseid', indexingUrl: 'https://crypto.org/explorer/croeseid/api/v1/', nodeUrl: CroNetwork.Testnet.defaultNodeUrl, network: CroNetwork.Testnet, disableDefaultClientMemo: false, enableGeneralSettings: false, analyticsDisabled: false, fee: { gasLimit: FIXED_DEFAULT_GAS_LIMIT, networkFee: FIXED_DEFAULT_FEE, }, }; const TestNetCroeseid3Config: WalletConfig = { enabled: true, name: 'TESTNET CROESEID 3', derivationPath: "m/44'/1'/0'/0/0", explorer: { baseUrl: 'https://crypto.org/explorer/croeseid3', tx: 'https://crypto.org/explorer/croeseid3/tx', address: 'https://crypto.org/explorer/croeseid3/account', validator: 'https://crypto.org/explorer/croeseid3/validator', }, explorerUrl: 'https://crypto.org/explorer/croeseid3', indexingUrl: 'https://crypto.org/explorer/croeseid3/api/v1/', nodeUrl: CroNetwork.TestnetCroeseid3.defaultNodeUrl, network: CroNetwork.TestnetCroeseid3, disableDefaultClientMemo: false, enableGeneralSettings: false, analyticsDisabled: false, fee: { gasLimit: FIXED_DEFAULT_GAS_LIMIT, networkFee: FIXED_DEFAULT_FEE, }, }; const TestnetCroeseid4: Network = { defaultNodeUrl: 'https://testnet-croeseid-4.crypto.org', chainId: 'testnet-croeseid-4', addressPrefix: 'tcro', validatorAddressPrefix: 'tcrocncl', validatorPubKeyPrefix: 'tcrocnclconspub', coin: { baseDenom: 'basetcro', croDenom: 'tcro', }, bip44Path: { coinType: 1, account: 0, }, rpcUrl: 'https://testnet-croeseid-4.crypto.org:26657', }; const TestNetCroeseid4Config: WalletConfig = { enabled: true, name: 'TESTNET CROESEID 4', derivationPath: "m/44'/1'/0'/0/0", explorer: { baseUrl: 'https://crypto.org/explorer/croeseid4', tx: 'https://crypto.org/explorer/croeseid4/tx', address: 'https://crypto.org/explorer/croeseid4/account', validator: 'https://crypto.org/explorer/croeseid4/validator', }, explorerUrl: 'https://crypto.org/explorer/croeseid4', indexingUrl: 'https://crypto.org/explorer/croeseid4/api/v1/', nodeUrl: TestnetCroeseid4.defaultNodeUrl, network: TestnetCroeseid4, disableDefaultClientMemo: false, enableGeneralSettings: false, analyticsDisabled: false, fee: { gasLimit: FIXED_DEFAULT_GAS_LIMIT, networkFee: FIXED_DEFAULT_FEE, }, }; const MainNetConfig: WalletConfig = { enabled: true, name: 'MAINNET', derivationPath: "m/44'/394'/0'/0/0", nodeUrl: CroNetwork.Mainnet.defaultNodeUrl, explorer: { baseUrl: 'https://crypto.org/explorer', tx: 'https://crypto.org/explorer/tx', address: 'https://crypto.org/explorer/account', validator: 'https://crypto.org/explorer/validator', }, explorerUrl: 'https://crypto.org/explorer', indexingUrl: 'https://crypto.org/explorer/api/v1/', network: CroNetwork.Mainnet, disableDefaultClientMemo: false, enableGeneralSettings: false, analyticsDisabled: false, fee: { gasLimit: FIXED_DEFAULT_GAS_LIMIT, networkFee: FIXED_DEFAULT_FEE, }, }; // Supposed to be fully customizable by the user when it will be supported export const CustomDevNet: WalletConfig = { derivationPath: "m/44'/394'/0'/0/0", enabled: true, name: 'CUSTOM DEVNET', disableDefaultClientMemo: false, enableGeneralSettings: false, analyticsDisabled: false, network: { defaultNodeUrl: '', chainId: 'test', addressPrefix: 'cro', bip44Path: { coinType: 394, account: 0 }, validatorPubKeyPrefix: 'crocnclpub', validatorAddressPrefix: 'crocncl', coin: { baseDenom: 'basecro', croDenom: 'cro' }, }, nodeUrl: '', indexingUrl: '', explorer: {}, explorerUrl: '', fee: { gasLimit: FIXED_DEFAULT_GAS_LIMIT, networkFee: FIXED_DEFAULT_FEE, }, }; // Available wallet configs will be presented to the user on wallet creation // The user can either select default configs available or simply configure their own configuration from scratch export const DefaultWalletConfigs = { TestNetConfig, MainNetConfig, CustomDevNet, TestNetCroeseid4Config, TestNetCroeseid3Config, }; // This type is a copy of the Network type defined inside chain-js // The redefinition is a work-around on limitation to lib to export it export type Network = { defaultNodeUrl: string; chainId: string; addressPrefix: string; bip44Path: { coinType: number; account: number }; validatorPubKeyPrefix: string; validatorAddressPrefix: string; coin: { baseDenom: string; croDenom: string }; rpcUrl?: string; };
the_stack
import {Platform} from '@angular/cdk/platform'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ReactiveFormsModule} from '@angular/forms'; import {MatRadioModule} from '@angular/material/radio'; import {MatRadioButtonHarness, MatRadioGroupHarness} from './radio-harness'; /** Shared tests to run on both the original and MDC-based radio components. */ export function runHarnessTests( radioModule: typeof MatRadioModule, radioGroupHarness: typeof MatRadioGroupHarness, radioButtonHarness: typeof MatRadioButtonHarness, ) { let platform: Platform; let fixture: ComponentFixture<MultipleRadioButtonsHarnessTest>; let loader: HarnessLoader; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [radioModule, ReactiveFormsModule], declarations: [MultipleRadioButtonsHarnessTest], }).compileComponents(); platform = TestBed.inject(Platform); fixture = TestBed.createComponent(MultipleRadioButtonsHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); describe('MatRadioGroupHarness', () => { it('should load all radio-group harnesses', async () => { const groups = await loader.getAllHarnesses(radioGroupHarness); expect(groups.length).toBe(3); }); it('should load radio-group with exact id', async () => { const groups = await loader.getAllHarnesses( radioGroupHarness.with({selector: '#my-group-2'}), ); expect(groups.length).toBe(1); }); it('should load radio-group by name', async () => { let groups = await loader.getAllHarnesses(radioGroupHarness.with({name: 'my-group-2-name'})); expect(groups.length).toBe(1); expect(await groups[0].getId()).toBe('my-group-2'); groups = await loader.getAllHarnesses(radioGroupHarness.with({name: 'my-group-1-name'})); expect(groups.length).toBe(1); expect(await groups[0].getId()).toBe('my-group-1'); }); it( 'should throw when finding radio-group with specific name that has mismatched ' + 'radio-button names', async () => { fixture.componentInstance.thirdGroupButtonName = 'other-name'; fixture.detectChanges(); await expectAsync( loader.getAllHarnesses(radioGroupHarness.with({name: 'third-group-name'})), ).toBeRejectedWithError( /locator found a radio-group with name "third-group-name".*have mismatching names/, ); }, ); it('should get name of radio-group', async () => { const groups = await loader.getAllHarnesses(radioGroupHarness); expect(groups.length).toBe(3); expect(await groups[0].getName()).toBe('my-group-1-name'); expect(await groups[1].getName()).toBe('my-group-2-name'); expect(await groups[2].getName()).toBe('third-group-name'); fixture.componentInstance.secondGroupId = 'new-group'; fixture.detectChanges(); expect(await groups[1].getName()).toBe('new-group-name'); fixture.componentInstance.thirdGroupButtonName = 'other-button-name'; fixture.detectChanges(); await expectAsync(groups[2].getName()).toBeRejectedWithError( /Radio buttons in radio-group have mismatching names./, ); }); it('should get id of radio-group', async () => { const groups = await loader.getAllHarnesses(radioGroupHarness); expect(groups.length).toBe(3); expect(await groups[0].getId()).toBe('my-group-1'); expect(await groups[1].getId()).toBe('my-group-2'); expect(await groups[2].getId()).toBe(''); fixture.componentInstance.secondGroupId = 'new-group-name'; fixture.detectChanges(); expect(await groups[1].getId()).toBe('new-group-name'); }); it('should get checked value of radio-group', async () => { const [firstGroup, secondGroup] = await loader.getAllHarnesses(radioGroupHarness); expect(await firstGroup.getCheckedValue()).toBe('opt2'); expect(await secondGroup.getCheckedValue()).toBe(null); }); it('should get radio-button harnesses of radio-group', async () => { const groups = await loader.getAllHarnesses(radioGroupHarness); expect(groups.length).toBe(3); expect((await groups[0].getRadioButtons()).length).toBe(3); expect((await groups[1].getRadioButtons()).length).toBe(1); expect((await groups[2].getRadioButtons()).length).toBe(2); }); it('should get radio buttons from group with filter', async () => { const group = await loader.getHarness(radioGroupHarness.with({name: 'my-group-1-name'})); expect((await group.getRadioButtons({label: 'opt2'})).length).toBe(1); }); it('should get checked radio-button harnesses of radio-group', async () => { const groups = await loader.getAllHarnesses(radioGroupHarness); expect(groups.length).toBe(3); const groupOneChecked = await groups[0].getCheckedRadioButton(); const groupTwoChecked = await groups[1].getCheckedRadioButton(); const groupThreeChecked = await groups[2].getCheckedRadioButton(); expect(groupOneChecked).not.toBeNull(); expect(groupTwoChecked).toBeNull(); expect(groupThreeChecked).toBeNull(); expect(await groupOneChecked!.getId()).toBe('opt2-group-one'); }); it('should check radio button in group', async () => { const group = await loader.getHarness(radioGroupHarness.with({name: 'my-group-1-name'})); expect(await group.getCheckedValue()).toBe('opt2'); await group.checkRadioButton({label: 'opt3'}); expect(await group.getCheckedValue()).toBe('opt3'); }); it('should throw error when checking invalid radio button', async () => { const group = await loader.getHarness(radioGroupHarness.with({name: 'my-group-1-name'})); await expectAsync(group.checkRadioButton({label: 'opt4'})).toBeRejectedWithError( /Could not find radio button matching {"label":"opt4"}/, ); }); }); describe('MatRadioButtonHarness', () => { it('should load all radio-button harnesses', async () => { const radios = await loader.getAllHarnesses(radioButtonHarness); expect(radios.length).toBe(9); }); it('should load radio-button with exact label', async () => { const radios = await loader.getAllHarnesses(radioButtonHarness.with({label: 'Option #2'})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt2'); expect(await radios[0].getLabelText()).toBe('Option #2'); }); it('should load radio-button with regex label match', async () => { const radios = await loader.getAllHarnesses(radioButtonHarness.with({label: /#3$/i})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt3'); expect(await radios[0].getLabelText()).toBe('Option #3'); }); it('should load radio-button with id', async () => { const radios = await loader.getAllHarnesses(radioButtonHarness.with({selector: '#opt3'})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt3'); expect(await radios[0].getLabelText()).toBe('Option #3'); }); it('should load radio-buttons with same name', async () => { const radios = await loader.getAllHarnesses(radioButtonHarness.with({name: 'group1'})); expect(radios.length).toBe(2); expect(await radios[0].getId()).toBe('opt1'); expect(await radios[1].getId()).toBe('opt2'); }); it('should get checked state', async () => { const [uncheckedRadio, checkedRadio] = await loader.getAllHarnesses(radioButtonHarness); expect(await uncheckedRadio.isChecked()).toBe(false); expect(await checkedRadio.isChecked()).toBe(true); }); it('should get label text', async () => { const [firstRadio, secondRadio, thirdRadio] = await loader.getAllHarnesses( radioButtonHarness, ); expect(await firstRadio.getLabelText()).toBe('Option #1'); expect(await secondRadio.getLabelText()).toBe('Option #2'); expect(await thirdRadio.getLabelText()).toBe('Option #3'); }); it('should get value', async () => { const [firstRadio, secondRadio, thirdRadio] = await loader.getAllHarnesses( radioButtonHarness, ); expect(await firstRadio.getValue()).toBe('opt1'); expect(await secondRadio.getValue()).toBe('opt2'); expect(await thirdRadio.getValue()).toBe('opt3'); }); it('should get disabled state', async () => { const [firstRadio] = await loader.getAllHarnesses(radioButtonHarness); expect(await firstRadio.isDisabled()).toBe(false); fixture.componentInstance.disableAll = true; fixture.detectChanges(); expect(await firstRadio.isDisabled()).toBe(true); }); it('should focus radio-button', async () => { const radioButton = await loader.getHarness(radioButtonHarness.with({selector: '#opt2'})); expect(await radioButton.isFocused()).toBe(false); await radioButton.focus(); expect(await radioButton.isFocused()).toBe(true); }); it('should blur radio-button', async () => { const radioButton = await loader.getHarness(radioButtonHarness.with({selector: '#opt2'})); await radioButton.focus(); expect(await radioButton.isFocused()).toBe(true); await radioButton.blur(); expect(await radioButton.isFocused()).toBe(false); }); it('should check radio-button', async () => { const [uncheckedRadio, checkedRadio] = await loader.getAllHarnesses(radioButtonHarness); await uncheckedRadio.check(); expect(await uncheckedRadio.isChecked()).toBe(true); // Checked radio state should change since the two radio's // have the same name and only one can be checked. expect(await checkedRadio.isChecked()).toBe(false); }); it('should not be able to check disabled radio-button', async () => { if (platform.FIREFOX) { // do run this test on firefox as click events on the label of the underlying // input checkbox cause the value to be changed. Read more in the bug report: // https://bugzilla.mozilla.org/show_bug.cgi?id=1540995 return; } fixture.componentInstance.disableAll = true; fixture.detectChanges(); const radioButton = await loader.getHarness(radioButtonHarness.with({selector: '#opt3'})); expect(await radioButton.isChecked()).toBe(false); await radioButton.check(); expect(await radioButton.isChecked()).toBe(false); fixture.componentInstance.disableAll = false; fixture.detectChanges(); expect(await radioButton.isChecked()).toBe(false); await radioButton.check(); expect(await radioButton.isChecked()).toBe(true); }); it('should get required state', async () => { const radioButton = await loader.getHarness( radioButtonHarness.with({selector: '#required-radio'}), ); expect(await radioButton.isRequired()).toBe(true); }); }); } @Component({ template: ` <mat-radio-button *ngFor="let value of values, let i = index" [name]="value === 'opt3' ? 'group2' : 'group1'" [disabled]="disableAll" [checked]="value === 'opt2'" [id]="value" [required]="value === 'opt2'" [value]="value"> Option #{{i + 1}} </mat-radio-button> <mat-radio-group id="my-group-1" name="my-group-1-name"> <mat-radio-button *ngFor="let value of values" [checked]="value === 'opt2'" [value]="value" [id]="value + '-group-one'"> {{value}} </mat-radio-button> </mat-radio-group> <mat-radio-group [id]="secondGroupId" [name]="secondGroupId + '-name'"> <mat-radio-button id="required-radio" required [value]="true"> Accept terms of conditions </mat-radio-button> </mat-radio-group> <mat-radio-group [name]="thirdGroupName"> <mat-radio-button [value]="true">First</mat-radio-button> <mat-radio-button [value]="false" [name]="thirdGroupButtonName"></mat-radio-button> </mat-radio-group> `, }) class MultipleRadioButtonsHarnessTest { values = ['opt1', 'opt2', 'opt3']; disableAll = false; secondGroupId = 'my-group-2'; thirdGroupName: string = 'third-group-name'; thirdGroupButtonName: string | undefined = undefined; }
the_stack
import React, { useEffect, useRef, useState } from 'react'; // import { userService } from "../services"; import toImage from '../labs/html2image'; import { ANIMATION_DURATION, IMAGE_URL_REG, MARKDOWN_URL_REG, MARKDOWN_WEB_URL_REG, WIKI_IMAGE_URL_REG, } from '../helpers/consts'; import utils from '../helpers/utils'; import { showDialog } from './Dialog'; import { formatMemoContent } from './Memo'; import Only from './common/OnlyWhen'; import '../less/share-memo-image-dialog.less'; import { moment, Notice, Platform, TFile, Vault } from 'obsidian'; import appStore from '../stores/appStore'; import { AutoSaveWhenOnMobile, DefaultDarkBackgroundImage, DefaultLightBackgroundImage, ShareFooterEnd, ShareFooterStart, UserName, } from '../memos'; import lightBackground from '../icons/lightBackground.svg'; import darkBackground from '../icons/darkBackground.svg'; import { getAllDailyNotes } from 'obsidian-daily-notes-interface'; import { t } from '../translations/helper'; import { dailyNotesService } from '../services'; import Share from '../icons/share.svg?component'; import Close from '../icons/close.svg?component'; interface Props extends DialogProps { memo: Model.Memo; } interface LinkMatch { linkText: string; altText: string; path: string; filePath?: string; } export const getPathOfImage = (vault: Vault, image: TFile) => { return vault.getResourcePath(image); }; const detectWikiInternalLink = (lineText: string): LinkMatch | null => { const { metadataCache, vault } = appStore.getState().dailyNotesState.app; const internalFileName = WIKI_IMAGE_URL_REG.exec(lineText)?.[1]; const internalAltName = WIKI_IMAGE_URL_REG.exec(lineText)?.[5]; const file = metadataCache.getFirstLinkpathDest(decodeURIComponent(internalFileName), ''); if (file === null) { return { linkText: internalFileName, altText: internalAltName, path: '', filePath: '', }; } else { const imagePath = getPathOfImage(vault, file); if (internalAltName) { return { linkText: internalFileName, altText: internalAltName, path: imagePath, filePath: file.path, }; } else { return { linkText: internalFileName, altText: '', path: imagePath, filePath: file.path, }; } } }; const detectMDInternalLink = (lineText: string): LinkMatch | null => { const { metadataCache, vault } = appStore.getState().dailyNotesState.app; const internalFileName = MARKDOWN_URL_REG.exec(lineText)?.[5]; const internalAltName = MARKDOWN_URL_REG.exec(lineText)?.[2]; const file = metadataCache.getFirstLinkpathDest(decodeURIComponent(internalFileName), ''); if (file === null) { return { linkText: internalFileName, altText: internalAltName, path: '', filePath: '', }; } else { const imagePath = getPathOfImage(vault, file); if (internalAltName) { return { linkText: internalFileName, altText: internalAltName, path: imagePath, filePath: file.path, }; } else { return { linkText: internalFileName, altText: '', path: imagePath, filePath: file.path, }; } } }; const ShareMemoImageDialog: React.FC<Props> = (props: Props) => { const { memo: propsMemo, destroy } = props; const { memos } = appStore.getState().memoState; let memosLength; let createdDays; if (memos.length) { memosLength = memos.length - 1; createdDays = memos ? Math.ceil((Date.now() - utils.getTimeStampByDate(memos[memosLength].createdAt)) / 1000 / 3600 / 24) : 0; } // const { user: userinfo } = userService.getState(); const memo: FormattedMemo = { ...propsMemo, createdAtStr: utils.getDateTimeString(propsMemo.createdAt), }; // const memoImgUrls = Array.from(memo.content.match(IMAGE_URL_REG) ?? []); // const memosNum = memos.length; const footerEnd = ShareFooterEnd.replace('{UserName}', UserName); const footerStart = ShareFooterStart.replace('{MemosNum}', memos.length.toString()).replace( '{UsedDay}', createdDays.toString(), ); let externalImageUrls = [] as string[]; const internalImageUrls = []; let allMarkdownLink: string | any[] = []; let allInternalLink = [] as any[]; if (new RegExp(IMAGE_URL_REG).test(memo.content)) { let allExternalImageUrls = [] as string[]; const anotherExternalImageUrls = [] as string[]; if (new RegExp(MARKDOWN_URL_REG).test(memo.content)) { allMarkdownLink = Array.from(memo.content.match(MARKDOWN_URL_REG)); } if (new RegExp(WIKI_IMAGE_URL_REG).test(memo.content)) { allInternalLink = Array.from(memo.content.match(WIKI_IMAGE_URL_REG)); } // const allInternalLink = Array.from(memo.content.match(WIKI_IMAGE_URL_REG)); if (new RegExp(MARKDOWN_WEB_URL_REG).test(memo.content)) { allExternalImageUrls = Array.from(memo.content.match(MARKDOWN_WEB_URL_REG)); } if (allInternalLink.length) { for (let i = 0; i < allInternalLink.length; i++) { const allInternalLinkElement = allInternalLink[i]; internalImageUrls.push(detectWikiInternalLink(allInternalLinkElement)); } } if (allMarkdownLink.length) { for (let i = 0; i < allMarkdownLink.length; i++) { const allMarkdownLinkElement = allMarkdownLink[i]; if (/(.*)http[s]?(.*)/.test(allMarkdownLinkElement)) { anotherExternalImageUrls.push(MARKDOWN_URL_REG.exec(allMarkdownLinkElement)?.[5]); } else { internalImageUrls.push(detectMDInternalLink(allMarkdownLinkElement)); } } } externalImageUrls = allExternalImageUrls.concat(anotherExternalImageUrls); // externalImageUrls = Array.from(memo.content.match(IMAGE_URL_REG) ?? []); } const [shortcutImgUrl, setShortcutImgUrl] = useState(''); const [imgAmount, setImgAmount] = useState(externalImageUrls.length); const memoElRef = useRef<HTMLDivElement>(null); useEffect(() => { if (imgAmount > 0) { return; } changeBackgroundImage(); setTimeout(() => { if (!memoElRef.current) { return; } let shareDialogBackgroundColor; if (document.body.className.contains('theme-dark')) { shareDialogBackgroundColor = '#727171'; } else { shareDialogBackgroundColor = '#eaeaea'; } toImage(memoElRef.current, { backgroundColor: shareDialogBackgroundColor, pixelRatio: window.devicePixelRatio * 2, }) .then((url) => { setShortcutImgUrl(url); }) .catch(() => { // do nth }); }, ANIMATION_DURATION); }, [imgAmount]); const handleCloseBtnClick = () => { destroy(); }; const convertBase64ToBlob = (base64: string, type: string) => { const bytes = window.atob(base64); const ab = new ArrayBuffer(bytes.length); const ia = new Uint8Array(ab); for (let i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: type }); }; const convertBackgroundToBase64 = async (path: string): Promise<string> => { const { vault } = dailyNotesService.getState().app; const buffer = await vault.adapter.readBinary(path); const arr = new Uint8Array(buffer); const blob = new Blob([arr], { type: 'image/png' }); return new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => { const base64Url = reader.result as string; // cachedResourceMap.set(url, base64Url); resolve(base64Url); }; reader.readAsDataURL(blob); }); }; const changeBackgroundImage = async () => { const { app } = dailyNotesService.getState(); let imageUrl; let imagePath; const lightBackgroundImage = encodeURI(lightBackground); const darkBackgroundImage = encodeURI(darkBackground); if (document.body.className.contains('theme-light')) { if ( (await app.vault.adapter.exists(DefaultLightBackgroundImage)) && /\.(png|svg|jpg|jpeg)/g.test(DefaultLightBackgroundImage) ) { imagePath = DefaultLightBackgroundImage; imageUrl = await convertBackgroundToBase64(imagePath); } else { imageUrl = lightBackgroundImage; } } else if (document.body.className.contains('theme-dark')) { if ( (await app.vault.adapter.exists(DefaultDarkBackgroundImage)) && /\.(png|svg|jpg|jpeg)/g.test(DefaultDarkBackgroundImage) ) { imagePath = DefaultDarkBackgroundImage; imageUrl = await convertBackgroundToBase64(imagePath); } else { imageUrl = darkBackgroundImage; } } const memoShareDiv = document.querySelector('.dialog-wrapper .memo-background .property-image') as HTMLElement; memoShareDiv.style.backgroundImage = "url('" + imageUrl + "')"; if (document.body.className.contains('theme-dark')) { memoShareDiv.style.backgroundColor = '#1f1f1f'; } }; const handleCopytoClipboardBtnClick = async () => { const { vault } = appStore.getState().dailyNotesState.app; const divs = document.querySelector('.memo-shortcut-img') as HTMLElement; const myBase64 = divs.getAttribute('src').split('base64,')[1]; const blobInput = convertBase64ToBlob(myBase64, 'image/png'); let aFile: TFile; let newFile; if (AutoSaveWhenOnMobile && Platform.isMobile) { blobInput.arrayBuffer().then(async (buffer) => { const ext = 'png'; const dailyNotes = getAllDailyNotes(); for (const string in dailyNotes) { if (dailyNotes[string] instanceof TFile) { aFile = dailyNotes[string]; break; } } if (aFile !== undefined) { newFile = await vault.createBinary( //@ts-expect-error, private method await vault.getAvailablePathForAttachments(`Pasted Image ${moment().format('YYYYMMDDHHmmss')}`, ext, aFile), buffer, ); } }); } const clipboardItemInput = new ClipboardItem({ 'image/png': blobInput }); window.navigator['clipboard'].write([clipboardItemInput]); new Notice('Send to clipboard successfully'); }; const handleImageOnLoad = (ev: React.SyntheticEvent<HTMLImageElement>) => { if (ev.type === 'error') { new Notice(t('Image load failed')); (ev.target as HTMLImageElement).remove(); } setImgAmount(imgAmount - 1); }; return ( <> <div className="dialog-header-container"> <p className="title-text"> <span className="icon-text">🥰</span> {t('Share Memo Image')} </p> <div className="btn-group"> <button className="btn copy-btn" onClick={handleCopytoClipboardBtnClick}> <Share className="icon-img" /> </button> <button className="btn close-btn" onClick={handleCloseBtnClick}> <Close className="icon-img" /> </button> </div> </div> <div className="dialog-content-container"> <div className={`tip-words-container ${shortcutImgUrl ? 'finish' : 'loading'}`}> <p className="tip-text">{shortcutImgUrl ? t('↗Click the button to save') : t('Image is generating...')}</p> </div> <div className="memo-container" ref={memoElRef}> <Only when={shortcutImgUrl !== ''}> <img className="memo-shortcut-img" src={shortcutImgUrl} /> </Only> <div className="memo-background"> <div className="property-image" style={{ backgroundSize: 'cover', backgroundRepeat: 'no-repeat', }} ></div> {/* <span className="time-text">{memo.createdAtStr}</span> */} <span className="background-container"></span> <div className="memo-content-text" dangerouslySetInnerHTML={{ __html: formatMemoContent(memo.content) }} ></div> <Only when={externalImageUrls.length > 0}> <div className="images-container"> {externalImageUrls.map((imgUrl, idx) => ( <img // crossOrigin="anonymous" // decoding="async" key={idx} src={imgUrl} alt="" referrerPolicy="no-referrer" onLoad={handleImageOnLoad} onError={handleImageOnLoad} /> ))} </div> </Only> <Only when={internalImageUrls.length > 0}> <div className="images-container internal-embed image-embed is-loaded"> {internalImageUrls.map((imgUrl, idx) => ( <img key={idx} className="memo-img" src={imgUrl.path} alt={imgUrl.altText} path={imgUrl.filePath} /> ))} </div> </Only> <div className="watermark-container"> <span className="normal-text footer-start"> <div className="property-social-icons"></div> <span className="name-text">{footerStart}</span> </span> <span className="normal-text footer-end"> <span className="name-text">{footerEnd}</span> </span> </div> </div> </div> </div> </> ); }; export default function showShareMemoImageDialog(memo: Model.Memo): void { showDialog( { className: 'share-memo-image-dialog', }, ShareMemoImageDialog, { memo }, ); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Virtual Machine Extension to provide post deployment configuration * and run automated tasks. * * > **NOTE:** Custom Script Extensions for Linux & Windows require that the `commandToExecute` returns a `0` exit code to be classified as successfully deployed. You can achieve this by appending `exit 0` to the end of your `commandToExecute`. * * > **NOTE:** Custom Script Extensions require that the Azure Virtual Machine Guest Agent is running on the Virtual Machine. * * ## 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 exampleVirtualNetwork = new azure.network.VirtualNetwork("exampleVirtualNetwork", { * addressSpaces: ["10.0.0.0/16"], * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * }); * const exampleSubnet = new azure.network.Subnet("exampleSubnet", { * resourceGroupName: exampleResourceGroup.name, * virtualNetworkName: exampleVirtualNetwork.name, * addressPrefixes: ["10.0.2.0/24"], * }); * const exampleNetworkInterface = new azure.network.NetworkInterface("exampleNetworkInterface", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * ipConfigurations: [{ * name: "testconfiguration1", * subnetId: exampleSubnet.id, * privateIpAddressAllocation: "Dynamic", * }], * }); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "LRS", * tags: { * environment: "staging", * }, * }); * const exampleContainer = new azure.storage.Container("exampleContainer", { * storageAccountName: exampleAccount.name, * containerAccessType: "private", * }); * const exampleVirtualMachine = new azure.compute.VirtualMachine("exampleVirtualMachine", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * networkInterfaceIds: [exampleNetworkInterface.id], * vmSize: "Standard_F2", * storageImageReference: { * publisher: "Canonical", * offer: "UbuntuServer", * sku: "16.04-LTS", * version: "latest", * }, * storageOsDisk: { * name: "myosdisk1", * vhdUri: pulumi.interpolate`${exampleAccount.primaryBlobEndpoint}${exampleContainer.name}/myosdisk1.vhd`, * caching: "ReadWrite", * createOption: "FromImage", * }, * osProfile: { * computerName: "hostname", * adminUsername: "testadmin", * adminPassword: "Password1234!", * }, * osProfileLinuxConfig: { * disablePasswordAuthentication: false, * }, * tags: { * environment: "staging", * }, * }); * const exampleExtension = new azure.compute.Extension("exampleExtension", { * virtualMachineId: exampleVirtualMachine.id, * publisher: "Microsoft.Azure.Extensions", * type: "CustomScript", * typeHandlerVersion: "2.0", * settings: ` { * "commandToExecute": "hostname && uptime" * } * `, * tags: { * environment: "Production", * }, * }); * ``` * * ## Import * * Virtual Machine Extensions can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:compute/extension:Extension example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Compute/virtualMachines/myVM/extensions/extensionName * ``` */ export class Extension extends pulumi.CustomResource { /** * Get an existing Extension 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?: ExtensionState, opts?: pulumi.CustomResourceOptions): Extension { return new Extension(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:compute/extension:Extension'; /** * Returns true if the given object is an instance of Extension. 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 Extension { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Extension.__pulumiType; } /** * Specifies if the platform deploys * the latest minor version update to the `typeHandlerVersion` specified. */ public readonly autoUpgradeMinorVersion!: pulumi.Output<boolean | undefined>; /** * Should the Extension be automatically updated whenever the Publisher releases a new version of this VM Extension? Defaults to `false`. */ public readonly automaticUpgradeEnabled!: pulumi.Output<boolean | undefined>; /** * The name of the virtual machine extension peering. Changing * this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * The protectedSettings passed to the * extension, like settings, these are specified as a JSON object in a string. */ public readonly protectedSettings!: pulumi.Output<string | undefined>; /** * The publisher of the extension, available publishers can be found by using the Azure CLI. Changing this forces a new resource to be created. */ public readonly publisher!: pulumi.Output<string>; /** * The settings passed to the extension, these are * specified as a JSON object in a string. */ public readonly settings!: pulumi.Output<string | undefined>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The type of extension, available types for a publisher can * be found using the Azure CLI. */ public readonly type!: pulumi.Output<string>; /** * Specifies the version of the extension to * use, available versions can be found using the Azure CLI. */ public readonly typeHandlerVersion!: pulumi.Output<string>; /** * The ID of the Virtual Machine. Changing this forces a new resource to be created */ public readonly virtualMachineId!: pulumi.Output<string>; /** * Create a Extension 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: ExtensionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ExtensionArgs | ExtensionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ExtensionState | undefined; inputs["autoUpgradeMinorVersion"] = state ? state.autoUpgradeMinorVersion : undefined; inputs["automaticUpgradeEnabled"] = state ? state.automaticUpgradeEnabled : undefined; inputs["name"] = state ? state.name : undefined; inputs["protectedSettings"] = state ? state.protectedSettings : undefined; inputs["publisher"] = state ? state.publisher : undefined; inputs["settings"] = state ? state.settings : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["type"] = state ? state.type : undefined; inputs["typeHandlerVersion"] = state ? state.typeHandlerVersion : undefined; inputs["virtualMachineId"] = state ? state.virtualMachineId : undefined; } else { const args = argsOrState as ExtensionArgs | undefined; if ((!args || args.publisher === undefined) && !opts.urn) { throw new Error("Missing required property 'publisher'"); } if ((!args || args.type === undefined) && !opts.urn) { throw new Error("Missing required property 'type'"); } if ((!args || args.typeHandlerVersion === undefined) && !opts.urn) { throw new Error("Missing required property 'typeHandlerVersion'"); } if ((!args || args.virtualMachineId === undefined) && !opts.urn) { throw new Error("Missing required property 'virtualMachineId'"); } inputs["autoUpgradeMinorVersion"] = args ? args.autoUpgradeMinorVersion : undefined; inputs["automaticUpgradeEnabled"] = args ? args.automaticUpgradeEnabled : undefined; inputs["name"] = args ? args.name : undefined; inputs["protectedSettings"] = args ? args.protectedSettings : undefined; inputs["publisher"] = args ? args.publisher : undefined; inputs["settings"] = args ? args.settings : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["type"] = args ? args.type : undefined; inputs["typeHandlerVersion"] = args ? args.typeHandlerVersion : undefined; inputs["virtualMachineId"] = args ? args.virtualMachineId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Extension.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Extension resources. */ export interface ExtensionState { /** * Specifies if the platform deploys * the latest minor version update to the `typeHandlerVersion` specified. */ autoUpgradeMinorVersion?: pulumi.Input<boolean>; /** * Should the Extension be automatically updated whenever the Publisher releases a new version of this VM Extension? Defaults to `false`. */ automaticUpgradeEnabled?: pulumi.Input<boolean>; /** * The name of the virtual machine extension peering. Changing * this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The protectedSettings passed to the * extension, like settings, these are specified as a JSON object in a string. */ protectedSettings?: pulumi.Input<string>; /** * The publisher of the extension, available publishers can be found by using the Azure CLI. Changing this forces a new resource to be created. */ publisher?: pulumi.Input<string>; /** * The settings passed to the extension, these are * specified as a JSON object in a string. */ settings?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The type of extension, available types for a publisher can * be found using the Azure CLI. */ type?: pulumi.Input<string>; /** * Specifies the version of the extension to * use, available versions can be found using the Azure CLI. */ typeHandlerVersion?: pulumi.Input<string>; /** * The ID of the Virtual Machine. Changing this forces a new resource to be created */ virtualMachineId?: pulumi.Input<string>; } /** * The set of arguments for constructing a Extension resource. */ export interface ExtensionArgs { /** * Specifies if the platform deploys * the latest minor version update to the `typeHandlerVersion` specified. */ autoUpgradeMinorVersion?: pulumi.Input<boolean>; /** * Should the Extension be automatically updated whenever the Publisher releases a new version of this VM Extension? Defaults to `false`. */ automaticUpgradeEnabled?: pulumi.Input<boolean>; /** * The name of the virtual machine extension peering. Changing * this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The protectedSettings passed to the * extension, like settings, these are specified as a JSON object in a string. */ protectedSettings?: pulumi.Input<string>; /** * The publisher of the extension, available publishers can be found by using the Azure CLI. Changing this forces a new resource to be created. */ publisher: pulumi.Input<string>; /** * The settings passed to the extension, these are * specified as a JSON object in a string. */ settings?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The type of extension, available types for a publisher can * be found using the Azure CLI. */ type: pulumi.Input<string>; /** * Specifies the version of the extension to * use, available versions can be found using the Azure CLI. */ typeHandlerVersion: pulumi.Input<string>; /** * The ID of the Virtual Machine. Changing this forces a new resource to be created */ virtualMachineId: pulumi.Input<string>; }
the_stack
import { Transaction } from "@sentry/tracing"; import { TransactionContext } from "@sentry/types"; import { getGlobalObject } from "@sentry/utils"; import { BLANK_TRANSACTION_CONTEXT, NavigationRoute, ReactNavigationInstrumentation, } from "../../src/js/tracing/reactnavigation"; const dummyRoute = { name: "Route", key: "0", }; class MockNavigationContainer { currentRoute: NavigationRoute = dummyRoute; listeners: Record<string, (e: any) => void> = {}; addListener: any = jest.fn( (eventType: string, listener: (e: any) => void): void => { this.listeners[eventType] = listener; } ); getCurrentRoute(): NavigationRoute { return this.currentRoute; } } const getMockTransaction = () => { const transaction = new Transaction(BLANK_TRANSACTION_CONTEXT); // Assume it's sampled transaction.sampled = true; return transaction; }; const _global = getGlobalObject<{ __sentry_rn_v5_registered?: boolean; }>(); afterEach(() => { _global.__sentry_rn_v5_registered = false; jest.resetAllMocks(); }); describe("ReactNavigationInstrumentation", () => { test("transaction set on initialize", () => { const instrumentation = new ReactNavigationInstrumentation(); const mockTransaction = getMockTransaction(); const tracingListener = jest.fn(() => mockTransaction); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); expect(mockTransaction.name).toBe(dummyRoute.name); expect(mockTransaction.tags).toStrictEqual({ ...BLANK_TRANSACTION_CONTEXT.tags, "routing.route.name": dummyRoute.name, }); expect(mockTransaction.data).toStrictEqual({ route: { name: dummyRoute.name, key: dummyRoute.key, params: {}, hasBeenSeen: false, }, previousRoute: null, }); }); test("transaction sent on navigation", async () => { const instrumentation = new ReactNavigationInstrumentation(); // Need a dummy transaction as the instrumentation will start a transaction right away when the first navigation container is attached. const mockTransactionDummy = getMockTransaction(); const transactionRef = { current: mockTransactionDummy, }; const tracingListener = jest.fn(() => transactionRef.current); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); const mockTransaction = getMockTransaction(); transactionRef.current = mockTransaction; mockNavigationContainerRef.current.listeners["__unsafe_action__"]({}); await new Promise<void>((resolve) => { setTimeout(() => { const route = { name: "New Route", key: "1", params: { someParam: 42, }, }; mockNavigationContainerRef.current.currentRoute = route; mockNavigationContainerRef.current.listeners["state"]({}); expect(mockTransaction.name).toBe(route.name); expect(mockTransaction.tags).toStrictEqual({ ...BLANK_TRANSACTION_CONTEXT.tags, "routing.route.name": route.name, }); expect(mockTransaction.data).toStrictEqual({ route: { name: route.name, key: route.key, params: route.params, hasBeenSeen: false, }, previousRoute: { name: dummyRoute.name, key: dummyRoute.key, params: {}, }, }); resolve(); }, 50); }); }); test("transaction context changed with beforeNavigate", async () => { const instrumentation = new ReactNavigationInstrumentation(); // Need a dummy transaction as the instrumentation will start a transaction right away when the first navigation container is attached. const mockTransactionDummy = getMockTransaction(); const transactionRef = { current: mockTransactionDummy, }; const tracingListener = jest.fn(() => transactionRef.current); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => { context.sampled = false; context.description = "Description"; context.name = "New Name"; return context; }, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); const mockTransaction = getMockTransaction(); transactionRef.current = mockTransaction; mockNavigationContainerRef.current.listeners["__unsafe_action__"]({}); await new Promise<void>((resolve) => { setTimeout(() => { const route = { name: "DoNotSend", key: "1", }; mockNavigationContainerRef.current.currentRoute = route; mockNavigationContainerRef.current.listeners["state"]({}); expect(mockTransaction.sampled).toBe(false); expect(mockTransaction.name).toBe("New Name"); expect(mockTransaction.description).toBe("Description"); resolve(); }, 50); }); }); test("transaction not sent on a cancelled navigation", async () => { const instrumentation = new ReactNavigationInstrumentation(); // Need a dummy transaction as the instrumentation will start a transaction right away when the first navigation container is attached. const mockTransactionDummy = getMockTransaction(); const transactionRef = { current: mockTransactionDummy, }; const tracingListener = jest.fn(() => transactionRef.current); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); const mockTransaction = getMockTransaction(); transactionRef.current = mockTransaction; mockNavigationContainerRef.current.listeners["__unsafe_action__"]({}); await new Promise<void>((resolve) => { setTimeout(() => { expect(mockTransaction.sampled).toBe(false); expect(mockTransaction.name).toStrictEqual( BLANK_TRANSACTION_CONTEXT.name ); expect(mockTransaction.tags).toStrictEqual( BLANK_TRANSACTION_CONTEXT.tags ); expect(mockTransaction.data).toStrictEqual({}); resolve(); }, 1100); }); }); describe("navigation container registration", () => { test("registers navigation container object ref", () => { const instrumentation = new ReactNavigationInstrumentation(); const mockNavigationContainer = new MockNavigationContainer(); instrumentation.registerNavigationContainer({ current: mockNavigationContainer, }); expect(_global.__sentry_rn_v5_registered).toBe(true); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).toHaveBeenNthCalledWith( 1, "__unsafe_action__", expect.any(Function) ); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).toHaveBeenNthCalledWith( 2, "state", expect.any(Function) ); }); test("registers navigation container direct ref", () => { const instrumentation = new ReactNavigationInstrumentation(); const mockNavigationContainer = new MockNavigationContainer(); instrumentation.registerNavigationContainer(mockNavigationContainer); expect(_global.__sentry_rn_v5_registered).toBe(true); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).toHaveBeenNthCalledWith( 1, "__unsafe_action__", expect.any(Function) ); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).toHaveBeenNthCalledWith( 2, "state", expect.any(Function) ); }); test("does not register navigation container if there is an existing one", () => { _global.__sentry_rn_v5_registered = true; const instrumentation = new ReactNavigationInstrumentation(); const mockNavigationContainer = new MockNavigationContainer(); instrumentation.registerNavigationContainer({ current: mockNavigationContainer, }); expect(_global.__sentry_rn_v5_registered).toBe(true); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).not.toHaveBeenCalled(); // eslint-disable-next-line @typescript-eslint/unbound-method expect(mockNavigationContainer.addListener).not.toHaveBeenCalled(); }); test("works if routing instrumentation registration is after navigation registration", async () => { const instrumentation = new ReactNavigationInstrumentation(); const mockNavigationContainer = new MockNavigationContainer(); instrumentation.registerNavigationContainer(mockNavigationContainer); const mockTransaction = getMockTransaction(); const tracingListener = jest.fn(() => mockTransaction); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); await new Promise<void>((resolve) => { setTimeout(() => { expect(mockTransaction.sampled).not.toBe(false); resolve(); }, 500); }); }); }); describe("options", () => { test("waits until routeChangeTimeoutMs", async () => { const instrumentation = new ReactNavigationInstrumentation({ routeChangeTimeoutMs: 200, }); const mockTransaction = getMockTransaction(); const tracingListener = jest.fn(() => mockTransaction); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; return new Promise<void>((resolve) => { setTimeout(() => { instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); expect(mockTransaction.sampled).toBe(true); expect(mockTransaction.name).toBe(dummyRoute.name); resolve(); }, 190); }); }); test("discards if after routeChangeTimeoutMs", async () => { const instrumentation = new ReactNavigationInstrumentation({ routeChangeTimeoutMs: 200, }); const mockTransaction = getMockTransaction(); const tracingListener = jest.fn(() => mockTransaction); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, () => {} ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; return new Promise<void>((resolve) => { setTimeout(() => { instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); expect(mockTransaction.sampled).toBe(false); resolve(); }, 210); }); }); }); describe("onRouteConfirmed", () => { test("onRouteConfirmed called with correct route data", () => { const instrumentation = new ReactNavigationInstrumentation(); // Need a dummy transaction as the instrumentation will start a transaction right away when the first navigation container is attached. const mockTransactionDummy = getMockTransaction(); const transactionRef = { current: mockTransactionDummy, }; let confirmedContext: TransactionContext | undefined; const tracingListener = jest.fn(() => transactionRef.current); instrumentation.registerRoutingInstrumentation( tracingListener as any, (context) => context, (context) => { confirmedContext = context; } ); const mockNavigationContainerRef = { current: new MockNavigationContainer(), }; instrumentation.registerNavigationContainer( mockNavigationContainerRef as any ); const mockTransaction = getMockTransaction(); transactionRef.current = mockTransaction; mockNavigationContainerRef.current.listeners["__unsafe_action__"]({}); const route1 = { name: "New Route 1", key: "1", params: { someParam: 42, }, }; mockNavigationContainerRef.current.currentRoute = route1; mockNavigationContainerRef.current.listeners["state"]({}); const route2 = { name: "New Route 2", key: "2", params: { someParam: 42, }, }; mockNavigationContainerRef.current.currentRoute = route2; mockNavigationContainerRef.current.listeners["state"]({}); expect(confirmedContext).toBeDefined(); if (confirmedContext) { expect(confirmedContext.name).toBe(route2.name); expect(confirmedContext.data).toBeDefined(); if (confirmedContext.data) { expect(confirmedContext.data.route.name).toBe(route2.name); expect(confirmedContext.data.previousRoute).toBeDefined(); if (confirmedContext.data.previousRoute) { expect(confirmedContext.data.previousRoute.name).toBe(route1.name); } } } }); }); });
the_stack
* @module Curve */ import { CurvePrimitive } from "../curve/CurvePrimitive"; import { StrokeCountMap } from "../curve/Query/StrokeCountMap"; import { Geometry } from "../Geometry"; import { GeometryHandler, IStrokeHandler } from "../geometry3d/GeometryHandler"; import { Plane3dByOriginAndUnitNormal } from "../geometry3d/Plane3dByOriginAndUnitNormal"; import { Plane3dByOriginAndVectors } from "../geometry3d/Plane3dByOriginAndVectors"; import { Point3d, Vector3d } from "../geometry3d/Point3dVector3d"; import { Range3d } from "../geometry3d/Range"; import { Ray3d } from "../geometry3d/Ray3d"; import { Transform } from "../geometry3d/Transform"; import { CurveChain } from "./CurveCollection"; import { CurveExtendMode, CurveExtendOptions, VariantCurveExtendParameter } from "./CurveExtendMode"; import { CurveLocationDetail } from "./CurveLocationDetail"; import { GeometryQuery } from "./GeometryQuery"; import { LineString3d } from "./LineString3d"; import { StrokeOptions } from "./StrokeOptions"; /** * * Annotation of an interval of a curve. * * The interval is marked with two pairs of numbers: * * * fraction0, fraction1 = fraction parameters along the child curve * * * distance0,distance1 = distances within containing CurveChainWithDistanceIndex * @public */ export class PathFragment { /** distance along parent to this fragment start */ public chainDistance0: number; /** distance along parent to this fragment end */ public chainDistance1: number; /** Fractional position of this fragment start within its curve primitive. */ public childFraction0: number; /** Fractional position of this fragment end within its curve primitive.. */ public childFraction1: number; /** Curve primitive of this fragment */ public childCurve: CurvePrimitive; /** Create a fragment with complete fraction, distance and child data. */ public constructor(childFraction0: number, childFraction1: number, distance0: number, distance1: number, childCurve: CurvePrimitive) { this.childFraction0 = childFraction0; this.childFraction1 = childFraction1; this.chainDistance0 = distance0; this.chainDistance1 = distance1; this.childCurve = childCurve; } /** * Return true if the distance is within the distance limits of this fragment. * @param distance */ public containsChainDistance(distance: number): boolean { return distance >= this.chainDistance0 && distance <= this.chainDistance1; } /** * Return true if this fragment addresses `curve` and brackets `fraction` * @param distance */ public containsChildCurveAndChildFraction(curve: CurvePrimitive, fraction: number): boolean { return this.childCurve === curve && fraction >= this.childFraction0 && fraction <= this.childFraction1; } /** Convert distance to local fraction, and apply that to interpolate between the stored curve fractions. * Note that proportional calculation does NOT account for nonuniform parameterization in the child curve. */ public chainDistanceToInterpolatedChildFraction(distance: number): number { return Geometry.inverseInterpolate( this.childFraction0, this.chainDistance0, this.childFraction1, this.chainDistance1, distance, this.childFraction0)!; // the interval "must" have nonzero length, division should be safe . .. } /** Convert chainDistance to true chidFraction, using detailed moveSignedDistanceFromFraction */ public chainDistanceToAccurateChildFraction(chainDistance: number): number { // The fragments are really expected to do good mappings in their distance range ... const childDetail = this.childCurve.moveSignedDistanceFromFraction( this.childFraction0, chainDistance - this.chainDistance0, false); return childDetail.fraction; } /** Return the scale factor to map childCurve fraction derivatives to chain fraction derivatives * @param globalDistance total length of the global curve. */ public fractionScaleFactor(globalDistance: number): number { return globalDistance * (this.childFraction1 - this.childFraction0) / (this.chainDistance1 - this.chainDistance0); } /** Reverse the fraction and distance data. * * each child fraction `f` is replaced by `1-f` * * each `chainDistance` is replaced by `totalDistance-chainDistance` */ public reverseFractionsAndDistances(totalDistance: number) { const f0 = this.childFraction0; const f1 = this.childFraction1; const d0 = this.chainDistance0; const d1 = this.chainDistance1; this.childFraction0 = 1.0 - f1; this.childFraction1 = 1.0 - f0; this.chainDistance0 = totalDistance - d1; this.chainDistance1 = totalDistance - d0; } /** * convert a fractional position on the childCurve to distance in the chain space. * * Return value is SIGNED -- will be negative when fraction < this.childFraction0. * @param fraction fraction along the curve within this fragment */ public childFractionTChainDistance(fraction: number): number { let d = this.childCurve.curveLengthBetweenFractions(this.childFraction0, fraction); if (fraction < this.childFraction0) d = -d; return this.chainDistance0 + d; } } /** Non-instantiable class to build a distance index for a path. */ class DistanceIndexConstructionContext implements IStrokeHandler { private _fragments: PathFragment[]; private _accumulatedDistance: number; private constructor() { this._accumulatedDistance = 0; this._fragments = []; } // ignore curve announcements -- they are repeated in stroke announcements public startParentCurvePrimitive(_cp: CurvePrimitive) { } public startCurvePrimitive(_cp: CurvePrimitive) { } public endParentCurvePrimitive(_cp: CurvePrimitive) { } public endCurvePrimitive(_cp: CurvePrimitive) { } // um .. we need to see curves? how to reject? public announcePointTangent(_xyz: Point3d, _fraction: number, _tangent: Vector3d) { } /** Announce numPoints interpolated between point0 and point1, with associated fractions */ public announceSegmentInterval( cp: CurvePrimitive, point0: Point3d, point1: Point3d, numStrokes: number, fraction0: number, fraction1: number): void { let d0 = this._accumulatedDistance; if (numStrokes <= 1) { this._accumulatedDistance += point0.distance(point1); this._fragments.push(new PathFragment(fraction0, fraction1, d0, this._accumulatedDistance, cp)); } else { let f1; for (let i = 1, f0 = 0.0; i <= numStrokes; i++, f0 = f1) { f1 = Geometry.interpolate(fraction0, i / numStrokes, fraction1); d0 = this._accumulatedDistance; this._accumulatedDistance += (Math.abs(f1 - f0) * point0.distance(point1)); this._fragments.push(new PathFragment(f0, f1, d0, this._accumulatedDistance, cp)); } } } public announceIntervalForUniformStepStrokes( cp: CurvePrimitive, numStrokes: number, fraction0: number, fraction1: number): void { let f1, d, d0; for (let i = 1, f0 = fraction0; i <= numStrokes; i++, f0 = f1) { f1 = Geometry.interpolate(fraction0, i / numStrokes, fraction1); d = cp.curveLengthBetweenFractions(f0, f1); d0 = this._accumulatedDistance; this._accumulatedDistance += d; this._fragments.push(new PathFragment(f0, f1, d0, this._accumulatedDistance, cp)); } } public needPrimaryGeometryForStrokes?(): boolean { return true;} public static createPathFragmentIndex(path: CurveChain, options?: StrokeOptions): PathFragment[] { const handler = new DistanceIndexConstructionContext(); for (const curve of path.children) { curve.emitStrokableParts(handler, options); } const fragments = handler._fragments; return fragments; } } /** * `CurveChainWithDistanceIndex` is a CurvePrimitive whose fractional parameterization is proportional to true * distance along a CurveChain. * * The curve chain can be any type derived from CurveChain. * * * i.e. either a `Path` or a `Loop` * @public */ export class CurveChainWithDistanceIndex extends CurvePrimitive { /** String name for schema properties */ public readonly curvePrimitiveType = "curveChainWithDistanceIndex"; private _path: CurveChain; private _fragments: PathFragment[]; private _totalLength: number; // matches final fragment distance1. /** Test if other is a `CurveChainWithDistanceIndex` */ public isSameGeometryClass(other: GeometryQuery): boolean { return other instanceof CurveChainWithDistanceIndex; } // final assembly of CurveChainWithDistanceIndex -- caller must create valid fragment index. private constructor(path: CurveChain, fragments: PathFragment[]) { super(); this._path = path; this._fragments = fragments; this._totalLength = fragments[fragments.length - 1].chainDistance1; } /** * Create a clone, transformed and with its own distance index. * @param transform transform to apply in the clone. */ public cloneTransformed(transform: Transform): CurvePrimitive | undefined { const c = this._path.clone(); if (c !== undefined && c instanceof CurveChain && c.tryTransformInPlace(transform)) return CurveChainWithDistanceIndex.createCapture(c); return undefined; } /** Reference to the contained path. * * Do not modify the path. The distance index will be wrong. */ public get path(): CurveChain { return this._path; } /** Return a deep clone */ public clone(): CurvePrimitive | undefined { const c = this._path.clone(); if (c !== undefined && c instanceof CurveChain) return CurveChainWithDistanceIndex.createCapture(c); return undefined; } /** Ask if the curve is within tolerance of a plane. * @returns Returns true if the curve is completely within tolerance of the plane. */ public isInPlane(plane: Plane3dByOriginAndUnitNormal): boolean { for (const c of this._path.children) { if (!c.isInPlane(plane)) return false; } return true; } /** return the start point of the primitive. The default implementation returns fractionToPoint (0.0) */ public override startPoint(result?: Point3d): Point3d { const c = this._path.cyclicCurvePrimitive(0); if (c) return c.startPoint(result); return Point3d.createZero(result); } /** Return the end point of the primitive. The default implementation returns fractionToPoint(1.0) */ public override endPoint(result?: Point3d): Point3d { const c = this._path.cyclicCurvePrimitive(-1); if (c) return c.endPoint(result); return Point3d.createZero(result); } /** Add strokes to caller-supplied linestring */ public emitStrokes(dest: LineString3d, options?: StrokeOptions): void { for (const c of this._path.children) { c.emitStrokes(dest, options); } } /** Ask the curve to announce points and simple subcurve fragments for stroking. * See IStrokeHandler for description of the sequence of the method calls. */ public emitStrokableParts(dest: IStrokeHandler, options?: StrokeOptions): void { for (const c of this._path.children) { c.emitStrokableParts(dest, options); } } /** * return the stroke count required for given options. * @param options StrokeOptions that determine count */ public computeStrokeCountForOptions(options?: StrokeOptions): number { let numStroke = 0; for (const c of this._path.children) { numStroke += c.computeStrokeCountForOptions(options); } return numStroke; } /** * Return an array containing only the curve primitives. * * This DEFAULT simply pushes `this` to the collectorArray. * * CurvePrimitiveWithDistanceIndex optionally collects its members. * @param collectorArray array to receive primitives (pushed -- the array is not cleared) * @param smallestPossiblePrimitives if false, CurvePrimitiveWithDistanceIndex returns only itself. If true, it recurses to its (otherwise hidden) children. */ public override collectCurvePrimitivesGo(collectorArray: CurvePrimitive[], smallestPossiblePrimitives: boolean) { if (smallestPossiblePrimitives) { for (const c of this._path.children) { c.collectCurvePrimitivesGo(collectorArray, smallestPossiblePrimitives); } } else { collectorArray.push(this); } } /** * construct StrokeCountMap for each child, accumulating data to stroke count map for this primitive. * @param options StrokeOptions that determine count * @param parentStrokeMap evolving parent map. */ public override computeAndAttachRecursiveStrokeCounts(options?: StrokeOptions, parentStrokeMap?: StrokeCountMap) { const myMap = StrokeCountMap.createWithCurvePrimitiveAndOptionalParent(this, parentStrokeMap); for (const c of this._path.children) { c.computeAndAttachRecursiveStrokeCounts(options, myMap); } CurvePrimitive.installStrokeCountMap(this, myMap, parentStrokeMap); } /** Second step of double dispatch: call `this._path.dispatchToGeometryHandler (handler)` * * Note that this exposes the children individually to the handler. */ public dispatchToGeometryHandler(handler: GeometryHandler): any { return this._path.dispatchToGeometryHandler(handler); } /** Extend (increase) `rangeToExtend` as needed to include these curves (optionally transformed) */ public extendRange(rangeToExtend: Range3d, transform?: Transform): void { this._path.extendRange(rangeToExtend, transform); } /** * * * Curve length is always positive. * @returns Returns a (high accuracy) length of the curve between fractional positions * @returns Returns the length of the curve. */ public override curveLengthBetweenFractions(fraction0: number, fraction1: number): number { return Math.abs(fraction1 - fraction0) * this._totalLength; } /** * Capture (not clone) a path into a new `CurveChainWithDistanceIndex` * @param primitives primitive array to be CAPTURED (not cloned) */ public static createCapture(path: CurveChain, options?: StrokeOptions): CurveChainWithDistanceIndex | undefined { if (path.children.length === 0) return undefined; const fragments = DistanceIndexConstructionContext.createPathFragmentIndex(path, options); const result = new CurveChainWithDistanceIndex(path, fragments); return result; } /** * Resolve a fraction of the CurveChain to a PathFragment * @param distance * @param allowExtrapolation */ protected chainDistanceToFragment(distance: number, allowExtrapolation: boolean = false): PathFragment | undefined { const numFragments = this._fragments.length; const fragments = this._fragments; if (numFragments > 0) { if (distance < 0.0) return allowExtrapolation ? fragments[0] : undefined; if (distance >= this._totalLength) return allowExtrapolation ? fragments[numFragments - 1] : undefined; // humbug, linear search for (const fragment of fragments) { if (fragment.containsChainDistance(distance)) return fragment; } } return undefined; } /** * Convert distance along the chain to fraction along the chain. * @param distance distance along the chain */ public chainDistanceToChainFraction(distance: number): number { return distance / this._totalLength; } /** * Resolve a fraction within a specific curve to a fragment. * @param curve * @param fraction */ protected curveAndChildFractionToFragment(curve: CurvePrimitive, fraction: number): PathFragment | undefined { const numFragments = this._fragments.length; const fragments = this._fragments; if (numFragments > 0) { // humbug, linear search for (const fragment of fragments) { if (fragment.containsChildCurveAndChildFraction(curve, fraction)) return fragment; } if (fraction <= 0) return fragments[0]; if (fraction > 1.0) return fragments[numFragments - 1]; } return undefined; } /** * Returns the total length of curves. */ public override curveLength(): number { return this._totalLength; } /** * Returns the total length of the path. * * This is exact (and simple property lookup) because the true lengths were summed at construction time. */ public quickLength(): number { return this._totalLength; } /** * Return the point (x,y,z) on the curve at fractional position along the chain. * @param fraction fractional position along the geometry. * @returns Returns a point on the curve. */ public fractionToPoint(fraction: number, result?: Point3d): Point3d { const chainDistance = fraction * this._totalLength; const fragment = this.chainDistanceToFragment(chainDistance, true); if (fragment) { const childFraction = fragment.chainDistanceToAccurateChildFraction(chainDistance); return fragment.childCurve.fractionToPoint(childFraction, result); } // no fragment found. Use _fragments[0] // fragment = this.chainDistanceToFragment(chainDistance, true); return this._fragments[0].childCurve.fractionToPoint(0.0, result); } /** Return the point (x,y,z) and derivative on the curve at fractional position. * * * Note that this derivative is "derivative of xyz with respect to fraction." * * this derivative shows the speed of the "fractional point" moving along the curve. * * this is not generally a unit vector. use fractionToPointAndUnitTangent for a unit vector. * @param fraction fractional position along the geometry. * @returns Returns a ray whose origin is the curve point and direction is the derivative with respect to the fraction. */ public fractionToPointAndDerivative(fraction: number, result?: Ray3d): Ray3d { const distanceAlongPath = fraction * this._totalLength; const fragment = this.chainDistanceToFragment(distanceAlongPath, true)!; const curveFraction = fragment.chainDistanceToAccurateChildFraction(distanceAlongPath); result = fragment.childCurve.fractionToPointAndDerivative(curveFraction, result); const a = this._totalLength / result.direction.magnitude(); result.direction.scaleInPlace(a); return result; } /** * Returns a ray whose origin is the curve point and direction is the unit tangent. * @param fraction fractional position on the curve * @param result optional receiver for the result. * Returns a ray whose origin is the curve point and direction is the unit tangent. */ public override fractionToPointAndUnitTangent(fraction: number, result?: Ray3d): Ray3d { const distanceAlongPath = fraction * this._totalLength; const fragment = this.chainDistanceToFragment(distanceAlongPath, true)!; const curveFraction = fragment.chainDistanceToAccurateChildFraction(distanceAlongPath); result = fragment.childCurve.fractionToPointAndDerivative(curveFraction, result); result.direction.normalizeInPlace(); return result; } /** Return a plane with * * * origin at fractional position along the curve * * vectorU is the first derivative, i.e. tangent vector with length equal to the rate of change with respect to the fraction. * * vectorV is the second derivative, i.e.derivative of vectorU. */ public fractionToPointAnd2Derivatives(fraction: number, result?: Plane3dByOriginAndVectors): Plane3dByOriginAndVectors | undefined { const totalLength = this._totalLength; const distanceAlongPath = fraction * totalLength; const fragment = this.chainDistanceToFragment(distanceAlongPath, true)!; const curveFraction = fragment.chainDistanceToAccurateChildFraction(distanceAlongPath); result = fragment.childCurve.fractionToPointAnd2Derivatives(curveFraction, result); if (!result) return undefined; const dotUU = result.vectorU.magnitudeSquared(); const magU = Math.sqrt(dotUU); const dotUV = result.vectorU.dotProduct(result.vectorV); const duds = 1.0 / magU; const a = duds * duds; Vector3d.createAdd2Scaled(result.vectorV, a, result.vectorU, -a * dotUV / dotUU, result.vectorV); // IN PLACE update to vectorV. result.vectorU.scale(duds); // scale for 0..1 parameterization .... result.vectorU.scaleInPlace(totalLength); result.vectorV.scaleInPlace(totalLength * totalLength); return result; } /** Attempt to transform in place. * * Warning: If any child fails, this object becomes invalid. But that should never happen. */ public tryTransformInPlace(transform: Transform): boolean { let numFail = 0; for (const c of this._path.children) { if (!c.tryTransformInPlace(transform)) numFail++; } return numFail === 0; } /** Reverse the curve's data so that its fractional stroking moves in the opposite direction. */ public reverseInPlace(): void { this._path.reverseChildrenInPlace(); const totalLength = this._totalLength; for (const fragment of this._fragments) fragment.reverseFractionsAndDistances(totalLength); for (let i = 0, j = this._fragments.length - 1; i < j; i++, j--) { const fragment = this._fragments[i]; this._fragments[i] = this._fragments[j]; this._fragments[j] = fragment; } } /** * Test for equality conditions: * * Mismatched totalLength is a quick exit condition * * If totalLength matches, recurse to the path for matching primitives. * @param other */ public override isAlmostEqual(other: GeometryQuery): boolean { if (other instanceof CurveChainWithDistanceIndex) { return Geometry.isSameCoordinate(this._totalLength, other._totalLength) && this._path.isAlmostEqual(other._path); } return false; } /** Implement moveSignedDistanceFromFraction. * * See `CurvePrimitive` for parameter details. * * The returned location directly identifies fractional position along the CurveChainWithDistanceIndex, and has pointer to an additional detail for the child curve. */ public override moveSignedDistanceFromFraction(startFraction: number, signedDistance: number, allowExtension: boolean, result?: CurveLocationDetail): CurveLocationDetail { const distanceA = startFraction * this._totalLength; const distanceB = distanceA + signedDistance; const fragmentB = this.chainDistanceToFragment(distanceB, true)!; const childDetail = fragmentB.childCurve.moveSignedDistanceFromFraction(fragmentB.childFraction0, distanceB - fragmentB.chainDistance0, allowExtension, result); const endFraction = startFraction + (signedDistance / this._totalLength); const chainDetail = CurveLocationDetail.createConditionalMoveSignedDistance(allowExtension, this, startFraction, endFraction, signedDistance, result); chainDetail.childDetail = childDetail; return chainDetail; } /** Search for the curve point that is closest to the spacePoint. * * The CurveChainWithDistanceIndex invokes the base class CurvePrimitive method, which * (via a handler) determines a CurveLocation detail among the children. * * The returned detail directly identifies fractional position along the CurveChainWithDistanceIndex, and has pointer to an additional detail for the child curve. * @param spacePoint point in space * @param extend true to extend the curve (NOT USED) * @returns Returns a CurveLocationDetail structure that holds the details of the close point. */ public override closestPoint(spacePoint: Point3d, extend: VariantCurveExtendParameter): CurveLocationDetail | undefined { // umm... to "extend", would require selective extension of first, last let childDetail: CurveLocationDetail | undefined; let aMin = Number.MAX_VALUE; const numChildren = this.path.children.length; if (numChildren === 1) { childDetail = this.path.children[0].closestPoint(spacePoint, extend); } else { const extend0 = [CurveExtendOptions.resolveVariantCurveExtendParameterToCurveExtendMode(extend, 0), CurveExtendMode.None]; const extend1 = [CurveExtendMode.None, CurveExtendOptions.resolveVariantCurveExtendParameterToCurveExtendMode(extend, 1)]; for (let childIndex = 0; childIndex < numChildren; childIndex++) { const child = this.path.children[childIndex]; const detailA = child.closestPoint(spacePoint, childIndex === 0 ? extend0 : childIndex + 1 === numChildren ? extend1 : false); if (detailA && detailA.a < aMin) { aMin = detailA.a; childDetail = CurveLocationDetail.createCurveFractionPoint(detailA.curve, detailA.fraction, detailA.point, childDetail)!; childDetail.a = detailA.a; } } } if (!childDetail) return undefined; const fragment = this.curveAndChildFractionToFragment(childDetail.curve!, childDetail.fraction); if (fragment) { const chainDistance = fragment.childFractionTChainDistance(childDetail.fraction); const chainFraction = this.chainDistanceToChainFraction(chainDistance); const chainDetail = CurveLocationDetail.createCurveFractionPoint(this, chainFraction, childDetail.point); chainDetail.childDetail = childDetail; return chainDetail; } return undefined; } }
the_stack
import { AddressType, assert, ASTNode, ASTNodeFactory, ContractDefinition, DataLocation, Expression, ExpressionStatement, ExternalReferenceType, FunctionCall, FunctionCallKind, FunctionCallOptions, FunctionDefinition, FunctionKind, FunctionStateMutability, FunctionType, FunctionVisibility, getNodeType, MemberAccess, ModifierDefinition, Mutability, PointerType, StateVariableVisibility, TypeName, TypeNode, UserDefinedType, VariableDeclaration } from "solc-typed-ast"; import { getFQName, getScopeFun, isChangingState, single } from "../util"; import { FunSet } from "./callgraph"; import { changesMutability } from "./instrument"; import { InstrumentationContext } from "./instrumentation_context"; import { transpileType } from "./transpile"; const semver = require("semver"); /** * Generate a Statement calling the passed-in `original` function from the `stub` function. * * Note that `original` and `stub` must have the same arguments. */ function callOriginal( ctx: InstrumentationContext, stub: FunctionDefinition, original: FunctionDefinition ): ExpressionStatement { const factory = ctx.factory; const argIds = stub.vParameters.vParameters.map((decl) => factory.makeIdentifierFor(decl)); const call = factory.makeFunctionCall( "<missing>", FunctionCallKind.FunctionCall, factory.makeIdentifierFor(original), argIds ); const returnIds = stub.vReturnParameters.vParameters.map((decl) => factory.makeIdentifierFor(decl) ); /** * There is no need for assignments if there are no return parameters */ if (returnIds.length === 0) { const exprStmt = factory.makeExpressionStatement(call); ctx.addGeneralInstrumentation(exprStmt); return exprStmt; } const lhs = returnIds.length === 1 ? returnIds[0] : factory.makeTupleExpression("<missing>", false, returnIds); const assignment = factory.makeAssignment("<missing>", "=", lhs, call); const assignmentStmt = factory.makeExpressionStatement(assignment); ctx.addGeneralInstrumentation(assignmentStmt); return assignmentStmt; } /** * Rename any unnamed returns for the given `stub` function to `RET_<x>`. */ function renameReturns(stub: FunctionDefinition): void { for (let i = 0; i < stub.vReturnParameters.vParameters.length; i++) { const param = stub.vReturnParameters.vParameters[i]; if (param.name === "") { param.name = `RET_${i}`; } } } /** * Makes copy of a passed function with an empty body block */ function makeStub(fun: FunctionDefinition, factory: ASTNodeFactory): FunctionDefinition { const stub = factory.copy(fun); /** * Replace function body */ const newBody = factory.makeBlock([]); stub.vBody = newBody; newBody.parent = stub; /** * Fix up parameters with missing names */ let idx = 0; for (const param of stub.vParameters.vParameters) { if (param.name !== "") continue; // TODO: Check for accidental shadowing param.name = `_DUMMY_ARG_${idx++}`; } return stub; } /** * Given a function `fun` change the mutability of the transitive closure of callers/overriders/overridees which are * pure/view to non-payable * * @param fun - FunctionDefinition from which to start the search * @param ctx - InstrumentationContext * @param skipStartingFun - whether to skip changing the mutuability of `fun` itself. */ function changeDependentsMutabilty( fun: FunctionDefinition, ctx: InstrumentationContext, skipStartingFun = false ) { const queue = [fun]; const seen = new Set<FunctionDefinition>(); // Walk back recursively through all callers, overriden and overriding functions of fun, and // mark all of those that have view/pure mutability to be modified. while (queue.length > 0) { const cur = queue.shift() as FunctionDefinition; if (isChangingState(cur) || seen.has(cur)) { continue; } if (cur !== fun || !skipStartingFun) { seen.add(cur); cur.stateMutability = FunctionStateMutability.NonPayable; } queue.push(...(ctx.callgraph.callers.get(cur) as FunSet)); queue.push(...(ctx.callgraph.overridenBy.get(cur) as FunSet)); queue.push(...(ctx.callgraph.overrides.get(cur) as FunSet)); } } /** * Given a function `fun` create a stub interposing on `fun` and rename the original function */ export function interpose( fun: FunctionDefinition, ctx: InstrumentationContext ): FunctionDefinition { assert( fun.vScope instanceof ContractDefinition, "Instrumenting free functions is not supported yet" ); const factory = ctx.factory; const stub = makeStub(fun, factory); const contract = fun.vScope; // The compiler may emit some internal code related to named returns. for (const retDecl of stub.vReturnParameters.vParameters) { ctx.addGeneralInstrumentation(retDecl); } ctx.wrapperMap.set(fun, stub); const name = fun.kind === FunctionKind.Function ? fun.name : fun.kind; contract.insertBefore(stub, fun); fun.name = ctx.nameGenerator.getFresh(`_original_${fun.vScope.name}_${name}`, true); if (!isChangingState(stub) && changesMutability(ctx)) { stub.stateMutability = FunctionStateMutability.NonPayable; changeDependentsMutabilty(fun, ctx, true); } if (fun.stateMutability === FunctionStateMutability.Payable) { fun.stateMutability = FunctionStateMutability.NonPayable; } fun.documentation = undefined; stub.documentation = undefined; fun.visibility = FunctionVisibility.Private; fun.isConstructor = false; renameReturns(stub); if (stub.kind === FunctionKind.Constructor) { fun.vModifiers = fun.vModifiers.filter( (mod) => mod.vModifier instanceof ModifierDefinition ); stub.vModifiers = stub.vModifiers.filter( (mod) => mod.vModifier instanceof ContractDefinition ); } else { stub.vModifiers = []; } stub.vBody?.appendChild(callOriginal(ctx, stub, fun)); fun.vOverrideSpecifier = undefined; fun.virtual = false; fun.kind = FunctionKind.Function; /** * In solc < 0.6.9 internal functions cannot have calldata arguments/returns. * In solc >= 0.6.9 they can have calldata arguments and returns. * * So in solc < 0.6.9 we should change arguments to memory. * If in solc < 0.6.9 the function returns a calldata array then it cannot be instrumented. * * For solc >= 0.6.9 we don't change the arguments' locations of the wrapped function. */ if (semver.lt(ctx.compilerVersion, "0.6.9")) { for (const arg of fun.vReturnParameters.vParameters) { if (arg.storageLocation === DataLocation.CallData) { throw new Error( `Scribble doesn't support instrumenting functions that return values in calldata for solc older than 0.6.9` ); } } for (const arg of fun.vParameters.vParameters) { if (arg.storageLocation === DataLocation.CallData) { arg.storageLocation = DataLocation.Memory; } } } return stub; } /** * Given a `FunctionCall` `s`, extract the following from the callee: * - gas option (if any) * - value option (if any) * - the underlying callee without the call options * @param s - `FunctionCall` whose callee we are decoding. */ function decodeCallsite(s: FunctionCall): { callee: Expression; gas?: Expression; value?: Expression; } { let callee = s.vExpression; let gas: Expression | undefined; let value: Expression | undefined; if (callee instanceof FunctionCallOptions) { gas = callee.vOptionsMap.get("gas"); value = callee.vOptionsMap.get("value"); callee = callee.vExpression; } else if (callee instanceof FunctionCall) { while (callee instanceof FunctionCall) { assert(callee.vExpression instanceof MemberAccess, "Unexpected callee", callee); if (callee.vExpression.memberName === "gas") { gas = gas ? gas : single(callee.vArguments); } else if (callee.vExpression.memberName === "value") { value = value ? value : single(callee.vArguments); } else { assert(false, "Unexpected callee", callee); } callee = callee.vExpression.vExpression; } } return { callee, gas, value }; } function copySrc(originalNode: ASTNode, newNode: ASTNode): void { assert( originalNode.constructor === newNode.constructor, "New node and original node have different type" ); newNode.src = originalNode.src; const originalChildren = originalNode.children; const newChildren = newNode.children; assert( originalChildren.length === newChildren.length, "New node children and original node children count differs" ); for (let i = 0; i < originalChildren.length; i++) { copySrc(originalChildren[i], newChildren[i]); } } /** * Given an external function call node `call`, generate a wrapper function for `call` and * the recipe to replace `call` with a call to the wrapper function. This needs to handle * some builtin functions such as (address).{call, delegatecall, staticcall}(). */ export function interposeCall( ctx: InstrumentationContext, contract: ContractDefinition, call: FunctionCall ): FunctionDefinition { const factory = ctx.factory; const callsite = decodeCallsite(call); const callee = callsite.callee; const calleeT = getNodeType(callee, ctx.compilerVersion); assert( call.kind === FunctionCallKind.FunctionCall, 'Expected call kind "{0}", not "{1}"', FunctionCallKind.FunctionCall, call.kind, call ); assert( calleeT instanceof FunctionType, "Expected external function type, not {0} for callee in {1}", calleeT, call ); assert( callee instanceof MemberAccess, "Expected a MemberAccess as external call callee, not {0}", callee ); let wrapperMut: FunctionStateMutability; // In `log` mode the wrapper is always non-payable. In 'mstore' all // functions preserve their mutability, unless they are payable (wrappers // can't be payable as they are internal) if (changesMutability(ctx)) { wrapperMut = FunctionStateMutability.NonPayable; } else { wrapperMut = calleeT.mutability === FunctionStateMutability.Payable ? FunctionStateMutability.NonPayable : calleeT.mutability; } const wrapper = factory.makeFunctionDefinition( contract.id, FunctionKind.Function, `_callsite_${call.id}`, false, FunctionVisibility.Private, wrapperMut, false, factory.makeParameterList([]), factory.makeParameterList([]), [], undefined, factory.makeBlock([]) ); ctx.addGeneralInstrumentation(wrapper); const params: VariableDeclaration[] = []; const returns: VariableDeclaration[] = []; let receiver: Expression; let callOriginalExp: Expression; const baseT = getNodeType(callee.vExpression, ctx.compilerVersion); if (call.vFunctionCallType === ExternalReferenceType.UserDefined) { assert( baseT instanceof UserDefinedType && baseT.definition instanceof ContractDefinition, "Expected base to be a reference to a contract, not {0}", baseT ); params.push( factory.makeVariableDeclaration( false, false, "receiver", wrapper.id, false, DataLocation.Default, StateVariableVisibility.Default, Mutability.Mutable, baseT.pp(), undefined, factory.makeUserDefinedTypeName( "<missing>", getFQName(baseT.definition, call), baseT.definition.id ) ) ); params.push( ...calleeT.parameters.map((paramT, idx) => factory.typeNodeToVariableDecl(paramT, `arg${idx}`, call) ) ); returns.push( ...calleeT.returns.map((retT, idx) => factory.typeNodeToVariableDecl(retT, `ret${idx}`, call) ) ); receiver = factory.copy(callee.vExpression); copySrc(callee.vExpression, receiver); callOriginalExp = factory.makeMemberAccess( call.vExpression.typeString, factory.makeIdentifierFor(params[0]), callee.memberName, callee.referencedDeclaration ); } else { assert( baseT instanceof AddressType, "Expected base to have an address type, not {0}", baseT ); assert( ["call", "delegatecall", "staticcall"].includes(callee.memberName), 'Expected member name "call", "delegatecall" or "staticcall". Got {0}', callee.memberName, callee ); params.push( factory.makeVariableDeclaration( false, false, "receiver", wrapper.id, false, DataLocation.Default, StateVariableVisibility.Default, Mutability.Mutable, callee.vExpression.typeString, undefined, transpileType(baseT, factory) ) ); const getTypeAndLoc = (t: TypeNode): [TypeName, DataLocation] => { return t instanceof PointerType ? [transpileType(t.to, factory), t.location] : [transpileType(t, factory), DataLocation.Default]; }; calleeT.parameters.forEach((paramT, idx) => { const [type, loc] = getTypeAndLoc(paramT); params.push( factory.makeVariableDeclaration( false, false, `arg${idx}`, wrapper.id, false, loc, StateVariableVisibility.Default, Mutability.Mutable, paramT.pp(), undefined, type ) ); }); calleeT.returns.forEach((retT, idx) => { const [type, loc] = getTypeAndLoc(retT); returns.push( factory.makeVariableDeclaration( false, false, `ret${idx}`, wrapper.id, false, loc, StateVariableVisibility.Default, Mutability.Mutable, retT.pp(), undefined, type ) ); }); receiver = factory.copy(callee.vExpression); copySrc(callee.vExpression, receiver); callOriginalExp = factory.makeMemberAccess( call.vExpression.typeString, factory.makeIdentifierFor(params[0]), callee.memberName, -1 ); } let nImplicitArgs = 1; /** * If the original call had gas/value function call options, we need * to turn those into arguments for the callsite wrapper. */ if (callsite.gas || callsite.value) { const options: Map<string, Expression> = new Map(); for (const [name, expr] of [ ["gas", callsite.gas], ["value", callsite.value] ] as Array<[string, Expression]>) { if (expr === undefined) { continue; } const param = factory.makeVariableDeclaration( false, false, `_${name}`, wrapper.id, false, DataLocation.Default, StateVariableVisibility.Default, Mutability.Mutable, "uint256", undefined, factory.makeElementaryTypeName("<missing>", "uint256") ); params.splice(1, 0, param); options.set(name, factory.makeIdentifierFor(param)); // Insert implicit gas arguments at begining call.vArguments.splice(0, 0, expr); nImplicitArgs++; } if (semver.lt(ctx.compilerVersion, "0.6.2")) { for (const [name, val] of options) { callOriginalExp = factory.makeFunctionCall( "<missing>", FunctionCallKind.FunctionCall, factory.makeMemberAccess("<missing>", callOriginalExp, name, -1), [val] ); } } else { callOriginalExp = factory.makeFunctionCallOptions( "<missing>", callOriginalExp, options ); } } wrapper.vParameters.vParameters.push(...params); wrapper.vReturnParameters.vParameters.push(...returns); let callOriginal: Expression = factory.makeFunctionCall( call.typeString, FunctionCallKind.FunctionCall, callOriginalExp, params.slice(nImplicitArgs).map((param) => factory.makeIdentifierFor(param)) ); if (wrapper.vReturnParameters.vParameters.length !== 0) { callOriginal = factory.makeAssignment( "<missing>", "=", factory.makeTupleExpression( "<missing>", false, wrapper.vReturnParameters.vParameters.map((param) => factory.makeIdentifierFor(param) ) ), callOriginal ); } factory.addStmt(wrapper, callOriginal); const newCallee = factory.makeIdentifierFor(wrapper); newCallee.src = call.vExpression.src; contract.appendChild(wrapper); call.vExpression = newCallee; call.vArguments.unshift(receiver); // If the call is in a pure/view function change its mutability const containingFun = getScopeFun(call); if (containingFun !== undefined && !isChangingState(containingFun) && changesMutability(ctx)) { changeDependentsMutabilty(containingFun, ctx); } return wrapper; }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AddProfileKeyCommand, AddProfileKeyCommandInput, AddProfileKeyCommandOutput, } from "./commands/AddProfileKeyCommand"; import { CreateDomainCommand, CreateDomainCommandInput, CreateDomainCommandOutput, } from "./commands/CreateDomainCommand"; import { CreateProfileCommand, CreateProfileCommandInput, CreateProfileCommandOutput, } from "./commands/CreateProfileCommand"; import { DeleteDomainCommand, DeleteDomainCommandInput, DeleteDomainCommandOutput, } from "./commands/DeleteDomainCommand"; import { DeleteIntegrationCommand, DeleteIntegrationCommandInput, DeleteIntegrationCommandOutput, } from "./commands/DeleteIntegrationCommand"; import { DeleteProfileCommand, DeleteProfileCommandInput, DeleteProfileCommandOutput, } from "./commands/DeleteProfileCommand"; import { DeleteProfileKeyCommand, DeleteProfileKeyCommandInput, DeleteProfileKeyCommandOutput, } from "./commands/DeleteProfileKeyCommand"; import { DeleteProfileObjectCommand, DeleteProfileObjectCommandInput, DeleteProfileObjectCommandOutput, } from "./commands/DeleteProfileObjectCommand"; import { DeleteProfileObjectTypeCommand, DeleteProfileObjectTypeCommandInput, DeleteProfileObjectTypeCommandOutput, } from "./commands/DeleteProfileObjectTypeCommand"; import { GetDomainCommand, GetDomainCommandInput, GetDomainCommandOutput } from "./commands/GetDomainCommand"; import { GetIntegrationCommand, GetIntegrationCommandInput, GetIntegrationCommandOutput, } from "./commands/GetIntegrationCommand"; import { GetMatchesCommand, GetMatchesCommandInput, GetMatchesCommandOutput } from "./commands/GetMatchesCommand"; import { GetProfileObjectTypeCommand, GetProfileObjectTypeCommandInput, GetProfileObjectTypeCommandOutput, } from "./commands/GetProfileObjectTypeCommand"; import { GetProfileObjectTypeTemplateCommand, GetProfileObjectTypeTemplateCommandInput, GetProfileObjectTypeTemplateCommandOutput, } from "./commands/GetProfileObjectTypeTemplateCommand"; import { ListAccountIntegrationsCommand, ListAccountIntegrationsCommandInput, ListAccountIntegrationsCommandOutput, } from "./commands/ListAccountIntegrationsCommand"; import { ListDomainsCommand, ListDomainsCommandInput, ListDomainsCommandOutput } from "./commands/ListDomainsCommand"; import { ListIntegrationsCommand, ListIntegrationsCommandInput, ListIntegrationsCommandOutput, } from "./commands/ListIntegrationsCommand"; import { ListProfileObjectsCommand, ListProfileObjectsCommandInput, ListProfileObjectsCommandOutput, } from "./commands/ListProfileObjectsCommand"; import { ListProfileObjectTypesCommand, ListProfileObjectTypesCommandInput, ListProfileObjectTypesCommandOutput, } from "./commands/ListProfileObjectTypesCommand"; import { ListProfileObjectTypeTemplatesCommand, ListProfileObjectTypeTemplatesCommandInput, ListProfileObjectTypeTemplatesCommandOutput, } from "./commands/ListProfileObjectTypeTemplatesCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { MergeProfilesCommand, MergeProfilesCommandInput, MergeProfilesCommandOutput, } from "./commands/MergeProfilesCommand"; import { PutIntegrationCommand, PutIntegrationCommandInput, PutIntegrationCommandOutput, } from "./commands/PutIntegrationCommand"; import { PutProfileObjectCommand, PutProfileObjectCommandInput, PutProfileObjectCommandOutput, } from "./commands/PutProfileObjectCommand"; import { PutProfileObjectTypeCommand, PutProfileObjectTypeCommandInput, PutProfileObjectTypeCommandOutput, } from "./commands/PutProfileObjectTypeCommand"; import { SearchProfilesCommand, SearchProfilesCommandInput, SearchProfilesCommandOutput, } from "./commands/SearchProfilesCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateDomainCommand, UpdateDomainCommandInput, UpdateDomainCommandOutput, } from "./commands/UpdateDomainCommand"; import { UpdateProfileCommand, UpdateProfileCommandInput, UpdateProfileCommandOutput, } from "./commands/UpdateProfileCommand"; import { CustomerProfilesClient } from "./CustomerProfilesClient"; /** * <fullname>Amazon Connect Customer Profiles</fullname> * <p>Welcome to the Amazon Connect Customer Profiles API Reference. This guide provides information * about the Amazon Connect Customer Profiles API, including supported operations, data types, * parameters, and schemas.</p> * <p>Amazon Connect Customer Profiles is a unified customer profile for your contact center that has * pre-built connectors powered by AppFlow that make it easy to combine customer information * from third party applications, such as Salesforce (CRM), ServiceNow (ITSM), and your * enterprise resource planning (ERP), with contact history from your Amazon Connect contact * center.</p> * <p>If you're new to Amazon Connect , you might find it helpful to also review the <a href="https://docs.aws.amazon.com/connect/latest/adminguide/what-is-amazon-connect.html">Amazon Connect Administrator Guide</a>.</p> */ export class CustomerProfiles extends CustomerProfilesClient { /** * <p>Associates a new key value with a specific profile, such as a Contact Trace Record (CTR) * ContactId.</p> * <p>A profile object can have a single unique key and any number of additional keys that can * be used to identify the profile that it belongs to.</p> */ public addProfileKey( args: AddProfileKeyCommandInput, options?: __HttpHandlerOptions ): Promise<AddProfileKeyCommandOutput>; public addProfileKey( args: AddProfileKeyCommandInput, cb: (err: any, data?: AddProfileKeyCommandOutput) => void ): void; public addProfileKey( args: AddProfileKeyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddProfileKeyCommandOutput) => void ): void; public addProfileKey( args: AddProfileKeyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddProfileKeyCommandOutput) => void), cb?: (err: any, data?: AddProfileKeyCommandOutput) => void ): Promise<AddProfileKeyCommandOutput> | void { const command = new AddProfileKeyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a domain, which is a container for all customer data, such as customer profile * attributes, object types, profile keys, and encryption keys. You can create multiple * domains, and each domain can have multiple third-party integrations.</p> * <p>Each Amazon Connect instance can be associated with only one domain. Multiple Amazon Connect instances can * be associated with one domain.</p> * <p>Use this API or <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_UpdateDomain.html">UpdateDomain</a> to * enable <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_GetMatches.html">identity * resolution</a>: set <code>Matching</code> to true. </p> */ public createDomain( args: CreateDomainCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDomainCommandOutput>; public createDomain(args: CreateDomainCommandInput, cb: (err: any, data?: CreateDomainCommandOutput) => void): void; public createDomain( args: CreateDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDomainCommandOutput) => void ): void; public createDomain( args: CreateDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDomainCommandOutput) => void), cb?: (err: any, data?: CreateDomainCommandOutput) => void ): Promise<CreateDomainCommandOutput> | void { const command = new CreateDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a standard profile.</p> * <p>A standard profile represents the following attributes for a customer profile in a * domain.</p> */ public createProfile( args: CreateProfileCommandInput, options?: __HttpHandlerOptions ): Promise<CreateProfileCommandOutput>; public createProfile( args: CreateProfileCommandInput, cb: (err: any, data?: CreateProfileCommandOutput) => void ): void; public createProfile( args: CreateProfileCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateProfileCommandOutput) => void ): void; public createProfile( args: CreateProfileCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateProfileCommandOutput) => void), cb?: (err: any, data?: CreateProfileCommandOutput) => void ): Promise<CreateProfileCommandOutput> | void { const command = new CreateProfileCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a specific domain and all of its customer data, such as customer profile * attributes and their related objects.</p> */ public deleteDomain( args: DeleteDomainCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDomainCommandOutput>; public deleteDomain(args: DeleteDomainCommandInput, cb: (err: any, data?: DeleteDomainCommandOutput) => void): void; public deleteDomain( args: DeleteDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDomainCommandOutput) => void ): void; public deleteDomain( args: DeleteDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDomainCommandOutput) => void), cb?: (err: any, data?: DeleteDomainCommandOutput) => void ): Promise<DeleteDomainCommandOutput> | void { const command = new DeleteDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes an integration from a specific domain.</p> */ public deleteIntegration( args: DeleteIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteIntegrationCommandOutput>; public deleteIntegration( args: DeleteIntegrationCommandInput, cb: (err: any, data?: DeleteIntegrationCommandOutput) => void ): void; public deleteIntegration( args: DeleteIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteIntegrationCommandOutput) => void ): void; public deleteIntegration( args: DeleteIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIntegrationCommandOutput) => void), cb?: (err: any, data?: DeleteIntegrationCommandOutput) => void ): Promise<DeleteIntegrationCommandOutput> | void { const command = new DeleteIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the standard customer profile and all data pertaining to the profile.</p> */ public deleteProfile( args: DeleteProfileCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProfileCommandOutput>; public deleteProfile( args: DeleteProfileCommandInput, cb: (err: any, data?: DeleteProfileCommandOutput) => void ): void; public deleteProfile( args: DeleteProfileCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProfileCommandOutput) => void ): void; public deleteProfile( args: DeleteProfileCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProfileCommandOutput) => void), cb?: (err: any, data?: DeleteProfileCommandOutput) => void ): Promise<DeleteProfileCommandOutput> | void { const command = new DeleteProfileCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes a searchable key from a customer profile.</p> */ public deleteProfileKey( args: DeleteProfileKeyCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProfileKeyCommandOutput>; public deleteProfileKey( args: DeleteProfileKeyCommandInput, cb: (err: any, data?: DeleteProfileKeyCommandOutput) => void ): void; public deleteProfileKey( args: DeleteProfileKeyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProfileKeyCommandOutput) => void ): void; public deleteProfileKey( args: DeleteProfileKeyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProfileKeyCommandOutput) => void), cb?: (err: any, data?: DeleteProfileKeyCommandOutput) => void ): Promise<DeleteProfileKeyCommandOutput> | void { const command = new DeleteProfileKeyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes an object associated with a profile of a given ProfileObjectType.</p> */ public deleteProfileObject( args: DeleteProfileObjectCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProfileObjectCommandOutput>; public deleteProfileObject( args: DeleteProfileObjectCommandInput, cb: (err: any, data?: DeleteProfileObjectCommandOutput) => void ): void; public deleteProfileObject( args: DeleteProfileObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProfileObjectCommandOutput) => void ): void; public deleteProfileObject( args: DeleteProfileObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProfileObjectCommandOutput) => void), cb?: (err: any, data?: DeleteProfileObjectCommandOutput) => void ): Promise<DeleteProfileObjectCommandOutput> | void { const command = new DeleteProfileObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes a ProfileObjectType from a specific domain as well as removes all the * ProfileObjects of that type. It also disables integrations from this specific * ProfileObjectType. In addition, it scrubs all of the fields of the standard profile that * were populated from this ProfileObjectType.</p> */ public deleteProfileObjectType( args: DeleteProfileObjectTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProfileObjectTypeCommandOutput>; public deleteProfileObjectType( args: DeleteProfileObjectTypeCommandInput, cb: (err: any, data?: DeleteProfileObjectTypeCommandOutput) => void ): void; public deleteProfileObjectType( args: DeleteProfileObjectTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProfileObjectTypeCommandOutput) => void ): void; public deleteProfileObjectType( args: DeleteProfileObjectTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProfileObjectTypeCommandOutput) => void), cb?: (err: any, data?: DeleteProfileObjectTypeCommandOutput) => void ): Promise<DeleteProfileObjectTypeCommandOutput> | void { const command = new DeleteProfileObjectTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about a specific domain.</p> */ public getDomain(args: GetDomainCommandInput, options?: __HttpHandlerOptions): Promise<GetDomainCommandOutput>; public getDomain(args: GetDomainCommandInput, cb: (err: any, data?: GetDomainCommandOutput) => void): void; public getDomain( args: GetDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetDomainCommandOutput) => void ): void; public getDomain( args: GetDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDomainCommandOutput) => void), cb?: (err: any, data?: GetDomainCommandOutput) => void ): Promise<GetDomainCommandOutput> | void { const command = new GetDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an integration for a domain.</p> */ public getIntegration( args: GetIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<GetIntegrationCommandOutput>; public getIntegration( args: GetIntegrationCommandInput, cb: (err: any, data?: GetIntegrationCommandOutput) => void ): void; public getIntegration( args: GetIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetIntegrationCommandOutput) => void ): void; public getIntegration( args: GetIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIntegrationCommandOutput) => void), cb?: (err: any, data?: GetIntegrationCommandOutput) => void ): Promise<GetIntegrationCommandOutput> | void { const command = new GetIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>This API is in preview release for Amazon Connect and subject to change.</p> * <p>Before calling this API, use <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_CreateDomain.html">CreateDomain</a> or * <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_UpdateDomain.html">UpdateDomain</a> to * enable identity resolution: set <code>Matching</code> to true.</p> * <p>GetMatches returns potentially matching profiles, based on the results of the latest run * of a machine learning process. </p> * <important> * <p>Amazon Connect starts a batch process every Saturday at 12AM UTC to identify matching profiles. * The results are returned up to seven days after the Saturday run.</p> * </important> * * <p>Amazon Connect uses the following profile attributes to identify matches:</p> * <ul> * <li> * <p>PhoneNumber</p> * </li> * <li> * <p>HomePhoneNumber</p> * </li> * <li> * <p>BusinessPhoneNumber</p> * </li> * <li> * <p>MobilePhoneNumber</p> * </li> * <li> * <p>EmailAddress</p> * </li> * <li> * <p>PersonalEmailAddress</p> * </li> * <li> * <p>BusinessEmailAddress</p> * </li> * <li> * <p>FullName</p> * </li> * <li> * <p>BusinessName</p> * </li> * </ul> * <p>For example, two or more profiles—with spelling mistakes such as <b>John Doe</b> and <b>Jhn Doe</b>, or different casing * email addresses such as <b>JOHN_DOE@ANYCOMPANY.COM</b> and * <b>johndoe@anycompany.com</b>, or different phone number * formats such as <b>555-010-0000</b> and <b>+1-555-010-0000</b>—can be detected as belonging to the same customer <b>John Doe</b> and merged into a unified profile.</p> */ public getMatches(args: GetMatchesCommandInput, options?: __HttpHandlerOptions): Promise<GetMatchesCommandOutput>; public getMatches(args: GetMatchesCommandInput, cb: (err: any, data?: GetMatchesCommandOutput) => void): void; public getMatches( args: GetMatchesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMatchesCommandOutput) => void ): void; public getMatches( args: GetMatchesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMatchesCommandOutput) => void), cb?: (err: any, data?: GetMatchesCommandOutput) => void ): Promise<GetMatchesCommandOutput> | void { const command = new GetMatchesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the object types for a specific domain.</p> */ public getProfileObjectType( args: GetProfileObjectTypeCommandInput, options?: __HttpHandlerOptions ): Promise<GetProfileObjectTypeCommandOutput>; public getProfileObjectType( args: GetProfileObjectTypeCommandInput, cb: (err: any, data?: GetProfileObjectTypeCommandOutput) => void ): void; public getProfileObjectType( args: GetProfileObjectTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetProfileObjectTypeCommandOutput) => void ): void; public getProfileObjectType( args: GetProfileObjectTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetProfileObjectTypeCommandOutput) => void), cb?: (err: any, data?: GetProfileObjectTypeCommandOutput) => void ): Promise<GetProfileObjectTypeCommandOutput> | void { const command = new GetProfileObjectTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the template information for a specific object type.</p> * <p>A template is a predefined ProfileObjectType, such as “Salesforce-Account” or * “Salesforce-Contact.” When a user sends a ProfileObject, using the PutProfileObject API, * with an ObjectTypeName that matches one of the TemplateIds, it uses the mappings from the * template.</p> */ public getProfileObjectTypeTemplate( args: GetProfileObjectTypeTemplateCommandInput, options?: __HttpHandlerOptions ): Promise<GetProfileObjectTypeTemplateCommandOutput>; public getProfileObjectTypeTemplate( args: GetProfileObjectTypeTemplateCommandInput, cb: (err: any, data?: GetProfileObjectTypeTemplateCommandOutput) => void ): void; public getProfileObjectTypeTemplate( args: GetProfileObjectTypeTemplateCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetProfileObjectTypeTemplateCommandOutput) => void ): void; public getProfileObjectTypeTemplate( args: GetProfileObjectTypeTemplateCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetProfileObjectTypeTemplateCommandOutput) => void), cb?: (err: any, data?: GetProfileObjectTypeTemplateCommandOutput) => void ): Promise<GetProfileObjectTypeTemplateCommandOutput> | void { const command = new GetProfileObjectTypeTemplateCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all of the integrations associated to a specific URI in the AWS account.</p> */ public listAccountIntegrations( args: ListAccountIntegrationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListAccountIntegrationsCommandOutput>; public listAccountIntegrations( args: ListAccountIntegrationsCommandInput, cb: (err: any, data?: ListAccountIntegrationsCommandOutput) => void ): void; public listAccountIntegrations( args: ListAccountIntegrationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAccountIntegrationsCommandOutput) => void ): void; public listAccountIntegrations( args: ListAccountIntegrationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAccountIntegrationsCommandOutput) => void), cb?: (err: any, data?: ListAccountIntegrationsCommandOutput) => void ): Promise<ListAccountIntegrationsCommandOutput> | void { const command = new ListAccountIntegrationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of all the domains for an AWS account that have been created.</p> */ public listDomains(args: ListDomainsCommandInput, options?: __HttpHandlerOptions): Promise<ListDomainsCommandOutput>; public listDomains(args: ListDomainsCommandInput, cb: (err: any, data?: ListDomainsCommandOutput) => void): void; public listDomains( args: ListDomainsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDomainsCommandOutput) => void ): void; public listDomains( args: ListDomainsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDomainsCommandOutput) => void), cb?: (err: any, data?: ListDomainsCommandOutput) => void ): Promise<ListDomainsCommandOutput> | void { const command = new ListDomainsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all of the integrations in your domain.</p> */ public listIntegrations( args: ListIntegrationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListIntegrationsCommandOutput>; public listIntegrations( args: ListIntegrationsCommandInput, cb: (err: any, data?: ListIntegrationsCommandOutput) => void ): void; public listIntegrations( args: ListIntegrationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListIntegrationsCommandOutput) => void ): void; public listIntegrations( args: ListIntegrationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIntegrationsCommandOutput) => void), cb?: (err: any, data?: ListIntegrationsCommandOutput) => void ): Promise<ListIntegrationsCommandOutput> | void { const command = new ListIntegrationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of objects associated with a profile of a given ProfileObjectType.</p> */ public listProfileObjects( args: ListProfileObjectsCommandInput, options?: __HttpHandlerOptions ): Promise<ListProfileObjectsCommandOutput>; public listProfileObjects( args: ListProfileObjectsCommandInput, cb: (err: any, data?: ListProfileObjectsCommandOutput) => void ): void; public listProfileObjects( args: ListProfileObjectsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListProfileObjectsCommandOutput) => void ): void; public listProfileObjects( args: ListProfileObjectsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListProfileObjectsCommandOutput) => void), cb?: (err: any, data?: ListProfileObjectsCommandOutput) => void ): Promise<ListProfileObjectsCommandOutput> | void { const command = new ListProfileObjectsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all of the templates available within the service.</p> */ public listProfileObjectTypes( args: ListProfileObjectTypesCommandInput, options?: __HttpHandlerOptions ): Promise<ListProfileObjectTypesCommandOutput>; public listProfileObjectTypes( args: ListProfileObjectTypesCommandInput, cb: (err: any, data?: ListProfileObjectTypesCommandOutput) => void ): void; public listProfileObjectTypes( args: ListProfileObjectTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListProfileObjectTypesCommandOutput) => void ): void; public listProfileObjectTypes( args: ListProfileObjectTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListProfileObjectTypesCommandOutput) => void), cb?: (err: any, data?: ListProfileObjectTypesCommandOutput) => void ): Promise<ListProfileObjectTypesCommandOutput> | void { const command = new ListProfileObjectTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all of the template information for object types.</p> */ public listProfileObjectTypeTemplates( args: ListProfileObjectTypeTemplatesCommandInput, options?: __HttpHandlerOptions ): Promise<ListProfileObjectTypeTemplatesCommandOutput>; public listProfileObjectTypeTemplates( args: ListProfileObjectTypeTemplatesCommandInput, cb: (err: any, data?: ListProfileObjectTypeTemplatesCommandOutput) => void ): void; public listProfileObjectTypeTemplates( args: ListProfileObjectTypeTemplatesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListProfileObjectTypeTemplatesCommandOutput) => void ): void; public listProfileObjectTypeTemplates( args: ListProfileObjectTypeTemplatesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListProfileObjectTypeTemplatesCommandOutput) => void), cb?: (err: any, data?: ListProfileObjectTypeTemplatesCommandOutput) => void ): Promise<ListProfileObjectTypeTemplatesCommandOutput> | void { const command = new ListProfileObjectTypeTemplatesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Displays the tags associated with an Amazon Connect Customer Profiles resource. In Connect * Customer Profiles, domains, profile object types, and integrations can be tagged.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>This API is in preview release for Amazon Connect and subject to change.</p> * <p>Runs an AWS Lambda job that does the following:</p> * <ol> * <li> * <p>All the profileKeys in the <code>ProfileToBeMerged</code> will be moved to the * main profile.</p> * </li> * <li> * <p>All the objects in the <code>ProfileToBeMerged</code> will be moved to the main * profile.</p> * </li> * <li> * <p>All the <code>ProfileToBeMerged</code> will be deleted at the end.</p> * </li> * <li> * <p>All the profileKeys in the <code>ProfileIdsToBeMerged</code> will be moved to the * main profile.</p> * </li> * <li> * <p>Standard fields are merged as follows:</p> * <ol> * <li> * <p>Fields are always "union"-ed if there are no conflicts in standard fields or * attributeKeys.</p> * </li> * <li> * <p>When there are conflicting fields:</p> * * <ol> * <li> * <p>If no <code>SourceProfileIds</code> entry is specified, the main * Profile value is always taken. </p> * </li> * <li> * <p>If a <code>SourceProfileIds</code> entry is specified, the specified * profileId is always taken, even if it is a NULL value.</p> * </li> * </ol> * </li> * </ol> * </li> * </ol> * <p>You can use MergeProfiles together with <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_GetMatches.html">GetMatches</a>, which * returns potentially matching profiles, or use it with the results of another matching * system. After profiles have been merged, they cannot be separated (unmerged).</p> */ public mergeProfiles( args: MergeProfilesCommandInput, options?: __HttpHandlerOptions ): Promise<MergeProfilesCommandOutput>; public mergeProfiles( args: MergeProfilesCommandInput, cb: (err: any, data?: MergeProfilesCommandOutput) => void ): void; public mergeProfiles( args: MergeProfilesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: MergeProfilesCommandOutput) => void ): void; public mergeProfiles( args: MergeProfilesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: MergeProfilesCommandOutput) => void), cb?: (err: any, data?: MergeProfilesCommandOutput) => void ): Promise<MergeProfilesCommandOutput> | void { const command = new MergeProfilesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds an integration between the service and a third-party service, which includes * Amazon AppFlow and Amazon Connect.</p> * <p>An integration can belong to only one domain.</p> */ public putIntegration( args: PutIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<PutIntegrationCommandOutput>; public putIntegration( args: PutIntegrationCommandInput, cb: (err: any, data?: PutIntegrationCommandOutput) => void ): void; public putIntegration( args: PutIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutIntegrationCommandOutput) => void ): void; public putIntegration( args: PutIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutIntegrationCommandOutput) => void), cb?: (err: any, data?: PutIntegrationCommandOutput) => void ): Promise<PutIntegrationCommandOutput> | void { const command = new PutIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds additional objects to customer profiles of a given ObjectType.</p> * <p>When adding a specific profile object, like a Contact Trace Record (CTR), an inferred * profile can get created if it is not mapped to an existing profile. The resulting profile * will only have a phone number populated in the standard ProfileObject. Any additional CTRs * with the same phone number will be mapped to the same inferred profile.</p> * <p>When a ProfileObject is created and if a ProfileObjectType already exists for the * ProfileObject, it will provide data to a standard profile depending on the * ProfileObjectType definition.</p> * <p>PutProfileObject needs an ObjectType, which can be created using * PutProfileObjectType.</p> */ public putProfileObject( args: PutProfileObjectCommandInput, options?: __HttpHandlerOptions ): Promise<PutProfileObjectCommandOutput>; public putProfileObject( args: PutProfileObjectCommandInput, cb: (err: any, data?: PutProfileObjectCommandOutput) => void ): void; public putProfileObject( args: PutProfileObjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutProfileObjectCommandOutput) => void ): void; public putProfileObject( args: PutProfileObjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutProfileObjectCommandOutput) => void), cb?: (err: any, data?: PutProfileObjectCommandOutput) => void ): Promise<PutProfileObjectCommandOutput> | void { const command = new PutProfileObjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Defines a ProfileObjectType.</p> */ public putProfileObjectType( args: PutProfileObjectTypeCommandInput, options?: __HttpHandlerOptions ): Promise<PutProfileObjectTypeCommandOutput>; public putProfileObjectType( args: PutProfileObjectTypeCommandInput, cb: (err: any, data?: PutProfileObjectTypeCommandOutput) => void ): void; public putProfileObjectType( args: PutProfileObjectTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutProfileObjectTypeCommandOutput) => void ): void; public putProfileObjectType( args: PutProfileObjectTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutProfileObjectTypeCommandOutput) => void), cb?: (err: any, data?: PutProfileObjectTypeCommandOutput) => void ): Promise<PutProfileObjectTypeCommandOutput> | void { const command = new PutProfileObjectTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Searches for profiles within a specific domain name using name, phone number, email * address, account number, or a custom defined index.</p> */ public searchProfiles( args: SearchProfilesCommandInput, options?: __HttpHandlerOptions ): Promise<SearchProfilesCommandOutput>; public searchProfiles( args: SearchProfilesCommandInput, cb: (err: any, data?: SearchProfilesCommandOutput) => void ): void; public searchProfiles( args: SearchProfilesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SearchProfilesCommandOutput) => void ): void; public searchProfiles( args: SearchProfilesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SearchProfilesCommandOutput) => void), cb?: (err: any, data?: SearchProfilesCommandOutput) => void ): Promise<SearchProfilesCommandOutput> | void { const command = new SearchProfilesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Assigns one or more tags (key-value pairs) to the specified Amazon Connect Customer Profiles * resource. Tags can help you organize and categorize your resources. You can also use them * to scope user permissions by granting a user permission to access or change only resources * with certain tag values. In Connect Customer Profiles, domains, profile object types, and * integrations can be tagged.</p> * <p>Tags don't have any semantic meaning to AWS and are interpreted strictly as strings of * characters.</p> * <p>You can use the TagResource action with a resource that already has tags. If you specify * a new tag key, this tag is appended to the list of tags associated with the resource. If * you specify a tag key that is already associated with the resource, the new tag value that * you specify replaces the previous value for that tag.</p> * <p>You can associate as many as 50 tags with a resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes one or more tags from the specified Amazon Connect Customer Profiles resource. In Connect * Customer Profiles, domains, profile object types, and integrations can be tagged.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the properties of a domain, including creating or selecting a dead letter queue * or an encryption key.</p> * <p>After a domain is created, the name can’t be changed.</p> * <p>Use this API or <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_CreateDomain.html">CreateDomain</a> to * enable <a href="https://docs.aws.amazon.com/customerprofiles/latest/APIReference/API_GetMatches.html">identity * resolution</a>: set <code>Matching</code> to true. </p> */ public updateDomain( args: UpdateDomainCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateDomainCommandOutput>; public updateDomain(args: UpdateDomainCommandInput, cb: (err: any, data?: UpdateDomainCommandOutput) => void): void; public updateDomain( args: UpdateDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateDomainCommandOutput) => void ): void; public updateDomain( args: UpdateDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDomainCommandOutput) => void), cb?: (err: any, data?: UpdateDomainCommandOutput) => void ): Promise<UpdateDomainCommandOutput> | void { const command = new UpdateDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the properties of a profile. The ProfileId is required for updating a customer * profile.</p> * <p>When calling the UpdateProfile API, specifying an empty string value means that any * existing value will be removed. Not specifying a string value means that any value already * there will be kept.</p> */ public updateProfile( args: UpdateProfileCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateProfileCommandOutput>; public updateProfile( args: UpdateProfileCommandInput, cb: (err: any, data?: UpdateProfileCommandOutput) => void ): void; public updateProfile( args: UpdateProfileCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateProfileCommandOutput) => void ): void; public updateProfile( args: UpdateProfileCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateProfileCommandOutput) => void), cb?: (err: any, data?: UpdateProfileCommandOutput) => void ): Promise<UpdateProfileCommandOutput> | void { const command = new UpdateProfileCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import * as assert from 'assert'; import * as path from 'path'; import * as os from 'os'; import * as tmp from 'tmp-promise'; import { PddlExtensionContext, planner } from 'pddl-workspace'; import { Disposable, workspace, ExtensionContext, Memento, extensions, Event, FileType, Uri, ConfigurationTarget, EnvironmentVariableCollection, EnvironmentVariableMutator, ExtensionMode, SecretStorage, SecretStorageChangeEvent, ExtensionKind } from 'vscode'; import { assertDefined } from '../../utils'; import { CONF_PDDL } from '../../configuration/configuration'; import { CONF_PLANNERS, CONF_SELECTED_PLANNER } from '../../configuration/PlannersConfiguration'; export function assertStrictEqualDecorated(actualText: string, expectedText: string, message: string): void { assert.strictEqual(decorate(actualText), decorate(expectedText), message); } export function decorate(text: string): string { return text .split(' ').join('·') .split('\t').join('→') .split('\r').join('⤵') .split('\n').join('⤶'); } export async function createTestPddlExtensionContext(): Promise<PddlExtensionContext> { const storage = await tmp.dir({ mode: 0o644, prefix: 'extensionTestStoragePath' }); return { // eslint-disable-next-line @typescript-eslint/no-unused-vars asAbsolutePath: function (_path: string): string { throw new Error('asAbsolutePath not supported in test extension context'); }, extensionPath: '.', storagePath: storage.path, storageUri: Uri.file(storage.path), subscriptions: new Array<Disposable>(), pythonPath: function (): string { return workspace.getConfiguration().get("python.pythonPath", "python"); } }; } class MockMemento implements Memento { map: Map<string, unknown>; constructor() { this.map = new Map<string, unknown>(); } keys(): readonly string[] { throw new Error('Method not implemented.'); } // will be needed for a future version of VS Code? // get keys(): string[] { // return [...this.map.keys()]; // } get<T>(key: string, defaultValue?: T): T { return (this.map.get(key) as T) ?? assertDefined(defaultValue, "Default value not specified"); } // eslint-disable-next-line @typescript-eslint/no-explicit-any async update(key: string, value: any): Promise<void> { this.map.set(key, value); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setKeysForSync(keys: readonly string[]): void { console.warn(`Key syncing not supported in mock. ${keys}`); } } class MockSecretStorage implements SecretStorage { // eslint-disable-next-line @typescript-eslint/no-unused-vars async get(_key: string): Promise<string | undefined> { return undefined; } // eslint-disable-next-line @typescript-eslint/no-unused-vars async store(_key: string, _value: string): Promise<void> { return void(0); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async delete(_key: string): Promise<void>{ return void (0); } get onDidChange(): Event<SecretStorageChangeEvent> { throw new Error('Unsupported.'); } } class MockEnvironmentVariableCollection implements EnvironmentVariableCollection { persistent = true; // eslint-disable-next-line @typescript-eslint/no-unused-vars replace(_variable: string, _value: string): void { throw new Error('Method not implemented.'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars append(_variable: string, _value: string): void { throw new Error('Method not implemented.'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars prepend(_variable: string, _value: string): void { throw new Error('Method not implemented.'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars get(_variable: string): EnvironmentVariableMutator { throw new Error('Method not implemented.'); } // eslint-disable-next-line @typescript-eslint/no-explicit-any forEach(callback: (variable: string, mutator: EnvironmentVariableMutator, collection: EnvironmentVariableCollection) => any, thisArg?: any): void { throw new Error(`Method not implemented. ${callback}, ${thisArg}`); } // eslint-disable-next-line @typescript-eslint/no-unused-vars delete(_variable: string): void { throw new Error('Method not implemented.'); } clear(): void { throw new Error('Method not implemented.'); } } export async function createTestExtensionContext(): Promise<ExtensionContext> { const storage = await tmp.dir({ prefix: 'extensionTestStoragePath' }); // simulate the space in the 'Application\ Support' on MacOS const globalStoragePrefix = os.platform() === 'darwin' ? 'extensionGlobalTest StoragePath' : 'extensionGlobalTestStoragePath'; const globalStorage = await tmp.dir({ prefix: globalStoragePrefix }); const log = await tmp.file({ mode: 0o644, prefix: 'extensionTests', postfix: 'log' }); return { asAbsolutePath: function (path: string): string { throw new Error(`Unsupported. ` + path); }, extensionPath: '.', // extensionRuntime: ExtensionRuntime.Node, storagePath: storage.path, storageUri: Uri.file(storage.path), subscriptions: new Array<Disposable>(), globalState: new MockMemento(), workspaceState: new MockMemento(), globalStoragePath: globalStorage.path, globalStorageUri: Uri.file(globalStorage.path), logPath: log.path, logUri: Uri.file(log.path), environmentVariableCollection: new MockEnvironmentVariableCollection(), extension: { id: "jan-dolejsi.pddl", extensionUri: Uri.file(process.cwd()), extensionPath: process.cwd(), isActive: true, packageJSON: {}, extensionKind: ExtensionKind.UI, exports: null, activate(): Thenable<unknown> { throw new Error('Method not implemented.'); } }, extensionMode: ExtensionMode.Development, extensionUri: Uri.file(process.cwd()), secrets: new MockSecretStorage(), }; } export class MockPlannerProvider implements planner.PlannerProvider { private path: string | undefined; constructor(private options?: { canConfigure?: boolean }) { } get kind(): planner.PlannerKind { return new planner.PlannerKind("mock"); } getNewPlannerLabel(): string { throw new Error("Method not implemented."); } // eslint-disable-next-line @typescript-eslint/no-unused-vars configurePlanner(_previousConfiguration?: planner.PlannerConfiguration): Promise<planner.PlannerConfiguration> { return Promise.resolve({ kind: this.kind.kind, canConfigure: this.options?.canConfigure ?? false, title: 'Mock planner', path: this.path ?? getMockPlanner(), isSelected: true }); } setExpectedPath(path: string): void { this.path = path; if (this.options) { this.options.canConfigure = true; } } } function getMockPlanner(): string { const plannerPath = path.resolve(__dirname, path.join('..', '..', '..', 'src', 'test', 'planning', 'mock-planner.js')); return "node " + plannerPath; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function activateExtension(): Promise<any> { const thisExtension = assertDefined(extensions.getExtension("jan-dolejsi.pddl"), `Extension 'jan-dolejsi.pddl' not found`); if (!thisExtension.isActive) { return await thisExtension.activate(); } } /** * Awaits a `T` event. * @param event event emitter to subscribe to * @param param1 action to execute after subscribing to the event and filter to apply to events */ export async function waitFor<T>(event: Event<T>, { action: workload, filter }: { action?: () => void; filter?: (event: T) => boolean } = {}): Promise<T> { return new Promise<T>(resolve => { const subscription = event(e => { if ((filter && filter(e)) ?? true) { resolve(e); subscription.dispose(); } }); // if the workload action is defined, call it workload && workload(); }); } /** * Deletes all files in the workspace folder(s) recursively. */ export async function clearWorkspaceFolder(): Promise<void> { if (!workspace.workspaceFolders) { console.warn('No workspace folder is open.'); return; } else { const workspaceFolderDeletions = workspace.workspaceFolders.map(async wf => { const workspaceFolderEntries = await workspace.fs.readDirectory(wf.uri); const fileDeletions = workspaceFolderEntries .filter(entry => entry[0] !== '.gitkeep') .map(async entry => { const [fileName, fileType] = entry; const fileAbsPath = path.join(wf.uri.fsPath, fileName); console.log(`Deleting ${fileAbsPath}/**`); const recursive = fileType === FileType.Directory; return await workspace.fs.delete(Uri.file(fileAbsPath), { recursive: recursive, useTrash: false }); }); await Promise.all(fileDeletions); }); await Promise.all(workspaceFolderDeletions); } } export async function clearConfiguration(): Promise<void> { await workspace.getConfiguration(CONF_PDDL).update(CONF_PLANNERS, undefined, ConfigurationTarget.Global); await workspace.getConfiguration(CONF_PDDL).update(CONF_SELECTED_PLANNER, undefined, ConfigurationTarget.Global); await workspace.getConfiguration(CONF_PDDL).update(CONF_PLANNERS, undefined, ConfigurationTarget.Workspace); await workspace.getConfiguration(CONF_PDDL).update(CONF_SELECTED_PLANNER, undefined, ConfigurationTarget.Workspace); const workspaceFolderDeletions = workspace.workspaceFolders?.map(async wf => { console.warn(`Skipped clearing of workspace-folder configuration for ${wf.name}`); // await workspace.getConfiguration(CONF_PDDL, wf).update(CONF_PLANNERS, undefined, ConfigurationTarget.WorkspaceFolder); // await workspace.getConfiguration(CONF_PDDL, wf).update(CONF_SELECTED_PLANNER, undefined, ConfigurationTarget.WorkspaceFolder); }) ?? []; await Promise.all(workspaceFolderDeletions); }
the_stack
import { NodeFileTraceOptions, NodeFileTraceResult, NodeFileTraceReasons, Stats, NodeFileTraceReasonType } from './types'; import { basename, dirname, extname, relative, resolve, sep } from 'path'; import fs from 'graceful-fs'; import analyze, { AnalyzeResult } from './analyze'; import resolveDependency from './resolve-dependency'; import { isMatch } from 'micromatch'; import { sharedLibEmit } from './utils/sharedlib-emit'; import { join } from 'path'; const fsReadFile = fs.promises.readFile; const fsReadlink = fs.promises.readlink; const fsStat = fs.promises.stat; function inPath (path: string, parent: string) { const pathWithSep = join(parent, sep); return path.startsWith(pathWithSep) && path !== pathWithSep; } export async function nodeFileTrace(files: string[], opts: NodeFileTraceOptions = {}): Promise<NodeFileTraceResult> { const job = new Job(opts); if (opts.readFile) job.readFile = opts.readFile if (opts.stat) job.stat = opts.stat if (opts.readlink) job.readlink = opts.readlink if (opts.resolve) job.resolve = opts.resolve job.ts = true; await Promise.all(files.map(async file => { const path = resolve(file); await job.emitFile(path, 'initial'); if (path.endsWith('.js') || path.endsWith('.cjs') || path.endsWith('.mjs') || path.endsWith('.node') || job.ts && (path.endsWith('.ts') || path.endsWith('.tsx'))) { return job.emitDependency(path); } return undefined; })); const result: NodeFileTraceResult = { fileList: job.fileList, esmFileList: job.esmFileList, reasons: job.reasons, warnings: job.warnings }; return result; }; export class Job { public ts: boolean; public base: string; public cwd: string; public conditions: string[]; public exportsOnly: boolean; public paths: Record<string, string>; public ignoreFn: (path: string, parent?: string) => boolean; public log: boolean; public mixedModules: boolean; public analysis: { emitGlobs?: boolean, computeFileReferences?: boolean, evaluatePureExpressions?: boolean }; private fileCache: Map<string, string | null>; private statCache: Map<string, Stats | null>; private symlinkCache: Map<string, string | null>; private analysisCache: Map<string, AnalyzeResult>; public fileList: Set<string>; public esmFileList: Set<string>; public processed: Set<string>; public warnings: Set<Error>; public reasons: NodeFileTraceReasons = new Map() constructor ({ base = process.cwd(), processCwd, exports, conditions = exports || ['node'], exportsOnly = false, paths = {}, ignore, log = false, mixedModules = false, ts = true, analysis = {}, cache, }: NodeFileTraceOptions) { this.ts = ts; base = resolve(base); this.ignoreFn = (path: string) => { if (path.startsWith('..' + sep)) return true; return false; }; if (typeof ignore === 'string') ignore = [ignore]; if (typeof ignore === 'function') { const ig = ignore; this.ignoreFn = (path: string) => { if (path.startsWith('..' + sep)) return true; if (ig(path)) return true; return false; }; } else if (Array.isArray(ignore)) { const resolvedIgnores = ignore.map(ignore => relative(base, resolve(base || process.cwd(), ignore))); this.ignoreFn = (path: string) => { if (path.startsWith('..' + sep)) return true; if (isMatch(path, resolvedIgnores)) return true; return false; } } this.base = base; this.cwd = resolve(processCwd || base); this.conditions = conditions; this.exportsOnly = exportsOnly; const resolvedPaths: Record<string, string> = {}; for (const path of Object.keys(paths)) { const trailer = paths[path].endsWith('/'); const resolvedPath = resolve(base, paths[path]); resolvedPaths[path] = resolvedPath + (trailer ? '/' : ''); } this.paths = resolvedPaths; this.log = log; this.mixedModules = mixedModules; this.analysis = {}; if (analysis !== false) { Object.assign(this.analysis, { // whether to glob any analysis like __dirname + '/dir/' or require('x/' + y) // that might output any file in a directory emitGlobs: true, // whether __filename and __dirname style // expressions should be analyzed as file references computeFileReferences: true, // evaluate known bindings to assist with glob and file reference analysis evaluatePureExpressions: true, }, analysis === true ? {} : analysis); } this.fileCache = cache && cache.fileCache || new Map(); this.statCache = cache && cache.statCache || new Map(); this.symlinkCache = cache && cache.symlinkCache || new Map(); this.analysisCache = cache && cache.analysisCache || new Map(); if (cache) { cache.fileCache = this.fileCache; cache.statCache = this.statCache; cache.symlinkCache = this.symlinkCache; cache.analysisCache = this.analysisCache; } this.fileList = new Set(); this.esmFileList = new Set(); this.processed = new Set(); this.warnings = new Set(); } async readlink (path: string) { const cached = this.symlinkCache.get(path); if (cached !== undefined) return cached; try { const link = await fsReadlink(path); // also copy stat cache to symlink const stats = this.statCache.get(path); if (stats) this.statCache.set(resolve(path, link), stats); this.symlinkCache.set(path, link); return link; } catch (e) { if (e.code !== 'EINVAL' && e.code !== 'ENOENT' && e.code !== 'UNKNOWN') throw e; this.symlinkCache.set(path, null); return null; } } async isFile (path: string) { const stats = await this.stat(path); if (stats) return stats.isFile(); return false; } async isDir (path: string) { const stats = await this.stat(path); if (stats) return stats.isDirectory(); return false; } async stat (path: string) { const cached = this.statCache.get(path); if (cached) return cached; try { const stats = await fsStat(path); this.statCache.set(path, stats); return stats; } catch (e) { if (e.code === 'ENOENT') { this.statCache.set(path, null); return null; } throw e; } } async resolve (id: string, parent: string, job: Job, cjsResolve: boolean): Promise<string | string[]> { return resolveDependency(id, parent, job, cjsResolve); } async readFile (path: string): Promise<string | Buffer | null> { const cached = this.fileCache.get(path); if (cached !== undefined) return cached; try { const source = (await fsReadFile(path)).toString(); this.fileCache.set(path, source); return source; } catch (e) { if (e.code === 'ENOENT' || e.code === 'EISDIR') { this.fileCache.set(path, null); return null; } throw e; } } async realpath (path: string, parent?: string, seen = new Set()): Promise<string> { if (seen.has(path)) throw new Error('Recursive symlink detected resolving ' + path); seen.add(path); const symlink = await this.readlink(path); // emit direct symlink paths only if (symlink) { const parentPath = dirname(path); const resolved = resolve(parentPath, symlink); const realParent = await this.realpath(parentPath, parent); if (inPath(path, realParent)) await this.emitFile(path, 'resolve', parent, true); return this.realpath(resolved, parent, seen); } // keep backtracking for realpath, emitting folder symlinks within base if (!inPath(path, this.base)) return path; return join(await this.realpath(dirname(path), parent, seen), basename(path)); } async emitFile (path: string, reasonType: NodeFileTraceReasonType, parent?: string, isRealpath = false) { if (!isRealpath) { path = await this.realpath(path, parent); } path = relative(this.base, path); if (parent) { parent = relative(this.base, parent); } let reasonEntry = this.reasons.get(path) if (!reasonEntry) { reasonEntry = { type: [reasonType], ignored: false, parents: new Set() }; this.reasons.set(path, reasonEntry) } else if (!reasonEntry.type.includes(reasonType)) { reasonEntry.type.push(reasonType) } if (parent && this.ignoreFn(path, parent)) { if (!this.fileList.has(path) && reasonEntry) { reasonEntry.ignored = true; } return false; } if (parent) { reasonEntry.parents.add(parent); } this.fileList.add(path); return true; } async getPjsonBoundary (path: string) { const rootSeparatorIndex = path.indexOf(sep); let separatorIndex: number; while ((separatorIndex = path.lastIndexOf(sep)) > rootSeparatorIndex) { path = path.slice(0, separatorIndex); if (await this.isFile(path + sep + 'package.json')) return path; } return undefined; } async emitDependency (path: string, parent?: string) { if (this.processed.has(path)) { if (parent) { await this.emitFile(path, 'dependency', parent) } return }; this.processed.add(path); const emitted = await this.emitFile(path, 'dependency', parent); if (!emitted) return; if (path.endsWith('.json')) return; if (path.endsWith('.node')) return await sharedLibEmit(path, this); // js files require the "type": "module" lookup, so always emit the package.json if (path.endsWith('.js')) { const pjsonBoundary = await this.getPjsonBoundary(path); if (pjsonBoundary) await this.emitFile(pjsonBoundary + sep + 'package.json', 'resolve', path); } let analyzeResult: AnalyzeResult; const cachedAnalysis = this.analysisCache.get(path); if (cachedAnalysis) { analyzeResult = cachedAnalysis; } else { const source = await this.readFile(path); if (source === null) throw new Error('File ' + path + ' does not exist.'); analyzeResult = await analyze(path, source.toString(), this); this.analysisCache.set(path, analyzeResult); } const { deps, imports, assets, isESM } = analyzeResult; if (isESM) this.esmFileList.add(relative(this.base, path)); await Promise.all([ ...[...assets].map(async asset => { const ext = extname(asset); if (ext === '.js' || ext === '.mjs' || ext === '.node' || ext === '' || this.ts && (ext === '.ts' || ext === '.tsx') && asset.startsWith(this.base) && asset.slice(this.base.length).indexOf(sep + 'node_modules' + sep) === -1) await this.emitDependency(asset, path); else await this.emitFile(asset, 'asset', path); }), ...[...deps].map(async dep => { try { var resolved = await this.resolve(dep, path, this, !isESM); } catch (e) { this.warnings.add(new Error(`Failed to resolve dependency ${dep}:\n${e && e.message}`)); return; } if (Array.isArray(resolved)) { for (const item of resolved) { // ignore builtins if (item.startsWith('node:')) return; await this.emitDependency(item, path); } } else { // ignore builtins if (resolved.startsWith('node:')) return; await this.emitDependency(resolved, path); } }), ...[...imports].map(async dep => { try { var resolved = await this.resolve(dep, path, this, false); } catch (e) { this.warnings.add(new Error(`Failed to resolve dependency ${dep}:\n${e && e.message}`)); return; } if (Array.isArray(resolved)) { for (const item of resolved) { // ignore builtins if (item.startsWith('node:')) return; await this.emitDependency(item, path); } } else { // ignore builtins if (resolved.startsWith('node:')) return; await this.emitDependency(resolved, path); } }) ]); } }
the_stack
import React, { useCallback, useReducer } from 'react'; import classNames from 'classnames'; import { makeStyles } from '@material-ui/core/styles'; import { SymbolColor, useColor, useShapeViewerStyles } from './SharedStyles'; import _isEqual from 'lodash.isequal'; import _get from 'lodash.get'; import _uniq from 'lodash.uniq'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import WarningIcon from '@material-ui/icons/Warning'; import { toCommonJsPath } from '@useoptic/cli-shared/build/diffs/json-trail'; import CheckIcon from '@material-ui/icons/Check'; import { ICopy, ICopyRenderSpan } from './ICopyRender'; import { IChangeType } from '../../../lib/Interfaces'; import { AddedGreen, secondary, ShapeViewerTheme } from '<src>/styles'; /* WARNING: Lots of unconstrained types here from the JS -> Typescript port. We need to come back and remove `:any` once we have this working vertically. Worth the 1-2 hrs to keep this complex component maintainable. +1 */ export type InteractionViewerBody = { noBody?: boolean; asJson?: any; asText?: string; empty?: boolean; }; type InteractionBodyViewerProps = { diff?: any; description?: any; jsonTrails?: any[]; body: InteractionViewerBody; assertion?: ICopy[]; trailsAreCorrect?: boolean; }; export default function InteractionBodyViewerAllJS({ description, jsonTrails = [], body, assertion, trailsAreCorrect = true, }: InteractionBodyViewerProps) { const generalClasses = useShapeViewerStyles(); const [{ rows }, dispatch] = useReducer( updateState, { body, jsonTrails, description }, createInitialState ); const diffDetails = description && { description, assertion, changeType: description.changeType, trailsAreCorrect, // changeDescription: 'changed!', }; return ( <div className={generalClasses.root}> {rows.map((row: IDiffExampleViewerRow, index: number) => { return ( <Row key={row.id} index={index} {...row} diffDetails={row.compliant ? {} : diffDetails} dispatch={dispatch} /> ); })} </div> ); } export function Row(props: any) { const classes = useStyles(); const { collapsed, compliant, diffDetails, indent, index, fieldsHidden, seqIndex, fieldName, fieldValue, type, dispatch, } = props; const onRowClick = useCallback( (e) => { if (!collapsed) return; e.preventDefault(); if (type === 'array_item_collapsed') { dispatch({ type: 'unfold-index', payload: index }); } if (type === 'object_keys_collapsed') { dispatch({ type: 'unfold-fields', payload: index }); } }, [index, type, dispatch, collapsed] ); const indentPadding = ' '.repeat(indent * 2); return ( <div className={classNames(classes.row, { // [generalClasses.isTracked]: !!props.tracked, // important for the compass to work [classes.isCollapsed]: collapsed, [classes.isIncompliant]: !compliant && !collapsed, [classes.isCollapsedIncompliant]: !compliant && collapsed, [classes.requiresAddition]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Added, [classes.requiresUpdate]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Changed, [classes.requiresRemoval]: diffDetails && !diffDetails.trailsAreCorrect && diffDetails.changeType === IChangeType.Removed, [classes.trailsAreCorrect]: diffDetails.trailsAreCorrect, })} > <div className={classes.rowContent} onClick={onRowClick}> {indentPadding} <RowFieldName type={type} name={fieldName} /> <RowSeqIndex type={type} index={seqIndex} /> <RowValue isRoot={indent === 0} type={type} fieldsHidden={fieldsHidden} value={fieldValue} compliant={compliant} changeDescription={diffDetails && diffDetails.changeDescription} /> </div> {!compliant && !collapsed && (diffDetails.trailsAreCorrect ? ( <TrailCheck {...diffDetails} /> ) : ( <DiffAssertion {...diffDetails} /> ))} </div> ); } Row.displayName = 'ShapeViewer/Row'; function RowValue({ type, value, compliant, changeDescription, trailsAreCorrect, isRoot, fieldsHidden, }: any) { const generalClasses = useShapeViewerStyles(); const classes = useStyles(); if (type === 'null') { return ( <span className={classNames( generalClasses.symbols, classes.symbolContent, 'fs-exclude' )} > {'null'} </span> ); } if (type === 'array_open') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'['} </span> ); } if (type === 'array_item_collapsed') { return ( <span className={classes.collapsedSymbol}> {'⋯'} {!compliant ? ( changeDescription || !trailsAreCorrect ? ( <CheckCircleIcon className={classes.collapsedChangeIcon} /> ) : ( <WarningIcon className={classes.collapsedWarning} /> ) ) : ( '' )} </span> ); } if (type === 'object_keys_collapsed') { return ( <span className={classes.collapsedObjectSymbol}> {`...expand ${fieldsHidden} additional fields`} </span> ); } if (type === 'array_close') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {']'} </span> ); } if (type === 'object_open') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'{'} </span> ); } if (type === 'object_close') { return ( <span className={classNames(generalClasses.symbols, classes.symbolContent)} > {'}'} </span> ); } if (type === 'string') { const quote = isRoot ? '' : '"'; return ( <span className={classNames(classes.stringContent, 'fs-exclude')}> {quote} {value} {quote} </span> ); } if (type === 'boolean') { return ( <span className="fs-exclude" style={{ color: '#d9ba99', fontWeight: 600 }} > {value ? 'true' : 'false'} </span> ); } if (type === 'number') { return ( <span className="fs-exclude" style={{ color: '#99d9d9', fontWeight: 600 }} > {value} </span> ); } if (type === 'undefined') { return null; } if (type === 'empty') { return ( <span className={classNames(generalClasses.symbols, classes.emptyContent)} > empty </span> ); } throw new Error(`Cannot render RowValue for type '${type}'`); } RowValue.displayName = 'ShapeViewer/RowValue'; function RowFieldName({ type, name }: any) { const classes = useStyles(); const missing = type === 'undefined'; if (!name) return null; return ( <span className={classNames(classes.fieldName, { [classes.isMissing]: type === 'undefined', })} > {name} {!missing && ': '} </span> ); } function RowSeqIndex({ type, index, missing }: any) { const classes = useStyles(); if (!index && index !== 0) return null; return ( <span className={classNames(classes.fieldIndex, { [classes.isMissing]: !!missing, })} > {index}:{' '} </span> ); } function DiffAssertion({ assertion, changeDescription }: any) { const classes = useStyles(); return ( <div className={classes.diffAssertion}> {changeDescription ? ( <> <CheckCircleIcon className={classes.selectectedChangeIcon} /> {/*<span className={classes.changeDescription}>*/} <span> <ICopyRenderSpan variant="subtitle2" copy={assertion} /> {/*{changeDescription.map(({ value }) => value).join(' ')}*/} </span> </> ) : ( <> <WarningIcon className={classes.assertionWarningIcon} /> <ICopyRenderSpan variant="subtitle2" copy={assertion} /> </> )} </div> ); } function TrailCheck({ assertion }: any) { const classes = useStyles(); return ( <div className={classes.diffAssertion}> <div style={{ flex: 1 }} /> <CheckIcon className={classes.correctTrailIcon} /> </div> ); } const useStyles = makeStyles((theme) => ({ row: { display: 'flex', padding: 0, paddingLeft: 4, flexDirection: 'row', alignItems: 'baseline', '&:hover': { backgroundColor: 'rgba(78,165,255,0.27)', }, '&$isCollapsed': { cursor: 'pointer', }, '&$isIncompliant, &$isCollapsedIncompliant:hover': { '&$requiresAddition': { backgroundColor: ShapeViewerTheme.added.background, }, '&$requiresRemoval': { backgroundColor: ShapeViewerTheme.removed.background, }, '&$requiresUpdate': { backgroundColor: ShapeViewerTheme.changed.background, }, }, }, rowContent: { flexGrow: 1, flexShrink: 1, overflow: 'hidden', padding: theme.spacing(0, 5 / 8), lineHeight: '25px', fontSize: 12, fontFamily: "'Source Code Pro', monospace", whiteSpace: 'pre', color: SymbolColor, }, collapsedRowValue: {}, collapsedSymbol: { paddingLeft: theme.spacing(1), paddingRight: theme.spacing(1), paddingTop: 3, color: '#070707', fontSize: 10, backgroundColor: '#ababab', borderRadius: 12, '$isCollapsedIncompliant$requiresAddition &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, '$isCollapsedIncompliant$requiresRemoval &': { backgroundColor: ShapeViewerTheme.removed.background, color: ShapeViewerTheme.removed.main, }, '$isCollapsedIncompliant$requiresUpdate &': { backgroundColor: ShapeViewerTheme.changed.background, color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, }, collapsedObjectSymbol: { paddingRight: theme.spacing(1), paddingTop: 3, color: '#8f8f8f', fontSize: 10, borderRadius: 12, '$isCollapsedIncompliant$requiresAddition &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, '$isCollapsedIncompliant$requiresRemoval &': { backgroundColor: ShapeViewerTheme.removed.background, color: ShapeViewerTheme.removed.main, }, '$isCollapsedIncompliant$requiresUpdate &': { backgroundColor: ShapeViewerTheme.changed.background, color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { backgroundColor: ShapeViewerTheme.added.background, color: ShapeViewerTheme.added.main, }, }, collapsedWarning: { width: 10, height: 10, marginLeft: theme.spacing(0.5), color: theme.palette.secondary.main, }, collapsedChangeIcon: { width: 10, height: 10, marginLeft: theme.spacing(0.5), '$requiresAddition &': { color: ShapeViewerTheme.added.main, }, '$requiresRemoval &': { color: ShapeViewerTheme.removed.main, }, '$requiresUpdate &': { color: ShapeViewerTheme.changed.main, }, '$trailsAreCorrect &': { color: ShapeViewerTheme.added.main, }, }, booleanContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", color: useColor.BooleanColor, }, symbolContent: { color: SymbolColor, }, emptyContent: { color: SymbolColor, fontStyle: 'italic', }, numberContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", color: useColor.NumberColor, }, stringContent: { fontWeight: 600, whiteSpace: 'pre-line', wordBreak: 'break-all', overflowWrap: 'break-word', fontFamily: "'Source Code Pro', monospace", color: useColor.StringColor, }, missingContent: { fontWeight: 600, fontFamily: "'Source Code Pro', monospace", fontStyle: 'italic', opacity: 0.8, }, fieldName: { fontWeight: 600, color: '#cfcfcf', fontSize: 12, fontFamily: "'Source Code Pro', monospace", opacity: 1, '&$isMissing': { fontStyle: 'italic', opacity: 0.6, }, }, fieldIndex: { fontWeight: 500, color: '#9cdcfe', fontSize: 12, fontFamily: "'Source Code Pro', monospace", opacity: 1, '&$isMissing': { opacity: 0.4, }, }, diffAssertion: { flexGrow: 0, flexShrink: 0, alignSelf: 'center', minWidth: '35%', maxWidth: '50%', display: 'flex', alignItems: 'center', padding: theme.spacing(0, 2), color: '#f8edf4', fontSize: 14, fontWeight: 800, fontFamily: "'Source Code Pro', monospace", }, assertionWarningIcon: { width: 14, height: 14, marginRight: theme.spacing(1), color: secondary, }, selectectedChangeIcon: { width: 14, height: 14, marginRight: theme.spacing(1), '$requiresAddition &': { color: ShapeViewerTheme.added.main, }, '$requiresRemoval &': { color: ShapeViewerTheme.removed.main, }, '$requiresUpdate &': { color: ShapeViewerTheme.changed.main, }, }, correctTrailIcon: { width: 20, height: 20, marginRight: theme.spacing(1), color: AddedGreen, }, isCollapsed: {}, isMissing: {}, isIncompliant: {}, isCollapsedIncompliant: {}, requiresAddition: {}, requiresUpdate: {}, requiresRemoval: {}, trailsAreCorrect: {}, })); // ShapeViewer view model // ---------------------- // // We're using a reducer model so we can use pure transformation functions to // manage the view model's state. That should especially come in handy when we // want to cover this with tests, but will also help in making it into something // re-usable, using Typescript to implement it, etc. // // TODO: consider moving this to it's own module, partly to enable the usecase // stated above. function createInitialState({ jsonTrails, body }: any) { const diffTrails = jsonTrails.map(toCommonJsPath); if (!body.empty) { const shape = !body.noBody ? body.asJson || body.asText : undefined; const [rows, collapsedTrails] = shapeRows(shape, diffTrails); return { body: shape, rows, collapsedTrails, diffTrails }; } else { const rows = [emptyRow()]; const collapsedTrails = [] as any[]; return { body: undefined, rows, collapsedTrails, diffTrails }; } } function updateState(state: any, action: any) { const index = action.payload; switch (action.type) { case 'unfold-index': return unfoldRows(state, index); case 'unfold-fields': return unfoldObjectRows(state, index); default: throw new Error( `State cannot be updated through action of type '${action.type}'` ); } } function unfoldRows(currentState: any, index: number) { const row = currentState.rows[index]; if (row.type !== 'array_item_collapsed') return currentState; const collapsedShape = _get(currentState.body, row.trail); const rowField = { fieldValue: row.fieldValue, fieldName: row.fieldName, seqIndex: row.seqIndex, trail: [...row.trail], }; const [replacementRows, newCollapsedTrails] = shapeRows( collapsedShape, currentState.diffTrails, [], [], row.indent, rowField ); const updatedRows = [...currentState.rows]; updatedRows.splice(index, 1, ...replacementRows); const updatedCollapsedTrails = currentState.collapsedTrails .filter((trail: any) => !_isEqual(trail, row.trail)) .concat(newCollapsedTrails); return { ...currentState, rows: updatedRows, collapsedTrails: updatedCollapsedTrails, }; } function unfoldObjectRows(currentState: any, index: number) { const row = currentState.rows[index]; if (row.type !== 'object_keys_collapsed') return currentState; const updatedRows = [...currentState.rows]; const startIndex = updatedRows.findIndex( (i) => i.type === 'object_open' && _isEqual(i.trail, row.trail) ); const open = updatedRows[startIndex]; const collapsedShape = _get(currentState.body, open.trail, currentState.body); const rowField = { fieldValue: open.fieldValue, fieldName: open.fieldName, seqIndex: open.seqIndex, trail: [...open.trail], }; const [replacementRows, newCollapsedTrails] = shapeRows( collapsedShape, currentState.diffTrails, [], [], row.indent - 1, rowField, row.trail ); const endIndex = updatedRows.findIndex( (i, index) => i.type === 'object_close' && index > startIndex && _isEqual(i.trail, row.trail) ) + 1; const offset = endIndex - startIndex; updatedRows.splice(startIndex, offset, ...replacementRows); const updatedCollapsedTrails = currentState.collapsedTrails .filter((trail: any) => !_isEqual(trail, row.trail)) .concat(newCollapsedTrails); return { ...currentState, rows: updatedRows, collapsedTrails: updatedCollapsedTrails, }; } // Since we've run into performance issue before traversing entire shapes, we're doing this // the mutative way to prevent a lot of re-alloctions for big bodies. function shapeRows( shape: any, diffTrails: any[] = [], rows: any[] = [], collapsedTrails: any[] = [], indent: number = 0, field: { fieldName: string | undefined; fieldValue: any | undefined; seqIndex: number | undefined; trail: any[]; } = { fieldName: undefined, fieldValue: undefined, seqIndex: undefined, trail: [], }, expandObjectWithTrail?: any ) { const typeString = Object.prototype.toString.call(shape); switch (typeString) { case '[object Object]': // debugger; objectRows( shape, diffTrails, rows, collapsedTrails, indent, field, expandObjectWithTrail ); break; case '[object Array]': // debugger; listRows(shape, diffTrails, rows, collapsedTrails, indent, field); break; default: let type = getFieldType(shape); let row = createRow( { type, ...field, fieldValue: field && field.fieldValue ? field.fieldValue : shape, indent, }, { diffTrails } ); rows.push(createRow(row)); break; } return [rows, collapsedTrails]; } function objectRows( objectShape: any, diffTrails: any[], rows: any[], collapsedTrails: any[], indent: number, field: any, expandObjectWithTrail: any ) { const { trail } = field; rows.push( createRow( { type: 'object_open', fieldName: field.fieldName, seqIndex: field.seqIndex, trail, indent, }, { diffTrails } ) ); const nestedDiffs = diffTrails.filter((diffTrail: any) => trail.every( (trailComponent: any, n: any) => trailComponent === diffTrail[n] ) ); function hasNestedDiff(trail: any) { return nestedDiffs.some((i: any) => _isEqual(i.slice(0, trail.length), trail) ); } const keysWithDiffs = nestedDiffs .filter((nestedDiff: any) => nestedDiff.length === trail.length + 1) .map((diff: any) => diff[diff.length - 1]); const objectKeys = _uniq([...Object.keys(objectShape), ...keysWithDiffs]); const collapseAt = 9; const shouldCollapse = objectKeys.length > collapseAt && !_isEqual(expandObjectWithTrail, trail) && keysWithDiffs.length === 0 && indent !== 0; if (shouldCollapse) { collapsedTrails.push(trail); rows.push( createRow({ type: 'object_keys_collapsed', collapsed: true, indent: indent + 1, fieldsHidden: objectKeys.filter( (key: string) => !(keysWithDiffs.includes(key) || hasNestedDiff([...trail, key])) ).length, trail: trail, }) ); } objectKeys .sort(alphabetizeCaseInsensitve) .forEach((key: string, index: number) => { const fieldName = key; const fieldTrail = [...trail, fieldName]; const value = objectShape[key]; if (shouldCollapse) { if (keysWithDiffs.includes(key) || hasNestedDiff(fieldTrail)) { shapeRows(value, nestedDiffs, rows, collapsedTrails, indent + 1, { fieldName, seqIndex: undefined, fieldValue: value, trail: fieldTrail, }); } else { } } else { shapeRows(value, nestedDiffs, rows, collapsedTrails, indent + 1, { fieldName, seqIndex: undefined, fieldValue: value, trail: fieldTrail, }); } }); rows.push(createRow({ type: 'object_close', indent, trail })); } function alphabetizeCaseInsensitve(A: string, B: string): number { const a = A.toLowerCase ? A.toLowerCase() : A; const b = B.toLowerCase ? B.toLowerCase() : B; if (a > b) { return 1; } else if (b > a) { return -1; } return 0; } function listRows( list: any, diffTrails: any[], rows: any[], collapsedTrails: any[], indent: number, field: any ) { const { trail } = field; rows.push( createRow( { type: 'array_open', indent, fieldName: field.fieldName, seqIndex: field.seqIndex, trail, }, { diffTrails } ) ); const nestedDiffs = diffTrails.filter( (diffTrail) => diffTrail.length > trail.length && trail.every( (trailComponent: any, n: number) => trailComponent === diffTrail[n] ) ); const indexesWithDiffs = list .map((item: any, index: number) => index) .filter((index: number) => { return nestedDiffs.some((diffTrail) => index === diffTrail[trail.length]); }); list.forEach((item: any, index: number) => { let itemTypeString = Object.prototype.toString.call(item); let itemTrail = [...trail, index]; let itemIndent = indent + 1; if ( (itemTypeString !== '[object Object]' && itemTypeString !== '[object Array]') || (indexesWithDiffs.length > 0 && indexesWithDiffs[0] === index) || (indexesWithDiffs.length === 0 && index === 0) ) { shapeRows(item, diffTrails, rows, collapsedTrails, itemIndent, { fieldName: undefined, seqIndex: index, fieldValue: item, trail: itemTrail, }); } else { rows.push( createRow({ type: 'array_item_collapsed', collapsed: true, compliant: !indexesWithDiffs.includes(index), seqIndex: index, indent: itemIndent, trail: itemTrail, }) ); collapsedTrails.push(itemTrail); } }); rows.push(createRow({ type: 'array_close', indent, trail })); } function emptyRow() { return createRow({ type: 'empty', collapsed: false, compliant: true, trail: [], }); } function getFieldType(fieldValue: any): string { if (typeof fieldValue === 'undefined') { return 'undefined'; } const jsTypeString = Object.prototype.toString.call(fieldValue); switch (jsTypeString) { case '[object Null]': return 'null'; case '[object String]': return 'string'; case '[object Boolean]': return 'boolean'; case '[object Number]': return 'number'; default: debugger; throw new Error( `Can not return field type for fieldValue with type string '${jsTypeString}'` ); } } interface IDiffExampleViewerRow { id: string; collapsed: false; compliant: boolean; type: string; trail: any[]; } function createRow(row: any, options: any = {}): IDiffExampleViewerRow { const trail = row && row.trail; const type = row && row.type; if (!trail || !Array.isArray(trail)) new TypeError('trail (array) must be known to create a row'); if (!type) new TypeError('type must be known to create a row'); const id = `${row.trail.join('.') || 'root'}-${row.type}`; const isCompliant = !options.diffTrails || !options.diffTrails.some((diffTrail: any) => _isEqual(diffTrail, trail)); return { id, collapsed: false, compliant: isCompliant, ...row, }; }
the_stack
import { Page, Book } from '../book'; import Controls from '../controls'; import { ViewerMode, SheetMarks, SheetSize, SheetLayout } from '../constants'; import { classes, allModeClasses, classForMode, div } from '../dom'; import { throttleFrame, throttleTime } from '../utils'; import { renderGridViewer } from './gridViewer'; import { renderSheetViewer } from './sheetViewer'; import { renderFlipbookViewer } from './flipbookViewer'; import { scrollToBottom, scrollToPercent, getScrollAsPercent, } from './scrollUtils'; import errorView from './error'; import listenForPrint from './listenForPrint'; import PageSetup from '../page-setup'; const throttleProgressBar = throttleFrame(); const throttleRender = throttleTime(100); const throttleResize = throttleTime(50); const pageSpread = (...pgs: HTMLElement[]) => { return div('.spread-wrapper.spread-centered.spread-size', ...pgs); }; interface ViewerOptions { pageSetup: PageSetup; mode: ViewerMode; layout: SheetLayout; marks: SheetMarks; } interface RenderedViewer { element: DocumentFragment; contentSizer?: HTMLElement; next?: () => void; previous?: () => void; } class Viewer { book?: Book; pageSetup: PageSetup; currentResult?: RenderedViewer; progressBar: HTMLElement; content: HTMLElement; scaler: HTMLElement; element: HTMLElement; error?: HTMLElement; isDoubleSided: boolean; sheetLayout: SheetLayout; marks: SheetMarks; mode: ViewerMode; currentLeaf: number; controls: Controls; lastSpreadInProgress: any; hasRendered: boolean = false; constructor({ pageSetup, mode, layout, marks }: ViewerOptions) { this.pageSetup = pageSetup; this.controls = new Controls(); this.updateControls(); this.progressBar = div('.progress-bar'); this.content = div('.zoom-content'); this.scaler = div('.zoom-scaler', this.content); this.element = div( '.root', this.progressBar, this.controls.element, this.scaler, ); this.isDoubleSided = true; this.sheetLayout = layout; this.marks = marks; this.mode = mode; this.element.classList.add(classes.viewPreview); this.currentLeaf = 0; listenForPrint(() => { this.mode = ViewerMode.PRINT; this.render(); }); document.body.addEventListener('keydown', (e) => { switch (e.key) { case 'ArrowLeft': const prev = this.currentResult?.previous; if (prev) prev(); break; case 'ArrowRight': const next = this.currentResult?.next; if (next) next(); break; default: break; } }); window.addEventListener('resize', () => { throttleResize(() => this.scaleToFit()); }); this.setInProgress(true); this.setMarks(marks); this.show(); } updateControls() { this.controls.update( { // Initial props paper: this.pageSetup.paper, layout: this.sheetLayout, mode: this.mode, marks: this.marks, pageSize: this.pageSetup.displaySize, }, { // Actions setMode: this.setMode.bind(this), setPaper: this.setSheetSize.bind(this), setLayout: this.setLayout.bind(this), setMarks: this.setMarks.bind(this), }, ); } setMode(newMode: ViewerMode) { if (newMode === this.mode) return; this.mode = newMode; this.updateControls(); this.render(); } get isInProgress() { return this.element.classList.contains(classes.inProgress); } setInProgress(newVal: boolean) { this.element.classList.toggle(classes.inProgress, newVal); } get isTwoUp() { return this.sheetLayout !== SheetLayout.PAGES; } setShowingCropMarks(newVal: boolean) { this.element.classList.toggle(classes.showCrop, newVal); } setShowingBleedMarks(newVal: boolean) { this.element.classList.toggle(classes.showBleedMarks, newVal); } setShowingBleed(newVal: boolean) { this.element.classList.toggle(classes.showBleed, newVal); } get isViewing() { return window.document.body.classList.contains(classes.isViewing); } set isViewing(newVal) { window.document.body.classList.toggle(classes.isViewing, newVal); } setSheetSize(newVal: SheetSize) { this.pageSetup.paper = newVal; this.pageSetup.updateStyleVars(); this.mode = ViewerMode.PRINT; this.render(); this.scaleToFit(); setTimeout(() => { this.scaleToFit(); }, 300); } setLayout(newVal: SheetLayout) { if (newVal === this.sheetLayout) return; this.sheetLayout = newVal; this.pageSetup.printTwoUp = this.isTwoUp; this.pageSetup.updateStyleVars(); this.mode = ViewerMode.PRINT; this.render(); } setMarks(newVal: SheetMarks) { this.marks = newVal; this.updateControls(); this.setShowingCropMarks( newVal === SheetMarks.CROP || newVal === SheetMarks.BOTH, ); this.setShowingBleedMarks( newVal === SheetMarks.BLEED || newVal === SheetMarks.BOTH, ); } displayError(title: string, text: string) { this.show(); if (!this.error) { this.error = errorView(title, text); this.element.append(this.error); scrollToBottom(); if (this.book) { const flow = this.book.currentPage.flow; if (flow) flow.currentElement.style.outline = '3px solid red'; } } } clear() { this.book = undefined; this.lastSpreadInProgress = undefined; // TODO: Make this clearer, after first render this.content.innerHTML = ''; } show() { if (this.element.parentNode) return; window.document.body.appendChild(this.element); this.isViewing = true; } hide() { // TODO this doesn't work if the target is an existing node this.element.parentNode?.removeChild(this.element); this.isViewing = false; } render(newBook?: Book) { if (newBook) this.book = newBook; if (!this.book) return; this.show(); this.updateControls(); this.element.classList.remove(...allModeClasses); this.element.classList.add(classForMode(this.mode)); this.setShowingBleed(this.mode === ViewerMode.PRINT); const prevScroll = getScrollAsPercent(); this.setProgressAmount(1); window.requestAnimationFrame(() => { const result = this.renderViewMode(); this.currentResult = result; this.content.innerHTML = ''; this.content.append(result.element); if (!this.hasRendered) this.hasRendered = true; else scrollToPercent(prevScroll); this.scaleToFit(); }); } renderViewMode(): RenderedViewer { if (!this.book) throw Error('Book missing'); const pages = this.book.pages.slice(); switch (this.mode) { case ViewerMode.PREVIEW: return renderGridViewer(pages, this.isDoubleSided); case ViewerMode.FLIPBOOK: return renderFlipbookViewer(pages, this.isDoubleSided); case ViewerMode.PRINT: return renderSheetViewer(pages, this.isDoubleSided, this.sheetLayout); default: throw Error(`Invalid layout mode: ${this.mode} (type ${typeof this.mode})`); } } setProgressAmount(newVal: number) { if (newVal < 1) { throttleProgressBar(() => { this.progressBar.style.transform = `scaleX(${newVal})`; }); } else { this.progressBar.style.transform = ''; } } updateProgress(book: Book, estimatedProgress: number) { this.book = book; this.setProgressAmount(estimatedProgress); if (!window.document.scrollingElement) return; const scroller = window.document.scrollingElement as HTMLElement; // don't bother rerendering if preview is out of view const scrollTop = scroller.scrollTop; const scrollH = scroller.scrollHeight; const h = scroller.offsetHeight; if (scrollH > h * 3 && scrollTop < h) return; // don't rerender too often throttleRender(() => this.renderProgress(book, estimatedProgress)); } renderProgress(book: Book, estimatedProgress: number) { const needsZoomUpdate = !this.content.firstElementChild; const sideBySide = this.mode === ViewerMode.PREVIEW || (this.mode === ViewerMode.PRINT && this.sheetLayout !== SheetLayout.PAGES); const limit = sideBySide ? 2 : 1; book.pages.forEach((page: Page, i: number) => { if ( this.content.contains(page.element) && page.element.parentNode !== this.content ) return; if ( this.lastSpreadInProgress && this.lastSpreadInProgress.children.length < limit ) { this.lastSpreadInProgress.append(page.element); return; } this.lastSpreadInProgress = pageSpread(page.element); if (i === 0 && sideBySide) { const spacer = new Page(); spacer.element.style.visibility = 'hidden'; this.lastSpreadInProgress.insertBefore( spacer.element, this.lastSpreadInProgress.firstElementChild, ); } this.content.append(this.lastSpreadInProgress); }); if (needsZoomUpdate) this.scaleToFit(); } scaleToFit() { if (!this.content.firstElementChild) return; const prevScroll = getScrollAsPercent(); const { xScale, yScale } = this.scaleThatFits(); const scale = this.mode === ViewerMode.FLIPBOOK ? Math.min(1, xScale, yScale) : Math.min(1, xScale); this.scaler.style.transform = `scale(${scale})`; scrollToPercent(prevScroll); } scaleThatFits(): { xScale: number, yScale: number } { const contentEl = this.currentResult?.contentSizer ?? this.content; const availableSize = { width: window.innerWidth, height: window.innerHeight - 40, // toolbar }; // Note use of offsetWidth rather than getBoundingClientRect // so we can calculate using untransformed/unscaled dimensions const contentSize = { width: contentEl.offsetWidth, height: contentEl.offsetHeight, } const xScale = availableSize.width / contentSize.width; const yScale = availableSize.height / contentSize.height; return { xScale, yScale }; } } export default Viewer;
the_stack
import { PresentArray } from '@glimmer/interfaces'; import { assert, assign, isPresent } from '@glimmer/util'; import Printer from '../generation/printer'; import { PrecompileOptions, preprocess } from '../parser/tokenizer-event-handlers'; import { SourceLocation } from '../source/location'; import { SourceSlice } from '../source/slice'; import { Source } from '../source/source'; import { SourceSpan } from '../source/span'; import { SpanList } from '../source/span-list'; import { BlockSymbolTable, ProgramSymbolTable, SymbolTable } from '../symbol-table'; import { generateSyntaxError } from '../syntax-error'; import { isLowerCase, isUpperCase } from '../utils'; import * as ASTv1 from '../v1/api'; import b from '../v1/parser-builders'; import * as ASTv2 from './api'; import { BuildElement, Builder, CallParts } from './builders'; import { AppendSyntaxContext, AttrValueSyntaxContext, BlockSyntaxContext, ComponentSyntaxContext, ModifierSyntaxContext, Resolution, SexpSyntaxContext, } from './loose-resolution'; export function normalize( source: Source, options: PrecompileOptions = {} ): [ast: ASTv2.Template, locals: string[]] { let ast = preprocess(source, options); let normalizeOptions = assign( { strictMode: false, locals: [], }, options ); let top = SymbolTable.top( normalizeOptions.locals, // eslint-disable-next-line @typescript-eslint/unbound-method options.customizeComponentName ?? ((name) => name) ); let block = new BlockContext(source, normalizeOptions, top); let normalizer = new StatementNormalizer(block); let astV2 = new TemplateChildren( block.loc(ast.loc), ast.body.map((b) => normalizer.normalize(b)), block ).assertTemplate(top); let locals = top.getUsedTemplateLocals(); return [astV2, locals]; } /** * A `BlockContext` represents the block that a particular AST node is contained inside of. * * `BlockContext` is aware of template-wide options (such as strict mode), as well as the bindings * that are in-scope within that block. * * Concretely, it has the `PrecompileOptions` and current `SymbolTable`, and provides * facilities for working with those options. * * `BlockContext` is stateless. */ export class BlockContext<Table extends SymbolTable = SymbolTable> { readonly builder: Builder; constructor( readonly source: Source, private readonly options: PrecompileOptions, readonly table: Table ) { this.builder = new Builder(); } get strict(): boolean { return this.options.strictMode || false; } loc(loc: SourceLocation): SourceSpan { return this.source.spanFor(loc); } resolutionFor<N extends ASTv1.CallNode | ASTv1.PathExpression>( node: N, resolution: Resolution<N> ): { resolution: ASTv2.FreeVarResolution } | { resolution: 'error'; path: string; head: string } { if (this.strict) { return { resolution: ASTv2.STRICT_RESOLUTION }; } if (this.isFreeVar(node)) { let r = resolution(node); if (r === null) { return { resolution: 'error', path: printPath(node), head: printHead(node), }; } return { resolution: r }; } else { return { resolution: ASTv2.STRICT_RESOLUTION }; } } private isFreeVar(callee: ASTv1.CallNode | ASTv1.PathExpression): boolean { if (callee.type === 'PathExpression') { if (callee.head.type !== 'VarHead') { return false; } return !this.table.has(callee.head.name); } else if (callee.path.type === 'PathExpression') { return this.isFreeVar(callee.path); } else { return false; } } hasBinding(name: string): boolean { return this.table.has(name); } child(blockParams: string[]): BlockContext<BlockSymbolTable> { return new BlockContext(this.source, this.options, this.table.child(blockParams)); } customizeComponentName(input: string): string { if (this.options.customizeComponentName) { return this.options.customizeComponentName(input); } else { return input; } } } /** * An `ExpressionNormalizer` normalizes expressions within a block. * * `ExpressionNormalizer` is stateless. */ class ExpressionNormalizer { constructor(private block: BlockContext) {} /** * The `normalize` method takes an arbitrary expression and its original syntax context and * normalizes it to an ASTv2 expression. * * @see {SyntaxContext} */ normalize(expr: ASTv1.Literal, resolution: ASTv2.FreeVarResolution): ASTv2.LiteralExpression; normalize( expr: ASTv1.MinimalPathExpression, resolution: ASTv2.FreeVarResolution ): ASTv2.PathExpression; normalize(expr: ASTv1.SubExpression, resolution: ASTv2.FreeVarResolution): ASTv2.CallExpression; normalize(expr: ASTv1.Expression, resolution: ASTv2.FreeVarResolution): ASTv2.ExpressionNode; normalize( expr: ASTv1.Expression | ASTv1.MinimalPathExpression, resolution: ASTv2.FreeVarResolution ): ASTv2.ExpressionNode { switch (expr.type) { case 'NullLiteral': case 'BooleanLiteral': case 'NumberLiteral': case 'StringLiteral': case 'UndefinedLiteral': return this.block.builder.literal(expr.value, this.block.loc(expr.loc)); case 'PathExpression': return this.path(expr, resolution); case 'SubExpression': { let resolution = this.block.resolutionFor(expr, SexpSyntaxContext); if (resolution.resolution === 'error') { throw generateSyntaxError( `You attempted to invoke a path (\`${resolution.path}\`) but ${resolution.head} was not in scope`, expr.loc ); } return this.block.builder.sexp( this.callParts(expr, resolution.resolution), this.block.loc(expr.loc) ); } } } private path( expr: ASTv1.MinimalPathExpression, resolution: ASTv2.FreeVarResolution ): ASTv2.PathExpression { let headOffsets = this.block.loc(expr.head.loc); let tail = []; // start with the head let offset = headOffsets; for (let part of expr.tail) { offset = offset.sliceStartChars({ chars: part.length, skipStart: 1 }); tail.push( new SourceSlice({ loc: offset, chars: part, }) ); } return this.block.builder.path(this.ref(expr.head, resolution), tail, this.block.loc(expr.loc)); } /** * The `callParts` method takes ASTv1.CallParts as well as a syntax context and normalizes * it to an ASTv2 CallParts. */ callParts(parts: ASTv1.CallParts, context: ASTv2.FreeVarResolution): CallParts { let { path, params, hash } = parts; let callee = this.normalize(path, context); let paramList = params.map((p) => this.normalize(p, ASTv2.ARGUMENT_RESOLUTION)); let paramLoc = SpanList.range(paramList, callee.loc.collapse('end')); let namedLoc = this.block.loc(hash.loc); let argsLoc = SpanList.range([paramLoc, namedLoc]); let positional = this.block.builder.positional( params.map((p) => this.normalize(p, ASTv2.ARGUMENT_RESOLUTION)), paramLoc ); let named = this.block.builder.named( hash.pairs.map((p) => this.namedArgument(p)), this.block.loc(hash.loc) ); return { callee, args: this.block.builder.args(positional, named, argsLoc), }; } private namedArgument(pair: ASTv1.HashPair): ASTv2.NamedArgument { let offsets = this.block.loc(pair.loc); let keyOffsets = offsets.sliceStartChars({ chars: pair.key.length }); return this.block.builder.namedArgument( new SourceSlice({ chars: pair.key, loc: keyOffsets }), this.normalize(pair.value, ASTv2.ARGUMENT_RESOLUTION) ); } /** * The `ref` method normalizes an `ASTv1.PathHead` into an `ASTv2.VariableReference`. * This method is extremely important, because it is responsible for normalizing free * variables into an an ASTv2.PathHead *with appropriate context*. * * The syntax context is originally determined by the syntactic position that this `PathHead` * came from, and is ultimately attached to the `ASTv2.VariableReference` here. In ASTv2, * the `VariableReference` node bears full responsibility for loose mode rules that control * the behavior of free variables. */ private ref(head: ASTv1.PathHead, resolution: ASTv2.FreeVarResolution): ASTv2.VariableReference { let { block } = this; let { builder, table } = block; let offsets = block.loc(head.loc); switch (head.type) { case 'ThisHead': return builder.self(offsets); case 'AtHead': { let symbol = table.allocateNamed(head.name); return builder.at(head.name, symbol, offsets); } case 'VarHead': { if (block.hasBinding(head.name)) { let [symbol, isRoot] = table.get(head.name); return block.builder.localVar(head.name, symbol, isRoot, offsets); } else { let context = block.strict ? ASTv2.STRICT_RESOLUTION : resolution; let symbol = block.table.allocateFree(head.name, context); return block.builder.freeVar({ name: head.name, context, symbol, loc: offsets, }); } } } } } /** * `TemplateNormalizer` normalizes top-level ASTv1 statements to ASTv2. */ class StatementNormalizer { constructor(private readonly block: BlockContext) {} normalize(node: ASTv1.Statement): ASTv2.ContentNode | ASTv2.NamedBlock { switch (node.type) { case 'PartialStatement': throw new Error(`Handlebars partial syntax ({{> ...}}) is not allowed in Glimmer`); case 'BlockStatement': return this.BlockStatement(node); case 'ElementNode': return new ElementNormalizer(this.block).ElementNode(node); case 'MustacheStatement': return this.MustacheStatement(node); // These are the same in ASTv2 case 'MustacheCommentStatement': return this.MustacheCommentStatement(node); case 'CommentStatement': { let loc = this.block.loc(node.loc); return new ASTv2.HtmlComment({ loc, text: loc.slice({ skipStart: 4, skipEnd: 3 }).toSlice(node.value), }); } case 'TextNode': return new ASTv2.HtmlText({ loc: this.block.loc(node.loc), chars: node.chars, }); } } MustacheCommentStatement(node: ASTv1.MustacheCommentStatement): ASTv2.GlimmerComment { let loc = this.block.loc(node.loc); let textLoc: SourceSpan; if (loc.asString().slice(0, 5) === '{{!--') { textLoc = loc.slice({ skipStart: 5, skipEnd: 4 }); } else { textLoc = loc.slice({ skipStart: 3, skipEnd: 2 }); } return new ASTv2.GlimmerComment({ loc, text: textLoc.toSlice(node.value), }); } /** * Normalizes an ASTv1.MustacheStatement to an ASTv2.AppendStatement */ MustacheStatement(mustache: ASTv1.MustacheStatement): ASTv2.AppendContent { let { escaped } = mustache; let loc = this.block.loc(mustache.loc); // Normalize the call parts in AppendSyntaxContext let callParts = this.expr.callParts( { path: mustache.path, params: mustache.params, hash: mustache.hash, }, AppendSyntaxContext(mustache) ); let value = callParts.args.isEmpty() ? callParts.callee : this.block.builder.sexp(callParts, loc); return this.block.builder.append( { table: this.block.table, trusting: !escaped, value, }, loc ); } /** * Normalizes a ASTv1.BlockStatement to an ASTv2.BlockStatement */ BlockStatement(block: ASTv1.BlockStatement): ASTv2.InvokeBlock { let { program, inverse } = block; let loc = this.block.loc(block.loc); let resolution = this.block.resolutionFor(block, BlockSyntaxContext); if (resolution.resolution === 'error') { throw generateSyntaxError( `You attempted to invoke a path (\`{{#${resolution.path}}}\`) but ${resolution.head} was not in scope`, loc ); } let callParts = this.expr.callParts(block, resolution.resolution); return this.block.builder.blockStatement( assign( { symbols: this.block.table, program: this.Block(program), inverse: inverse ? this.Block(inverse) : null, }, callParts ), loc ); } Block({ body, loc, blockParams }: ASTv1.Block): ASTv2.Block { let child = this.block.child(blockParams); let normalizer = new StatementNormalizer(child); return new BlockChildren( this.block.loc(loc), body.map((b) => normalizer.normalize(b)), this.block ).assertBlock(child.table); } private get expr(): ExpressionNormalizer { return new ExpressionNormalizer(this.block); } } class ElementNormalizer { constructor(private readonly ctx: BlockContext) {} /** * Normalizes an ASTv1.ElementNode to: * * - ASTv2.NamedBlock if the tag name begins with `:` * - ASTv2.Component if the tag name matches the component heuristics * - ASTv2.SimpleElement if the tag name doesn't match the component heuristics * * A tag name represents a component if: * * - it begins with `@` * - it is exactly `this` or begins with `this.` * - the part before the first `.` is a reference to an in-scope variable binding * - it begins with an uppercase character */ ElementNode(element: ASTv1.ElementNode): ASTv2.ElementNode { let { tag, selfClosing, comments } = element; let loc = this.ctx.loc(element.loc); let [tagHead, ...rest] = tag.split('.'); // the head, attributes and modifiers are in the current scope let path = this.classifyTag(tagHead, rest, element.loc); let attrs = element.attributes.filter((a) => a.name[0] !== '@').map((a) => this.attr(a)); let args = element.attributes.filter((a) => a.name[0] === '@').map((a) => this.arg(a)); let modifiers = element.modifiers.map((m) => this.modifier(m)); // the element's block params are in scope for the children let child = this.ctx.child(element.blockParams); let normalizer = new StatementNormalizer(child); let childNodes = element.children.map((s) => normalizer.normalize(s)); let el = this.ctx.builder.element({ selfClosing, attrs, componentArgs: args, modifiers, comments: comments.map((c) => new StatementNormalizer(this.ctx).MustacheCommentStatement(c)), }); let children = new ElementChildren(el, loc, childNodes, this.ctx); let offsets = this.ctx.loc(element.loc); let tagOffsets = offsets.sliceStartChars({ chars: tag.length, skipStart: 1 }); if (path === 'ElementHead') { if (tag[0] === ':') { return children.assertNamedBlock( tagOffsets.slice({ skipStart: 1 }).toSlice(tag.slice(1)), child.table ); } else { return children.assertElement(tagOffsets.toSlice(tag), element.blockParams.length > 0); } } if (element.selfClosing) { return el.selfClosingComponent(path, loc); } else { let blocks = children.assertComponent(tag, child.table, element.blockParams.length > 0); return el.componentWithNamedBlocks(path, blocks, loc); } } private modifier(m: ASTv1.ElementModifierStatement): ASTv2.ElementModifier { let resolution = this.ctx.resolutionFor(m, ModifierSyntaxContext); if (resolution.resolution === 'error') { throw generateSyntaxError( `You attempted to invoke a path (\`{{#${resolution.path}}}\`) as a modifier, but ${resolution.head} was not in scope. Try adding \`this\` to the beginning of the path`, m.loc ); } let callParts = this.expr.callParts(m, resolution.resolution); return this.ctx.builder.modifier(callParts, this.ctx.loc(m.loc)); } /** * This method handles attribute values that are curlies, as well as curlies nested inside of * interpolations: * * ```hbs * <a href={{url}} /> * <a href="{{url}}.html" /> * ``` */ private mustacheAttr(mustache: ASTv1.MustacheStatement): ASTv2.ExpressionNode { // Normalize the call parts in AttrValueSyntaxContext let sexp = this.ctx.builder.sexp( this.expr.callParts(mustache, AttrValueSyntaxContext(mustache)), this.ctx.loc(mustache.loc) ); // If there are no params or hash, just return the function part as its own expression if (sexp.args.isEmpty()) { return sexp.callee; } else { return sexp; } } /** * attrPart is the narrowed down list of valid attribute values that are also * allowed as a concat part (you can't nest concats). */ private attrPart( part: ASTv1.MustacheStatement | ASTv1.TextNode ): { expr: ASTv2.ExpressionNode; trusting: boolean } { switch (part.type) { case 'MustacheStatement': return { expr: this.mustacheAttr(part), trusting: !part.escaped }; case 'TextNode': return { expr: this.ctx.builder.literal(part.chars, this.ctx.loc(part.loc)), trusting: true, }; } } private attrValue( part: ASTv1.MustacheStatement | ASTv1.TextNode | ASTv1.ConcatStatement ): { expr: ASTv2.ExpressionNode; trusting: boolean } { switch (part.type) { case 'ConcatStatement': { let parts = part.parts.map((p) => this.attrPart(p).expr); return { expr: this.ctx.builder.interpolate(parts, this.ctx.loc(part.loc)), trusting: false, }; } default: return this.attrPart(part); } } private attr(m: ASTv1.AttrNode): ASTv2.HtmlOrSplatAttr { assert(m.name[0] !== '@', 'An attr name must not start with `@`'); if (m.name === '...attributes') { return this.ctx.builder.splatAttr(this.ctx.table.allocateBlock('attrs'), this.ctx.loc(m.loc)); } let offsets = this.ctx.loc(m.loc); let nameSlice = offsets.sliceStartChars({ chars: m.name.length }).toSlice(m.name); let value = this.attrValue(m.value); return this.ctx.builder.attr( { name: nameSlice, value: value.expr, trusting: value.trusting }, offsets ); } private maybeDeprecatedCall( arg: SourceSlice, part: ASTv1.MustacheStatement | ASTv1.TextNode | ASTv1.ConcatStatement ): { expr: ASTv2.DeprecatedCallExpression; trusting: boolean } | null { if (this.ctx.strict) { return null; } if (part.type !== 'MustacheStatement') { return null; } let { path } = part; if (path.type !== 'PathExpression') { return null; } if (path.head.type !== 'VarHead') { return null; } let { name } = path.head; if (name === 'has-block' || name === 'has-block-params') { return null; } if (this.ctx.hasBinding(name)) { return null; } if (path.tail.length !== 0) { return null; } if (part.params.length !== 0 || part.hash.pairs.length !== 0) { return null; } let context = ASTv2.LooseModeResolution.attr(); let callee = this.ctx.builder.freeVar({ name, context, symbol: this.ctx.table.allocateFree(name, context), loc: path.loc, }); return { expr: this.ctx.builder.deprecatedCall(arg, callee, part.loc), trusting: false, }; } private arg(arg: ASTv1.AttrNode): ASTv2.ComponentArg { assert(arg.name[0] === '@', 'An arg name must start with `@`'); let offsets = this.ctx.loc(arg.loc); let nameSlice = offsets.sliceStartChars({ chars: arg.name.length }).toSlice(arg.name); let value = this.maybeDeprecatedCall(nameSlice, arg.value) || this.attrValue(arg.value); return this.ctx.builder.arg( { name: nameSlice, value: value.expr, trusting: value.trusting }, offsets ); } /** * This function classifies the head of an ASTv1.Element into an ASTv2.PathHead (if the * element is a component) or `'ElementHead'` (if the element is a simple element). * * Rules: * * 1. If the variable is an `@arg`, return an `AtHead` * 2. If the variable is `this`, return a `ThisHead` * 3. If the variable is in the current scope: * a. If the scope is the root scope, then return a Free `LocalVarHead` * b. Else, return a standard `LocalVarHead` * 4. If the tag name is a path and the variable is not in the current scope, Syntax Error * 5. If the variable is uppercase return a FreeVar(ResolveAsComponentHead) * 6. Otherwise, return `'ElementHead'` */ private classifyTag( variable: string, tail: string[], loc: SourceSpan ): ASTv2.ExpressionNode | 'ElementHead' { let uppercase = isUpperCase(variable); let inScope = variable[0] === '@' || variable === 'this' || this.ctx.hasBinding(variable); if (this.ctx.strict && !inScope) { if (uppercase) { throw generateSyntaxError( `Attempted to invoke a component that was not in scope in a strict mode template, \`<${variable}>\`. If you wanted to create an element with that name, convert it to lowercase - \`<${variable.toLowerCase()}>\``, loc ); } // In strict mode, values are always elements unless they are in scope return 'ElementHead'; } // Since the parser handed us the HTML element name as a string, we need // to convert it into an ASTv1 path so it can be processed using the // expression normalizer. let isComponent = inScope || uppercase; let variableLoc = loc.sliceStartChars({ skipStart: 1, chars: variable.length }); let tailLength = tail.reduce((accum, part) => accum + 1 + part.length, 0); let pathEnd = variableLoc.getEnd().move(tailLength); let pathLoc = variableLoc.withEnd(pathEnd); if (isComponent) { let path = b.path({ head: b.head(variable, variableLoc), tail, loc: pathLoc, }); let resolution = this.ctx.resolutionFor(path, ComponentSyntaxContext); if (resolution.resolution === 'error') { throw generateSyntaxError( `You attempted to invoke a path (\`<${resolution.path}>\`) but ${resolution.head} was not in scope`, loc ); } return new ExpressionNormalizer(this.ctx).normalize(path, resolution.resolution); } // If the tag name wasn't a valid component but contained a `.`, it's // a syntax error. if (tail.length > 0) { throw generateSyntaxError( `You used ${variable}.${tail.join('.')} as a tag name, but ${variable} is not in scope`, loc ); } return 'ElementHead'; } private get expr(): ExpressionNormalizer { return new ExpressionNormalizer(this.ctx); } } class Children { readonly namedBlocks: ASTv2.NamedBlock[]; readonly hasSemanticContent: boolean; readonly nonBlockChildren: ASTv2.ContentNode[]; constructor( readonly loc: SourceSpan, readonly children: (ASTv2.ContentNode | ASTv2.NamedBlock)[], readonly block: BlockContext ) { this.namedBlocks = children.filter((c): c is ASTv2.NamedBlock => c instanceof ASTv2.NamedBlock); this.hasSemanticContent = Boolean( children.filter((c): c is ASTv2.ContentNode => { if (c instanceof ASTv2.NamedBlock) { return false; } switch (c.type) { case 'GlimmerComment': case 'HtmlComment': return false; case 'HtmlText': return !/^\s*$/.exec(c.chars); default: return true; } }).length ); this.nonBlockChildren = children.filter( (c): c is ASTv2.ContentNode => !(c instanceof ASTv2.NamedBlock) ); } } class TemplateChildren extends Children { assertTemplate(table: ProgramSymbolTable): ASTv2.Template { if (isPresent(this.namedBlocks)) { throw generateSyntaxError(`Unexpected named block at the top-level of a template`, this.loc); } return this.block.builder.template(table, this.nonBlockChildren, this.block.loc(this.loc)); } } class BlockChildren extends Children { assertBlock(table: BlockSymbolTable): ASTv2.Block { if (isPresent(this.namedBlocks)) { throw generateSyntaxError(`Unexpected named block nested in a normal block`, this.loc); } return this.block.builder.block(table, this.nonBlockChildren, this.loc); } } class ElementChildren extends Children { constructor( private el: BuildElement, loc: SourceSpan, children: (ASTv2.ContentNode | ASTv2.NamedBlock)[], block: BlockContext ) { super(loc, children, block); } assertNamedBlock(name: SourceSlice, table: BlockSymbolTable): ASTv2.NamedBlock { if (this.el.base.selfClosing) { throw generateSyntaxError( `<:${name.chars}/> is not a valid named block: named blocks cannot be self-closing`, this.loc ); } if (isPresent(this.namedBlocks)) { throw generateSyntaxError( `Unexpected named block inside <:${name.chars}> named block: named blocks cannot contain nested named blocks`, this.loc ); } if (!isLowerCase(name.chars)) { throw generateSyntaxError( `<:${name.chars}> is not a valid named block, and named blocks must begin with a lowercase letter`, this.loc ); } if ( this.el.base.attrs.length > 0 || this.el.base.componentArgs.length > 0 || this.el.base.modifiers.length > 0 ) { throw generateSyntaxError( `named block <:${name.chars}> cannot have attributes, arguments, or modifiers`, this.loc ); } let offsets = SpanList.range(this.nonBlockChildren, this.loc); return this.block.builder.namedBlock( name, this.block.builder.block(table, this.nonBlockChildren, offsets), this.loc ); } assertElement(name: SourceSlice, hasBlockParams: boolean): ASTv2.SimpleElement { if (hasBlockParams) { throw generateSyntaxError( `Unexpected block params in <${name}>: simple elements cannot have block params`, this.loc ); } if (isPresent(this.namedBlocks)) { let names = this.namedBlocks.map((b) => b.name); if (names.length === 1) { throw generateSyntaxError( `Unexpected named block <:foo> inside <${name.chars}> HTML element`, this.loc ); } else { let printedNames = names.map((n) => `<:${n.chars}>`).join(', '); throw generateSyntaxError( `Unexpected named blocks inside <${name.chars}> HTML element (${printedNames})`, this.loc ); } } return this.el.simple(name, this.nonBlockChildren, this.loc); } assertComponent( name: string, table: BlockSymbolTable, hasBlockParams: boolean ): PresentArray<ASTv2.NamedBlock> { if (isPresent(this.namedBlocks) && this.hasSemanticContent) { throw generateSyntaxError( `Unexpected content inside <${name}> component invocation: when using named blocks, the tag cannot contain other content`, this.loc ); } if (isPresent(this.namedBlocks)) { if (hasBlockParams) { throw generateSyntaxError( `Unexpected block params list on <${name}> component invocation: when passing named blocks, the invocation tag cannot take block params`, this.loc ); } let seenNames = new Set<string>(); for (let block of this.namedBlocks) { let name = block.name.chars; if (seenNames.has(name)) { throw generateSyntaxError( `Component had two named blocks with the same name, \`<:${name}>\`. Only one block with a given name may be passed`, this.loc ); } if ( (name === 'inverse' && seenNames.has('else')) || (name === 'else' && seenNames.has('inverse')) ) { throw generateSyntaxError( `Component has both <:else> and <:inverse> block. <:inverse> is an alias for <:else>`, this.loc ); } seenNames.add(name); } return this.namedBlocks; } else { return [ this.block.builder.namedBlock( SourceSlice.synthetic('default'), this.block.builder.block(table, this.nonBlockChildren, this.loc), this.loc ), ]; } } } function printPath(node: ASTv1.PathExpression | ASTv1.CallNode): string { if (node.type !== 'PathExpression' && node.path.type === 'PathExpression') { return printPath(node.path); } else { return new Printer({ entityEncoding: 'raw' }).print(node); } } function printHead(node: ASTv1.PathExpression | ASTv1.CallNode): string { if (node.type === 'PathExpression') { switch (node.head.type) { case 'AtHead': case 'VarHead': return node.head.name; case 'ThisHead': return 'this'; } } else if (node.path.type === 'PathExpression') { return printHead(node.path); } else { return new Printer({ entityEncoding: 'raw' }).print(node); } }
the_stack
import { assertEquals, assertThrowsAsync, deferred } from "./test_deps.ts"; import { getClearConfiguration, getMainConfiguration, getMd5Configuration, getScramConfiguration, getTlsOnlyConfiguration, } from "./config.ts"; import { Client, ConnectionError, PostgresError } from "../mod.ts"; function getRandomString() { return Math.random().toString(36).substring(7); } Deno.test("Clear password authentication (unencrypted)", async () => { const client = new Client(getClearConfiguration(false)); await client.connect(); try { assertEquals(client.session.tls, false); } finally { await client.end(); } }); Deno.test("Clear password authentication (tls)", async () => { const client = new Client(getClearConfiguration(true)); await client.connect(); try { assertEquals(client.session.tls, true); } finally { await client.end(); } }); Deno.test("MD5 authentication (unencrypted)", async () => { const client = new Client(getMd5Configuration(false)); await client.connect(); try { assertEquals(client.session.tls, false); } finally { await client.end(); } }); Deno.test("MD5 authentication (tls)", async () => { const client = new Client(getMd5Configuration(true)); await client.connect(); try { assertEquals(client.session.tls, true); } finally { await client.end(); } }); Deno.test("SCRAM-SHA-256 authentication (unencrypted)", async () => { const client = new Client(getScramConfiguration(false)); await client.connect(); try { assertEquals(client.session.tls, false); } finally { await client.end(); } }); Deno.test("SCRAM-SHA-256 authentication (tls)", async () => { const client = new Client(getScramConfiguration(true)); await client.connect(); try { assertEquals(client.session.tls, true); } finally { await client.end(); } }); Deno.test("Skips TLS connection when TLS disabled", async () => { const client = new Client({ ...getTlsOnlyConfiguration(), tls: { enabled: false }, }); // Connection will fail due to TLS only user try { await assertThrowsAsync( () => client.connect(), PostgresError, "no pg_hba.conf", ); } finally { try { assertEquals(client.session.tls, undefined); } finally { await client.end(); } } }); Deno.test("Aborts TLS connection when certificate is untrusted", async () => { // Force TLS but don't provide CA const client = new Client({ ...getTlsOnlyConfiguration(), tls: { enabled: true, enforce: true, }, }); try { await assertThrowsAsync( async (): Promise<void> => { await client.connect(); }, Error, "The certificate used to secure the TLS connection is invalid", ); } finally { try { assertEquals(client.session.tls, undefined); } finally { await client.end(); } } }); Deno.test("Defaults to unencrypted when certificate is invalid and TLS is not enforced", async () => { // Remove CA, request tls and disable enforce const client = new Client({ ...getMainConfiguration(), tls: { enabled: true, enforce: false }, }); await client.connect(); // Connection will fail due to TLS only user try { assertEquals(client.session.tls, false); } finally { await client.end(); } }); Deno.test("Handles bad authentication correctly", async function () { const badConnectionData = getMainConfiguration(); badConnectionData.password += getRandomString(); const client = new Client(badConnectionData); try { await assertThrowsAsync( async (): Promise<void> => { await client.connect(); }, PostgresError, "password authentication failed for user", ); } finally { await client.end(); } }); // This test requires current user database connection permissions // on "pg_hba.conf" set to "all" Deno.test("Startup error when database does not exist", async function () { const badConnectionData = getMainConfiguration(); badConnectionData.database += getRandomString(); const client = new Client(badConnectionData); try { await assertThrowsAsync( async (): Promise<void> => { await client.connect(); }, PostgresError, "does not exist", ); } finally { await client.end(); } }); Deno.test("Exposes session PID", async () => { const client = new Client(getMainConfiguration()); await client.connect(); try { const { rows } = await client.queryObject<{ pid: string }>( "SELECT PG_BACKEND_PID() AS PID", ); assertEquals(client.session.pid, rows[0].pid); } finally { await client.end(); assertEquals( client.session.pid, undefined, "PID was not cleared after disconnection", ); } }); Deno.test("Exposes session encryption", async () => { const client = new Client(getMainConfiguration()); await client.connect(); try { assertEquals(client.session.tls, true); } finally { await client.end(); assertEquals( client.session.tls, undefined, "TLS was not cleared after disconnection", ); } }); Deno.test("Closes connection on bad TLS availability verification", async function () { const server = new Worker( new URL("./workers/postgres_server.ts", import.meta.url).href, { type: "module", deno: { namespace: true, }, }, ); // Await for server initialization const initialized = deferred(); server.onmessage = ({ data }) => { if (data !== "initialized") { initialized.reject(`Unexpected message "${data}" received from worker`); } initialized.resolve(); }; server.postMessage("initialize"); await initialized; const client = new Client({ database: "none", hostname: "127.0.0.1", port: "8080", user: "none", }); // The server will try to emit a message everytime it receives a connection // For this test we don't need them, so we just discard them server.onmessage = () => {}; let bad_tls_availability_message = false; try { await client.connect(); } catch (e) { if ( e instanceof Error || e.message.startsWith("Could not check if server accepts SSL connections") ) { bad_tls_availability_message = true; } else { // Early fail, if the connection fails for an unexpected error server.terminate(); throw e; } } finally { await client.end(); } const closed = deferred(); server.onmessage = ({ data }) => { if (data !== "closed") { closed.reject( `Unexpected message "${data}" received from worker`, ); } closed.resolve(); }; server.postMessage("close"); await closed; server.terminate(); assertEquals(bad_tls_availability_message, true); }); async function mockReconnection(attempts: number) { const server = new Worker( new URL("./workers/postgres_server.ts", import.meta.url).href, { type: "module", deno: { namespace: true, }, }, ); // Await for server initialization const initialized = deferred(); server.onmessage = ({ data }) => { if (data !== "initialized") { initialized.reject(`Unexpected message "${data}" received from worker`); } initialized.resolve(); }; server.postMessage("initialize"); await initialized; const client = new Client({ connection: { attempts, }, database: "none", hostname: "127.0.0.1", port: "8080", user: "none", }); let connection_attempts = 0; server.onmessage = ({ data }) => { if (data !== "connection") { closed.reject( `Unexpected message "${data}" received from worker`, ); } connection_attempts++; }; try { await client.connect(); } catch (e) { if ( !(e instanceof Error) || !e.message.startsWith("Could not check if server accepts SSL connections") ) { // Early fail, if the connection fails for an unexpected error server.terminate(); throw e; } } finally { await client.end(); } const closed = deferred(); server.onmessage = ({ data }) => { if (data !== "closed") { closed.reject( `Unexpected message "${data}" received from worker`, ); } closed.resolve(); }; server.postMessage("close"); await closed; server.terminate(); // If reconnections are set to zero, it will attempt to connect at least once, but won't // attempt to reconnect assertEquals( connection_attempts, attempts === 0 ? 1 : attempts, `Attempted "${connection_attempts}" reconnections, "${attempts}" expected`, ); } Deno.test("Attempts reconnection on connection startup", async function () { await mockReconnection(5); await mockReconnection(0); }); // This test ensures a failed query that is disconnected after execution but before // status report is only executed one (regression test) Deno.test("Attempts reconnection on disconnection", async function () { const client = new Client({ ...getMainConfiguration(), connection: { attempts: 1, }, }); await client.connect(); try { const test_table = "TEST_DENO_RECONNECTION_1"; const test_value = 1; await client.queryArray(`DROP TABLE IF EXISTS ${test_table}`); await client.queryArray(`CREATE TABLE ${test_table} (X INT)`); await assertThrowsAsync( () => client.queryArray( `INSERT INTO ${test_table} VALUES (${test_value}); COMMIT; SELECT PG_TERMINATE_BACKEND(${client.session.pid})`, ), ConnectionError, "The session was terminated by the database", ); assertEquals(client.connected, false); const { rows: result_1 } = await client.queryObject<{ pid: string }>({ text: "SELECT PG_BACKEND_PID() AS PID", fields: ["pid"], }); assertEquals( client.session.pid, result_1[0].pid, "The PID is not reseted after reconnection", ); const { rows: result_2 } = await client.queryObject<{ x: number }>({ text: `SELECT X FROM ${test_table}`, fields: ["x"], }); assertEquals( result_2.length, 1, ); assertEquals( result_2[0].x, test_value, ); } finally { await client.end(); } }); Deno.test("Doesn't attempt reconnection when attempts are set to zero", async function () { const client = new Client({ ...getMainConfiguration(), connection: { attempts: 0 }, }); await client.connect(); try { await assertThrowsAsync(() => client.queryArray`SELECT PG_TERMINATE_BACKEND(${client.session.pid})` ); assertEquals(client.connected, false); await assertThrowsAsync( () => client.queryArray`SELECT 1`, Error, "The client has been disconnected from the database", ); } finally { // End the connection in case the previous assertions failed await client.end(); } });
the_stack
import {assert} from 'chai'; import * as path from 'path'; import stripIndent = require('strip-indent'); import {jsTransform} from '../js-transform'; import {interceptOutput} from './util'; suite('jsTransform', () => { const rootDir = path.join(__dirname, '..', '..', 'test-fixtures', 'npm-modules'); const filePath = path.join(rootDir, 'foo.js'); suite('compilation', () => { test('compiles to ES5 when compile=true', () => { assert.equal( jsTransform('const foo = 3;', {compile: true}), 'var foo = 3;'); }); test('compiles to ES5 when compile=es5', () => { assert.equal( jsTransform('const foo = 3;', {compile: 'es5'}), 'var foo = 3;'); }); test('compiles to ES2015 when compile=es2015', () => { assert.equal( jsTransform('2 ** 5;', {compile: 'es2015'}), 'Math.pow(2, 5);'); }); test('compiles ES2017 to ES5', async () => { const result = jsTransform('async function test() { await 0; }', {compile: 'es5'}); assert.include(result, '_asyncToGenerator'); assert.notInclude(result, 'async function test'); assert.include(result, 'regeneratorRuntime'); }); test('compiles ES2017 to ES2015', async () => { const result = jsTransform( 'async function test() { await 0; }', {compile: 'es2015'}); assert.include(result, 'asyncToGenerator'); assert.notInclude(result, 'async function test'); assert.notInclude(result, 'regeneratorRuntime'); }); test('does not unnecessarily reformat', () => { // Even with no transform plugins, parsing and serializing with Babel will // make some minor formatting changes to the code, such as removing // trailing newlines. Check that we don't do this when no transformations // were configured. assert.equal(jsTransform('const foo = 3;\n', {}), 'const foo = 3;\n'); }); }); suite('minification', () => { test('minifies a simple expression', () => { assert.equal( jsTransform('const foo = 3;', {minify: true}), 'const foo=3;'); }); test('minifies an exported const', () => { assert.equal( jsTransform('const foo = "foo"; export { foo };', {minify: true}), 'const foo="foo";export{foo};'); }); test('minifies and compiles', () => { assert.equal( jsTransform('const foo = 3;', {compile: true, minify: true}), 'var foo=3;'); }); test('minifies but does not try to remove dead code', () => { assert.equal( jsTransform('if (false) { never(); } always();', {minify: true}), 'if(!1){never()}always();'); }); }); suite('babel helpers', () => { const classJs = `class MyClass {}`; const helperSnippet = `function _classCallCheck(`; test('inlined when external helpers are disabled', () => { const result = jsTransform(classJs, {compile: true, externalHelpers: false}); assert.include(result, helperSnippet); assert.include(result, 'MyClass'); }); test('omitted when external helpers are enabled', () => { const result = jsTransform(classJs, {compile: true, externalHelpers: true}); assert.notInclude(result, helperSnippet); assert.include(result, 'MyClass'); }); }); suite('regenerator runtime', () => { const asyncJs = `async () => { await myFunction(); } `; const regeneratorSnippet = `regeneratorRuntime=`; test('inlined when external helpers are disabled', () => { const result = jsTransform(asyncJs, {compile: 'es5', externalHelpers: false}); assert.include(result, regeneratorSnippet); assert.include(result, 'myFunction'); }); test('omitted when external helpers are enabled', () => { const result = jsTransform(asyncJs, {compile: 'es5', externalHelpers: true}); assert.notInclude(result, regeneratorSnippet); assert.include(result, 'myFunction'); }); test('omitted when compile target is es2015', () => { const result = jsTransform(asyncJs, {compile: 'es2015', externalHelpers: false}); assert.notInclude(result, regeneratorSnippet); assert.include(result, 'myFunction'); }); test('omitted when code does not require it', () => { const result = jsTransform( `class MyClass {}`, {compile: 'es5', externalHelpers: false}); assert.notInclude(result, regeneratorSnippet); assert.include(result, 'MyClass'); }); }); suite('parse errors', () => { const invalidJs = ';var{'; test('throw when softSyntaxError is false', () => { assert.throws( () => jsTransform(invalidJs, {compile: true, softSyntaxError: false})); }); test('do not throw when softSyntaxError is true', async () => { const output = await interceptOutput(async () => { assert.equal( jsTransform(invalidJs, {compile: true, softSyntaxError: true}), invalidJs); }); assert.include(output, '[polymer-build]: failed to parse JavaScript:'); }); }); suite('exponentiation', () => { const js = 'const foo = 2**2;'; test('minifies', () => { assert.equal(jsTransform(js, {minify: true}), 'const foo=2**2;'); }); test('compiles to ES5', () => { assert.equal( jsTransform(js, {compile: true}), 'var foo = Math.pow(2, 2);'); }); }); suite('rest properties', () => { const js = 'let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };'; test('minifies', () => { assert.equal( jsTransform(js, {minify: true}), 'let{x,y,...z}={x:1,y:2,a:3,b:4};'); }); test('compiles to ES5', () => { assert.include( jsTransform(js, {compile: true}), // Some compiled features are very verbose. Just look for the Babel // helper call so we know the plugin ran. 'objectWithoutProperties'); }); }); suite('spread properties', () => { const js = 'let n = { x, y, ...z };'; test('minifies', () => { assert.equal(jsTransform(js, {minify: true}), 'let n={x,y,...z};'); }); test('compiles to ES5', () => { assert.include(jsTransform(js, {compile: true}), 'objectSpread'); }); }); suite('async/await', () => { const js = 'async function foo() { await bar(); }'; test('minifies', () => { assert.equal( jsTransform(js, {minify: true}), 'async function foo(){await bar()}'); }); test('compiles to ES5', () => { assert.include(jsTransform(js, {compile: true}), 'asyncToGenerator'); }); }); suite('async generator', () => { const js = 'async function* foo() { yield bar; }'; test('minifies', () => { assert.equal( jsTransform(js, {minify: true}), 'async function*foo(){yield bar}'); }); test('compiles to ES5', () => { assert.include(jsTransform(js, {compile: true}), 'wrapAsyncGenerator'); }); }); suite('dynamic import', () => { const js = 'const foo = import("bar.js");'; test('minifies', () => { assert.equal( jsTransform(js, {minify: true}), 'const foo=import("bar.js");'); }); }); suite('rewrites bare module specifiers', () => { test('node packages', () => { const input = stripIndent(` import { dep1 } from 'dep1'; import { dep2 } from 'dep2'; import { dep2A } from 'dep2/a'; import { dep3 } from 'dep3'; import { dep4 } from 'dep4'; `); const expected = stripIndent(` import { dep1 } from "./node_modules/dep1/index.js"; import { dep2 } from "./node_modules/dep2/dep2.js"; import { dep2A } from "./node_modules/dep2/a.js"; import { dep3 } from "./node_modules/dep3/dep3-module.js"; import { dep4 } from "./node_modules/dep4/dep4-module.js"; `); const result = jsTransform(input, {moduleResolution: 'node', filePath}); assert.equal(result.trim(), expected.trim()); }); test('regular paths and urls', () => { const input = stripIndent(` import { p1 } from '/already/a/path.js'; import { p2 } from './already/a/path.js'; import { p3 } from '../already/a/path.js'; import { p4 } from '../already/a/path.js'; import { p5 } from 'http://example.com/already/a/path.js'; `); const expected = stripIndent(` import { p1 } from '/already/a/path.js'; import { p2 } from './already/a/path.js'; import { p3 } from '../already/a/path.js'; import { p4 } from '../already/a/path.js'; import { p5 } from 'http://example.com/already/a/path.js'; `); const result = jsTransform(input, {moduleResolution: 'node', filePath}); assert.equal(result.trim(), expected.trim()); }); test('paths that still need node resolution', () => { const input = // Resolves to a .js file. `import { bar } from './bar';\n` + // Resolves to a .json file (invalid for the web, but we still do it). `import { baz } from './baz';\n` + // Resolves to an actual extension-less file in preference to a .js // file with the same basename. `import { qux } from './qux';\n`; const expected = stripIndent(` import { bar } from "./bar.js"; import { baz } from "./baz.json"; import { qux } from './qux'; `); const result = jsTransform(input, {moduleResolution: 'node', filePath}); assert.equal(result.trim(), expected.trim()); }); test('paths for dependencies', () => { const input = stripIndent(` import { dep1 } from 'dep1'; `); const expected = stripIndent(` import { dep1 } from "../dep1/index.js"; `); const result = jsTransform(input, { moduleResolution: 'node', filePath, isComponentRequest: true, packageName: 'some-package', componentDir: path.join(rootDir, 'node_modules'), rootDir, }); assert.equal(result.trim(), expected.trim()); }); test('dependencies from a scoped package', () => { const input = stripIndent(` import { dep1 } from 'dep1'; `); const expected = stripIndent(` import { dep1 } from "../../dep1/index.js"; `); const result = jsTransform(input, { moduleResolution: 'node', filePath, isComponentRequest: true, packageName: '@some-scope/some-package', componentDir: path.join(rootDir, 'node_modules'), rootDir, }); assert.equal(result.trim(), expected.trim()); }); }); test('transforms ES modules to AMD', () => { const input = stripIndent(` import { dep1 } from 'dep1'; export const foo = 'foo'; `); const expected = stripIndent(` define(["exports", "dep1"], function (_exports, _dep) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.foo = void 0; const foo = 'foo'; _exports.foo = foo; }); `); const result = jsTransform(input, { transformModulesToAmd: true, filePath, rootDir, }); assert.equal(result.trim(), expected.trim()); }); test('transforms import.meta', () => { const input = stripIndent(` console.log(import.meta); `); const expected = stripIndent(` define(["meta"], function (meta) { "use strict"; meta = babelHelpers.interopRequireWildcard(meta); console.log(meta); }); `); const result = jsTransform(input, { transformModulesToAmd: true, externalHelpers: true, }); assert.equal(result.trim(), expected.trim()); }); test('transforms dynamic import()', () => { const input = stripIndent(` import { dep1 } from 'dep1'; export const foo = 'foo'; console.log(import('./bar.js')); `); const result = jsTransform(input, { transformModulesToAmd: true, filePath, rootDir, }); assert.include( result, `define(["exports", "require", "dep1"], function (_exports, _require, _dep) {`); assert.include( result, `console.log(new Promise((res, rej) => _require.default(['./bar.js'], res, rej)));`); }); // https://github.com/babel/babel/pull/8501 test('includes the native function check', () => { const input = stripIndent(` class TestElement extends HTMLElement { constructor() { super(); this.x = 1234; } } window.customElements.define("test-element", TestElement); `); const result = jsTransform(input, {compile: true}); assert.include(result, '_isNativeFunction'); }); // https://github.com/babel/minify/issues/824 test('does not remove statements preceding certain loops', () => { const input = stripIndent(` let foo = 'bar'; while (0); console.log(foo); `); const result = jsTransform(input, {compile: true, minify: true}); assert.include(result, 'bar'); }); });
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>The user is not authorized to access a resource.</p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; message?: string; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } export enum AccessPropertyValue { ALLOW = "ALLOW", DENY = "DENY", } export enum DedicatedTenancySupportResultEnum { DISABLED = "DISABLED", ENABLED = "ENABLED", } export enum DedicatedTenancyModificationStateEnum { COMPLETED = "COMPLETED", FAILED = "FAILED", PENDING = "PENDING", } /** * <p>Describes a modification to the configuration of Bring Your Own License (BYOL) for the * specified account. </p> */ export interface AccountModification { /** * <p>The state of the modification to the configuration of BYOL.</p> */ ModificationState?: DedicatedTenancyModificationStateEnum | string; /** * <p>The status of BYOL (whether BYOL is being enabled or disabled).</p> */ DedicatedTenancySupport?: DedicatedTenancySupportResultEnum | string; /** * <p>The IP address range, specified as an IPv4 CIDR block, for the management network * interface used for the account.</p> */ DedicatedTenancyManagementCidrRange?: string; /** * <p>The timestamp when the modification of the BYOL configuration was started.</p> */ StartTime?: Date; /** * <p>The error code that is returned if the configuration of BYOL cannot be modified.</p> */ ErrorCode?: string; /** * <p>The text of the error message that is returned if the configuration of BYOL cannot be * modified.</p> */ ErrorMessage?: string; } export namespace AccountModification { /** * @internal */ export const filterSensitiveLog = (obj: AccountModification): any => ({ ...obj, }); } export enum Application { Microsoft_Office_2016 = "Microsoft_Office_2016", Microsoft_Office_2019 = "Microsoft_Office_2019", } export interface AssociateConnectionAliasRequest { /** * <p>The identifier of the connection alias.</p> */ AliasId: string | undefined; /** * <p>The identifier of the directory to associate the connection alias with.</p> */ ResourceId: string | undefined; } export namespace AssociateConnectionAliasRequest { /** * @internal */ export const filterSensitiveLog = (obj: AssociateConnectionAliasRequest): any => ({ ...obj, }); } export interface AssociateConnectionAliasResult { /** * <p>The identifier of the connection alias association. You use the connection identifier in the DNS TXT record when * you're configuring your DNS routing policies. </p> */ ConnectionIdentifier?: string; } export namespace AssociateConnectionAliasResult { /** * @internal */ export const filterSensitiveLog = (obj: AssociateConnectionAliasResult): any => ({ ...obj, }); } /** * <p>One or more parameter values are not valid.</p> */ export interface InvalidParameterValuesException extends __SmithyException, $MetadataBearer { name: "InvalidParameterValuesException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace InvalidParameterValuesException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidParameterValuesException): any => ({ ...obj, }); } /** * <p>The state of the resource is not valid for this operation.</p> */ export interface InvalidResourceStateException extends __SmithyException, $MetadataBearer { name: "InvalidResourceStateException"; $fault: "client"; message?: string; } export namespace InvalidResourceStateException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidResourceStateException): any => ({ ...obj, }); } /** * <p>This operation is not supported.</p> */ export interface OperationNotSupportedException extends __SmithyException, $MetadataBearer { name: "OperationNotSupportedException"; $fault: "client"; message?: string; } export namespace OperationNotSupportedException { /** * @internal */ export const filterSensitiveLog = (obj: OperationNotSupportedException): any => ({ ...obj, }); } /** * <p>The resource is associated with a directory.</p> */ export interface ResourceAssociatedException extends __SmithyException, $MetadataBearer { name: "ResourceAssociatedException"; $fault: "client"; message?: string; } export namespace ResourceAssociatedException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceAssociatedException): any => ({ ...obj, }); } /** * <p>The resource could not be found.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The resource could not be found.</p> */ message?: string; /** * <p>The ID of the resource that could not be found.</p> */ ResourceId?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface AssociateIpGroupsRequest { /** * <p>The identifier of the directory.</p> */ DirectoryId: string | undefined; /** * <p>The identifiers of one or more IP access control groups.</p> */ GroupIds: string[] | undefined; } export namespace AssociateIpGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: AssociateIpGroupsRequest): any => ({ ...obj, }); } export interface AssociateIpGroupsResult {} export namespace AssociateIpGroupsResult { /** * @internal */ export const filterSensitiveLog = (obj: AssociateIpGroupsResult): any => ({ ...obj, }); } /** * <p>Your resource limits have been exceeded.</p> */ export interface ResourceLimitExceededException extends __SmithyException, $MetadataBearer { name: "ResourceLimitExceededException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace ResourceLimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceLimitExceededException): any => ({ ...obj, }); } export enum AssociationStatus { ASSOCIATED_WITH_OWNER_ACCOUNT = "ASSOCIATED_WITH_OWNER_ACCOUNT", ASSOCIATED_WITH_SHARED_ACCOUNT = "ASSOCIATED_WITH_SHARED_ACCOUNT", NOT_ASSOCIATED = "NOT_ASSOCIATED", PENDING_ASSOCIATION = "PENDING_ASSOCIATION", PENDING_DISASSOCIATION = "PENDING_DISASSOCIATION", } /** * <p>Describes a rule for an IP access control group.</p> */ export interface IpRuleItem { /** * <p>The IP address range, in CIDR notation.</p> */ ipRule?: string; /** * <p>The description.</p> */ ruleDesc?: string; } export namespace IpRuleItem { /** * @internal */ export const filterSensitiveLog = (obj: IpRuleItem): any => ({ ...obj, }); } export interface AuthorizeIpRulesRequest { /** * <p>The identifier of the group.</p> */ GroupId: string | undefined; /** * <p>The rules to add to the group.</p> */ UserRules: IpRuleItem[] | undefined; } export namespace AuthorizeIpRulesRequest { /** * @internal */ export const filterSensitiveLog = (obj: AuthorizeIpRulesRequest): any => ({ ...obj, }); } export interface AuthorizeIpRulesResult {} export namespace AuthorizeIpRulesResult { /** * @internal */ export const filterSensitiveLog = (obj: AuthorizeIpRulesResult): any => ({ ...obj, }); } export enum Compute { GRAPHICS = "GRAPHICS", GRAPHICSPRO = "GRAPHICSPRO", PERFORMANCE = "PERFORMANCE", POWER = "POWER", POWERPRO = "POWERPRO", STANDARD = "STANDARD", VALUE = "VALUE", } /** * <p>Describes the compute type of the bundle.</p> */ export interface ComputeType { /** * <p>The compute type.</p> */ Name?: Compute | string; } export namespace ComputeType { /** * @internal */ export const filterSensitiveLog = (obj: ComputeType): any => ({ ...obj, }); } /** * <p>Describes the root volume for a WorkSpace bundle.</p> */ export interface RootStorage { /** * <p>The size of the root volume.</p> */ Capacity?: string; } export namespace RootStorage { /** * @internal */ export const filterSensitiveLog = (obj: RootStorage): any => ({ ...obj, }); } /** * <p>Describes the user volume for a WorkSpace bundle.</p> */ export interface UserStorage { /** * <p>The size of the user volume.</p> */ Capacity?: string; } export namespace UserStorage { /** * @internal */ export const filterSensitiveLog = (obj: UserStorage): any => ({ ...obj, }); } /** * <p>Describes a WorkSpace bundle.</p> */ export interface WorkspaceBundle { /** * <p>The identifier of the bundle.</p> */ BundleId?: string; /** * <p>The name of the bundle.</p> */ Name?: string; /** * <p>The owner of the bundle. This is the account identifier of the owner, or * <code>AMAZON</code> if the bundle is provided by Amazon Web Services.</p> */ Owner?: string; /** * <p>The description of the bundle.</p> */ Description?: string; /** * <p>The identifier of the image that was used to create the bundle.</p> */ ImageId?: string; /** * <p>The size of the root volume.</p> */ RootStorage?: RootStorage; /** * <p>The size of the user volume.</p> */ UserStorage?: UserStorage; /** * <p>The compute type of the bundle. For more information, see * <a href="http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles">Amazon WorkSpaces Bundles</a>.</p> */ ComputeType?: ComputeType; /** * <p>The last time that the bundle was updated.</p> */ LastUpdatedTime?: Date; /** * <p>The time when the bundle was created.</p> */ CreationTime?: Date; } export namespace WorkspaceBundle { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceBundle): any => ({ ...obj, }); } export enum ReconnectEnum { DISABLED = "DISABLED", ENABLED = "ENABLED", } /** * <p>Describes an Amazon WorkSpaces client.</p> */ export interface ClientProperties { /** * <p>Specifies whether users can cache their credentials on the Amazon WorkSpaces client. * When enabled, users can choose to reconnect to their WorkSpaces without re-entering their * credentials. </p> */ ReconnectEnabled?: ReconnectEnum | string; } export namespace ClientProperties { /** * @internal */ export const filterSensitiveLog = (obj: ClientProperties): any => ({ ...obj, }); } /** * <p>Information about the Amazon WorkSpaces client.</p> */ export interface ClientPropertiesResult { /** * <p>The resource identifier, in the form of a directory ID.</p> */ ResourceId?: string; /** * <p>Information about the Amazon WorkSpaces client.</p> */ ClientProperties?: ClientProperties; } export namespace ClientPropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: ClientPropertiesResult): any => ({ ...obj, }); } /** * <p>Describes a connection alias association that is used for cross-Region redirection. For more information, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/cross-region-redirection.html"> * Cross-Region Redirection for Amazon WorkSpaces</a>.</p> */ export interface ConnectionAliasAssociation { /** * <p>The association status of the connection alias.</p> */ AssociationStatus?: AssociationStatus | string; /** * <p>The identifier of the Amazon Web Services account that associated the connection alias with a directory.</p> */ AssociatedAccountId?: string; /** * <p>The identifier of the directory associated with a connection alias.</p> */ ResourceId?: string; /** * <p>The identifier of the connection alias association. You use the connection identifier in the DNS TXT record when * you're configuring your DNS routing policies.</p> */ ConnectionIdentifier?: string; } export namespace ConnectionAliasAssociation { /** * @internal */ export const filterSensitiveLog = (obj: ConnectionAliasAssociation): any => ({ ...obj, }); } export enum ConnectionAliasState { CREATED = "CREATED", CREATING = "CREATING", DELETING = "DELETING", } /** * <p>Describes a connection alias. Connection aliases are used for cross-Region redirection. For more information, * see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/cross-region-redirection.html"> * Cross-Region Redirection for Amazon WorkSpaces</a>.</p> */ export interface ConnectionAlias { /** * <p>The connection string specified for the connection alias. The connection string must be in the form of * a fully qualified domain name (FQDN), such as <code>www.example.com</code>.</p> */ ConnectionString?: string; /** * <p>The identifier of the connection alias.</p> */ AliasId?: string; /** * <p>The current state of the connection alias.</p> */ State?: ConnectionAliasState | string; /** * <p>The identifier of the Amazon Web Services account that owns the connection alias.</p> */ OwnerAccountId?: string; /** * <p>The association status of the connection alias.</p> */ Associations?: ConnectionAliasAssociation[]; } export namespace ConnectionAlias { /** * @internal */ export const filterSensitiveLog = (obj: ConnectionAlias): any => ({ ...obj, }); } /** * <p>Describes the permissions for a connection alias. Connection aliases are used for cross-Region redirection. * For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/cross-region-redirection.html"> * Cross-Region Redirection for Amazon WorkSpaces</a>.</p> */ export interface ConnectionAliasPermission { /** * <p>The identifier of the Amazon Web Services account that the connection alias is shared with.</p> */ SharedAccountId: string | undefined; /** * <p>Indicates whether the specified Amazon Web Services account is allowed to associate the connection alias with a directory.</p> */ AllowAssociation: boolean | undefined; } export namespace ConnectionAliasPermission { /** * @internal */ export const filterSensitiveLog = (obj: ConnectionAliasPermission): any => ({ ...obj, }); } export enum ConnectionState { CONNECTED = "CONNECTED", DISCONNECTED = "DISCONNECTED", UNKNOWN = "UNKNOWN", } /** * <p>Describes a tag.</p> */ export interface Tag { /** * <p>The key of the tag.</p> */ Key: string | undefined; /** * <p>The value of the tag.</p> */ Value?: string; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } export interface CopyWorkspaceImageRequest { /** * <p>The name of the image.</p> */ Name: string | undefined; /** * <p>A description of the image.</p> */ Description?: string; /** * <p>The identifier of the source image.</p> */ SourceImageId: string | undefined; /** * <p>The identifier of the source Region.</p> */ SourceRegion: string | undefined; /** * <p>The tags for the image.</p> */ Tags?: Tag[]; } export namespace CopyWorkspaceImageRequest { /** * @internal */ export const filterSensitiveLog = (obj: CopyWorkspaceImageRequest): any => ({ ...obj, }); } export interface CopyWorkspaceImageResult { /** * <p>The identifier of the image.</p> */ ImageId?: string; } export namespace CopyWorkspaceImageResult { /** * @internal */ export const filterSensitiveLog = (obj: CopyWorkspaceImageResult): any => ({ ...obj, }); } /** * <p>The specified resource already exists.</p> */ export interface ResourceAlreadyExistsException extends __SmithyException, $MetadataBearer { name: "ResourceAlreadyExistsException"; $fault: "client"; message?: string; } export namespace ResourceAlreadyExistsException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceAlreadyExistsException): any => ({ ...obj, }); } /** * <p>The specified resource is not available.</p> */ export interface ResourceUnavailableException extends __SmithyException, $MetadataBearer { name: "ResourceUnavailableException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; /** * <p>The identifier of the resource that is not available.</p> */ ResourceId?: string; } export namespace ResourceUnavailableException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceUnavailableException): any => ({ ...obj, }); } export interface CreateConnectionAliasRequest { /** * <p>A connection string in the form of a fully qualified domain name (FQDN), such as <code>www.example.com</code>.</p> * * <important> * <p>After you create a connection string, it is always associated to your Amazon Web Services account. You cannot recreate the same * connection string with a different account, even if you delete all instances of it from the original account. The * connection string is globally reserved for your account.</p> * </important> */ ConnectionString: string | undefined; /** * <p>The tags to associate with the connection alias.</p> */ Tags?: Tag[]; } export namespace CreateConnectionAliasRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateConnectionAliasRequest): any => ({ ...obj, }); } export interface CreateConnectionAliasResult { /** * <p>The identifier of the connection alias.</p> */ AliasId?: string; } export namespace CreateConnectionAliasResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateConnectionAliasResult): any => ({ ...obj, }); } export interface CreateIpGroupRequest { /** * <p>The name of the group.</p> */ GroupName: string | undefined; /** * <p>The description of the group.</p> */ GroupDesc?: string; /** * <p>The rules to add to the group.</p> */ UserRules?: IpRuleItem[]; /** * <p>The tags. Each WorkSpaces resource can have a maximum of 50 tags.</p> */ Tags?: Tag[]; } export namespace CreateIpGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateIpGroupRequest): any => ({ ...obj, }); } export interface CreateIpGroupResult { /** * <p>The identifier of the group.</p> */ GroupId?: string; } export namespace CreateIpGroupResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateIpGroupResult): any => ({ ...obj, }); } /** * <p>The resource could not be created.</p> */ export interface ResourceCreationFailedException extends __SmithyException, $MetadataBearer { name: "ResourceCreationFailedException"; $fault: "client"; message?: string; } export namespace ResourceCreationFailedException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceCreationFailedException): any => ({ ...obj, }); } export interface CreateTagsRequest { /** * <p>The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, * registered directories, images, custom bundles, IP access control groups, and connection aliases.</p> */ ResourceId: string | undefined; /** * <p>The tags. Each WorkSpaces resource can have a maximum of 50 tags.</p> */ Tags: Tag[] | undefined; } export namespace CreateTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateTagsRequest): any => ({ ...obj, }); } export interface CreateTagsResult {} export namespace CreateTagsResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateTagsResult): any => ({ ...obj, }); } export interface CreateUpdatedWorkspaceImageRequest { /** * <p>The name of the new updated WorkSpace image.</p> */ Name: string | undefined; /** * <p>A description of whether updates for the WorkSpace image are available.</p> */ Description: string | undefined; /** * <p>The identifier of the source WorkSpace image.</p> */ SourceImageId: string | undefined; /** * <p>The tags that you want to add to the new updated WorkSpace image.</p> * * <note> * <p>To add tags at the same time when you're creating the updated image, you must create * an IAM policy that grants your IAM user permissions to use <code>workspaces:CreateTags</code>. </p> * </note> */ Tags?: Tag[]; } export namespace CreateUpdatedWorkspaceImageRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateUpdatedWorkspaceImageRequest): any => ({ ...obj, }); } export interface CreateUpdatedWorkspaceImageResult { /** * <p>The identifier of the new updated WorkSpace image.</p> */ ImageId?: string; } export namespace CreateUpdatedWorkspaceImageResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateUpdatedWorkspaceImageResult): any => ({ ...obj, }); } export interface CreateWorkspaceBundleRequest { /** * <p>The name of the bundle.</p> */ BundleName: string | undefined; /** * <p>The description of the bundle.</p> */ BundleDescription: string | undefined; /** * <p>The identifier of the image that is used to create the bundle.</p> */ ImageId: string | undefined; /** * <p>Describes the compute type of the bundle.</p> */ ComputeType: ComputeType | undefined; /** * <p>Describes the user volume for a WorkSpace bundle.</p> */ UserStorage: UserStorage | undefined; /** * <p>Describes the root volume for a WorkSpace bundle.</p> */ RootStorage?: RootStorage; /** * <p>The tags associated with the bundle.</p> * * <note> * <p>To add tags at the same time when you're creating the bundle, you must create an IAM policy that * grants your IAM user permissions to use <code>workspaces:CreateTags</code>. </p> * </note> */ Tags?: Tag[]; } export namespace CreateWorkspaceBundleRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspaceBundleRequest): any => ({ ...obj, }); } export interface CreateWorkspaceBundleResult { /** * <p>Describes a WorkSpace bundle.</p> */ WorkspaceBundle?: WorkspaceBundle; } export namespace CreateWorkspaceBundleResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspaceBundleResult): any => ({ ...obj, }); } export enum RunningMode { ALWAYS_ON = "ALWAYS_ON", AUTO_STOP = "AUTO_STOP", } /** * <p>Describes a WorkSpace.</p> */ export interface WorkspaceProperties { /** * <p>The running mode. For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html">Manage the WorkSpace Running * Mode</a>.</p> */ RunningMode?: RunningMode | string; /** * <p>The time after a user logs off when WorkSpaces are automatically stopped. Configured in 60-minute intervals.</p> */ RunningModeAutoStopTimeoutInMinutes?: number; /** * <p>The size of the root volume. For important information about how to modify the size of the root and user volumes, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html">Modify a WorkSpace</a>.</p> */ RootVolumeSizeGib?: number; /** * <p>The size of the user storage. For important information about how to modify the size of the root and user volumes, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html">Modify a WorkSpace</a>.</p> */ UserVolumeSizeGib?: number; /** * <p>The compute type. For more information, see <a href="http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles">Amazon WorkSpaces * Bundles</a>.</p> */ ComputeTypeName?: Compute | string; } export namespace WorkspaceProperties { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceProperties): any => ({ ...obj, }); } /** * <p>Describes the information used to create a WorkSpace.</p> */ export interface WorkspaceRequest { /** * <p>The identifier of the Directory Service directory for the WorkSpace. You can use * <a>DescribeWorkspaceDirectories</a> to list the available directories.</p> */ DirectoryId: string | undefined; /** * <p>The user name of the user for the WorkSpace. This user name must exist in the Directory Service * directory for the WorkSpace.</p> */ UserName: string | undefined; /** * <p>The identifier of the bundle for the WorkSpace. You can use <a>DescribeWorkspaceBundles</a> to list the available bundles.</p> */ BundleId: string | undefined; /** * <p>The symmetric KMS key used to encrypt data stored on your WorkSpace. * Amazon WorkSpaces does not support asymmetric KMS keys.</p> */ VolumeEncryptionKey?: string; /** * <p>Indicates whether the data stored on the user volume is encrypted.</p> */ UserVolumeEncryptionEnabled?: boolean; /** * <p>Indicates whether the data stored on the root volume is encrypted.</p> */ RootVolumeEncryptionEnabled?: boolean; /** * <p>The WorkSpace properties.</p> */ WorkspaceProperties?: WorkspaceProperties; /** * <p>The tags for the WorkSpace.</p> */ Tags?: Tag[]; } export namespace WorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceRequest): any => ({ ...obj, }); } export interface CreateWorkspacesRequest { /** * <p>The WorkSpaces to create. You can specify up to 25 WorkSpaces.</p> */ Workspaces: WorkspaceRequest[] | undefined; } export namespace CreateWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspacesRequest): any => ({ ...obj, }); } /** * <p>Describes a WorkSpace that cannot be created.</p> */ export interface FailedCreateWorkspaceRequest { /** * <p>Information about the WorkSpace.</p> */ WorkspaceRequest?: WorkspaceRequest; /** * <p>The error code that is returned if the WorkSpace cannot be created.</p> */ ErrorCode?: string; /** * <p>The text of the error message that is returned if the WorkSpace cannot be * created.</p> */ ErrorMessage?: string; } export namespace FailedCreateWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: FailedCreateWorkspaceRequest): any => ({ ...obj, }); } export enum ModificationResourceEnum { COMPUTE_TYPE = "COMPUTE_TYPE", ROOT_VOLUME = "ROOT_VOLUME", USER_VOLUME = "USER_VOLUME", } export enum ModificationStateEnum { UPDATE_INITIATED = "UPDATE_INITIATED", UPDATE_IN_PROGRESS = "UPDATE_IN_PROGRESS", } /** * <p>Describes a WorkSpace modification.</p> */ export interface ModificationState { /** * <p>The resource.</p> */ Resource?: ModificationResourceEnum | string; /** * <p>The modification state.</p> */ State?: ModificationStateEnum | string; } export namespace ModificationState { /** * @internal */ export const filterSensitiveLog = (obj: ModificationState): any => ({ ...obj, }); } export enum WorkspaceState { ADMIN_MAINTENANCE = "ADMIN_MAINTENANCE", AVAILABLE = "AVAILABLE", ERROR = "ERROR", IMPAIRED = "IMPAIRED", MAINTENANCE = "MAINTENANCE", PENDING = "PENDING", REBOOTING = "REBOOTING", REBUILDING = "REBUILDING", RESTORING = "RESTORING", STARTING = "STARTING", STOPPED = "STOPPED", STOPPING = "STOPPING", SUSPENDED = "SUSPENDED", TERMINATED = "TERMINATED", TERMINATING = "TERMINATING", UNHEALTHY = "UNHEALTHY", UPDATING = "UPDATING", } /** * <p>Describes a WorkSpace.</p> */ export interface Workspace { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId?: string; /** * <p>The identifier of the Directory Service directory for the WorkSpace.</p> */ DirectoryId?: string; /** * <p>The user for the WorkSpace.</p> */ UserName?: string; /** * <p>The IP address of the WorkSpace.</p> */ IpAddress?: string; /** * <p>The operational state of the WorkSpace.</p> * * <note> * <p>After a WorkSpace is terminated, the <code>TERMINATED</code> state is returned * only briefly before the WorkSpace directory metadata is cleaned up, so this state is rarely * returned. To confirm that a WorkSpace is terminated, check for the WorkSpace ID by using * <a href="https://docs.aws.amazon.com/workspaces/latest/api/API_DescribeWorkspaces.html"> * DescribeWorkSpaces</a>. If the WorkSpace ID isn't returned, then the WorkSpace has * been successfully terminated.</p> * </note> */ State?: WorkspaceState | string; /** * <p>The identifier of the bundle used to create the WorkSpace.</p> */ BundleId?: string; /** * <p>The identifier of the subnet for the WorkSpace.</p> */ SubnetId?: string; /** * <p>The text of the error message that is returned if the WorkSpace cannot be * created.</p> */ ErrorMessage?: string; /** * <p>The error code that is returned if the WorkSpace cannot be created.</p> */ ErrorCode?: string; /** * <p>The name of the WorkSpace, as seen by the operating system. The format of this name varies. * For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspaces-tutorials.html"> * Launch a WorkSpace</a>. </p> */ ComputerName?: string; /** * <p>The symmetric KMS key used to encrypt data stored on your WorkSpace. * Amazon WorkSpaces does not support asymmetric KMS keys.</p> */ VolumeEncryptionKey?: string; /** * <p>Indicates whether the data stored on the user volume is encrypted.</p> */ UserVolumeEncryptionEnabled?: boolean; /** * <p>Indicates whether the data stored on the root volume is encrypted.</p> */ RootVolumeEncryptionEnabled?: boolean; /** * <p>The properties of the WorkSpace.</p> */ WorkspaceProperties?: WorkspaceProperties; /** * <p>The modification states of the WorkSpace.</p> */ ModificationStates?: ModificationState[]; } export namespace Workspace { /** * @internal */ export const filterSensitiveLog = (obj: Workspace): any => ({ ...obj, }); } export interface CreateWorkspacesResult { /** * <p>Information about the WorkSpaces that could not be created.</p> */ FailedRequests?: FailedCreateWorkspaceRequest[]; /** * <p>Information about the WorkSpaces that were created.</p> * <p>Because this operation is asynchronous, the identifier returned is not immediately * available for use with other operations. For example, if you call <a>DescribeWorkspaces</a> before the WorkSpace is created, the information returned * can be incomplete.</p> */ PendingRequests?: Workspace[]; } export namespace CreateWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspacesResult): any => ({ ...obj, }); } export enum DedicatedTenancySupportEnum { ENABLED = "ENABLED", } /** * <p>Describes the default values that are used to create WorkSpaces. For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/update-directory-details.html">Update Directory Details for Your WorkSpaces</a>.</p> */ export interface DefaultWorkspaceCreationProperties { /** * <p>Specifies whether the directory is enabled for Amazon WorkDocs.</p> */ EnableWorkDocs?: boolean; /** * <p>Specifies whether to automatically assign an Elastic public IP address to WorkSpaces in this directory by default. * If enabled, the Elastic public IP address allows outbound internet access from your WorkSpaces when you’re using an * internet gateway in the Amazon VPC in which your WorkSpaces are located. If you're using a Network Address * Translation (NAT) gateway for outbound internet access from your VPC, or if your WorkSpaces are in public * subnets and you manually assign them Elastic IP addresses, you should disable this setting. This setting * applies to new WorkSpaces that you launch or to existing WorkSpaces that you rebuild. For more information, * see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-vpc.html"> * Configure a VPC for Amazon WorkSpaces</a>.</p> */ EnableInternetAccess?: boolean; /** * <p>The organizational unit (OU) in the directory for the WorkSpace machine accounts.</p> */ DefaultOu?: string; /** * <p>The identifier of the default security group to apply to WorkSpaces when they are created. * For more information, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-security-groups.html"> * Security Groups for Your WorkSpaces</a>.</p> */ CustomSecurityGroupId?: string; /** * <p>Specifies whether WorkSpace users are local administrators on their WorkSpaces.</p> */ UserEnabledAsLocalAdministrator?: boolean; /** * <p>Specifies whether maintenance mode is enabled for WorkSpaces. For more information, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/workspace-maintenance.html">WorkSpace * Maintenance</a>.</p> */ EnableMaintenanceMode?: boolean; } export namespace DefaultWorkspaceCreationProperties { /** * @internal */ export const filterSensitiveLog = (obj: DefaultWorkspaceCreationProperties): any => ({ ...obj, }); } export interface DeleteConnectionAliasRequest { /** * <p>The identifier of the connection alias to delete.</p> */ AliasId: string | undefined; } export namespace DeleteConnectionAliasRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConnectionAliasRequest): any => ({ ...obj, }); } export interface DeleteConnectionAliasResult {} export namespace DeleteConnectionAliasResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConnectionAliasResult): any => ({ ...obj, }); } export interface DeleteIpGroupRequest { /** * <p>The identifier of the IP access control group.</p> */ GroupId: string | undefined; } export namespace DeleteIpGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteIpGroupRequest): any => ({ ...obj, }); } export interface DeleteIpGroupResult {} export namespace DeleteIpGroupResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteIpGroupResult): any => ({ ...obj, }); } export interface DeleteTagsRequest { /** * <p>The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, * registered directories, images, custom bundles, IP access control groups, and connection aliases.</p> */ ResourceId: string | undefined; /** * <p>The tag keys.</p> */ TagKeys: string[] | undefined; } export namespace DeleteTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteTagsRequest): any => ({ ...obj, }); } export interface DeleteTagsResult {} export namespace DeleteTagsResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteTagsResult): any => ({ ...obj, }); } export interface DeleteWorkspaceBundleRequest { /** * <p>The identifier of the bundle.</p> */ BundleId?: string; } export namespace DeleteWorkspaceBundleRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceBundleRequest): any => ({ ...obj, }); } export interface DeleteWorkspaceBundleResult {} export namespace DeleteWorkspaceBundleResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceBundleResult): any => ({ ...obj, }); } export interface DeleteWorkspaceImageRequest { /** * <p>The identifier of the image.</p> */ ImageId: string | undefined; } export namespace DeleteWorkspaceImageRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceImageRequest): any => ({ ...obj, }); } export interface DeleteWorkspaceImageResult {} export namespace DeleteWorkspaceImageResult { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceImageResult): any => ({ ...obj, }); } export interface DeregisterWorkspaceDirectoryRequest { /** * <p>The identifier of the directory. If any WorkSpaces are registered to this directory, you must * remove them before you deregister the directory, or you will receive an OperationNotSupportedException * error.</p> */ DirectoryId: string | undefined; } export namespace DeregisterWorkspaceDirectoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterWorkspaceDirectoryRequest): any => ({ ...obj, }); } export interface DeregisterWorkspaceDirectoryResult {} export namespace DeregisterWorkspaceDirectoryResult { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterWorkspaceDirectoryResult): any => ({ ...obj, }); } export interface DescribeAccountRequest {} export namespace DescribeAccountRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountRequest): any => ({ ...obj, }); } export interface DescribeAccountResult { /** * <p>The status of BYOL (whether BYOL is enabled or disabled).</p> */ DedicatedTenancySupport?: DedicatedTenancySupportResultEnum | string; /** * <p>The IP address range, specified as an IPv4 CIDR block, used for the management network * interface.</p> * <p>The management network interface is connected to a secure Amazon WorkSpaces management * network. It is used for interactive streaming of the WorkSpace desktop to Amazon WorkSpaces * clients, and to allow Amazon WorkSpaces to manage the WorkSpace.</p> */ DedicatedTenancyManagementCidrRange?: string; } export namespace DescribeAccountResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountResult): any => ({ ...obj, }); } export interface DescribeAccountModificationsRequest { /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; } export namespace DescribeAccountModificationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountModificationsRequest): any => ({ ...obj, }); } export interface DescribeAccountModificationsResult { /** * <p>The list of modifications to the configuration of BYOL.</p> */ AccountModifications?: AccountModification[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there * are no more results to return. </p> */ NextToken?: string; } export namespace DescribeAccountModificationsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountModificationsResult): any => ({ ...obj, }); } export interface DescribeClientPropertiesRequest { /** * <p>The resource identifier, in the form of directory IDs.</p> */ ResourceIds: string[] | undefined; } export namespace DescribeClientPropertiesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeClientPropertiesRequest): any => ({ ...obj, }); } export interface DescribeClientPropertiesResult { /** * <p>Information about the specified Amazon WorkSpaces clients.</p> */ ClientPropertiesList?: ClientPropertiesResult[]; } export namespace DescribeClientPropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeClientPropertiesResult): any => ({ ...obj, }); } export interface DescribeConnectionAliasesRequest { /** * <p>The identifiers of the connection aliases to describe.</p> */ AliasIds?: string[]; /** * <p>The identifier of the directory associated with the connection alias.</p> */ ResourceId?: string; /** * <p>The maximum number of connection aliases to return.</p> */ Limit?: number; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, provide this token to receive the * next set of results. </p> */ NextToken?: string; } export namespace DescribeConnectionAliasesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConnectionAliasesRequest): any => ({ ...obj, }); } export interface DescribeConnectionAliasesResult { /** * <p>Information about the specified connection aliases.</p> */ ConnectionAliases?: ConnectionAlias[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeConnectionAliasesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConnectionAliasesResult): any => ({ ...obj, }); } export interface DescribeConnectionAliasPermissionsRequest { /** * <p>The identifier of the connection alias.</p> */ AliasId: string | undefined; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, provide this token to receive the * next set of results. </p> */ NextToken?: string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; } export namespace DescribeConnectionAliasPermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConnectionAliasPermissionsRequest): any => ({ ...obj, }); } export interface DescribeConnectionAliasPermissionsResult { /** * <p>The identifier of the connection alias.</p> */ AliasId?: string; /** * <p>The permissions associated with a connection alias.</p> */ ConnectionAliasPermissions?: ConnectionAliasPermission[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeConnectionAliasPermissionsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConnectionAliasPermissionsResult): any => ({ ...obj, }); } export interface DescribeIpGroupsRequest { /** * <p>The identifiers of one or more IP access control groups.</p> */ GroupIds?: string[]; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; /** * <p>The maximum number of items to return.</p> */ MaxResults?: number; } export namespace DescribeIpGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeIpGroupsRequest): any => ({ ...obj, }); } /** * <p>Describes an IP access control group.</p> */ export interface WorkspacesIpGroup { /** * <p>The identifier of the group.</p> */ groupId?: string; /** * <p>The name of the group.</p> */ groupName?: string; /** * <p>The description of the group.</p> */ groupDesc?: string; /** * <p>The rules.</p> */ userRules?: IpRuleItem[]; } export namespace WorkspacesIpGroup { /** * @internal */ export const filterSensitiveLog = (obj: WorkspacesIpGroup): any => ({ ...obj, }); } export interface DescribeIpGroupsResult { /** * <p>Information about the IP access control groups.</p> */ Result?: WorkspacesIpGroup[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeIpGroupsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeIpGroupsResult): any => ({ ...obj, }); } export interface DescribeTagsRequest { /** * <p>The identifier of the WorkSpaces resource. The supported resource types are WorkSpaces, * registered directories, images, custom bundles, IP access control groups, and connection aliases.</p> */ ResourceId: string | undefined; } export namespace DescribeTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTagsRequest): any => ({ ...obj, }); } export interface DescribeTagsResult { /** * <p>The tags.</p> */ TagList?: Tag[]; } export namespace DescribeTagsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTagsResult): any => ({ ...obj, }); } export interface DescribeWorkspaceBundlesRequest { /** * <p>The identifiers of the bundles. You cannot combine this parameter with any other filter.</p> */ BundleIds?: string[]; /** * <p>The owner of the bundles. You cannot combine this parameter with any other filter.</p> * <p>To describe the bundles provided by Amazon Web Services, specify <code>AMAZON</code>. * To describe the bundles that belong to your account, don't specify a value.</p> */ Owner?: string; /** * <p>The token for the next set of results. (You received this token from a previous call.)</p> */ NextToken?: string; } export namespace DescribeWorkspaceBundlesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceBundlesRequest): any => ({ ...obj, }); } export interface DescribeWorkspaceBundlesResult { /** * <p>Information about the bundles.</p> */ Bundles?: WorkspaceBundle[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more * results to return. This token is valid for one day and must be used within that time * frame.</p> */ NextToken?: string; } export namespace DescribeWorkspaceBundlesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceBundlesResult): any => ({ ...obj, }); } export interface DescribeWorkspaceDirectoriesRequest { /** * <p>The identifiers of the directories. If the value is null, all directories are * retrieved.</p> */ DirectoryIds?: string[]; /** * <p>The maximum number of directories to return.</p> */ Limit?: number; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; } export namespace DescribeWorkspaceDirectoriesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceDirectoriesRequest): any => ({ ...obj, }); } export enum WorkspaceDirectoryType { AD_CONNECTOR = "AD_CONNECTOR", SIMPLE_AD = "SIMPLE_AD", } /** * <p>Describes the self-service permissions for a directory. For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/enable-user-self-service-workspace-management.html">Enable Self-Service WorkSpace Management Capabilities for Your Users</a>.</p> */ export interface SelfservicePermissions { /** * <p>Specifies whether users can restart their WorkSpace.</p> */ RestartWorkspace?: ReconnectEnum | string; /** * <p>Specifies whether users can increase the volume size of the drives on their * WorkSpace.</p> */ IncreaseVolumeSize?: ReconnectEnum | string; /** * <p>Specifies whether users can change the compute type (bundle) for their WorkSpace.</p> */ ChangeComputeType?: ReconnectEnum | string; /** * <p>Specifies whether users can switch the running mode of their WorkSpace.</p> */ SwitchRunningMode?: ReconnectEnum | string; /** * <p>Specifies whether users can rebuild the operating system of a WorkSpace to its original * state.</p> */ RebuildWorkspace?: ReconnectEnum | string; } export namespace SelfservicePermissions { /** * @internal */ export const filterSensitiveLog = (obj: SelfservicePermissions): any => ({ ...obj, }); } export enum WorkspaceDirectoryState { DEREGISTERED = "DEREGISTERED", DEREGISTERING = "DEREGISTERING", ERROR = "ERROR", REGISTERED = "REGISTERED", REGISTERING = "REGISTERING", } export enum Tenancy { DEDICATED = "DEDICATED", SHARED = "SHARED", } /** * <p>The device types and operating systems that can be used to access a WorkSpace. For more * information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/workspaces-network-requirements.html">Amazon * WorkSpaces Client Network Requirements</a>.</p> */ export interface WorkspaceAccessProperties { /** * <p>Indicates whether users can use Windows clients to access their WorkSpaces.</p> */ DeviceTypeWindows?: AccessPropertyValue | string; /** * <p>Indicates whether users can use macOS clients to access their WorkSpaces.</p> */ DeviceTypeOsx?: AccessPropertyValue | string; /** * <p>Indicates whether users can access their WorkSpaces through a web browser.</p> */ DeviceTypeWeb?: AccessPropertyValue | string; /** * <p>Indicates whether users can use iOS devices to access their WorkSpaces.</p> */ DeviceTypeIos?: AccessPropertyValue | string; /** * <p>Indicates whether users can use Android and Android-compatible Chrome OS devices * to access their WorkSpaces.</p> */ DeviceTypeAndroid?: AccessPropertyValue | string; /** * <p>Indicates whether users can use Chromebooks to access their WorkSpaces.</p> */ DeviceTypeChromeOs?: AccessPropertyValue | string; /** * <p>Indicates whether users can use zero client devices to access their WorkSpaces.</p> */ DeviceTypeZeroClient?: AccessPropertyValue | string; /** * <p>Indicates whether users can use Linux clients to access their WorkSpaces.</p> */ DeviceTypeLinux?: AccessPropertyValue | string; } export namespace WorkspaceAccessProperties { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceAccessProperties): any => ({ ...obj, }); } /** * <p>Describes a directory that is used with Amazon WorkSpaces.</p> */ export interface WorkspaceDirectory { /** * <p>The directory identifier.</p> */ DirectoryId?: string; /** * <p>The directory alias.</p> */ Alias?: string; /** * <p>The name of the directory.</p> */ DirectoryName?: string; /** * <p>The registration code for the directory. This is the code that users enter in their * Amazon WorkSpaces client application to connect to the directory.</p> */ RegistrationCode?: string; /** * <p>The identifiers of the subnets used with the directory.</p> */ SubnetIds?: string[]; /** * <p>The IP addresses of the DNS servers for the directory.</p> */ DnsIpAddresses?: string[]; /** * <p>The user name for the service account.</p> */ CustomerUserName?: string; /** * <p>The identifier of the IAM role. This is the role that allows Amazon WorkSpaces to make * calls to other services, such as Amazon EC2, on your behalf.</p> */ IamRoleId?: string; /** * <p>The directory type.</p> */ DirectoryType?: WorkspaceDirectoryType | string; /** * <p>The identifier of the security group that is assigned to new WorkSpaces.</p> */ WorkspaceSecurityGroupId?: string; /** * <p>The state of the directory's registration with Amazon WorkSpaces. After a directory is * deregistered, the <code>DEREGISTERED</code> state is returned very briefly before the directory * metadata is cleaned up, so this state is rarely returned. To confirm that a directory is deregistered, * check for the directory ID by using * <a href="https://docs.aws.amazon.com/workspaces/latest/api/API_DescribeWorkspaceDirectories.html"> * DescribeWorkspaceDirectories</a>. If the directory ID isn't returned, then the directory has been * successfully deregistered.</p> */ State?: WorkspaceDirectoryState | string; /** * <p>The default creation properties for all WorkSpaces in the directory.</p> */ WorkspaceCreationProperties?: DefaultWorkspaceCreationProperties; /** * <p>The identifiers of the IP access control groups associated with the directory.</p> */ ipGroupIds?: string[]; /** * <p>The devices and operating systems that users can use to access WorkSpaces.</p> */ WorkspaceAccessProperties?: WorkspaceAccessProperties; /** * <p>Specifies whether the directory is dedicated or shared. To use Bring Your Own License * (BYOL), this value must be set to <code>DEDICATED</code>. For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/byol-windows-images.html">Bring * Your Own Windows Desktop Images</a>.</p> */ Tenancy?: Tenancy | string; /** * <p>The default self-service permissions for WorkSpaces in the directory.</p> */ SelfservicePermissions?: SelfservicePermissions; } export namespace WorkspaceDirectory { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceDirectory): any => ({ ...obj, }); } export interface DescribeWorkspaceDirectoriesResult { /** * <p>Information about the directories.</p> */ Directories?: WorkspaceDirectory[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeWorkspaceDirectoriesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceDirectoriesResult): any => ({ ...obj, }); } export interface DescribeWorkspaceImagePermissionsRequest { /** * <p>The identifier of the image.</p> */ ImageId: string | undefined; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; /** * <p>The maximum number of items to return.</p> */ MaxResults?: number; } export namespace DescribeWorkspaceImagePermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceImagePermissionsRequest): any => ({ ...obj, }); } /** * <p>Describes the Amazon Web Services accounts that have been granted permission to use a shared image. * For more information about sharing images, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/share-custom-image.html"> * Share or Unshare a Custom WorkSpaces Image</a>.</p> */ export interface ImagePermission { /** * <p>The identifier of the Amazon Web Services account that an image has been shared with.</p> */ SharedAccountId?: string; } export namespace ImagePermission { /** * @internal */ export const filterSensitiveLog = (obj: ImagePermission): any => ({ ...obj, }); } export interface DescribeWorkspaceImagePermissionsResult { /** * <p>The identifier of the image.</p> */ ImageId?: string; /** * <p>The identifiers of the Amazon Web Services accounts that the image has been shared with.</p> */ ImagePermissions?: ImagePermission[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeWorkspaceImagePermissionsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceImagePermissionsResult): any => ({ ...obj, }); } export enum ImageType { OWNED = "OWNED", SHARED = "SHARED", } export interface DescribeWorkspaceImagesRequest { /** * <p>The identifier of the image.</p> */ ImageIds?: string[]; /** * <p>The type (owned or shared) of the image.</p> */ ImageType?: ImageType | string; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; /** * <p>The maximum number of items to return.</p> */ MaxResults?: number; } export namespace DescribeWorkspaceImagesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceImagesRequest): any => ({ ...obj, }); } export enum OperatingSystemType { LINUX = "LINUX", WINDOWS = "WINDOWS", } /** * <p>The operating system that the image is running.</p> */ export interface OperatingSystem { /** * <p>The operating system.</p> */ Type?: OperatingSystemType | string; } export namespace OperatingSystem { /** * @internal */ export const filterSensitiveLog = (obj: OperatingSystem): any => ({ ...obj, }); } export enum WorkspaceImageRequiredTenancy { DEDICATED = "DEDICATED", DEFAULT = "DEFAULT", } export enum WorkspaceImageState { AVAILABLE = "AVAILABLE", ERROR = "ERROR", PENDING = "PENDING", } /** * <p>Describes whether a WorkSpace image needs to be updated with the latest * drivers and other components required by Amazon WorkSpaces.</p> * * <note> * <p>Only Windows 10 WorkSpace images can be programmatically updated at this time.</p> * </note> */ export interface UpdateResult { /** * <p>Indicates whether updated drivers or other components are available for the specified WorkSpace image.</p> */ UpdateAvailable?: boolean; /** * <p>A description of whether updates for the WorkSpace image are pending or available.</p> */ Description?: string; } export namespace UpdateResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateResult): any => ({ ...obj, }); } /** * <p>Describes a WorkSpace image.</p> */ export interface WorkspaceImage { /** * <p>The identifier of the image.</p> */ ImageId?: string; /** * <p>The name of the image.</p> */ Name?: string; /** * <p>The description of the image.</p> */ Description?: string; /** * <p>The operating system that the image is running. </p> */ OperatingSystem?: OperatingSystem; /** * <p>The status of the image.</p> */ State?: WorkspaceImageState | string; /** * <p>Specifies whether the image is running on dedicated hardware. When Bring Your Own * License (BYOL) is enabled, this value is set to <code>DEDICATED</code>. For more * information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/byol-windows-images.html">Bring Your Own Windows * Desktop Images</a>.</p> */ RequiredTenancy?: WorkspaceImageRequiredTenancy | string; /** * <p>The error code that is returned for the image.</p> */ ErrorCode?: string; /** * <p>The text of the error message that is returned for the image.</p> */ ErrorMessage?: string; /** * <p>The date when the image was created. If the image has been shared, the Amazon Web Services account * that the image has been shared with sees the original creation date of the image.</p> */ Created?: Date; /** * <p>The identifier of the Amazon Web Services account that owns the image.</p> */ OwnerAccountId?: string; /** * <p>The updates (if any) that are available for the specified image.</p> */ Updates?: UpdateResult; } export namespace WorkspaceImage { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceImage): any => ({ ...obj, }); } export interface DescribeWorkspaceImagesResult { /** * <p>Information about the images.</p> */ Images?: WorkspaceImage[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeWorkspaceImagesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceImagesResult): any => ({ ...obj, }); } export interface DescribeWorkspacesRequest { /** * <p>The identifiers of the WorkSpaces. You cannot combine this parameter with any other * filter.</p> * <p>Because the <a>CreateWorkspaces</a> operation is asynchronous, the identifier * it returns is not immediately available. If you immediately call <a>DescribeWorkspaces</a> with this identifier, no information is returned.</p> */ WorkspaceIds?: string[]; /** * <p>The identifier of the directory. In addition, you can optionally specify a specific * directory user (see <code>UserName</code>). You cannot combine this parameter with any * other filter.</p> */ DirectoryId?: string; /** * <p>The name of the directory user. You must specify this parameter with * <code>DirectoryId</code>.</p> */ UserName?: string; /** * <p>The identifier of the bundle. All WorkSpaces that are created from this bundle are * retrieved. You cannot combine this parameter with any other filter.</p> */ BundleId?: string; /** * <p>The maximum number of items to return.</p> */ Limit?: number; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; } export namespace DescribeWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspacesRequest): any => ({ ...obj, }); } export interface DescribeWorkspacesResult { /** * <p>Information about the WorkSpaces.</p> * <p>Because <a>CreateWorkspaces</a> is an asynchronous operation, some of the * returned information could be incomplete.</p> */ Workspaces?: Workspace[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspacesResult): any => ({ ...obj, }); } export interface DescribeWorkspacesConnectionStatusRequest { /** * <p>The identifiers of the WorkSpaces. You can specify up to 25 WorkSpaces.</p> */ WorkspaceIds?: string[]; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; } export namespace DescribeWorkspacesConnectionStatusRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspacesConnectionStatusRequest): any => ({ ...obj, }); } /** * <p>Describes the connection status of a WorkSpace.</p> */ export interface WorkspaceConnectionStatus { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId?: string; /** * <p>The connection state of the WorkSpace. The connection state is unknown if the WorkSpace * is stopped.</p> */ ConnectionState?: ConnectionState | string; /** * <p>The timestamp of the connection status check.</p> */ ConnectionStateCheckTimestamp?: Date; /** * <p>The timestamp of the last known user connection.</p> */ LastKnownUserConnectionTimestamp?: Date; } export namespace WorkspaceConnectionStatus { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceConnectionStatus): any => ({ ...obj, }); } export interface DescribeWorkspacesConnectionStatusResult { /** * <p>Information about the connection status of the WorkSpace.</p> */ WorkspacesConnectionStatus?: WorkspaceConnectionStatus[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace DescribeWorkspacesConnectionStatusResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspacesConnectionStatusResult): any => ({ ...obj, }); } export interface DescribeWorkspaceSnapshotsRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; } export namespace DescribeWorkspaceSnapshotsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceSnapshotsRequest): any => ({ ...obj, }); } /** * <p>Describes a snapshot.</p> */ export interface Snapshot { /** * <p>The time when the snapshot was created.</p> */ SnapshotTime?: Date; } export namespace Snapshot { /** * @internal */ export const filterSensitiveLog = (obj: Snapshot): any => ({ ...obj, }); } export interface DescribeWorkspaceSnapshotsResult { /** * <p>Information about the snapshots that can be used to rebuild a WorkSpace. These snapshots include * the user volume.</p> */ RebuildSnapshots?: Snapshot[]; /** * <p>Information about the snapshots that can be used to restore a WorkSpace. These snapshots * include both the root volume and the user volume.</p> */ RestoreSnapshots?: Snapshot[]; } export namespace DescribeWorkspaceSnapshotsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceSnapshotsResult): any => ({ ...obj, }); } export interface DisassociateConnectionAliasRequest { /** * <p>The identifier of the connection alias to disassociate.</p> */ AliasId: string | undefined; } export namespace DisassociateConnectionAliasRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateConnectionAliasRequest): any => ({ ...obj, }); } export interface DisassociateConnectionAliasResult {} export namespace DisassociateConnectionAliasResult { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateConnectionAliasResult): any => ({ ...obj, }); } export interface DisassociateIpGroupsRequest { /** * <p>The identifier of the directory.</p> */ DirectoryId: string | undefined; /** * <p>The identifiers of one or more IP access control groups.</p> */ GroupIds: string[] | undefined; } export namespace DisassociateIpGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateIpGroupsRequest): any => ({ ...obj, }); } export interface DisassociateIpGroupsResult {} export namespace DisassociateIpGroupsResult { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateIpGroupsResult): any => ({ ...obj, }); } /** * <p>Describes a WorkSpace that could not be rebooted. * (<a>RebootWorkspaces</a>), rebuilt (<a>RebuildWorkspaces</a>), restored (<a>RestoreWorkspace</a>), terminated * (<a>TerminateWorkspaces</a>), started (<a>StartWorkspaces</a>), or stopped (<a>StopWorkspaces</a>).</p> */ export interface FailedWorkspaceChangeRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId?: string; /** * <p>The error code that is returned if the WorkSpace cannot be rebooted.</p> */ ErrorCode?: string; /** * <p>The text of the error message that is returned if the WorkSpace cannot be * rebooted.</p> */ ErrorMessage?: string; } export namespace FailedWorkspaceChangeRequest { /** * @internal */ export const filterSensitiveLog = (obj: FailedWorkspaceChangeRequest): any => ({ ...obj, }); } export enum WorkspaceImageIngestionProcess { BYOL_GRAPHICS = "BYOL_GRAPHICS", BYOL_GRAPHICSPRO = "BYOL_GRAPHICSPRO", BYOL_REGULAR = "BYOL_REGULAR", BYOL_REGULAR_WSP = "BYOL_REGULAR_WSP", } export interface ImportWorkspaceImageRequest { /** * <p>The identifier of the EC2 image.</p> */ Ec2ImageId: string | undefined; /** * <p>The ingestion process to be used when importing the image, depending on which protocol * you want to use for your BYOL Workspace image, either PCoIP or WorkSpaces Streaming Protocol * (WSP). To use WSP, specify a value that ends in <code>_WSP</code>. To use PCoIP, specify a value * that does not end in <code>_WSP</code>. </p> * * <p>For non-GPU-enabled bundles (bundles other than Graphics or GraphicsPro), specify * <code>BYOL_REGULAR</code> or <code>BYOL_REGULAR_WSP</code>, depending on the protocol.</p> */ IngestionProcess: WorkspaceImageIngestionProcess | string | undefined; /** * <p>The name of the WorkSpace image.</p> */ ImageName: string | undefined; /** * <p>The description of the WorkSpace image.</p> */ ImageDescription: string | undefined; /** * <p>The tags. Each WorkSpaces resource can have a maximum of 50 tags.</p> */ Tags?: Tag[]; /** * <p>If specified, the version of Microsoft Office to subscribe to. Valid only for Windows 10 * BYOL images. For more information about subscribing to Office for BYOL images, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/byol-windows-images.html"> * Bring Your Own Windows Desktop Licenses</a>.</p> * * <note> * <p>Although this parameter is an array, only one item is allowed at this time.</p> * </note> */ Applications?: (Application | string)[]; } export namespace ImportWorkspaceImageRequest { /** * @internal */ export const filterSensitiveLog = (obj: ImportWorkspaceImageRequest): any => ({ ...obj, }); } export interface ImportWorkspaceImageResult { /** * <p>The identifier of the WorkSpace image.</p> */ ImageId?: string; } export namespace ImportWorkspaceImageResult { /** * @internal */ export const filterSensitiveLog = (obj: ImportWorkspaceImageResult): any => ({ ...obj, }); } export interface ListAvailableManagementCidrRangesRequest { /** * <p>The IP address range to search. Specify an IP address range that is compatible with your * network and in CIDR notation (that is, specify the range as an IPv4 CIDR block).</p> */ ManagementCidrRangeConstraint: string | undefined; /** * <p>The maximum number of items to return.</p> */ MaxResults?: number; /** * <p>If you received a <code>NextToken</code> from a previous call that was paginated, * provide this token to receive the next set of results.</p> */ NextToken?: string; } export namespace ListAvailableManagementCidrRangesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAvailableManagementCidrRangesRequest): any => ({ ...obj, }); } export interface ListAvailableManagementCidrRangesResult { /** * <p>The list of available IP address ranges, specified as IPv4 CIDR blocks.</p> */ ManagementCidrRanges?: string[]; /** * <p>The token to use to retrieve the next page of results. This value is null when there are no more results to return. </p> */ NextToken?: string; } export namespace ListAvailableManagementCidrRangesResult { /** * @internal */ export const filterSensitiveLog = (obj: ListAvailableManagementCidrRangesResult): any => ({ ...obj, }); } export interface MigrateWorkspaceRequest { /** * <p>The identifier of the WorkSpace to migrate from.</p> */ SourceWorkspaceId: string | undefined; /** * <p>The identifier of the target bundle type to migrate the WorkSpace to.</p> */ BundleId: string | undefined; } export namespace MigrateWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: MigrateWorkspaceRequest): any => ({ ...obj, }); } export interface MigrateWorkspaceResult { /** * <p>The original identifier of the WorkSpace that is being migrated.</p> */ SourceWorkspaceId?: string; /** * <p>The new identifier of the WorkSpace that is being migrated. If the migration does not succeed, * the target WorkSpace ID will not be used, and the WorkSpace will still have the original WorkSpace ID.</p> */ TargetWorkspaceId?: string; } export namespace MigrateWorkspaceResult { /** * @internal */ export const filterSensitiveLog = (obj: MigrateWorkspaceResult): any => ({ ...obj, }); } /** * <p>The properties of this WorkSpace are currently being modified. Try again in a moment.</p> */ export interface OperationInProgressException extends __SmithyException, $MetadataBearer { name: "OperationInProgressException"; $fault: "client"; message?: string; } export namespace OperationInProgressException { /** * @internal */ export const filterSensitiveLog = (obj: OperationInProgressException): any => ({ ...obj, }); } export interface ModifyAccountRequest { /** * <p>The status of BYOL.</p> */ DedicatedTenancySupport?: DedicatedTenancySupportEnum | string; /** * <p>The IP address range, specified as an IPv4 CIDR block, for the management network * interface. Specify an IP address range that is compatible with your network and in CIDR * notation (that is, specify the range as an IPv4 CIDR block). The CIDR block size must be * /16 (for example, 203.0.113.25/16). It must also be specified as available by the * <code>ListAvailableManagementCidrRanges</code> operation.</p> */ DedicatedTenancyManagementCidrRange?: string; } export namespace ModifyAccountRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyAccountRequest): any => ({ ...obj, }); } export interface ModifyAccountResult {} export namespace ModifyAccountResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyAccountResult): any => ({ ...obj, }); } export interface ModifyClientPropertiesRequest { /** * <p>The resource identifiers, in the form of directory IDs.</p> */ ResourceId: string | undefined; /** * <p>Information about the Amazon WorkSpaces client.</p> */ ClientProperties: ClientProperties | undefined; } export namespace ModifyClientPropertiesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyClientPropertiesRequest): any => ({ ...obj, }); } export interface ModifyClientPropertiesResult {} export namespace ModifyClientPropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyClientPropertiesResult): any => ({ ...obj, }); } export interface ModifySelfservicePermissionsRequest { /** * <p>The identifier of the directory.</p> */ ResourceId: string | undefined; /** * <p>The permissions to enable or disable self-service capabilities.</p> */ SelfservicePermissions: SelfservicePermissions | undefined; } export namespace ModifySelfservicePermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifySelfservicePermissionsRequest): any => ({ ...obj, }); } export interface ModifySelfservicePermissionsResult {} export namespace ModifySelfservicePermissionsResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifySelfservicePermissionsResult): any => ({ ...obj, }); } export interface ModifyWorkspaceAccessPropertiesRequest { /** * <p>The identifier of the directory.</p> */ ResourceId: string | undefined; /** * <p>The device types and operating systems to enable or disable for access.</p> */ WorkspaceAccessProperties: WorkspaceAccessProperties | undefined; } export namespace ModifyWorkspaceAccessPropertiesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceAccessPropertiesRequest): any => ({ ...obj, }); } export interface ModifyWorkspaceAccessPropertiesResult {} export namespace ModifyWorkspaceAccessPropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceAccessPropertiesResult): any => ({ ...obj, }); } /** * <p>Describes the default properties that are used for creating WorkSpaces. For more * information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/update-directory-details.html">Update Directory * Details for Your WorkSpaces</a>. </p> */ export interface WorkspaceCreationProperties { /** * <p>Indicates whether Amazon WorkDocs is enabled for your WorkSpaces.</p> * * <note> * <p>If WorkDocs is already enabled for a WorkSpaces directory and you disable it, new WorkSpaces launched in the * directory will not have WorkDocs enabled. However, WorkDocs remains enabled for any existing WorkSpaces, unless * you either disable users' access to WorkDocs or you delete the WorkDocs site. To disable users' access to WorkDocs, * see <a href="https://docs.aws.amazon.com/workdocs/latest/adminguide/inactive-user.html">Disabling Users</a> in the * <i>Amazon WorkDocs Administration Guide</i>. To delete a WorkDocs site, see * <a href="https://docs.aws.amazon.com/workdocs/latest/adminguide/manage-sites.html">Deleting a Site</a> in the * <i>Amazon WorkDocs Administration Guide</i>.</p> * * <p>If you enable WorkDocs on a directory that already has existing WorkSpaces, the existing WorkSpaces and any * new WorkSpaces that are launched in the directory will have WorkDocs enabled.</p> * </note> */ EnableWorkDocs?: boolean; /** * <p>Indicates whether internet access is enabled for your WorkSpaces.</p> */ EnableInternetAccess?: boolean; /** * <p>The default organizational unit (OU) for your WorkSpaces directories. This string must be the full Lightweight * Directory Access Protocol (LDAP) distinguished name for the target domain and OU. It must be in the form * <code>"OU=<i>value</i>,DC=<i>value</i>,DC=<i>value</i>"</code>, * where <i>value</i> is any string of characters, and the number of domain components (DCs) is * two or more. For example, <code>OU=WorkSpaces_machines,DC=machines,DC=example,DC=com</code>. </p> * * <important> * <ul> * <li> * <p>To avoid errors, certain characters in the distinguished name must be escaped. For more information, * see <a href="https://docs.microsoft.com/previous-versions/windows/desktop/ldap/distinguished-names"> * Distinguished Names</a> in the Microsoft documentation.</p> * </li> * <li> * <p>The API doesn't validate whether the OU exists.</p> * </li> * </ul> * </important> */ DefaultOu?: string; /** * <p>The identifier of your custom security group.</p> */ CustomSecurityGroupId?: string; /** * <p>Indicates whether users are local administrators of their WorkSpaces.</p> */ UserEnabledAsLocalAdministrator?: boolean; /** * <p>Indicates whether maintenance mode is enabled for your WorkSpaces. For more information, * see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/workspace-maintenance.html">WorkSpace * Maintenance</a>. </p> */ EnableMaintenanceMode?: boolean; } export namespace WorkspaceCreationProperties { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceCreationProperties): any => ({ ...obj, }); } export interface ModifyWorkspaceCreationPropertiesRequest { /** * <p>The identifier of the directory.</p> */ ResourceId: string | undefined; /** * <p>The default properties for creating WorkSpaces.</p> */ WorkspaceCreationProperties: WorkspaceCreationProperties | undefined; } export namespace ModifyWorkspaceCreationPropertiesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceCreationPropertiesRequest): any => ({ ...obj, }); } export interface ModifyWorkspaceCreationPropertiesResult {} export namespace ModifyWorkspaceCreationPropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceCreationPropertiesResult): any => ({ ...obj, }); } export interface ModifyWorkspacePropertiesRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; /** * <p>The properties of the WorkSpace.</p> */ WorkspaceProperties: WorkspaceProperties | undefined; } export namespace ModifyWorkspacePropertiesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspacePropertiesRequest): any => ({ ...obj, }); } export interface ModifyWorkspacePropertiesResult {} export namespace ModifyWorkspacePropertiesResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspacePropertiesResult): any => ({ ...obj, }); } /** * <p>The configuration of this WorkSpace is not supported for this operation. For more information, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/required-service-components.html">Required * Configuration and Service Components for WorkSpaces </a>.</p> */ export interface UnsupportedWorkspaceConfigurationException extends __SmithyException, $MetadataBearer { name: "UnsupportedWorkspaceConfigurationException"; $fault: "client"; message?: string; } export namespace UnsupportedWorkspaceConfigurationException { /** * @internal */ export const filterSensitiveLog = (obj: UnsupportedWorkspaceConfigurationException): any => ({ ...obj, }); } export enum TargetWorkspaceState { ADMIN_MAINTENANCE = "ADMIN_MAINTENANCE", AVAILABLE = "AVAILABLE", } export interface ModifyWorkspaceStateRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; /** * <p>The WorkSpace state.</p> */ WorkspaceState: TargetWorkspaceState | string | undefined; } export namespace ModifyWorkspaceStateRequest { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceStateRequest): any => ({ ...obj, }); } export interface ModifyWorkspaceStateResult {} export namespace ModifyWorkspaceStateResult { /** * @internal */ export const filterSensitiveLog = (obj: ModifyWorkspaceStateResult): any => ({ ...obj, }); } /** * <p>Describes the information used to reboot a WorkSpace.</p> */ export interface RebootRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; } export namespace RebootRequest { /** * @internal */ export const filterSensitiveLog = (obj: RebootRequest): any => ({ ...obj, }); } export interface RebootWorkspacesRequest { /** * <p>The WorkSpaces to reboot. You can specify up to 25 WorkSpaces.</p> */ RebootWorkspaceRequests: RebootRequest[] | undefined; } export namespace RebootWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: RebootWorkspacesRequest): any => ({ ...obj, }); } export interface RebootWorkspacesResult { /** * <p>Information about the WorkSpaces that could not be rebooted.</p> */ FailedRequests?: FailedWorkspaceChangeRequest[]; } export namespace RebootWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: RebootWorkspacesResult): any => ({ ...obj, }); } /** * <p>Describes the information used to rebuild a WorkSpace.</p> */ export interface RebuildRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; } export namespace RebuildRequest { /** * @internal */ export const filterSensitiveLog = (obj: RebuildRequest): any => ({ ...obj, }); } export interface RebuildWorkspacesRequest { /** * <p>The WorkSpace to rebuild. You can specify a single WorkSpace.</p> */ RebuildWorkspaceRequests: RebuildRequest[] | undefined; } export namespace RebuildWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: RebuildWorkspacesRequest): any => ({ ...obj, }); } export interface RebuildWorkspacesResult { /** * <p>Information about the WorkSpace that could not be rebuilt.</p> */ FailedRequests?: FailedWorkspaceChangeRequest[]; } export namespace RebuildWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: RebuildWorkspacesResult): any => ({ ...obj, }); } export interface RegisterWorkspaceDirectoryRequest { /** * <p>The identifier of the directory. You cannot register a directory if it does not have a status * of Active. If the directory does not have a status of Active, you will receive an * InvalidResourceStateException error. If you have already registered the maximum number of directories * that you can register with Amazon WorkSpaces, you will receive a ResourceLimitExceededException error. * Deregister directories that you are not using for WorkSpaces, and try again.</p> */ DirectoryId: string | undefined; /** * <p>The identifiers of the subnets for your virtual private cloud (VPC). Make sure that the subnets * are in supported Availability Zones. The subnets must also be in separate Availability Zones. If these * conditions are not met, you will receive an OperationNotSupportedException error.</p> */ SubnetIds?: string[]; /** * <p>Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled this parameter and * WorkDocs is not available in the Region, you will receive an OperationNotSupportedException error. Set * <code>EnableWorkDocs</code> to disabled, and try again.</p> */ EnableWorkDocs: boolean | undefined; /** * <p>Indicates whether self-service capabilities are enabled or disabled.</p> */ EnableSelfService?: boolean; /** * <p>Indicates whether your WorkSpace directory is dedicated or shared. To use Bring Your Own * License (BYOL) images, this value must be set to <code>DEDICATED</code> and your Amazon Web Services account must be * enabled for BYOL. If your account has not been enabled for BYOL, you will receive an * InvalidParameterValuesException error. For more information about BYOL images, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/byol-windows-images.html">Bring Your Own Windows Desktop Images</a>.</p> */ Tenancy?: Tenancy | string; /** * <p>The tags associated with the directory.</p> */ Tags?: Tag[]; } export namespace RegisterWorkspaceDirectoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: RegisterWorkspaceDirectoryRequest): any => ({ ...obj, }); } export interface RegisterWorkspaceDirectoryResult {} export namespace RegisterWorkspaceDirectoryResult { /** * @internal */ export const filterSensitiveLog = (obj: RegisterWorkspaceDirectoryResult): any => ({ ...obj, }); } /** * <p>The configuration of this network is not supported for this operation, or your network configuration * conflicts with the Amazon WorkSpaces management network IP range. For more information, see * <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-vpc.html"> * Configure a VPC for Amazon WorkSpaces</a>.</p> */ export interface UnsupportedNetworkConfigurationException extends __SmithyException, $MetadataBearer { name: "UnsupportedNetworkConfigurationException"; $fault: "client"; message?: string; } export namespace UnsupportedNetworkConfigurationException { /** * @internal */ export const filterSensitiveLog = (obj: UnsupportedNetworkConfigurationException): any => ({ ...obj, }); } /** * <p>The workspaces_DefaultRole role could not be found. If this is the first time you are registering a directory, you * will need to create the workspaces_DefaultRole role before you can register a directory. For more information, see <a href="https://docs.aws.amazon.com/workspaces/latest/adminguide/workspaces-access-control.html#create-default-role">Creating the workspaces_DefaultRole Role</a>.</p> */ export interface WorkspacesDefaultRoleNotFoundException extends __SmithyException, $MetadataBearer { name: "WorkspacesDefaultRoleNotFoundException"; $fault: "client"; message?: string; } export namespace WorkspacesDefaultRoleNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: WorkspacesDefaultRoleNotFoundException): any => ({ ...obj, }); } export interface RestoreWorkspaceRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; } export namespace RestoreWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: RestoreWorkspaceRequest): any => ({ ...obj, }); } export interface RestoreWorkspaceResult {} export namespace RestoreWorkspaceResult { /** * @internal */ export const filterSensitiveLog = (obj: RestoreWorkspaceResult): any => ({ ...obj, }); } export interface RevokeIpRulesRequest { /** * <p>The identifier of the group.</p> */ GroupId: string | undefined; /** * <p>The rules to remove from the group.</p> */ UserRules: string[] | undefined; } export namespace RevokeIpRulesRequest { /** * @internal */ export const filterSensitiveLog = (obj: RevokeIpRulesRequest): any => ({ ...obj, }); } export interface RevokeIpRulesResult {} export namespace RevokeIpRulesResult { /** * @internal */ export const filterSensitiveLog = (obj: RevokeIpRulesResult): any => ({ ...obj, }); } /** * <p>Information used to start a WorkSpace.</p> */ export interface StartRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId?: string; } export namespace StartRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartRequest): any => ({ ...obj, }); } export interface StartWorkspacesRequest { /** * <p>The WorkSpaces to start. You can specify up to 25 WorkSpaces.</p> */ StartWorkspaceRequests: StartRequest[] | undefined; } export namespace StartWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartWorkspacesRequest): any => ({ ...obj, }); } export interface StartWorkspacesResult { /** * <p>Information about the WorkSpaces that could not be started.</p> */ FailedRequests?: FailedWorkspaceChangeRequest[]; } export namespace StartWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: StartWorkspacesResult): any => ({ ...obj, }); } /** * <p>Describes the information used to stop a WorkSpace.</p> */ export interface StopRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId?: string; } export namespace StopRequest { /** * @internal */ export const filterSensitiveLog = (obj: StopRequest): any => ({ ...obj, }); } export interface StopWorkspacesRequest { /** * <p>The WorkSpaces to stop. You can specify up to 25 WorkSpaces.</p> */ StopWorkspaceRequests: StopRequest[] | undefined; } export namespace StopWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: StopWorkspacesRequest): any => ({ ...obj, }); } export interface StopWorkspacesResult { /** * <p>Information about the WorkSpaces that could not be stopped.</p> */ FailedRequests?: FailedWorkspaceChangeRequest[]; } export namespace StopWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: StopWorkspacesResult): any => ({ ...obj, }); } /** * <p>Describes the information used to terminate a WorkSpace.</p> */ export interface TerminateRequest { /** * <p>The identifier of the WorkSpace.</p> */ WorkspaceId: string | undefined; } export namespace TerminateRequest { /** * @internal */ export const filterSensitiveLog = (obj: TerminateRequest): any => ({ ...obj, }); } export interface TerminateWorkspacesRequest { /** * <p>The WorkSpaces to terminate. You can specify up to 25 WorkSpaces.</p> */ TerminateWorkspaceRequests: TerminateRequest[] | undefined; } export namespace TerminateWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: TerminateWorkspacesRequest): any => ({ ...obj, }); } export interface TerminateWorkspacesResult { /** * <p>Information about the WorkSpaces that could not be terminated.</p> */ FailedRequests?: FailedWorkspaceChangeRequest[]; } export namespace TerminateWorkspacesResult { /** * @internal */ export const filterSensitiveLog = (obj: TerminateWorkspacesResult): any => ({ ...obj, }); } export interface UpdateConnectionAliasPermissionRequest { /** * <p>The identifier of the connection alias that you want to update permissions for.</p> */ AliasId: string | undefined; /** * <p>Indicates whether to share or unshare the connection alias with the specified Amazon Web Services account.</p> */ ConnectionAliasPermission: ConnectionAliasPermission | undefined; } export namespace UpdateConnectionAliasPermissionRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateConnectionAliasPermissionRequest): any => ({ ...obj, }); } export interface UpdateConnectionAliasPermissionResult {} export namespace UpdateConnectionAliasPermissionResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateConnectionAliasPermissionResult): any => ({ ...obj, }); } export interface UpdateRulesOfIpGroupRequest { /** * <p>The identifier of the group.</p> */ GroupId: string | undefined; /** * <p>One or more rules.</p> */ UserRules: IpRuleItem[] | undefined; } export namespace UpdateRulesOfIpGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRulesOfIpGroupRequest): any => ({ ...obj, }); } export interface UpdateRulesOfIpGroupResult {} export namespace UpdateRulesOfIpGroupResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRulesOfIpGroupResult): any => ({ ...obj, }); } export interface UpdateWorkspaceBundleRequest { /** * <p>The identifier of the bundle.</p> */ BundleId?: string; /** * <p>The identifier of the image.</p> */ ImageId?: string; } export namespace UpdateWorkspaceBundleRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceBundleRequest): any => ({ ...obj, }); } export interface UpdateWorkspaceBundleResult {} export namespace UpdateWorkspaceBundleResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceBundleResult): any => ({ ...obj, }); } export interface UpdateWorkspaceImagePermissionRequest { /** * <p>The identifier of the image.</p> */ ImageId: string | undefined; /** * <p>The permission to copy the image. This permission can be revoked only after an image * has been shared.</p> */ AllowCopyImage: boolean | undefined; /** * <p>The identifier of the Amazon Web Services account to share or unshare the image with.</p> * * <important> * <p>Before sharing the image, confirm that you are sharing to the correct Amazon Web Services account ID.</p> * </important> */ SharedAccountId: string | undefined; } export namespace UpdateWorkspaceImagePermissionRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceImagePermissionRequest): any => ({ ...obj, }); } export interface UpdateWorkspaceImagePermissionResult {} export namespace UpdateWorkspaceImagePermissionResult { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceImagePermissionResult): any => ({ ...obj, }); }
the_stack
import { Trans } from "@lingui/macro"; import { i18nMark } from "@lingui/react"; import classNames from "classnames"; import { Link } from "react-router"; import { MountService } from "foundation-ui"; import * as React from "react"; import { Table, Tooltip } from "reactjs-components"; import { Icon } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import { green, iconSizeS, iconSizeXs, red, } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import DateUtil from "#SRC/js/utils/DateUtil"; import MesosStateStore from "#SRC/js/stores/MesosStateStore"; import TableUtil from "#SRC/js/utils/TableUtil"; import TimeAgo from "#SRC/js/components/TimeAgo"; import Units from "#SRC/js/utils/Units"; import DeclinedOffersReasons from "../constants/DeclinedOffersReasons"; const greenCheck = ( <Icon color={green} shape={SystemIcons.Check} size={iconSizeS} /> ); const redCross = ( <Icon color={red} shape={SystemIcons.Close} size={iconSizeXs} /> ); class DeclinedOffersTable extends React.Component { areResourcesMatched(requestedResource, receivedResource) { if (Array.isArray(receivedResource)) { return receivedResource.includes(requestedResource); } return receivedResource >= requestedResource; } getColumnClassNameFn(classes) { return (prop, sortBy) => classNames(classes, { active: prop === sortBy.prop, }); } getColumnHeadingFn(defaultHeading, abbreviation) { return (prop, order, sortBy) => { const caretClassNames = classNames("caret", { [`caret--${order}`]: order != null, "caret--visible": sortBy.prop === prop, }); const columnHeading = defaultHeading || prop; if (abbreviation != null) { return ( <span> <Trans id={columnHeading} render="span" key="full-text" className="hidden-medium-down" /> <Trans id={abbreviation} render="span" key="abbreviation" className="hidden-large-up" /> <span className={caretClassNames} /> </span> ); } return ( <span> <Trans render="span" id={columnHeading} /> <span className={caretClassNames} /> </span> ); }; } getMatchedResourcesSortFn(resource) { return (item, prop) => { // It's possible that prop is one of the resources, or timestamp for a // tiebreaker. Return the timestamp in ms if it's the current prop. if (prop === "timestamp") { return DateUtil.strToMs(item[prop]); } const { unmatchedResource = [] } = item; if (unmatchedResource.includes(resource)) { return 1; } return 0; }; } getMatchedOfferRenderFn(resource) { const { summary } = this.props; return (prop, row) => { const { unmatchedResource = [] } = row; const isResourceUnmatched = unmatchedResource.includes(resource); let receivedResourceClasses = classNames({ "text-danger": isResourceUnmatched, }); let requestedResource = (summary[prop] || { requested: 0 }).requested; let receivedResource = row.offered[prop]; let requestedResourceSuffix = ""; let receivedResourceSuffix = ""; const icon = isResourceUnmatched ? redCross : greenCheck; if (isResourceUnmatched) { if ( unmatchedResource.includes(DeclinedOffersReasons.UNFULFILLED_ROLE) && this.areResourcesMatched(requestedResource, receivedResource) ) { receivedResourceClasses = ""; requestedResourceSuffix = ( <Trans render="span">(Role: {summary.roles.requested})</Trans> ); receivedResourceSuffix = ( <Trans className="text-nowrap" render="span"> (Role: <span className="text-danger">{row.offered.roles}</span>) </Trans> ); } } if (Array.isArray(receivedResource)) { receivedResource = receivedResource.join(", "); } if (Array.isArray(requestedResource)) { requestedResource = requestedResource.join(", "); } if (["cpus", "mem", "disk"].includes(prop)) { requestedResource = Units.formatResource(prop, requestedResource); receivedResource = Units.formatResource(prop, receivedResource); } else { if (!requestedResource) { requestedResource = "N/A"; } if (!receivedResource) { receivedResource = "N/A"; } } const tooltipContent = ( <div> <div> <Trans render="strong">Requested</Trans> {": "} {requestedResource} {requestedResourceSuffix} </div> <div> <Trans render="strong">Received</Trans> {": "} <span className={receivedResourceClasses}> {receivedResource} </span>{" "} {receivedResourceSuffix} </div> </div> ); return ( <Tooltip content={tooltipContent} maxWidth={400} wrapText={true}> {icon} </Tooltip> ); }; } getColGroup() { return ( <colgroup> <col style={{ width: "13%" }} /> <col style={{ width: "9%" }} /> <col style={{ width: "15%" }} /> <col /> <col className="hidden-large-up" style={{ width: "9%" }} /> <col className="hidden-medium-down" style={{ width: "9%" }} /> <col className="hidden-medium-down" style={{ width: "9%" }} /> <col className="hidden-medium-down" style={{ width: "9%" }} /> <col /> <col /> <col className="hidden-small-down" style={{ width: "15%" }} /> </colgroup> ); } getColumns() { return [ { heading: this.getColumnHeadingFn(i18nMark("Host")), prop: "hostname", className: this.getColumnClassNameFn(), render: (prop, row) => { const hostname = row[prop]; const node = MesosStateStore.getNodeFromHostname(hostname); return ( <Tooltip content={hostname} maxWidth={400} wrapText={true}> {node && node.id ? ( <Link className="table-cell-link-primary" to={`/nodes/${node.id}`} > {hostname} </Link> ) : ( <span className="table-cell-link-primary">{hostname}</span> )} </Tooltip> ); }, sortable: true, }, { heading: this.getColumnHeadingFn(i18nMark("Role"), i18nMark("RLE")), prop: "roles", className: this.getColumnClassNameFn("text-align-center"), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.UNFULFILLED_ROLE ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn(DeclinedOffersReasons.UNFULFILLED_ROLE) ), }, { heading: this.getColumnHeadingFn( i18nMark("Constraint"), i18nMark("CSTR") ), prop: "constraints", className: this.getColumnClassNameFn("text-align-center"), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.UNFULFILLED_CONSTRAINT ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn( DeclinedOffersReasons.UNFULFILLED_CONSTRAINT ) ), }, { heading: this.getColumnHeadingFn(i18nMark("CPU/MEM/DSK")), prop: "cpus", className: this.getColumnClassNameFn( "text-align-center hidden-large-up" ), render: (prop, row) => ( <div className="flex flex-justify-items-space-around"> {this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_CPU )(prop, row)} {this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_MEM )(prop, row)} {this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_DISK )(prop, row)} </div> ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn(DeclinedOffersReasons.INSUFFICIENT_CPU) ), }, { heading: this.getColumnHeadingFn(i18nMark("CPU")), prop: "cpus", className: this.getColumnClassNameFn( "text-align-center hidden-medium-down" ), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_CPU ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn(DeclinedOffersReasons.INSUFFICIENT_CPU) ), }, { heading: this.getColumnHeadingFn(i18nMark("Mem")), prop: "mem", className: this.getColumnClassNameFn( "text-align-center hidden-medium-down" ), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_MEM ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn(DeclinedOffersReasons.INSUFFICIENT_MEM) ), }, { heading: this.getColumnHeadingFn(i18nMark("Disk"), i18nMark("DSK")), prop: "disk", className: this.getColumnClassNameFn( "text-align-center hidden-medium-down" ), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_DISK ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn( DeclinedOffersReasons.INSUFFICIENT_DISK ) ), }, { heading: this.getColumnHeadingFn(i18nMark("GPU")), prop: "gpus", className: this.getColumnClassNameFn("text-align-center"), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_GPU ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn(DeclinedOffersReasons.INSUFFICIENT_GPU) ), }, { heading: this.getColumnHeadingFn(i18nMark("Port"), i18nMark("PRT")), prop: "ports", className: this.getColumnClassNameFn("text-align-center"), render: this.getMatchedOfferRenderFn( DeclinedOffersReasons.INSUFFICIENT_PORTS ), sortable: true, sortFunction: TableUtil.getSortFunction( "timestamp", this.getMatchedResourcesSortFn( DeclinedOffersReasons.INSUFFICIENT_PORTS ) ), }, { heading: this.getColumnHeadingFn(i18nMark("Scarce Resources")), prop: "timestamp", className: this.getColumnClassNameFn( "text-align-right hidden-small-down" ), render: (_, row) => { const scarce = row.unmatchedResource?.includes( DeclinedOffersReasons.SCARCE_RESOURCES ); const icon = scarce ? redCross : greenCheck; const tooltipContent = scarce ? ( <Trans id="This host declined an offer because it has scarce resources (e.g. GPUs)." /> ) : ( "" ); return ( <Tooltip content={tooltipContent} maxWidth={600} wrapText={true}> {icon} </Tooltip> ); }, sortable: true, }, { heading: this.getColumnHeadingFn(i18nMark("Received")), prop: "timestamp", className: this.getColumnClassNameFn( "text-align-right hidden-small-down" ), render: (prop, row) => <TimeAgo time={DateUtil.strToMs(row[prop])} />, sortable: true, }, ]; } render() { const { offers } = this.props; return ( <MountService.Mount type="DeclinedOffersTable"> <Table className="table table-flush table-borderless-outer table-borderless-inner-columns table-break-word table-hover flush-bottom" colGroup={this.getColGroup()} columns={this.getColumns()} data={offers} sortBy={{ prop: "timestamp", order: "desc" }} /> </MountService.Mount> ); } } export default DeclinedOffersTable;
the_stack
import { SdkClient } from "../common/sdk-client"; import { TenantManagementModels } from "./tenant-management-models"; /** * The Tenant Management API provides endpoints for managing subtenants, * and the legal configuration and the basic properties of tenants * * @export * @class TenantManagementClient * @extends {SdkClient} */ export class TenantManagementClient extends SdkClient { private _baseUrl = "/api/tenantmanagement/v4"; /** * Get the complete legal information configuration of current tenant * * @returns {Promise<TenantManagementModels.LegalConfiguration>} * * @memberOf TenantManagementClient */ public async GetLegalConfigRegions(): Promise<TenantManagementModels.LegalConfiguration> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalConfigRegions`, }); return result as TenantManagementModels.LegalConfiguration; } /** * Creates tenant legal information * * @param {TenantManagementModels.LegalConfiguration} legalConfig * @returns {Promise<TenantManagementModels.LegalConfigurationResource>} * * @memberOf TenantManagementClient */ public async PostLegalConfigRegions( legalConfig: TenantManagementModels.LegalConfiguration ): Promise<TenantManagementModels.LegalConfigurationResource> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalConfigRegions`, body: legalConfig, }); return result as TenantManagementModels.LegalConfigurationResource; } /** * Update a region configuration of current tenant * * @param {string} regionId * @param {TenantManagementModels.Region} region * @param {{ ifMatch: string }} params * @returns {Promise<TenantManagementModels.RegionResource>} * * @memberOf TenantManagementClient */ public async PutLegalConfigRegions( regionId: string, region: TenantManagementModels.Region, params: { ifMatch: string } ): Promise<TenantManagementModels.RegionResource> { const parameters = params || {}; const { ifMatch } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalConfigRegions/${regionId}`, body: region, additionalHeaders: { "If-Match": ifMatch }, }); return result as TenantManagementModels.RegionResource; } /** * Delete legal Config Region * * @memberOf TenantManagementClient */ public async DeleteLegalConfigRegions() { await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalConfigRegions`, noResponse: true, }); } /** * Get specific legal information * * ! Fix: This was manually created in 3.12.0 as MindSphere has a copy/paste error * ! saying that this method returns LegalConfiguration * * @returns {Promise<TenantManagementModels.LegalInfo>} * * @memberOf TenantManagementClient */ public async GetLegalInfo(): Promise<TenantManagementModels.LegalInfo> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalInfo`, }); return result as TenantManagementModels.LegalInfo; } /** * Get the region specific legal information for a given tenant with fallback logic to core tenant * * ! Fix: This was manually created in 3.12.0 as MindSphere has a copy/paste error * ! saying that this method returns LegalConfiguration * * @param {string} tenantId * @returns {Promise<TenantManagementModels.LegalInfo>} * * @memberOf TenantManagementClient */ public async GetLegalInfoForTenant(tenantId: string): Promise<TenantManagementModels.LegalInfo> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalInfo/${tenantId}`, }); return result as TenantManagementModels.LegalInfo; } /** * Get the region specific legal information for a given tenant without fallback logic * * ! Fix: This was manually created in 3.12.0 as MindSphere has a copy/paste error * ! saying that this method returns LegalConfiguration * * @param {string} tenantId * @returns {Promise<TenantManagementModels.LegalInfo>} * * @memberOf TenantManagementClient */ public async GetLegalInfoForSpecificTenant(tenantId: string): Promise<TenantManagementModels.LegalInfo> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/legalInfoForSpecificTenant/${tenantId}`, }); return result as TenantManagementModels.LegalInfo; } /** * Get tenant info * * @returns {Promise<TenantManagementModels.TenantInfo>} * * @memberOf TenantManagementClient */ public async GetTenantInfo(): Promise<TenantManagementModels.TenantInfo> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/tenantInfo`, }); return result as TenantManagementModels.TenantInfo; } /** * Patch tenant info * * @param {TenantManagementModels.TenantInfoUpdateProperties} tenantInfoUpdateProperties * @param {{ ifMatch: string }} params * * @memberOf TenantManagementClient */ public async PatchTenantInfo( tenantInfoUpdateProperties: TenantManagementModels.TenantInfoUpdateProperties, params: { ifMatch: string } ) { const parameters = params || {}; const { ifMatch } = parameters; await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/tenantInfo`, body: tenantInfoUpdateProperties, additionalHeaders: { "If-Match": ifMatch }, }); } /** * Get tenant logo * * @returns {Promise<Response>} * * @memberOf TenantManagementClient */ public async GetTenantInfoLogo(): Promise<Response> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/tenantInfo/logo`, rawResponse: true, }); return result as Response; } /** * Upload tenant logo * * @param {Buffer} file * @param {string} [name] * @param {string} [mimeType] * @returns {Promise<Response>} * * @memberOf TenantManagementClient */ public async PostTenantInfoLogo(file: Buffer, name?: string, mimeType?: string): Promise<Response> { const template = `----mindsphere\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: ${ mimeType || "application/octet-stream" }\r\n\r\n`; const body = Buffer.concat([Buffer.from(template), file, Buffer.from("\r\n----mindsphere--")]); const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/tenantInfo/logo`, body: body, multiPartFormData: true, rawResponse: true, additionalHeaders: { enctype: "multipart/form-data" }, }); return result as Response; } /** * Get tenant logo metadata * * @returns {Promise<TenantManagementModels.UploadedFileResource>} * * @memberOf TenantManagementClient */ public async GetTenantInfoLogoMetaData(): Promise<TenantManagementModels.UploadedFileResource> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/tenantInfo/logoMetaData`, }); return result as TenantManagementModels.UploadedFileResource; } /** * Get subtenants * * @returns {Promise<TenantManagementModels.PageSubtenantResource>} * * @memberOf TenantManagementClient */ public async GetSubtenants(): Promise<TenantManagementModels.PageSubtenantResource> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/subtenants`, }); return result as TenantManagementModels.PageSubtenantResource; } /** * Create a subtenant * * @param {TenantManagementModels.Subtenant} subtenant * @returns {Promise<TenantManagementModels.SubtenantResource>} * * @memberOf TenantManagementClient */ public async PostSubtenant( subtenant: TenantManagementModels.Subtenant ): Promise<TenantManagementModels.SubtenantResource> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/subtenants`, body: subtenant, }); return result as TenantManagementModels.SubtenantResource; } /** * Get a subtenant by id. * * @param {string} id * @returns {Promise<TenantManagementModels.SubtenantResource>} * * @memberOf TenantManagementClient */ public async GetSubtenant(id: string): Promise<TenantManagementModels.SubtenantResource> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/subtenants/${id}`, }); return result as TenantManagementModels.SubtenantResource; } /** * Update a subtenant by id * * @param {string} id * @param {TenantManagementModels.SubtenantUpdateProperties} subtenantUpdateProperties * @param {{ ifMatch: string }} params * @returns {Promise<TenantManagementModels.SubtenantResource>} * * @memberOf TenantManagementClient */ public async PutSubtenant( id: string, subtenantUpdateProperties: TenantManagementModels.SubtenantUpdateProperties, params: { ifMatch: string } ): Promise<TenantManagementModels.SubtenantResource> { const parameters = params || {}; const { ifMatch } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/subtenants/${id}`, body: subtenantUpdateProperties, additionalHeaders: { "If-Match": ifMatch }, }); return result as TenantManagementModels.SubtenantResource; } /** * Delete a subtenant by id * * @param {string} id * * @memberOf TenantManagementClient */ public async DeleteSubtenant(id: string) { await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/subtenants/${id}`, noResponse: true, }); } }
the_stack
import * as vscode from 'vscode'; import * as jenkins from 'jenkins'; import * as request from 'request-promise-native'; import * as opn from 'open'; import * as htmlParser from 'cheerio'; import { sleep, timer, folderToUri, toDateString, msToTime, addDetail, QueryProperties } from './utils'; import { JenkinsConnection } from './jenkinsConnection'; import { JobType, JobTypeUtil } from './jobType'; import { ext } from './extensionVariables'; export class JenkinsService { // @ts-ignore public client: any; private _config: any; private _jenkinsUri: string; private _headers: any; private _disposed = false; private readonly messageItem: vscode.MessageItem = { title: 'Okay' }; public constructor(public readonly connection: JenkinsConnection) { this._jenkinsUri = this.connection.uri; ext.logger.info(`Using the following URI for Jenkins client: ${this._jenkinsUri}`); this.updateSettings(); vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('jenkins-jack.jenkins')) { this.updateSettings(); } }); } /** * Updates the settings for this service. */ private updateSettings() { if (this._disposed) { return; } this._config = vscode.workspace.getConfiguration('jenkins-jack.jenkins'); process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = this._config.strictTls ? '1' : '0'; } /** * Handles credential retrieval and creates the client connection to the targeted Jenkins. * @returns True if successfully connected to the remote Jenkins. False if not. */ public async initialize(): Promise<boolean> { // Attempt password retrieval let password = await this.connection.getPassword(); if (null == password) { if (this._disposed) { return false; } this.showCantConnectMessage(`Could not retrieve password for ${this.connection.serviceName} - ${this.connection.username}`); return false; } this._headers = { 'Authorization': 'Basic ' + new Buffer(`${this.connection.username}:${password}`).toString('base64') } try { this.client = jenkins({ baseUrl: this.connection.uri, crumbIssuer: this.connection.crumbIssuer, promisify: true, headers: this._headers }); await this.client.info(); } catch (err) { if (this._disposed) { return false; } this.showCantConnectMessage(); return false; } // If a folder filter path was provided, check that it exists if (this.connection.folderFilter) { let exists = await this.client.job.exists(this.connection.folderFilter); if (!exists) { this.showCantConnectMessage(`Folder filter path invalid: ${this.connection.folderFilter}`); return false; } } ext.logger.info('Jenkins service initialized.'); return true; } public dispose() { this.client = undefined; this._disposed = true; } /** * Initiates a 'get' request at the desired path from the Jenkins host. * @param path The targeted path from the Jenkins host. * @param token Optional cancellation token */ public async get(endpoint: string, token?: vscode.CancellationToken) { return new Promise<any>(async (resolve) => { try { let url = `${this._jenkinsUri}/${endpoint}`; let requestPromise = request.get(url, { headers: this._headers }) token?.onCancellationRequested(() => { requestPromise.abort(); resolve(undefined); }); resolve(await requestPromise); } catch (err) { ext.logger.error(err); resolve(undefined); } }); } /** * Uses the jenkins client to retrieve a job object. * @param job The Jenkins job JSON object. */ public async getJob(job: string) { try { return await this.client.job.get(job); } catch (err) { return undefined; } } /** * Wrapper around getJobsInternal with progress notification. * @param job The current Jenkins 'job' object. * @returns A list of Jenkins 'job' objects. */ public async getJobs(job?: any, options?: GetJobsOptions): Promise<any[]> { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: `Jenkins Jack`, cancellable: true }, async (progress, t) => { t.onCancellationRequested(() => { vscode.window.showWarningMessage(`User canceled job retrieval.`, this.messageItem); return undefined; }); progress.report({ message: 'Retrieving Jenkins jobs.' }); // If no job was provided and and a folder filter is specified in config, // start recursive job retrieval using the folder if (!job && this.connection.folderFilter && !options?.ignoreFolderFilter) { job = { type: JobType.Folder, url: `${this._jenkinsUri}/job/${folderToUri(this.connection.folderFilter)}` }; } return await this.getJobsInternal(job, options); }); } /** * Wrapper around getFoldersInternal with progress notification. * @param job The current Jenkins Folder 'job' object. * @returns A list of Jenkins Folder 'job' objects. */ public async getFolders(job?: any, ignoreFolderFilter?: boolean): Promise<any[]> { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: `Jenkins Jack`, cancellable: true }, async (progress, t) => { t.onCancellationRequested(() => { vscode.window.showWarningMessage(`User canceled job retrieval.`, this.messageItem); return undefined; }); progress.report({ message: 'Retrieving Jenkins Folder jobs.' }); // If no job was provided and and a folder filter is specified in config, // start recursive job retrieval using the folder if (!job && this.connection.folderFilter && !ignoreFolderFilter) { job = { type: JobType.Folder, url: `${this._jenkinsUri}/job/${folderToUri(this.connection.folderFilter)}` }; } return await this.getFoldersInternal(job, t); }); } /** * Recursive descent method for retrieving Jenkins jobs from * various job types (e.g. Multi-branch, Github Org, etc.). * @param job The current Jenkins 'job' object. * @returns A list of Jenkins 'job' objects. */ private async getJobsInternal(job?: any, options?: GetJobsOptions): Promise<any[]> { let token: vscode.CancellationToken | undefined = options?.token; if (token?.isCancellationRequested) { return []; } // If this is the first call of the recursive function, retrieve all jobs from the // Jenkins API, otherwise, grab all child jobs from the given parent job let jobs = job ? await this.getJobsFromUrl(job.url, QueryProperties.job, token) : await this.getJobsFromUrl(this._jenkinsUri, QueryProperties.job, token); if (undefined === jobs) { return []; } // Evaluate child jobs let jobList: any[] = []; for (let j of jobs) { let type = JobTypeUtil.classNameToType(j._class); switch(type) { case JobType.Folder: { j.type = JobType.Folder; if (options?.includeFolderJobs) { jobList.push(j); } jobList = jobList.concat(await this.getJobsInternal(j, options)); break; } case JobType.Multi: { for (let c of j.jobs) { c.type = JobType.Multi; jobList.push(c); } break; } case JobType.Org: { for (var pc of j.jobs) { for (let c of pc.jobs) { c.type = JobType.Org; jobList.push(c); } } break; } case JobType.Pipeline: { j.type = undefined === j.type ? JobType.Pipeline : j.type; jobList.push(j); break; } default: { j.type = undefined === j.type ? JobType.Default : job.type; jobList.push(j); } } } return jobList; } /** * Recursive descent method for retrieving Jenkins Folder jobs. * @param job The current Jenkins 'job' object. * @returns A list of Jenkins Folder 'job' objects. */ private async getFoldersInternal(job?: any, token?: vscode.CancellationToken): Promise<any[]> { if (token?.isCancellationRequested) { return []; } // If this is the first call of the recursive function, retrieve all jobs from the // Jenkins API, otherwise, grab all child jobs from the given parent job let jobs = []; if (job) { // If there are already child jobs attached to the parent, use those, otherwise query. jobs = job.jobs ?? await this.getJobsFromUrl(job.url, QueryProperties.jobMinimal, token); } else { jobs = await this.getJobsFromUrl(this._jenkinsUri, QueryProperties.jobMinimal, token); } if (!jobs) { return []; } let jobList: any[] = []; for (let j of jobs) { let type = JobTypeUtil.classNameToType(j._class); if (type === JobType.Folder) { j.type = JobType.Folder; jobList.push(j); jobList = jobList.concat(await this.getFoldersInternal(j, token)); } } return jobList; } /** * Retrieves the list of machines/nodes from Jenkins. * @param token The cancellation token. */ public async getNodes(token?: vscode.CancellationToken) { try { let url = `computer/api/json?tree=computer[${QueryProperties.node}]`; let r = await this.get(url, token); if (undefined === r) { return undefined; } let json = JSON.parse(r).computer; // Build label and details for quick-pick for (let n of json) { if (n.temporarilyOffline) { n.label = '$(alert)'; n.detail = '[OFFLINE]'; } else if (n.offline) { n.label = '$(error)'; n.detail = '[DISCONNECTED]'; } else { n.label = '$(check)'; n.detail = '[ONLINE]'; } n.label += ` ${n.displayName}` n.detail += n.description && n.description !== '' ? ` - ${n.description}` : ''; n.detail += n.temporarilyOffline ? ` - ${n.offlineCauseReason}` : '' let nodeLabels = this.getLabelsFromNode(n); n.detail += nodeLabels && nodeLabels.length > 0 ? ` - ${n.assignedLabels.map((l: any) => l.name).filter((l: string) => l.toUpperCase() !== n.displayName.toUpperCase()).join(',')}` : ''; } return json; } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); return undefined; } } /** * Wrapper around getBuilds with progress notification. * @param job The Jenkins JSON job object * @param numBuilds The number of builds to retrieve in the query * @param token (Optional) The cancellation token */ public async getBuildsWithProgress(job: any, numBuilds? : number, token?: vscode.CancellationToken) { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: `Jenkins Jack`, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { vscode.window.showWarningMessage(`User canceled build retrieval.`, this.messageItem); }); progress.report({ message: `Retrieving builds.` }); return await this.getBuilds(job, numBuilds, token); }); } /** * Retrieves build quick pick objects for the job and build number provided. * @param job The Jenkins job object * @param numBuilds (Optional) The number of builds to retrieve in the query * @param token (Optional) The cancellation token * @returns List of showQuickPick compatible Jenkins build objects or undefined. */ public async getBuilds( job: any, numBuilds?: number, token?: vscode.CancellationToken,) { let resultIconMap = new Map([ ['SUCCESS', '$(check)'], ['FAILURE', '$(x)'], ['ABORTED', '$(issues)'], ['UNSTABLE', '$(warning)'], [undefined, '']] ); return new Promise<any>(async resolve => { try { // Determine if we need to switch to the `allBuilds` field if the numBuilds // is over 100 (default number of results in Jenkins) numBuilds = numBuilds ?? 100; let buildsOrAllBuilds = (numBuilds > 100) ? 'allBuilds' : 'builds' let sw = timer(); let rootUrl = this.fromUrlFormat(job.url); let url = `${rootUrl}/api/json?tree=${buildsOrAllBuilds}[${QueryProperties.build}]{0,${numBuilds}}`; ext.logger.info(`getBuilds - ${url}`); let requestPromise = request.get(url, { headers: this._headers }); token?.onCancellationRequested(() => { requestPromise.abort(); resolve([]); }); let r = await requestPromise; let json = JSON.parse(r); ext.logger.debug(`getBuilds - ${sw.seconds}s`); resolve(json[buildsOrAllBuilds].map((n: any) => { let buildStatus = resultIconMap.get(n.result); buildStatus = null === n.result && n.building ? '$(loading~spin)' : buildStatus; n.label = String(`${n.number} ${buildStatus}`); // Add build meta-data to details for querying n.detail = `[${toDateString(n.timestamp)}] [${n.result ?? 'IN PROGRESS'}] [${msToTime(n.duration)}] - ${n.description ?? 'no description'}` return n; })); } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); resolve(undefined); } }); } /** * Returns a pipeline script from a previous build (replay). * @param job The Jenkins job JSON object * @param build The Jenkins build JSON object * @returns Pipeline script as string or undefined. */ public async getReplayScript(job: any, build: any) { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: `Jenkins Jack`, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { vscode.window.showWarningMessage(`User canceled script retrieval.`, this.messageItem); }); progress.report({ message: `Pulling replay script from ${job.fullName} #${build.number}` }); try { let url = `${this.fromUrlFormat(job.url)}/${build.number}/replay`; let r = await request.get(url, { headers: this._headers }); const root = htmlParser.load(r); if (root('textarea')[0].childNodes && 0 >= root('textarea')[0].childNodes.length) { return ''; } let source = root('textarea')[0].childNodes[0].data?.toString(); if (undefined === source) { throw new Error('Could not locate script text in <textarea>.'); } return source; } catch (err) { ext.logger.error(err); vscode.window.showWarningMessage('Jenkins Jack: Could not pull replay script.'); return undefined; } }); } /** * Deletes a build from Jenkins. "Found" status (302) * is considered success. * @param job The Jenkins job JSON object * @param buildNumber The build number to delete */ public async deleteBuild(job: any, buildNumber: any) { try { let url = `${this.fromUrlFormat(job.url)}/${buildNumber}/doDelete`; await request.post(url, { headers: this._headers }); } catch (err) { if (302 === err.statusCode) { return `${job.fullName} #${buildNumber} deleted`; } ext.logger.error(err); this.showCantConnectMessage(); } } /** * Retrieves a list of Jenkins 'job' objects. * @param rootUrl Root jenkins url for the request. * @returns Jobs json object or undefined. */ private async getJobsFromUrl(rootUrl: string, properties?: string, token?: vscode.CancellationToken) { return new Promise<any>(async (resolve) => { try { let sw = timer(); properties = properties ?? QueryProperties.job; rootUrl = rootUrl === undefined ? this._jenkinsUri : rootUrl; rootUrl = this.fromUrlFormat(rootUrl); let url = `${rootUrl}/api/json?tree=jobs[${properties},jobs[${properties},jobs[${properties}]]]`; ext.logger.info(`getJobsFromUrl - ${url}`); let requestPromise = request.get(url, { headers: this._headers }); token?.onCancellationRequested(() => { requestPromise.abort(); resolve([]); }); let r = await requestPromise; let json = JSON.parse(r); ext.logger.debug(`getJobsFromUrl - ${sw.seconds}`); this.addJobMetadata(json.jobs); resolve(json.jobs); } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); resolve(undefined); } }); } /** * Retrieves a list of Jenkins 'queue' objects. * @param token Optional cancellation token * @returns A list of queue item objects, otherwise undefined. */ public async getQueueItems(token?: vscode.CancellationToken): Promise<any[] | undefined> { try { let url = `queue/api/json`; let r = await this.get(url, token); if (undefined === r) { return undefined; } let items = JSON.parse(r).items; // Add queue item meta data for quick-picks for (let item of items) { item.name = `#${item.id} ${item.task?.name ?? '??'}` item.label = item.stuck ? '$(warning) ' : '$(watch) ' item.label += item.task?.name ?? '??'; item.description = item.why; item.detail = item.inQueueSince ? addDetail(msToTime(Date.now() - item.inQueueSince)) : ''; item.detail += item.inQueueSince ? addDetail(toDateString(item.inQueueSince)) : ''; item.detail += item.stuck ? addDetail('STUCK') : ''; item.detail += item.params ? addDetail(item.params.trim().split('\n').join(',')) : ''; } return items; } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); return undefined; } } private addJobMetadata(jobs: any) { jobs?.forEach((j: any) => { // Add meta-data fields to Jenkins job object j.fullName = (undefined === j.fullName) ? j.name : j.fullName; // Recurse on child jobs, if any this.addJobMetadata(j.jobs); }); } /** * Uses the /scriptText api to execute groovy console script on * the remote Jenkins. * @param source Groovy source. * @param node Optional targeted machine. * @returns Output of abort POST request or undefined. */ public async runConsoleScript( source: string, node: string | undefined = undefined, token?: vscode.CancellationToken) { try { let url = `${this._jenkinsUri}/scriptText`; if (undefined !== node) { url = `${this._jenkinsUri}/computer/${node}/scriptText`; } let r = request.post({ url: url, form: { script: source }, headers: this._headers }); if (undefined !== token) { token.onCancellationRequested(() => { r.abort(); }); } let output = await r; return output; } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); return err.error; } } /** * Streams the log output of the provided build to * the given output channel. * @param jobName The name of the job. * @param buildNumber The build number. * @param outputChannel The output channel to write to. */ public async streamBuildOutput( jobName: string, buildNumber: number, outputChannel: vscode.OutputChannel) { outputChannel.clear(); await outputChannel.show(); let outputConfig = await vscode.workspace.getConfiguration('jenkins-jack.outputView'); let suppressPipelineLog = outputConfig.suppressPipelineLog; // TODO: Arbitrary sleep to mitigate a race condition where the window // updates with empty content before the log stream can // append text to the OutputPanel's buffer. // A better solution would be for the show of OutputPanel to await on the // editor's visibility before firing an update with the OutputPanelProvider. await sleep(1000); // Stream the output. await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Streaming output for "${jobName}" #${buildNumber}`, cancellable: true }, async (progress: any, token: any) => { token.onCancellationRequested(() => { vscode.window.showInformationMessage(`User canceled output stream.`); }); var log = this.client.build.logStream({ name: jobName, number: buildNumber, delay: 500 }); return new Promise((resolve) => { token.onCancellationRequested(() =>{ log = undefined; resolve(undefined); }); log.on('data', (text: string) => { if (token.isCancellationRequested) { return; } if (suppressPipelineLog) { // Captures any "[Pipeline]" log line, including ones with timestamps let regex = new RegExp('^(\\S+\\s+)?\\[Pipeline\\] .*'); let content = text.split(/\r?\n/).filter((l: string) => !regex.test(l)); outputChannel.append(content.join('\n')); } else { outputChannel.append(text); } }); log.on('error', (err: string) => { if (token.isCancellationRequested) { return; } ext.logger.error(`[ERROR]: ${err}`); resolve(undefined); }); log.on('end', () => { if (token.isCancellationRequested) { return; } resolve(undefined); }); }); }); } /** * Opens the browser at the url provided. * @param url The url to open in the browser */ public openBrowserAt(url: string) { opn(url); } /** * Opens the browser at the targeted path using the Jenkins host. * @param path The desired path from the Jenkins host. Example: /job/someJob */ public openBrowserAtPath(path: string) { opn(`${this._jenkinsUri}${path}`); } public async queueCancel(itemId: any) { try { let url = `${this._jenkinsUri}/queue/cancelItem?id=${itemId}`; let r = request.post({ url: url, headers: this._headers }); let output = await r; return output; } catch (err) { ext.logger.error(err); this.showCantConnectMessage(); return err.error; } } /** * Blocks until a build is ready. Will timeout after a seconds * defined in global timeoutSecs. * @param jobName The name of the job. * @param buildNumber The build number to wait on. */ public async buildReady(jobName: string, buildNumber: number) { let timeoutSecs = 10; let timeout = timeoutSecs; let exists = false; ext.logger.info(`buildReady - Waiting for ${jobName} #${buildNumber} to start...`); while (timeout-- > 0) { exists = await this.client.build.get(jobName, buildNumber).then((data: any) => { return true; }).catch((err: any) => { return false; }); if (exists) { break; } await sleep(1000); } if (!exists) { throw new Error(`Timed out waiting waiting for build after ${timeoutSecs} seconds: ${jobName}`); } ext.logger.info(`buildReady - ${jobName} #${buildNumber} build is ready!`); } /** * Retrieves a list of label for the provided Jenkins 'node' object. * @param node The target agent/node to retrieve the labels from. * @returns A list of labels. */ public getLabelsFromNode(node: any): string[] { return node.assignedLabels.map((l: any) => l.name).filter((l: string) => l.toUpperCase() !== node.displayName.toUpperCase() ); } /** * Replace base Jenkins URI with the one defined in the config. * We do this since Jenkins will provide the URI with a base which may be * different from the one specified in the configuration. * @param url The url to format. */ private fromUrlFormat(url: string): string { url = url.charAt(url.length - 1) === '/' ? url.slice(0, -1) : url; let match = url.match('.*?/(job/.*)'); if (null !== match && match.length >= 0) { url = `${this._jenkinsUri}/${match[1]}`; } return url; } private async showCantConnectMessage(message?: string) { message = message ?? `Could not connect to the remote Jenkins "${this.connection.name}".`; let result = await vscode.window.showWarningMessage(message, { title: 'Okay' }, { title: 'Edit Connection' }); if ('Edit Connection' === result?.title) { vscode.commands.executeCommand('extension.jenkins-jack.connections.edit'); } } } /** * Options to configure the behavior of the jenkinsService.getJobs method for * job retrieval. */ export interface GetJobsOptions { /** * An optional flag to ignore usage of the folder filter for jobs retrieval. */ ignoreFolderFilter?: boolean; /** * An optional flag for including folder jobs in the results. */ includeFolderJobs?: boolean; /** * An optional cancellation token. */ token?: vscode.CancellationToken; }
the_stack
import { assert } from "@here/harp-utils"; /** @hidden */ export class Entry<Key, Value> { constructor( public key: Key, public value: Value, public size: number, public newer: Entry<Key, Value> | null, public older: Entry<Key, Value> | null ) {} } /** * Fixed size cache that evicts its entries in least-recently-used order when it overflows. * Modeled after standard JavaScript `Map` otherwise. */ export class LRUCache<Key, Value> { /** * Optional callback that is called on every item that is evicted from the cache. * * **Note**: This callback is not called when an item is explicitly deleted from the map via * [[delete]] or [[clear]]. */ evictionCallback?: (key: Key, value: Value) => void; /** * Optional callback that is called on every item that should be evicted from the cache to * determine if it can be removed, or should be locked in the cache. * * It returns `true` if the item can be removed from cache, `false` otherwise. Locking items in * the cache should be a temporary measure, since if the cache is filled with non-evictable * items only, it may grow beyond its capacity. * * **Note**: This callback is not called when an item is explicitly deleted from the map via * [[delete]] or [[clear]]. */ canEvict?: (key: Key, value: Value) => boolean; private m_capacity: number; private m_size = 0; /** * The internal map object that keeps the key-value pairs and their order. */ private readonly m_map = new Map<Key, Entry<Key, Value>>(); /** * The newest entry, i.e. the most recently used item. */ private m_newest: Entry<Key, Value> | null = null; /** * The oldest entry, i.e. the least recently used item. */ private m_oldest: Entry<Key, Value> | null = null; /** * A function determining the size per element. */ private m_sizeFunction: (v: Value) => number; /** * Creates a new instance of `LRUCache`. * * The optional [[sizeFunction]] can be used to fine tune the memory consumption of all cached * elements, thus [[cacheCapacity]] means then memory used (in MBs). Otherwise, if * [[sizeFunction]] is not specified, the [[cacheCapacity]] accounts for the maximum * number of elements stored. * * @param cacheCapacity - Number used to configure the maximum cache size, may express * number of entries or memory consumed in megabytes depending on [[sizeFunction]]. * @param sizeFunction - A function determining the size per element. */ constructor(cacheCapacity: number, sizeFunction: (v: Value) => number = () => 1) { this.m_capacity = cacheCapacity; this.m_sizeFunction = sizeFunction; } /** * Iterates over all items from the most recently used item to the least recently used one. * * **Note**: Results are undefined if the entire cache is modified during iteration. You may * although modify the current element in [[callbackfn]] function. * * @param callbackfn - The callback to call for each item. * @param thisArg - Optional this argument for the callback. */ forEach( callbackfn: (value: Value, key: Key, map: LRUCache<Key, Value>) => void, thisArg?: any ): void { let entry = this.m_newest; while (entry !== null) { const older = entry.older; callbackfn.call(thisArg, entry.value, entry.key, this); entry = older; } } /** * The size of the cache, i.e. the sum of all the sizes of all the objects in the cache. * * @returns The size of the cache. */ get size(): number { return this.m_size; } /** * Returns the maximum capacity of the cache, i.e. the maximum number of elements this cache * can contain or the total amount of memory that may be consumed by cache if element size * function was specified in cache c-tor. * * @returns The capacity of the cache. */ get capacity(): number { return this.m_capacity; } /** * @deprecated - DO NOT USE. Will be removed in future versions. * * Returns the internal map object that keeps the key-value pairs and their order. * * @returns The internal map object. */ get map(): Map<Key, Entry<Key, Value>> { // ### TODO - remove me. Cache must not expose its internal object, // modifications to it are fatal for the internal state machine. return this.m_map; } /** * Returns the newest entry in the cache. * * @returns Newest entry in the cache. */ get newest(): Entry<Key, Value> | null { return this.m_newest; } /** * Returns the oldest entry in the cache. * * Note: Does not promote the oldest item as most recently used item. * * @returns Oldest entry in the cache. */ get oldest(): Entry<Key, Value> | null { return this.m_oldest; } /** * Resets the capacity of this cache. If `newCapacity` is smaller than the current cache size, * all items will be evicted until the cache shrinks to `newCapacity`. * * @param newCapacity - The new capacity of this cache. */ setCapacity(newCapacity: number): void { this.m_capacity = newCapacity; this.evict(); } /** * Resets the cache capacity and function used to measure the element size. * * @param newCapacity - The new capacity masured in units returned from [[sizeMeasure]] funtion. * @param sizeMeasure - Function that defines the size of element, if you want to measure * number of elements only always return 1 from this function (default), you may also * specify own function that measures entries by memory consumed, nubmer of sub-elements, etc. */ setCapacityAndMeasure(newCapacity: number, sizeMeasure: (v: Value) => number = () => 1) { this.m_capacity = newCapacity; this.m_sizeFunction = sizeMeasure; this.shrinkToCapacity(); } /** * Updates the size of all elements in this cache. If their aggregated size is larger than the * capacity, items will be evicted until the cache shrinks to fit the capacity. */ shrinkToCapacity(): void { let size = 0; const sizeFunction = this.m_sizeFunction; let entry = this.m_newest; while (entry !== null) { const entrySize = sizeFunction(entry.value); entry.size = entrySize; size += entrySize; entry = entry.older; } this.m_size = size; this.evict(); } /** * Inserts or updates a key/value pair in the cache. * * If the key already existed in the cache, it will be updated and promoted to the most recently * used item. * * If the key didn't exist in the cache, it will be inserted as most recently used item. An * eviction of the least recently used item takes place if the cache exceeded its capacity. * * @param key - The key for the key-value pair to insert or update. * @param value - The value for the key-value pair to insert or update. */ set(key: Key, value: Value) { const valueSize = this.m_sizeFunction(value); let entry = this.m_map.get(key); if (entry !== undefined) { this.m_size = this.m_size - entry.size + valueSize; entry.value = value; entry.size = valueSize; this.promoteEntry(entry); this.evict(); } else { if (valueSize > this.m_capacity) { return; // single item too big to cache } entry = new Entry<Key, Value>(key, value, valueSize, null, null); if (this.m_map.size === 0) { this.m_newest = this.m_oldest = entry; } else { assert(this.m_newest !== null); const newest: Entry<Key, Value> = this.m_newest!; entry.older = this.m_newest; newest.newer = entry; this.m_newest = entry; } this.m_map.set(key, entry); this.m_size += valueSize; this.evict(); } } /** * Looks up key in the cache and returns the associated value. * * @param key - The key to look up. * @returns The associated value, or `undefined` if the key-value pair is not in the cache. */ get(key: Key): Value | undefined { const entry = this.m_map.get(key); if (entry === undefined) { return undefined; } this.promoteEntry(entry); return entry.value; } /** * Test if a key/value pair is in the cache. * * @param key - The key to look up. * @returns `true` if the key-value pair is in the cache, `false` otherwise. */ has(key: Key): boolean { return this.m_map.has(key); } /** * Clears the cache and removes all stored key-value pairs. * * Does not call the eviction callback. Use [[evictAll]] to clear the cache and call the * eviction callback. */ clear(): void { this.m_newest = this.m_oldest = null; this.m_size = 0; this.m_map.clear(); } /** * Evicts all items from the cache, calling the eviction callback on each item. * * Use [[clear]] to remove all items without calling the eviction callback. */ evictAll(): void { const cb = this.evictionCallback; if (cb !== undefined) { this.forEach((value, key) => cb(key, value)); } this.clear(); } /** * Evict selected elements from the cache using [[selector]] function. * * @param selector - The function for selecting elements for eviction. * @param thisArg - Optional _this_ object reference. */ evictSelected(selector: (value: Value, key: Key) => boolean, thisArg?: any) { const cb = this.evictionCallback; let entry = this.m_newest; while (entry !== null) { const entryOlder = entry.older; if (selector.call(thisArg, entry.value, entry.key)) { if (cb !== undefined) { cb(entry.key, entry.value); } this.deleteEntry(entry); this.m_map.delete(entry.key); } entry = entryOlder; } } /** * Explicitly removes a key-value pair from the cache. * * **Note**: This is an explicit removal, thus, the eviction callback will not be called. * * @param key - The key of the key-value pair to delete. * @returns `true` if the key-value pair existed and was deleted, `false` otherwise. */ delete(key: Key): boolean { const entry = this.m_map.get(key); if (entry === undefined) { return false; } this.deleteEntry(entry); return this.m_map.delete(key); } protected evict() { while (this.m_oldest !== null && this.m_size > this.m_capacity) { const evicted = this.evictOldest(); if (evicted === undefined) { return; } } } protected evictOldest(): Entry<Key, Value> | undefined { assert(this.m_oldest !== null); const oldest = this.m_oldest!; assert(oldest.older === null); let itemToRemove = oldest; if (this.canEvict !== undefined) { while (!this.canEvict(itemToRemove.key, itemToRemove.value)) { if (itemToRemove.newer === null) { return undefined; } itemToRemove = itemToRemove.newer; } } if (itemToRemove === oldest) { this.m_oldest = itemToRemove.newer; if (itemToRemove.newer !== null) { assert(itemToRemove.newer.older === itemToRemove); itemToRemove.newer.older = null; } } else { if (itemToRemove.newer !== null) { assert(itemToRemove.newer.older === itemToRemove); itemToRemove.newer.older = itemToRemove.older; if (itemToRemove.older !== null) { itemToRemove.older.newer = itemToRemove.newer; } } else { return undefined; } } const isOk = this.m_map.delete(itemToRemove.key); assert(isOk === true); if (isOk && this.evictionCallback !== undefined) { this.evictionCallback(itemToRemove.key, itemToRemove.value); } this.m_size -= itemToRemove.size; return itemToRemove; } private deleteEntry(entry: Entry<Key, Value>): void { if (entry === this.m_newest) { this.m_newest = entry.older; } else if (entry.newer) { entry.newer.older = entry.older; } else { assert(false); } if (entry === this.m_oldest) { this.m_oldest = entry.newer; } else if (entry.older) { entry.older.newer = entry.newer; } else { assert(false); } this.m_size -= entry.size; } private promoteEntry(entry: Entry<Key, Value>): void { if (entry === this.m_newest) { return; } // already newest, nothing to do // re-link newer and older items if (entry.newer) { assert(entry.newer.older === entry); entry.newer.older = entry.older; } if (entry.older) { assert(entry.older.newer === entry); entry.older.newer = entry.newer; } if (entry === this.m_oldest) { this.m_oldest = entry.newer; } // re-link ourselves entry.newer = null; entry.older = this.m_newest; // finally, set ourselves as the newest entry assert(this.m_newest !== null); const newest = this.m_newest!; assert(newest.newer === null); newest.newer = entry; this.m_newest = entry; } }
the_stack
import { Vector2, Vector3, Matrix4, Quaternion } from 'three' export function getQuery (id: string) { if (typeof window === 'undefined') return undefined const a = new RegExp(`${id}=([^&#=]*)`) const m = a.exec(window.location.search) if (m) { return decodeURIComponent(m[1]) } else { return undefined } } export function boolean (value: any) { if (!value) { return false } if (typeof value === 'string') { return /^1|true|t|yes|y$/i.test(value) } return true } export function defaults (value: any, defaultValue: any) { return value !== undefined ? value : defaultValue } export function createParams<T> (params: {[k in keyof T]?: any}, defaultParams: T) { const o: any = Object.assign({}, params) for (const k in defaultParams) { const value = params[k] if (value === undefined) o[k] = defaultParams[k] } return o as T } export function updateParams<T> (params: T, newParams: {[k in keyof T]?: any}) { for (const k in newParams) { const value = newParams[k] if (value !== undefined) params[k] = value } return params as T } export function pick (object: { [index: string]: any }) { const properties = [].slice.call(arguments, 1) return properties.reduce((a: { [index: string]: any }, e: any) => { a[ e ] = object[ e ] return a }, {}) } export function flatten (array: any[], ret: any[]) { ret = defaults(ret, []) for (let i = 0; i < array.length; i++) { if (Array.isArray(array[i])) { flatten(array[i], ret) } else { ret.push(array[i]) } } return ret } export function getProtocol () { const protocol = window.location.protocol return protocol.match(/http(s)?:/gi) === null ? 'http:' : protocol } export function getBrowser () { if (typeof window === 'undefined') return false const ua = window.navigator.userAgent if (/Opera|OPR/.test(ua)) { return 'Opera' } else if (/Chrome/i.test(ua)) { return 'Chrome' } else if (/Firefox/i.test(ua)) { return 'Firefox' } else if (/Mobile(\/.*)? Safari/i.test(ua)) { return 'Mobile Safari' } else if (/MSIE/i.test(ua)) { return 'Internet Explorer' } else if (/Safari/i.test(ua)) { return 'Safari' } return false } export function getAbsolutePath (relativePath: string) { const loc = window.location const pn = loc.pathname const basePath = pn.substring(0, pn.lastIndexOf('/') + 1) return loc.origin + basePath + relativePath } export function deepCopy (src: any) { if (typeof src !== 'object') { return src } const dst: { [index: string]: any } = Array.isArray(src) ? [] : {} for (let key in src) { dst[ key ] = deepCopy(src[ key ]) } return dst } export function deepEqual(a: any, b: any) { // from https://github.com/epoberezkin/fast-deep-equal MIT if (a === b) return true; const arrA = Array.isArray(a) const arrB = Array.isArray(b) if (arrA && arrB) { if (a.length !== b.length) return false for (let i = 0; i < a.length; i++) { if (!deepEqual(a[i], b[i])) return false } return true } if (arrA !== arrB) return false if (a && b && typeof a === 'object' && typeof b === 'object') { const keys = Object.keys(a) if (keys.length !== Object.keys(b).length) return false; const dateA = a instanceof Date const dateB = b instanceof Date if (dateA && dateB) return a.getTime() === b.getTime() if (dateA !== dateB) return false const regexpA = a instanceof RegExp const regexpB = b instanceof RegExp if (regexpA && regexpB) return a.toString() === b.toString() if (regexpA !== regexpB) return false for (let i = 0; i < keys.length; i++) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false } for (let i = 0; i < keys.length; i++) { if(!deepEqual(a[keys[i]], b[keys[i]])) return false } return true } return false } function openUrl (url: string) { const opened = window.open(url, '_blank') if (!opened) { window.location.href = url } } export function download (data: Blob|string, downloadName = 'download') { // using ideas from https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js if (!data) return const isSafari = getBrowser() === 'Safari' const isChromeIos = /CriOS\/[\d]+/.test(window.navigator.userAgent) const a = document.createElement('a') function open (str: string) { openUrl(isChromeIos ? str : str.replace(/^data:[^;]*;/, 'data:attachment/file;')) } if (typeof navigator !== 'undefined' && (navigator as any).msSaveOrOpenBlob) { // native saveAs in IE 10+ (navigator as any).msSaveOrOpenBlob(data, downloadName) } else if ((isSafari || isChromeIos) && FileReader) { if (data instanceof Blob) { // no downloading of blob urls in Safari var reader = new FileReader() reader.onloadend = function () { open(reader.result as string) } reader.readAsDataURL(data) } else { open(data) } } else { let objectUrlCreated = false if (data instanceof Blob) { data = URL.createObjectURL(data) objectUrlCreated = true } if ('download' in a) { // download link available a.style.display = 'hidden' document.body.appendChild(a) a.href = data a.download = downloadName a.target = '_blank' a.click() document.body.removeChild(a) } else { openUrl(data) } if (objectUrlCreated) { window.URL.revokeObjectURL(data) } } } export function submit (url: string, data: FormData, callback: Function, onerror: Function) { const xhr = new XMLHttpRequest() xhr.open('POST', url) xhr.addEventListener('load', function () { if (xhr.status === 200 || xhr.status === 304) { callback(xhr.response) } else { if (typeof onerror === 'function') { onerror(xhr.status) } } }, false) xhr.send(data) } interface HTMLInputEvent extends Event { target: HTMLInputElement & EventTarget } export function open (callback: Function, extensionList = ['*']) { const fileInput = document.createElement('input') fileInput.type = 'file' fileInput.multiple = true fileInput.style.display = 'hidden' document.body.appendChild(fileInput) fileInput.accept = '.' + extensionList.join(',.') fileInput.addEventListener('change', function (e: HTMLInputEvent) { callback(e.target.files) }, false) fileInput.click() } export function throttle (func: Function, wait: number, options: { leading?: boolean, trailing?: boolean }) { // from http://underscorejs.org/docs/underscore.html let context: any let args: any let result: any let timeout: any = null let previous = 0 if (!options) options = {} function later () { previous = options.leading === false ? 0 : Date.now() timeout = null result = func.apply(context, args) if (!timeout) context = args = null } return function throttle (this: any) { var now = Date.now() if (!previous && options.leading === false) previous = now var remaining = wait - (now - previous) context = this args = arguments if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout) timeout = null } previous = now result = func.apply(context, args) if (!timeout) context = args = null } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining) } return result } } export function lexicographicCompare<T> (elm1: T, elm2: T) { if (elm1 < elm2) return -1 if (elm1 > elm2) return 1 return 0 } /** * Does a binary search to get the index of an element in the input array * @function * @example * var array = [ 1, 2, 3, 4, 5, 6 ]; * var element = 4; * binarySearchIndexOf( array, element ); // returns 3 * * @param {Array} array - sorted array * @param {Anything} element - element to search for in the array * @param {Function} [compareFunction] - compare function * @return {Number} the index of the element or -1 if not in the array */ export function binarySearchIndexOf<T> (array: T[], element: T, compareFunction = lexicographicCompare) { let low = 0 let high = array.length - 1 while (low <= high) { const mid = (low + high) >> 1 const cmp = compareFunction(element, array[ mid ]) if (cmp > 0) { low = mid + 1 } else if (cmp < 0) { high = mid - 1 } else { return mid } } return -low - 1 } export function binarySearchForLeftRange (array: number[], leftRange: number) { let high = array.length - 1 if (array[ high ] < leftRange) return -1 let low = 0 while (low <= high) { const mid = (low + high) >> 1 if (array[ mid ] >= leftRange) { high = mid - 1 } else { low = mid + 1 } } return high + 1 } export function binarySearchForRightRange (array: number[], rightRange: number) { if (array[ 0 ] > rightRange) return -1 let low = 0 let high = array.length - 1 while (low <= high) { const mid = (low + high) >> 1 if (array[ mid ] > rightRange) { high = mid - 1 } else { low = mid + 1 } } return low - 1 } export function rangeInSortedArray (array: number[], min: number, max: number) { const indexLeft = binarySearchForLeftRange(array, min) const indexRight = binarySearchForRightRange(array, max) if (indexLeft === -1 || indexRight === -1 || indexLeft > indexRight) { return 0 } else { return indexRight - indexLeft + 1 } } export function dataURItoImage (dataURI: string) { const img = document.createElement('img') img.src = dataURI return img } export function uniqueArray (array: any[]) { return array.sort().filter(function (value, index, sorted) { return (index === 0) || (value !== sorted[ index - 1 ]) }) } // String/arraybuffer conversion export function uint8ToString (u8a: Uint8Array) { const chunkSize = 0x7000 if (u8a.length > chunkSize) { const c = [] for (let i = 0; i < u8a.length; i += chunkSize) { c.push(String.fromCharCode.apply( null, u8a.subarray(i, i + chunkSize) )) } return c.join('') } else { return String.fromCharCode.apply(null, u8a) } } export function uint8ToLines (u8a: Uint8Array, chunkSize = 1024 * 1024 * 10, newline = '\n') { let partialLine = '' let lines: string[] = [] for (let i = 0; i < u8a.length; i += chunkSize) { const str = uint8ToString(u8a.subarray(i, i + chunkSize)) const idx = str.lastIndexOf(newline) if (idx === -1) { partialLine += str } else { const str2 = partialLine + str.substr(0, idx) lines = lines.concat(str2.split(newline)) if (idx === str.length - newline.length) { partialLine = '' } else { partialLine = str.substr(idx + newline.length) } } } if (partialLine !== '') { lines.push(partialLine) } return lines } export type TypedArrayString = 'int8'|'int16'|'int32'|'uint8'|'uint16'|'uint32'|'float32' export function getTypedArray (arrayType: TypedArrayString, arraySize: number) { switch (arrayType) { case 'int8': return new Int8Array(arraySize) case 'int16': return new Int16Array(arraySize) case 'int32': return new Int32Array(arraySize) case 'uint8': return new Uint8Array(arraySize) case 'uint16': return new Uint16Array(arraySize) case 'uint32': return new Uint32Array(arraySize) case 'float32': return new Float32Array(arraySize) default: throw new Error('arrayType unknown: ' + arrayType) } } export function getUintArray (sizeOrArray: any, maxUint: number) { // TODO const TypedArray = maxUint > 65535 ? Uint32Array : Uint16Array return new TypedArray(sizeOrArray) } export function ensureArray (value: any) { return Array.isArray(value) ? value : [value] } export function ensureBuffer (a: any) { // TODO return (a.buffer && a.buffer instanceof ArrayBuffer) ? a.buffer : a } function _ensureClassFromArg (arg: any, constructor: { new (arg: any): any }) { return arg instanceof constructor ? arg : new constructor(arg) } function _ensureClassFromArray (array: any, constructor: { new (): any }) { if (array === undefined) { array = new constructor() } else if (Array.isArray(array)) { array = new constructor().fromArray(array) } return array } export function ensureVector2 (v?: number[]|Vector2) { return _ensureClassFromArray(v, Vector2) } export function ensureVector3 (v?: number[]|Vector3) { return _ensureClassFromArray(v, Vector3) } export function ensureMatrix4 (m?: number[]|Matrix4) { return _ensureClassFromArray(m, Matrix4) } export function ensureQuaternion (q?: number[]|Quaternion) { return _ensureClassFromArray(q, Quaternion) } export function ensureFloat32Array (a?: number[]|Float32Array) { return _ensureClassFromArg(a, Float32Array) } export interface RingBuffer<T> { has: (value: T) => boolean get: (value: number) => T push: (value: T) => void count: number data: T[] clear: () => void } export function createRingBuffer<T> (length: number): RingBuffer<T> { let pointer = 0 let count = 0 const buffer: T[] = [] return { has: function (value: any) { return buffer.indexOf(value) !== -1 }, get: function (idx: number) { return buffer[idx] }, push: function (item: any) { buffer[pointer] = item pointer = (length + pointer + 1) % length ++count }, get count () { return count }, get data () { return buffer.slice(0, Math.min(count, length)) }, clear: function () { count = 0 pointer = 0 buffer.length = 0 } } } export interface SimpleDict<K, V> { has: (k: K) => boolean add: (k: K, v: V) => void del: (k: K) => void values: V[] } export function createSimpleDict<K, V> (): SimpleDict<K, V> { const set: { [k: string]: V } = {} return { has: function (k: K) { return set[JSON.stringify(k)] !== undefined }, add: function (k: K, v: V) { set[JSON.stringify(k)] = v }, del: function (k: K) { delete set[JSON.stringify(k)] }, get values () { return Object.keys(set).map(k => set[k]) } } } export interface SimpleSet<T> { has: (value: T) => boolean add: (value: T) => void del: (value: T) => void list: T[] } export function createSimpleSet<T> (): SimpleSet<T> { const set: { [k: string]: T } = {} return { has: function (v: T) { return set[JSON.stringify(v)] !== undefined }, add: function (v: T) { set[JSON.stringify(v)] = v }, del: function (v: T) { delete set[JSON.stringify(v)] }, get list () { return Object.keys(set).map(k => set[k]) }, } }
the_stack
import { MockERC20Instance, MarginCalculatorInstance, MockAddressBookInstance, MockOracleInstance, MockOtokenInstance, } from '../../build/types/truffle-types' import { createVault, createTokenAmount } from '../utils' import { testCaseGenerator, Tests, Test, testToString, callMarginRequiredBeforeExpiry } from './testCaseGenerator' import BigNumber from 'bignumber.js' const { time } = require('@openzeppelin/test-helpers') const MockAddressBook = artifacts.require('MockAddressBook.sol') const MockOracle = artifacts.require('MockOracle.sol') const MockOtoken = artifacts.require('MockOtoken.sol') const MockERC20 = artifacts.require('MockERC20.sol') const MarginCalculator = artifacts.require('MarginCalculator.sol') contract('MarginCalculator Test Engine', () => { let expiry: number let calculator: MarginCalculatorInstance let addressBook: MockAddressBookInstance let oracle: MockOracleInstance let longOption: MockOtokenInstance let shortOption: MockOtokenInstance let usdc: MockERC20Instance let weth: MockERC20Instance const usdcDecimals = 6 const wethDecimals = 18 before('set up contracts', async () => { const now = (await time.latest()).toNumber() expiry = now + time.duration.days(30).toNumber() // initiate addressbook first. addressBook = await MockAddressBook.new() // setup oracle oracle = await MockOracle.new() // setup calculator calculator = await MarginCalculator.new(oracle.address) await addressBook.setOracle(oracle.address) // setup usdc and weth usdc = await MockERC20.new('USDC', 'USDC', usdcDecimals) weth = await MockERC20.new('WETH', 'WETH', wethDecimals) }) describe('Excess Margin Test', () => { let testPutsBeforeExpiry: Test[] let testPutsAfterExpiry: Test[] let testCallsBeforeExpiry: Test[] let testCallsAfterExpiry: Test[] before('generate all the tests', () => { const tests: Tests = testCaseGenerator() testPutsBeforeExpiry = tests.beforeExpiryPuts testPutsAfterExpiry = tests.afterExpiryPuts testCallsBeforeExpiry = tests.beforeExpiryCalls testCallsAfterExpiry = tests.afterExpiryCalls }) it('test the various excess margin scenarios for puts before expiry', async () => { const tests: Test[] = testPutsBeforeExpiry for (let i = 0; i < tests.length; i++) { const longStrike = tests[i].longStrike const shortStrike = tests[i].shortStrike const longAmount = tests[i].longAmount const shortAmount = tests[i].shortAmount const collateral = tests[i].collateral const expectedNetValue = tests[i].netValue const expectedIsExcess = tests[i].isExcess longOption = await MockOtoken.new() await longOption.init( addressBook.address, weth.address, usdc.address, usdc.address, createTokenAmount(longStrike), expiry, true, ) shortOption = await MockOtoken.new() await shortOption.init( addressBook.address, weth.address, usdc.address, usdc.address, createTokenAmount(shortStrike), expiry, true, ) // if the amount is zero, pass in an empty array const vaultShortAmount = shortAmount > 0 ? createTokenAmount(shortAmount) : undefined const vaultLongAmount = longAmount > 0 ? createTokenAmount(longAmount) : undefined const vaultCollateralAmount = collateral.gt(0) ? createTokenAmount(collateral, usdcDecimals) : undefined const shortAddress = shortAmount > 0 ? shortOption.address : undefined const longAddress = longAmount > 0 ? longOption.address : undefined const collateralAddress = collateral.gt(0) ? usdc.address : undefined // create the vault const vault = createVault( shortAddress, longAddress, collateralAddress, vaultShortAmount, vaultLongAmount, vaultCollateralAmount, ) // Check that the test passes, only fail if it doesn't const [netValue, isExcess] = await calculator.getExcessCollateral(vault, 0) assert.equal(netValue.toString(), createTokenAmount(expectedNetValue, usdcDecimals), testToString(tests[i])) assert.equal(isExcess, expectedIsExcess, testToString(tests[i])) } }) it('test the various excess margin scenarios for calls before expiry', async () => { const tests: Test[] = testCallsBeforeExpiry for (let i = 0; i < tests.length; i++) { const longStrike = tests[i].longStrike const shortStrike = tests[i].shortStrike const longAmount = tests[i].longAmount const shortAmount = tests[i].shortAmount const collateral = tests[i].collateral const expectedNetValue = new BigNumber(tests[i].netValue) const expectedIsExcess = tests[i].isExcess longOption = await MockOtoken.new() await longOption.init( addressBook.address, weth.address, usdc.address, weth.address, createTokenAmount(longStrike), expiry, false, ) shortOption = await MockOtoken.new() await shortOption.init( addressBook.address, weth.address, usdc.address, weth.address, createTokenAmount(shortStrike), expiry, false, ) const vaultWithCollateral = createVault( shortOption.address, longOption.address, weth.address, createTokenAmount(shortAmount), createTokenAmount(longAmount), createTokenAmount(collateral, wethDecimals), ) const [netValue, isExcess] = await calculator.getExcessCollateral(vaultWithCollateral, 0) assert.equal(netValue.toString(), createTokenAmount(expectedNetValue, wethDecimals), testToString(tests[i])) assert.equal(isExcess, expectedIsExcess, testToString(tests[i])) } }) it('test the various excess margin scenarios for puts after expiry', async () => { const tests: Test[] = testPutsAfterExpiry if ((await time.latest()) < expiry) { await time.increaseTo(expiry + 2) } for (let i = 0; i < tests.length; i++) { const longStrike = tests[i].longStrike const shortStrike = tests[i].shortStrike const longAmount = tests[i].longAmount const shortAmount = tests[i].shortAmount const collateral = tests[i].collateral const expectedNetValue = tests[i].netValue const expectedIsExcess = tests[i].isExcess const spotPrice = tests[i].oraclePrice // set the mock oracle price to have been finalized await oracle.setExpiryPriceFinalizedAllPeiodOver(weth.address, expiry, createTokenAmount(spotPrice), true) await oracle.setExpiryPriceFinalizedAllPeiodOver(usdc.address, expiry, createTokenAmount(1), true) longOption = await MockOtoken.new() await longOption.init( addressBook.address, weth.address, usdc.address, usdc.address, createTokenAmount(longStrike), expiry, true, ) shortOption = await MockOtoken.new() await shortOption.init( addressBook.address, weth.address, usdc.address, usdc.address, createTokenAmount(shortStrike), expiry, true, ) // if the amount is zero, pass in an empty array const vaultShortAmount = shortAmount > 0 ? createTokenAmount(shortAmount) : undefined const vaultLongAmount = longAmount > 0 ? createTokenAmount(longAmount) : undefined const vaultCollateralAmount = collateral.gt(0) ? createTokenAmount(collateral, usdcDecimals) : undefined const shortAddress = shortAmount > 0 ? shortOption.address : undefined const longAddress = longAmount > 0 ? longOption.address : undefined const collateralAddress = collateral.gt(0) ? usdc.address : undefined // create the vault const vault = createVault( shortAddress, longAddress, collateralAddress, vaultShortAmount, vaultLongAmount, vaultCollateralAmount, ) // Check that the test passes, only fail if it doesn't const [netValue, isExcess] = await calculator.getExcessCollateral(vault, 0) assert.equal(netValue.toString(), createTokenAmount(expectedNetValue, usdcDecimals), testToString(tests[i])) assert.equal(isExcess, expectedIsExcess, testToString(tests[i])) } }) it('test the various excess margin scenarios for calls after expiry', async () => { const tests: Test[] = testCallsAfterExpiry if ((await time.latest()) < expiry) { await time.increaseTo(expiry + 2) } for (let i = 0; i < tests.length; i++) { const longStrike = tests[i].longStrike const shortStrike = tests[i].shortStrike const longAmount = tests[i].longAmount const shortAmount = tests[i].shortAmount const collateral = tests[i].collateral const expectedNetValue = tests[i].netValue const expectedIsExcess = tests[i].isExcess const spotPrice = tests[i].oraclePrice // set the mock oracle price to have been finalized await oracle.setExpiryPriceFinalizedAllPeiodOver(weth.address, expiry, createTokenAmount(spotPrice), true) await oracle.setExpiryPriceFinalizedAllPeiodOver(usdc.address, expiry, createTokenAmount(1), true) longOption = await MockOtoken.new() await longOption.init( addressBook.address, weth.address, usdc.address, weth.address, createTokenAmount(longStrike), expiry, false, ) shortOption = await MockOtoken.new() await shortOption.init( addressBook.address, weth.address, usdc.address, weth.address, createTokenAmount(shortStrike), expiry, false, ) // if the amount is zero, pass in an empty array const vaultShortAmount = shortAmount > 0 ? createTokenAmount(shortAmount) : undefined const vaultLongAmount = longAmount > 0 ? createTokenAmount(longAmount) : undefined const vaultCollateralAmount = collateral.gt(0) ? createTokenAmount(collateral, wethDecimals) : undefined const shortAddress = shortAmount > 0 ? shortOption.address : undefined const longAddress = longAmount > 0 ? longOption.address : undefined const collateralAddress = collateral.gt(0) ? weth.address : undefined // create the vault const vault = createVault( shortAddress, longAddress, collateralAddress, vaultShortAmount, vaultLongAmount, vaultCollateralAmount, ) // Check that the test passes, only fail if it doesn't const [netValue, isExcess] = await calculator.getExcessCollateral(vault, 0) assert.equal(netValue.toString(), createTokenAmount(expectedNetValue, wethDecimals), testToString(tests[i])) assert.equal(isExcess, expectedIsExcess, testToString(tests[i])) } }) }) })
the_stack
interface JQuery { dimmer: SemanticUI.Dimmer; } declare namespace SemanticUI { interface Dimmer { settings: DimmerSettings; /** * Detaches a given element from DOM and reattaches element inside dimmer */ (behavior: 'add content', element: string | JQuery): JQuery; /** * Shows dimmer */ (behavior: 'show'): JQuery; /** * Hides dimmer */ (behavior: 'hide'): JQuery; /** * Toggles current dimmer visibility */ (behavior: 'toggle'): JQuery; /** * Changes dimmer opacity */ (behavior: 'set opacity', opacity: number): JQuery; /** * Creates a new dimmer in dimmable context */ (behavior: 'create'): JQuery; /** * Returns current duration for show or hide event depending on current visibility */ (behavior: 'get duration'): number; /** * Returns DOM element for dimmer */ (behavior: 'get dimmer'): JQuery; /** * Returns whether current dimmable has a dimmer */ (behavior: 'has dimmer'): boolean; /** * Whether section's dimmer is active */ (behavior: 'is active'): boolean; /** * Whether dimmer is animating */ (behavior: 'is animating'): boolean; /** * Whether current element is a dimmer */ (behavior: 'is dimmer'): boolean; /** * Whether current element is a dimmable section */ (behavior: 'is dimmable'): boolean; /** * Whether dimmer is disabled */ (behavior: 'is disabled'): boolean; /** * Whether dimmer is not disabled */ (behavior: 'is enabled'): boolean; /** * Whether dimmable section is body */ (behavior: 'is page'): boolean; /** * Whether dimmer is a page dimmer */ (behavior: 'is page dimmer'): boolean; /** * Sets page dimmer to active */ (behavior: 'set active'): JQuery; /** * Sets an element as a dimmable section */ (behavior: 'set dimmable'): JQuery; /** * Sets a dimmable section as dimmed */ (behavior: 'set dimmed'): JQuery; /** * Sets current dimmer as a page dimmer */ (behavior: 'set page dimmer'): JQuery; /** * Sets a dimmer as disabled */ (behavior: 'set disabled'): JQuery; (behavior: 'destroy'): JQuery; <K extends keyof DimmerSettings>(behavior: 'setting', name: K, value?: undefined): DimmerSettings._Impl[K]; <K extends keyof DimmerSettings>(behavior: 'setting', name: K, value: DimmerSettings._Impl[K]): JQuery; (behavior: 'setting', value: DimmerSettings): JQuery; (settings?: DimmerSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/dimmer.html#/settings} */ type DimmerSettings = DimmerSettings.Param; namespace DimmerSettings { type Param = (Pick<_Impl, 'opacity'> | Pick<_Impl, 'variation'> | Pick<_Impl, 'dimmerName'> | Pick<_Impl, 'closable'> | Pick<_Impl, 'on'> | Pick<_Impl, 'useCSS'> | Pick<_Impl, 'duration'> | Pick<_Impl, 'transition'> | Pick<_Impl, 'onShow'> | Pick<_Impl, 'onHide'> | Pick<_Impl, 'onChange'> | Pick<_Impl, 'selector'> | Pick<_Impl, 'template'> | Pick<_Impl, 'className'> | Pick<_Impl, 'error'> | Pick<_Impl, 'namespace'> | Pick<_Impl, 'name'> | Pick<_Impl, 'silent'> | Pick<_Impl, 'debug'> | Pick<_Impl, 'performance'> | Pick<_Impl, 'verbose'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { // region Behavior /** * Dimmers opacity from 0-1. Defaults to auto which uses the CSS specified opacity. * * @default 'auto' */ opacity: 'auto' | number; /** * Specify a variation to add when generating dimmer, like inverted * * @default false */ variation: false | string; /** * If initializing a dimmer on a dimmable context, you can use dimmerName to distinguish between multiple dimmers in that context. * * @default false */ dimmerName: false | string; /** * Whether clicking on the dimmer should hide the dimmer (Defaults to auto, closable only when settings.on is not hover * * @default 'auto' */ closable: 'auto' | boolean; /** * Can be set to hover or click to show/hide dimmer on dimmable event * * @default false */ on: false | 'hover' | 'click'; /** * Whether to dim dimmers using CSS transitions. * * @default true */ useCSS: boolean; /** * Animation duration of dimming. If an integer is used, that value will apply to both show and hide animations. */ duration: number | Dimmer.DurationSettings; /** * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions * * @default 'fade' * @see {@link http://semantic-ui.com/modules/transition.html} */ transition: string; // endregion // region Callbacks /** * Callback on element show */ onShow(this: JQuery): void; /** * Callback on element hide */ onHide(this: JQuery): void; /** * Callback on element show or hide */ onChange(this: JQuery): void; // endregion // region DOM Settings /** * Object containing selectors used by module. */ selector: Dimmer.SelectorSettings; /** * Templates used to generate dimmer content */ template: Dimmer.TemplateSettings; /** * Class names used to attach style to state */ className: Dimmer.ClassNameSettings; // endregion // region Debug Settings /** * Error messages displayed to console */ error: Dimmer.ErrorSettings; // endregion // region Component Settings // region DOM Settings /** * Event namespace. Makes sure module teardown does not effect other events attached to an element. */ namespace: string; // endregion // region Debug Settings /** * Name used in log statements */ name: string; /** * Silences all console output including error messages, regardless of other debug settings. */ silent: boolean; /** * Debug output to console */ debug: boolean; /** * Show console.table output with performance metrics */ performance: boolean; /** * Debug output includes all internal behaviors */ verbose: boolean; // endregion // endregion } } namespace Dimmer { type DurationSettings = DurationSettings.Param; namespace DurationSettings { type Param = (Pick<_Impl, 'show'> | Pick<_Impl, 'hide'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 500 */ show: number; /** * @default 500 */ hide: number; } } type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { type Param = (Pick<_Impl, 'dimmable'> | Pick<_Impl, 'dimmer'> | Pick<_Impl, 'content'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default '.dimmable' */ dimmable: string; /** * @default '.ui.dimmer' */ dimmer: string; /** * @default '.ui.dimmer > .content, .ui.dimmer > .content > .center' */ content: string; } } type TemplateSettings = TemplateSettings.Param; namespace TemplateSettings { type Param = (Pick<_Impl, 'dimmer'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { dimmer(): JQuery; } } type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { type Param = (Pick<_Impl, 'active'> | Pick<_Impl, 'dimmable'> | Pick<_Impl, 'dimmed'> | Pick<_Impl, 'disabled'> | Pick<_Impl, 'pageDimmer'> | Pick<_Impl, 'hide'> | Pick<_Impl, 'show'> | Pick<_Impl, 'transition'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'active' */ active: string; /** * @default 'dimmable' */ dimmable: string; /** * @default 'dimmed' */ dimmed: string; /** * @default 'disabled' */ disabled: string; /** * @default 'page' */ pageDimmer: string; /** * @default 'hide' */ hide: string; /** * @default 'show' */ show: string; /** * @default 'transition' */ transition: string; } } type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { type Param = (Pick<_Impl, 'method'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'The method you called is not defined.' */ method: string; } } } }
the_stack
import type { App } from 'vue'; import type { ComponentInternalInstance } from 'vue'; import type { ComputedRef } from '@vue/reactivity'; import { DateTimeOptions } from '@intlify/core-base'; import { FallbackLocale } from '@intlify/core-base'; import { DateTimeFormat as IntlDateTimeFormat } from '@intlify/core-base'; import { DateTimeFormats as IntlDateTimeFormats } from '@intlify/core-base'; import { FormatMatcher as IntlFormatMatcher } from '@intlify/core-base'; import { LocaleMatcher as IntlLocaleMatcher } from '@intlify/core-base'; import { NumberFormat as IntlNumberFormat } from '@intlify/core-base'; import { NumberFormats as IntlNumberFormats } from '@intlify/core-base'; import { LinkedModifiers } from '@intlify/core-base'; import { Locale } from '@intlify/core-base'; import { LocaleMessageArray } from '@intlify/core-base'; import { LocaleMessageDictionary } from '@intlify/core-base'; import { LocaleMessages } from '@intlify/core-base'; import { LocaleMessageValue } from '@intlify/core-base'; import { MessageFunction } from '@intlify/core-base'; import { MessageFunctions } from '@intlify/core-base'; import { NamedValue } from '@intlify/core-base'; import { NumberOptions } from '@intlify/core-base'; import type { ObjectDirective } from 'vue'; import { Path } from '@intlify/core-base'; import { PathValue } from '@intlify/core-base'; import { PluralizationRule } from '@intlify/core-base'; import type { PluralizationRules } from '@intlify/core-base'; import { PostTranslationHandler } from '@intlify/core-base'; import type { RenderFunction } from 'vue'; import type { SetupContext } from 'vue'; import { TranslateOptions } from '@intlify/core-base'; import type { VNode } from 'vue'; import type { WritableComputedRef } from '@vue/reactivity'; /** * BaseFormat Props for Components that is offered Vue I18n * * @remarks * The interface definitions of the underlying props of components such as Translation, DatetimeFormat, and NumberFormat. * * @VueI18nComponent */ export declare interface BaseFormatProps { /** * @remarks * Used to wrap the content that is distribute in the slot. If omitted, the slot content is treated as Fragments. * * You can specify a string-based tag name, such as `p`, or the object for which the component is defined. */ tag?: string | object; /** * @remarks * Specifies the locale to be used for the component. * * If specified, the global scope or the locale of the parent scope of the target component will not be overridden and the specified locale will be used. */ locale?: Locale; /** * @remarks * Specifies the scope to be used in the target component. * * You can specify either `global` or `parent`. * * If `global` is specified, global scope is used, else then `parent` is specified, the scope of the parent of the target component is used. * * If the parent is a global scope, the global scope is used, if it's a local scope, the local scope is used. */ scope?: ComponetI18nScope; /** * @remarks * A composer instance with an existing scope. * * This option takes precedence over the `scope` option. */ i18n?: Composer; } export declare type Choice = number; declare type ComponentInstanceCreatedListener = <Messages>(target: VueI18n<Messages>, global: VueI18n<Messages>) => void; export declare type ComponetI18nScope = Exclude<I18nScope, 'local'>; /** * Composer interfaces * * @remarks * This is the interface for being used for Vue 3 Composition API. * * @VueI18nComposition */ export declare interface Composer<Messages = {}, DateTimeFormats = {}, NumberFormats = {}, Message = VueMessageType> { /** * @remarks * Instance ID. */ id: number; /** * @remarks * The current locale this Composer instance is using. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ locale: WritableComputedRef<Locale>; /** * @remarks * The current fallback locales this Composer instance is using. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackLocale: WritableComputedRef<FallbackLocale>; /** * @remarks * Whether inherit the root level locale to the component localization locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) */ inheritLocale: boolean; /** * @remarks * The list of available locales in `messages` in lexical order. */ readonly availableLocales: Locale[]; /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) */ readonly messages: ComputedRef<Messages>; /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) */ readonly datetimeFormats: ComputedRef<DateTimeFormats>; /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) */ readonly numberFormats: ComputedRef<NumberFormats>; /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ readonly modifiers: LinkedModifiers<Message>; /** * @remarks * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) */ readonly pluralRules: PluralizationRules; /** * @remarks * Whether this composer instance is global or not */ readonly isGlobal: boolean; /** * @remarks * Whether suppress warnings outputted when localization fails. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ missingWarn: boolean | RegExp; /** * @remarks * Whether suppress fall back warnings when localization fails. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackWarn: boolean | RegExp; /** * @remarks * Whether to fall back to root level (global scope) localization when localization fails. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackRoot: boolean; /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackFormat: boolean; /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * If you set `false`, will check the locale messages on the Composer instance. * * If you are specified `true`, a warning will be output at console. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) */ warnHtmlMessage: boolean; /** * @remarks * Whether interpolation parameters are escaped before the message is translated. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) */ escapeParameter: boolean; /** * Locale message translation * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. * * If not, then it’s translated with global scope locale messages. * * @param key - A target locale message key * * @returns Translated message * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ t(key: Path | number): string; /** * Locale message translation for plurals * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, return a pluralized translation message. * * You can also suppress the warning, when the translation missing according to the options. * * About details of options, see the {@link TranslateOptions}. * * @param key - A target locale message key * @param plural - Which plural string to get. 1 returns the first one. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) */ t(key: Path | number, plural: number, options?: TranslateOptions): string; /** * Locale message translation for missing default message * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, if no translation was found, return a default message. * * You can also suppress the warning, when the translation missing according to the options. * * About details of options, see the {@link TranslateOptions}. * * @param key - A target locale message key * @param defaultMsg - A default message to return if no translation was found * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message */ t(key: Path | number, defaultMsg: string, options?: TranslateOptions): string; /** * Locale message translation for list interpolations * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list. * * You can also suppress the warning, when the translation missing according to the options. * * About details of options, see the {@link TranslateOptions}. * * @param key - A target locale message key * @param list - A values of list interpolation * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ t(key: Path | number, list: unknown[], options?: TranslateOptions): string; /** * Locale message translation for list interpolations and plurals * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list, and return a pluralized translation message. * * @param key - A target locale message key * @param list - A values of list interpolation * @param plural - Which plural string to get. 1 returns the first one. * * @returns Translated message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ t(key: Path | number, list: unknown[], plural: number): string; /** * Locale message translation for list interpolations and missing default message * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, the locale messages should contain a `{0}`, `{1}`, … for each placeholder in the list, and if no translation was found, return a default message. * * @param key - A target locale message key * @param list - A values of list interpolation * @param defaultMsg - A default message to return if no translation was found * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ t(key: Path | number, list: unknown[], defaultMsg: string): string; /** * Locale message translation for named interpolations * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token. * * You can also suppress the warning, when the translation missing according to the options. * * About details of options, see the {@link TranslateOptions}. * * @param key - A target locale message key * @param named - A values of named interpolation * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ t(key: Path | number, named: NamedValue, options?: TranslateOptions): string; /** * Locale message translation for named interpolations and plurals * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token, and return a pluralized translation message. * * @param key - A target locale message key * @param named - A values of named interpolation * @param plural - Which plural string to get. 1 returns the first one. * * @returns Translated message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ t(key: Path | number, named: NamedValue, plural: number): string; /** * Locale message translation for named interpolations and plurals * * @remarks * Overloaded `t`. About details, see the [t](composition#t-key) details. * * In this overloaded `t`, for each placeholder x, the locale messages should contain a `{x}` token, and if no translation was found, return a default message. * * @param key - A target locale message key * @param named - A values of named interpolation * @param defaultMsg - A default message to return if no translation was found * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ t(key: Path | number, named: NamedValue, defaultMsg: string): string; /* Excluded from this release type: t */ /** * Resolve locale message translation * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. * * If not, then it’s translated with global scope locale messages. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * * @returns Translated message * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ rt(message: MessageFunction<Message> | Message): string; /** * Resolve locale message translation for plurals * * @remarks * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. * * In this overloaded `rt`, return a pluralized translation message. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param plural - Which plural string to get. 1 returns the first one. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) */ rt(message: MessageFunction<Message> | Message, plural: number, options?: TranslateOptions): string; /** * Resolve locale message translation for list interpolations * * @remarks * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. * * In this overloaded `rt`, return a pluralized translation message. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param list - A values of list interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ rt(message: MessageFunction<Message> | Message, list: unknown[], options?: TranslateOptions): string; /** * Resolve locale message translation for named interpolations * * @remarks * Overloaded `rt`. About details, see the [rt](composition#rt-message) details. * * In this overloaded `rt`, for each placeholder x, the locale messages should contain a `{x}` token. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param named - A values of named interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ rt(message: MessageFunction<Message> | Message, named: NamedValue, options?: TranslateOptions): string; /* Excluded from this release type: rt */ /** * Datetime formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope datetime formats than global scope datetime formats. * * If not, then it’s formatted with global scope datetime formats. * * @param value - A value, timestamp number or `Date` instance or ISO 8601 string * * @returns Formatted value * * @VueI18nSee [Datetime formatting](../guide/essentials/datetime) */ d(value: number | Date | string): string; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](composition#d-value) details. * * In this overloaded `d`, format in datetime format for a key registered in datetime formats. * * @param value - A value, timestamp number or `Date` instance or ISO 8601 string * @param key - A key of datetime formats * * @returns Formatted value */ d(value: number | Date | string, key: string): string; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](composition#d-value) details. * * In this overloaded `d`, format in datetime format for a key registered in datetime formats at target locale * * @param value - A value, timestamp number or `Date` instance or ISO 8601 string * @param key - A key of datetime formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ d(value: number | Date | string, key: string, locale: Locale): string; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](composition#d-value) details. * * You can also suppress the warning, when the formatting missing according to the options. * * About details of options, see the {@link DateTimeOptions}. * * @param value - A value, timestamp number or `Date` instance or ISO 8601 string * @param options - Additional {@link DateTimeOptions | options} for datetime formatting * * @returns Formatted value */ d(value: number | Date | string, options: DateTimeOptions): string; /* Excluded from this release type: d */ /** * Number Formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope datetime formats than global scope datetime formats. * * If not, then it’s formatted with global scope number formats. * * @param value - A number value * * @returns Formatted value * * @VueI18nSee [Number formatting](../guide/essentials/number) */ n(value: number): string; /** * Number Formatting * * @remarks * Overloaded `n`. About details, see the [n](composition#n-value) details. * * In this overloaded `n`, format in number format for a key registered in number formats. * * @param value - A number value * @param key - A key of number formats * * @returns Formatted value */ n(value: number, key: string): string; /** * Number Formatting * * @remarks * Overloaded `n`. About details, see the [n](composition#n-value) details. * * In this overloaded `n`, format in number format for a key registered in number formats at target locale. * * @param value - A number value * @param key - A key of number formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ n(value: number, key: string, locale: Locale): string; /** * * Number Formatting * * @remarks * Overloaded `n`. About details, see the [n](composition#n-value) details. * * You can also suppress the warning, when the formatting missing according to the options. * * About details of options, see the {@link NumberOptions}. * * @param value - A number value * @param options - Additional {@link NumberOptions | options} for number formatting * * @returns Formatted value */ n(value: number, options: NumberOptions): string; /* Excluded from this release type: n */ /** * Translation locale message exist * * @remarks * whether do exist locale message on Composer instance [messages](composition#messages). * * If you specified `locale`, check the locale messages of `locale`. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope * * @returns If found locale message, `true`, else `false` */ te(key: Path, locale?: Locale): boolean; /** * Locale messages getter * * @remarks * If [UseI18nScope](general#usei18nscope) `'local'` or Some [UseI18nOptions](composition#usei18noptions) are specified at `useI18n`, it’s translated in preferentially local scope locale messages than global scope locale messages. * * Based on the current `locale`, locale messages will be returned from Composer instance messages. * * If you change the `locale`, the locale messages returned will also correspond to the locale. * * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with [fallbacking](../guide/essentials/fallback). * * @VueI18nWarning * You need to use `rt` for the locale message returned by `tm`. see the [rt](composition#rt-message) details. * * @example * template block: * ```html * <div class="container"> * <template v-for="content in tm('contents')"> * <h2>{{ rt(content.title) }}</h2> * <p v-for="paragraph in content.paragraphs"> * {{ rt(paragraph) }} * </p> * </template> * </div> * ``` * script block: * ```js * import { defineComponent } from 'vue * import { useI18n } from 'vue-i18n' * * export default defineComponent({ * setup() { * const { rt, tm } = useI18n({ * messages: { * en: { * contents: [ * { * title: 'Title1', * // ... * paragraphs: [ * // ... * ] * } * ] * } * } * // ... * }) * // ... * return { ... , rt, tm } * } * }) * ``` * * @param key - A target locale message key * * @return Locale messages */ tm(key: Path): LocaleMessageValue<Message> | {}; /** * Get locale message * * @remarks * get locale message from Composer instance [messages](composition#messages). * * @param locale - A target locale * * @returns Locale messages */ getLocaleMessage(locale: Locale): LocaleMessageDictionary<Message>; /** * Set locale message * * @remarks * Set locale message to Composer instance [messages](composition#messages). * * @param locale - A target locale * @param message - A message */ setLocaleMessage(locale: Locale, message: LocaleMessageDictionary<Message>): void; /** * Merge locale message * * @remarks * Merge locale message to Composer instance [messages](composition#messages). * * @param locale - A target locale * @param message - A message */ mergeLocaleMessage(locale: Locale, message: LocaleMessageDictionary<Message>): void; /** * Get datetime format * * @remarks * get datetime format from Composer instance [datetimeFormats](composition#datetimeformats). * * @param locale - A target locale * * @returns Datetime format */ getDateTimeFormat(locale: Locale): IntlDateTimeFormat; /** * Set datetime format * * @remarks * Set datetime format to Composer instance [datetimeFormats](composition#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ setDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; /** * Merge datetime format * * @remarks * Merge datetime format to Composer instance [datetimeFormats](composition#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ mergeDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; /** * Get number format * * @remarks * get number format from Composer instance [numberFormats](composition#numberFormats). * * @param locale - A target locale * * @returns Number format */ getNumberFormat(locale: Locale): IntlNumberFormat; /** * Set number format * * @remarks * Set number format to Composer instance [numberFormats](composition#numberFormats). * * @param locale - A target locale * @param format - A target number format */ setNumberFormat(locale: Locale, format: IntlNumberFormat): void; /** * Merge number format * * @remarks * Merge number format to Composer instance [numberFormats](composition#numberFormats). * * @param locale - A target locale * @param format - A target number format */ mergeNumberFormat(locale: Locale, format: IntlNumberFormat): void; /** * Get post translation handler * * @returns {@link PostTranslationHandler} * * @VueI18nSee [missing](composition#posttranslation) */ getPostTranslationHandler(): PostTranslationHandler<Message> | null; /** * Set post translation handler * * @param handler - A {@link PostTranslationHandler} * * @VueI18nSee [missing](composition#posttranslation) */ setPostTranslationHandler(handler: PostTranslationHandler<Message> | null): void; /** * Get missing handler * * @returns {@link MissingHandler} * * @VueI18nSee [missing](composition#missing) */ getMissingHandler(): MissingHandler | null; /** * Set missing handler * * @param handler - A {@link MissingHandler} * * @VueI18nSee [missing](composition#missing) */ setMissingHandler(handler: MissingHandler | null): void; } /** * Composer additional options for `useI18n` * * @remarks * `ComposerAdditionalOptions` is extend for {@link ComposerOptions}, so you can specify these options. * * @VueI18nSee [useI18n](composition#usei18n) * * @VueI18nComposition */ export declare interface ComposerAdditionalOptions { useScope?: I18nScope; } /** * Composer Options * * @remarks * This is options to create composer. * * @VueI18nComposition */ export declare interface ComposerOptions<Message = VueMessageType> { /** * @remarks * The locale of localization. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) * * @defaultValue `'en-US'` */ locale?: Locale; /** * @remarks * The locale of fallback localization. * * For more complex fallback definitions see fallback. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue The default `'en-US'` for the `locale` if it's not specified, or it's `locale` value */ fallbackLocale?: FallbackLocale; /** * @remarks * Whether inheritance the root level locale to the component localization locale. * * If `false`, regardless of the root level locale, localize for each component locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) * * @defaultValue `true` */ inheritLocale?: boolean; /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) * * @defaultValue `{}` */ messages?: LocaleMessages<Message>; /** * @remarks * Allow use flat json messages or not * * @defaultValue `false` */ flatJson?: boolean; /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) * * @defaultValue `{}` */ datetimeFormats?: IntlDateTimeFormats; /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) * * @defaultValue `{}` */ numberFormats?: IntlNumberFormats; /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ modifiers?: LinkedModifiers<Message>; /** * @remarks * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) * * @defaultValue `{}` */ pluralRules?: PluralizationRules; /** * @remarks * A handler for localization missing. * * The handler gets called with the localization target locale, localization path key, the Vue instance and values. * * If missing handler is assigned, and occurred localization missing, it's not warned. * * @defaultValue `null` */ missing?: MissingHandler; /** * @remarks * Whether suppress warnings outputted when localization fails. * * If `false`, suppress localization fail warnings. * * If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. `t`). * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `true` */ missingWarn?: boolean | RegExp; /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * If `false`, suppress fall back warnings. * * If you use regular expression, you can suppress fallback warnings that it match with translation key (e.g. `t`). * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `true` */ fallbackWarn?: boolean | RegExp; /** * @remarks * In the component localization, whether to fallback to root level (global scope) localization when localization fails. * * If `false`, it's not fallback to root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `true` */ fallbackRoot?: boolean; /** * @remarks * Whether do template interpolation on translation keys when your language lacks a translation for a key. * * If `true`, skip writing templates for your "base" language; the keys are your templates. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ fallbackFormat?: boolean; /** * @remarks * A handler for post processing of translation. * * The handler gets after being called with the `t`. * * This handler is useful if you want to filter on translated text such as space trimming. * * @defaultValue `null` */ postTranslation?: PostTranslationHandler<Message>; /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * See the warnHtmlMessage property. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) * * @defaultValue `'off'` */ warnHtmlMessage?: boolean; /** * @remarks * If `escapeParameter` is configured as true then interpolation parameters are escaped before the message is translated. * * This is useful when translation output is used in `v-html` and the translation resource contains html markup (e.g. <b> around a user provided value). * * This usage pattern mostly occurs when passing precomputed text strings into UI components. * * The escape process involves replacing the following symbols with their respective HTML character entities: `<`, `>`, `"`, `'`. * * Setting `escapeParameter` as true should not break existing functionality but provides a safeguard against a subtle type of XSS attack vectors. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * * @defaultValue `false` */ escapeParameter?: boolean; } /** * Vue I18n factory * * @param options - An options, see the {@link I18nOptions} * * @returns {@link I18n} instance * * @remarks * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. * * If you use composition API mode, you need to specify {@link ComposerOptions}. * * @VueI18nSee [Getting Started](../guide/) * @VueI18nSee [Composition API](../guide/advanced/composition) * * @example * case: for Legacy API * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * // ... * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @example * case: for composition API * ```js * import { createApp } from 'vue' * import { createI18n, useI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * legacy: false, // you must specify 'legacy: false' option * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * setup() { * // ... * const { t } = useI18n({ ... }) * return { ... , t } * } * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @VueI18nGeneral */ export declare function createI18n<Options extends I18nOptions = {}, Messages extends Record<keyof Options['messages'], LocaleMessageDictionary<VueMessageType>> = Record<keyof Options['messages'], LocaleMessageDictionary<VueMessageType>>, DateTimeFormats extends Record<keyof Options['datetimeFormats'], IntlDateTimeFormat> = Record<keyof Options['datetimeFormats'], IntlDateTimeFormat>, NumberFormats extends Record<keyof Options['numberFormats'], IntlNumberFormat> = Record<keyof Options['numberFormats'], IntlNumberFormat>>(options?: Options): I18n<Options['messages'], Options['datetimeFormats'], Options['numberFormats'], Options['legacy'] extends boolean ? Options['legacy'] : true>; export declare interface CustomBlock<Message = VueMessageType> { locale: Locale; resource: LocaleMessages<Message> | LocaleMessageDictionary<Message>; } export declare type CustomBlocks<Message = VueMessageType> = Array<CustomBlock<Message>>; /** * Datetime Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) * * @VueI18nComponent */ export declare const DatetimeFormat: { name: string; props: { value: { type: (NumberConstructor | DateConstructor)[]; required: boolean; }; format: { type: (ObjectConstructor | StringConstructor)[]; }; } & { tag: { type: (ObjectConstructor | StringConstructor)[]; }; locale: { type: StringConstructor; }; scope: { type: StringConstructor; validator: (val: "parent" | "global") => boolean; default: "parent" | "global"; }; i18n: { type: ObjectConstructor; }; }; setup(props: DatetimeFormatProps, context: SetupContext): RenderFunction; }; /** * DatetimeFormat Component Props * * @VueI18nComponent */ export declare type DatetimeFormatProps = FormattableProps<number | Date, Intl.DateTimeFormatOptions>; /** @VueI18nLegacy */ export declare type DateTimeFormatResult = string; export { DateTimeOptions } /** * Exported global composer instance * * @remarks * This interface is the [global composer](general#global) that is provided interface that is injected into each component with `app.config.globalProperties`. * * @VueI18nGeneral */ export declare interface ExportedGlobalComposer { /** * Locale * * @remarks * This property is proxy-like property for `Composer#locale`. About details, see the [Composer#locale](composition#locale) */ locale: Locale; /** * Fallback locale * * @remarks * This property is proxy-like property for `Composer#fallbackLocale`. About details, see the [Composer#fallbackLocale](composition#fallbacklocale) */ fallbackLocale: FallbackLocale; /** * Available locales * * @remarks * This property is proxy-like property for `Composer#availableLocales`. About details, see the [Composer#availableLocales](composition#availablelocales) */ readonly availableLocales: Locale[]; } export { FallbackLocale } /** * Formattable Props * * @remarks * The props used in DatetimeFormat, or NumberFormat component * * @VueI18nComponent */ export declare interface FormattableProps<Value, Format> extends BaseFormatProps { /** * @remarks * The value specified for the target component */ value: Value; /** * @remarks * The format to use in the target component. * * Specify the format key string or the format as defined by the Intl API in ECMA 402. */ format?: string | Format; } export declare interface Formatter { interpolate(message: string, values: any, path: string): Array<any> | null; } /** * I18n instance * * @remarks * The instance required for installation as the Vue plugin * * @VueI18nGeneral */ export declare interface I18n<Messages = {}, DateTimeFormats = {}, NumberFormats = {}, Legacy extends boolean = true> { /** * Vue I18n API mode * * @remarks * If you specified `legacy: true` option in `createI18n`, return `legacy`, else `composition` * * @defaultValue `'composition'` */ readonly mode: I18nMode; /** * The property accessible to the global Composer instance or VueI18n instance * * @remarks * If the [I18n#mode](general#mode) is `'legacy'`, then you can access to a global {@link VueI18n} instance, else then [I18n#mode](general#mode) is `'composition' `, you can access to the global {@link Composer} instance. * * An instance of this property is **global scope***. */ readonly global: Legacy extends true ? VueI18n<Messages, DateTimeFormats, NumberFormats> : Composer<Messages, DateTimeFormats, NumberFormats>; /** * Install entry point * * @param app - A target Vue app instance * @param options - An install options */ install(app: App, ...options: unknown[]): void; } /** * I18n Additional Options * * @remarks * Specific options for {@link createI18n} * * @VueI18nGeneral */ export declare interface I18nAdditionalOptions { /** * Whether vue-i18n Legacy API mode use on your Vue App * * @remarks * The default is to use the Legacy API mode. If you want to use the Composition API mode, you need to set it to `false`. * * @VueI18nSee [Composition API](../guide/advanced/composition) * * @defaultValue `true` */ legacy?: boolean; /** * Whether Whether to inject global properties & functions into for each component. * * @remarks * If set to `true`, then properties and methods prefixed with `$` are injected into Vue Component. * * @VueI18nSee [Implicit with injected properties and functions](../guide/advanced/composition#implicit-with-injected-properties-and-functions) * @VueI18nSee [ComponentCustomProperties](injection#componentcustomproperties) * * @defaultValue `false` */ globalInjection?: boolean; } /** * Vue I18n API mode * * @VueI18nSee [I18n#mode](general#mode) * * @VueI18nGeneral */ export declare type I18nMode = 'legacy' | 'composition'; /** * I18n Options for `createI18n` * * @remarks * `I18nOptions` is inherited {@link I18nAdditionalOptions}, {@link ComposerOptions} and {@link VueI18nOptions}, * so you can specify these options. * * @VueI18nGeneral */ export declare type I18nOptions = I18nAdditionalOptions & (ComposerOptions | VueI18nOptions); /** * Vue I18n plugin options * * @remarks * An options specified when installing Vue I18n as Vue plugin with using `app.use`. * * @VueI18nGeneral */ export declare interface I18nPluginOptions { /** * Whether to use the tag name `i18n` for Translation Component * * @remarks * This option is used for compatibility with Vue I18n v8.x. * * If you can't migrate right away, you can temporarily enable this option, and you can work Translation Component. * * @defaultValue `false` */ useI18nComponentName?: boolean; /** * Whether to globally install the components that is offered by Vue I18n * * @remarks * If this option is enabled, the components will be installed globally at `app.use` time. * * If you want to install manually in the `import` syntax, you can set it to `false` to install when needed. * * @defaultValue `true` */ globalInstall?: boolean; } /** * I18n Scope * * @VueI18nSee [ComposerAdditionalOptions#useScope](composition#usescope) * @VueI18nSee [useI18n](composition#usei18n) * * @VueI18nGeneral */ export declare type I18nScope = 'local' | 'parent' | 'global'; export { IntlDateTimeFormat } export { IntlDateTimeFormats } export { IntlFormatMatcher } export { IntlLocaleMatcher } export { IntlNumberFormat } export { IntlNumberFormats } export { LinkedModifiers } export { Locale } export { LocaleMessageArray } export { LocaleMessageDictionary } /** @VueI18nLegacy */ export declare type LocaleMessageObject<Message = string> = LocaleMessageDictionary<Message>; export { LocaleMessages } export { LocaleMessageValue } export { MessageFunction } export { MessageFunctions } /** @VueI18nComposition */ export declare type MissingHandler = (locale: Locale, key: Path, insttance?: ComponentInternalInstance, type?: string) => string | void; export { NamedValue } /** * Number Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) * * @VueI18nComponent */ export declare const NumberFormat: { name: string; props: { value: { type: NumberConstructor; required: boolean; }; format: { type: (ObjectConstructor | StringConstructor)[]; }; } & { tag: { type: (ObjectConstructor | StringConstructor)[]; }; locale: { type: StringConstructor; }; scope: { type: StringConstructor; validator: (val: "parent" | "global") => boolean; default: "parent" | "global"; }; i18n: { type: ObjectConstructor; }; }; setup(props: NumberFormatProps, context: SetupContext): RenderFunction; }; /** * NumberFormat Component Props * * @VueI18nComponent */ export declare type NumberFormatProps = FormattableProps<number, Intl.NumberFormatOptions>; /** @VueI18nLegacy */ export declare type NumberFormatResult = string; export { NumberOptions } export { Path } export { PathValue } export { PluralizationRule } export declare type PluralizationRulesMap = { [locale: string]: PluralizationRule; }; export { PostTranslationHandler } export { TranslateOptions } /** @VueI18nLegacy */ export declare type TranslateResult = string; /** * Translation Component * * @remarks * See the following items for property about details * * @VueI18nSee [TranslationProps](component#translationprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Component Interpolation](../guide/advanced/component) * * @example * ```html * <div id="app"> * <!-- ... --> * <i18n path="term" tag="label" for="tos"> * <a :href="url" target="_blank">{{ $t('tos') }}</a> * </i18n> * <!-- ... --> * </div> * ``` * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * const messages = { * en: { * tos: 'Term of Service', * term: 'I accept xxx {0}.' * }, * ja: { * tos: '利用規約', * term: '私は xxx の{0}に同意します。' * } * } * * const i18n = createI18n({ * locale: 'en', * messages * }) * * const app = createApp({ * data: { * url: '/term' * } * }).use(i18n).mount('#app') * ``` * * @VueI18nComponent */ export declare const Translation: { name: string; props: { keypath: { type: StringConstructor; required: boolean; }; plural: { type: (StringConstructor | NumberConstructor)[]; validator: (val: any) => boolean; }; } & { tag: { type: (ObjectConstructor | StringConstructor)[]; }; locale: { type: StringConstructor; }; scope: { type: StringConstructor; validator: (val: "parent" | "global") => boolean; default: "parent" | "global"; }; i18n: { type: ObjectConstructor; }; }; setup(props: TranslationProps, context: SetupContext): RenderFunction; }; /** * Translation Directive (`v-t`) * * @remarks * Update the element `textContent` that localized with locale messages. * * You can use string syntax or object syntax. * * String syntax can be specified as a keypath of locale messages. * * If you can be used object syntax, you need to specify as the object key the following params * * ``` * - path: required, key of locale messages * - locale: optional, locale * - args: optional, for list or named formatting * ``` * * @example * ```html * <!-- string syntax: literal --> * <p v-t="'foo.bar'"></p> * * <!-- string syntax: binding via data or computed props --> * <p v-t="msg"></p> * * <!-- object syntax: literal --> * <p v-t="{ path: 'hi', locale: 'ja', args: { name: 'kazupon' } }"></p> * * <!-- object syntax: binding via data or computed props --> * <p v-t="{ path: greeting, args: { name: fullName } }"></p> * ``` * * @VueI18nDirective */ export declare type TranslationDirective<T = HTMLElement> = ObjectDirective<T>; /** * Translation Component Props * * @VueI18nComponent */ export declare interface TranslationProps extends BaseFormatProps { /** * @remarks * The locale message key can be specified prop */ keypath: string; /** * @remarks * The Plural Choosing the message number prop */ plural?: number | string; } /** * Use Composition API for Vue I18n * * @param options - An options, see {@link UseI18nOptions} * * @returns {@link Composer} instance * * @remarks * This function is mainly used by `setup`. * * If options are specified, Composer instance is created for each component and you can be localized on the component. * * If options are not specified, you can be localized using the global Composer. * * @example * case: Component resource base localization * ```html * <template> * <form> * <label>{{ t('language') }}</label> * <select v-model="locale"> * <option value="en">en</option> * <option value="ja">ja</option> * </select> * </form> * <p>message: {{ t('hello') }}</p> * </template> * * <script> * import { useI18n } from 'vue-i18n' * * export default { * setup() { * const { t, locale } = useI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * // Something to do ... * * return { ..., t, locale } * } * } * </script> * ``` * * @VueI18nComposition */ export declare function useI18n<Options extends UseI18nOptions = object, Messages extends Record<keyof Options['messages'], LocaleMessageDictionary<VueMessageType>> = Record<keyof Options['messages'], LocaleMessageDictionary<VueMessageType>>, DateTimeFormats extends Record<keyof Options['datetimeFormats'], IntlDateTimeFormat> = Record<keyof Options['datetimeFormats'], IntlDateTimeFormat>, NumberFormats extends Record<keyof Options['numberFormats'], IntlNumberFormat> = Record<keyof Options['numberFormats'], IntlNumberFormat>>(options?: Options): Composer<Options['messages'], Options['datetimeFormats'], Options['numberFormats']>; /** * I18n Options for `useI18n` * * @remarks * `UseI18nOptions` is inherited {@link ComposerAdditionalOptions} and {@link ComposerOptions}, so you can specify these options. * * @VueI18nSee [useI18n](composition#usei18n) * * @VueI18nComposition */ export declare type UseI18nOptions = ComposerAdditionalOptions & ComposerOptions; /** * Vue I18n Version * * @remarks * Semver format. Same format as the package.json `version` field. * * @VueI18nGeneral */ export declare const VERSION: string; export declare function vTDirective<Messages, DateTimeFormats, NumberFormats, Legacy extends boolean>(i18n: I18n<Messages, DateTimeFormats, NumberFormats, Legacy>): TranslationDirective<HTMLElement>; /** * VueI18n legacy interfaces * * @remarks * This interface is compatible with interface of `VueI18n` class (offered with Vue I18n v8.x). * * @VueI18nLegacy */ export declare interface VueI18n<Messages = {}, DateTimeFormats = {}, NumberFormats = {}> { /** * @remarks * Instance ID. */ id: number; /** * @remarks * The current locale this VueI18n instance is using. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ locale: Locale; /** * @remarks * The current fallback locales this VueI18n instance is using. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackLocale: FallbackLocale; /** * @remarks * The list of available locales in `messages` in lexical order. */ readonly availableLocales: Locale[]; /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) */ readonly messages: Messages; /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) */ readonly datetimeFormats: DateTimeFormats; /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) */ readonly numberFormats: NumberFormats; /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ readonly modifiers: LinkedModifiers<VueMessageType>; /** * @remarks * The formatter that implemented with Formatter interface. * * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) */ formatter: Formatter; /** * @remarks * A handler for localization missing. */ missing: MissingHandler | null; /** * @remarks * A handler for post processing of translation. */ postTranslation: PostTranslationHandler<VueMessageType> | null; /** * @remarks * Whether suppress warnings outputted when localization fails. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ silentTranslationWarn: boolean | RegExp; /** * @remarks * Whether suppress fallback warnings when localization fails. */ silentFallbackWarn: boolean | RegExp; /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ formatFallbackMessages: boolean; /** * @remarks * Whether synchronize the root level locale to the component localization locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) */ sync: boolean; /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * If you set `warn` or` error`, will check the locale messages on the VueI18n instance. * * If you are specified `warn`, a warning will be output at console. * * If you are specified `error` will occurred an Error. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) */ warnHtmlInMessage: WarnHtmlInMessageLevel; /** * @remarks * Whether interpolation parameters are escaped before the message is translated. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) */ escapeParameterHtml: boolean; /** * @remarks * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. * * @VueI18nSee [Custom Directive](../guide/advanced/directive) * @VueI18nSee [Remove preserveDirectiveContent option](../guide/migration/breaking#remove-preservedirectivecontent-option) * * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. */ preserveDirectiveContent: boolean; /** * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) */ pluralizationRules: PluralizationRules; /** * Locale message translation. * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s translated in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s translated with global scope locale messages. * * @param key - A target locale message key * * @returns Translated message * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ t(key: Path): TranslateResult; /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [t](legacy#t-key) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Translated message */ t(key: Path, locale: Locale): TranslateResult; /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [t](legacy#t-key) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * @param list - A values of list interpolation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ t(key: Path, locale: Locale, list: unknown[]): TranslateResult; /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [t](legacy#t-key) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * @param named - A values of named interpolation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ t(key: Path, locale: Locale, named: object): TranslateResult; /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [t](legacy#t-key) details. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ t(key: Path, list: unknown[]): TranslateResult; /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [t](legacy#t-key) details. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ t(key: Path, named: Record<string, unknown>): TranslateResult; /* Excluded from this release type: t */ /** * Resolve locale message translation * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * * @returns Translated message * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ rt(message: MessageFunction<VueMessageType> | VueMessageType): string; /** * Resolve locale message translation for plurals * * @remarks * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. * * In this overloaded `rt`, return a pluralized translation message. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param plural - Which plural string to get. 1 returns the first one. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) */ rt(message: MessageFunction<VueMessageType> | VueMessageType, plural: number, options?: TranslateOptions): string; /** * Resolve locale message translation for list interpolations * * @remarks * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. * * In this overloaded `rt`, return a pluralized translation message. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param list - A values of list interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ rt(message: MessageFunction<VueMessageType> | VueMessageType, list: unknown[], options?: TranslateOptions): string; /** * Resolve locale message translation for named interpolations * * @remarks * Overloaded `rt`. About details, see the [rt](legacy#rt-message) details. * * In this overloaded `rt`, for each placeholder x, the locale messages should contain a `{x}` token. * * @VueI18nTip * The use-case for `rt` is for programmatic locale messages translation with using `tm`, `v-for`, javascript `for` statement. * * @VueI18nWarning * `rt` differs from `t` in that it processes the locale message directly, not the key of the locale message. There is no internal fallback with `rt`. You need to understand and use the structure of the locale messge returned by `tm`. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `tm`. * @param named - A values of named interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ rt(message: MessageFunction<VueMessageType> | VueMessageType, named: NamedValue, options?: TranslateOptions): string; /* Excluded from this release type: rt */ /** * Locale message pluralization * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s pluraled in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s pluraled with global scope locale messages. * * The plural choice number is handled with default `1`. * * @param key - A target locale message key * * @returns Pluraled message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) */ tc(key: Path): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Pluraled message */ tc(key: Path, locale: Locale): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns Pluraled message */ tc(key: Path, list: unknown[]): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns Pluraled message */ tc(key: Path, named: Record<string, unknown>): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * * @returns Pluraled message */ tc(key: Path, choice: number): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Pluraled message */ tc(key: Path, choice: number, locale: Locale): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param list - A values of list interpolation * * @returns Pluraled message */ tc(key: Path, choice: number, list: unknown[]): TranslateResult; /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [tc](legacy#tc-key) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param named - A values of named interpolation * * @returns Pluraled message */ tc(key: Path, choice: number, named: Record<string, unknown>): TranslateResult; /* Excluded from this release type: tc */ /** * Translation locale message exist * * @remarks * whether do exist locale message on VueI18n instance [messages](legacy#messages). * * If you specified `locale`, check the locale messages of `locale`. * * @param key - A target locale message key * @param locale - A target locale * * @returns If found locale message, `true`, else `false` */ te(key: Path, locale?: Locale): boolean; /** * Locale messages getter * * @remarks * If [i18n component options](injection#i18n) is specified, it’s get in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s get with global scope locale messages. * * Based on the current `locale`, locale messages will be returned from Composer instance messages. * * If you change the `locale`, the locale messages returned will also correspond to the locale. * * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with [fallbacking](../guide/essentials/fallback). * * @VueI18nWarning * You need to use `rt` for the locale message returned by `tm`. see the [rt](legacy#rt-message) details. * * @example * template: * ```html * <div class="container"> * <template v-for="content in $tm('contents')"> * <h2>{{ $rt(content.title) }}</h2> * <p v-for="paragraph in content.paragraphs"> * {{ $rt(paragraph) }} * </p> * </template> * </div> * ``` * * ```js * import { createI18n } from 'vue-i18n' * * const i18n = createI18n({ * messages: { * en: { * contents: [ * { * title: 'Title1', * // ... * paragraphs: [ * // ... * ] * } * ] * } * } * // ... * }) * ``` * @param key - A target locale message key * * @return Locale messages */ tm(key: Path): LocaleMessageValue<VueMessageType> | {}; /** * Get locale message * * @remarks * get locale message from VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * * @returns Locale messages */ getLocaleMessage(locale: Locale): LocaleMessageDictionary<VueMessageType>; /** * Set locale message * * @remarks * Set locale message to VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * @param message - A message */ setLocaleMessage(locale: Locale, message: LocaleMessageDictionary<VueMessageType>): void; /** * Merge locale message * * @remarks * Merge locale message to VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * @param message - A message */ mergeLocaleMessage(locale: Locale, message: LocaleMessageDictionary<VueMessageType>): void; /** * Datetime formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope datetime formats than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope datetime formats. * * @param value - A value, timestamp number or `Date` instance * * @returns Formatted value * * @VueI18nSee [Datetime formatting](../guide/essentials/datetime) */ d(value: number | Date): DateTimeFormatResult; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](legacy#d-value) details. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * * @returns Formatted value */ d(value: number | Date, key: string): DateTimeFormatResult; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](legacy#d-value) details. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ d(value: number | Date, key: string, locale: Locale): DateTimeFormatResult; /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [d](legacy#d-value) details. * * @param value - A value, timestamp number or `Date` instance * @param args - An argument values * * @returns Formatted value */ d(value: number | Date, args: { [key: string]: string; }): DateTimeFormatResult; /* Excluded from this release type: d */ /** * Get datetime format * * @remarks * get datetime format from VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * * @returns Datetime format */ getDateTimeFormat(locale: Locale): IntlDateTimeFormat; /** * Set datetime format * * @remarks * Set datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ setDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; /** * Merge datetime format * * @remarks * Merge datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ mergeDateTimeFormat(locale: Locale, format: IntlDateTimeFormat): void; /** * Number formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope number formats than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope number formats. * * @param value - A number value * * @returns Formatted value * * @VueI18nSee [Number formatting](../guide/essentials/number) */ n(value: number): NumberFormatResult; /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [n](legacy#n-value) details. * * @param value - A number value @param key - A key of number formats * * @returns Formatted value */ n(value: number, key: string): NumberFormatResult; /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [n](legacy#n-value) details. * * @param value - A number value * @param key - A key of number formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ n(value: number, key: string, locale: Locale): NumberFormatResult; /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [n](legacy#n-value) details. * * @param value - A number value * @param args - An argument values * * @returns Formatted value */ n(value: number, args: { [key: string]: string; }): NumberFormatResult; /* Excluded from this release type: n */ /** * Get number format * * @remarks * get number format from VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * * @returns Number format */ getNumberFormat(locale: Locale): IntlNumberFormat; /** * Set number format * * @remarks * Set number format to VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * @param format - A target number format */ setNumberFormat(locale: Locale, format: IntlNumberFormat): void; /** * Merge number format * * @remarks * Merge number format to VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * @param format - A target number format */ mergeNumberFormat(locale: Locale, format: IntlNumberFormat): void; /** * Get choice index * * @remarks * Get pluralization index for current pluralizing number and a given amount of choices. * * @deprecated Use `pluralizationRules` option instead of `getChoiceIndex`. */ getChoiceIndex: (choice: Choice, choicesLength: number) => number; } /** * VueI18n Options * * @remarks * This option is compatible with `VueI18n` class constructor options (offered with Vue I18n v8.x) * * @VueI18nLegacy */ export declare interface VueI18nOptions { /** * @remarks * The locale of localization. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) * * @defaultValue `'en-US'` */ locale?: Locale; /** * @remarks * The locale of fallback localization. * * For more complex fallback definitions see fallback. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue The default `'en-US'` for the `locale` if it's not specified, or it's `locale` value */ fallbackLocale?: FallbackLocale; /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) * * @defaultValue `{}` */ messages?: LocaleMessages<VueMessageType>; /** * @remarks * Allow use flat json messages or not * * @defaultValue `false` */ flatJson?: boolean; /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) * * @defaultValue `{}` */ datetimeFormats?: IntlDateTimeFormats; /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) * * @defaultValue `{}` */ numberFormats?: IntlNumberFormats; /** * @remarks * The list of available locales in messages in lexical order. * * @defaultValue `[]` */ availableLocales?: Locale[]; /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ modifiers?: LinkedModifiers<VueMessageType>; /** * @remarks * The formatter that implemented with Formatter interface. * * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) */ formatter?: Formatter; /** * @remarks * A handler for localization missing. * * The handler gets called with the localization target locale, localization path key, the Vue instance and values. * * If missing handler is assigned, and occurred localization missing, it's not warned. * * @defaultValue `null` */ missing?: MissingHandler; /** * @remarks * In the component localization, whether to fall back to root level (global scope) localization when localization fails. * * If `false`, it's not fallback to root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `true` */ fallbackRoot?: boolean; /** * @remarks * Whether suppress warnings outputted when localization fails. * * If `true`, suppress localization fail warnings. * * If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. `t`). * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ silentTranslationWarn?: boolean | RegExp; /** * @remarks * Whether do template interpolation on translation keys when your language lacks a translation for a key. * * If `true`, skip writing templates for your "base" language; the keys are your templates. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ silentFallbackWarn?: boolean | RegExp; /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ formatFallbackMessages?: boolean; /** * @remarks * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. * * @VueI18nSee [Custom Directive](../guide/advanced/directive) * @VueI18nSee [Remove `preserveDirectiveContent` option](../guide/migration/breaking#remove-preservedirectivecontent-option) * * @defaultValue `false` * * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. */ preserveDirectiveContent?: boolean; /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * See the warnHtmlInMessage property. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) * * @defaultValue `'off'` */ warnHtmlInMessage?: WarnHtmlInMessageLevel; /** * @remarks * If `escapeParameterHtml` is configured as true then interpolation parameters are escaped before the message is translated. * * This is useful when translation output is used in `v-html` and the translation resource contains html markup (e.g. <b> around a user provided value). * * This usage pattern mostly occurs when passing precomputed text strings into UI components. * * The escape process involves replacing the following symbols with their respective HTML character entities: `<`, `>`, `"`, `'`. * * Setting `escapeParameterHtml` as true should not break existing functionality but provides a safeguard against a subtle type of XSS attack vectors. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * * @defaultValue `false` */ escapeParameterHtml?: boolean; /** * @remarks * The shared locale messages of localization for components. More detail see Component based localization. * * @VueI18nSee [Shared locale messages for components](../guide/essentials/local#shared-locale-messages-for-components) * * @defaultValue `undefined` */ sharedMessages?: LocaleMessages<VueMessageType>; /** * @remarks * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) * * @defaultValue `{}` */ pluralizationRules?: PluralizationRules; /** * @remarks * A handler for post processing of translation. The handler gets after being called with the `$t`, `t`, `$tc`, and `tc`. * * This handler is useful if you want to filter on translated text such as space trimming. * * @defaultValue `null` */ postTranslation?: PostTranslationHandler<VueMessageType>; /** * @remarks * Whether synchronize the root level locale to the component localization locale. * * If `false`, regardless of the root level locale, localize for each component locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) * * @defaultValue `true` */ sync?: boolean; /** * @remarks * A handler for getting notified when component-local instance was created. * * The handler gets called with new and old (root) VueI18n instances. * * This handler is useful when extending the root VueI18n instance and wanting to also apply those extensions to component-local instance. * * @defaultValue `null` */ componentInstanceCreatedListener?: ComponentInstanceCreatedListener; } /** @VueI18nComposition */ export declare type VueMessageType = string | VNode; export declare type WarnHtmlInMessageLevel = 'off' | 'warn' | 'error'; export { } declare module '@vue/runtime-core' { /** * Component Custom Options for Vue I18n * * @VueI18nInjection */ export interface ComponentCustomOptions { /** * VueI18n options * * @remarks * See the {@link VueI18nOptions} */ i18n?: VueI18nOptions /** * For custom blocks options * @internal */ __i18n?: CustomBlocks /** * For devtools * @internal */ __INTLIFY_META__?: string } /** * Component Custom Properties for Vue I18n * * @VueI18nInjection */ export interface ComponentCustomProperties { /** * Exported Global Composer instance, or global VueI18n instance. * * @remarks * You can get the {@link ExportedGlobalComposer | exported composer instance} which are exported from global {@link Composer | composer instance} created with {@link createI18n}, or global {@link VueI18n | VueI18n instance}. * You can get the exported composer instance in {@link I18nMode | Composition API mode}, or the Vuei18n instance in {@link I18nMode | Legacy API mode}, which is the instance you can refer to with this property. * The locales, locale messages, and other resources managed by the instance referenced by this property are valid as global scope. * If the `i18n` component custom option is not specified, it's the same as the VueI18n instance that can be referenced by the i18n instance {@link I18n.global | global} property. */ $i18n: VueI18n | ExportedGlobalComposer /** * Locale message translation * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#t | `VueI18n#t`}. * * In {@link I18nMode | Composition API mode}, the `$t` is injected by `app.config.globalProperties`. * the input / output is the same as for Composer, and it work on **global scope**. About that details, see {@link Composer#t | `Composer#t` }. * * @param key - A target locale message key * * @returns translation message */ $t(key: Path): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param locale - A locale, override locale that global scope or local scope * * @returns translation message */ $t(key: Path, locale: Locale): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param locale - A locale, override locale that global scope or local scope * @param list - A values of list interpolation * * @returns translation message */ $t(key: Path, locale: Locale, list: unknown[]): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param locale - A locale, override locale that global scope or local scope * @param named - A values of named interpolation * * @returns translation message */ $t(key: Path, locale: Locale, named: object): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns translation message */ $t(key: Path, list: unknown[]): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns translation message */ $t(key: Path, named: Record<string, unknown>): TranslateResult /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * * @returns translation message */ $t(key: Path): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param plural - A choice number of plural * * @returns translation message */ $t(key: Path, plural: number): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param plural - Which plural string to get. 1 returns the first one. * @param options - An options, see the {@link TranslateOptions} * * @returns translation message */ $t(key: Path, plural: number, options: TranslateOptions): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param defaultMsg - A default message to return if no translation was found * * @returns translation message */ $t(key: Path, defaultMsg: string): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param defaultMsg - A default message to return if no translation was found * @param options - An options, see the {@link TranslateOptions} * * @returns translation message */ $t(key: Path, defaultMsg: string, options: TranslateOptions): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns translation message */ $t(key: Path, list: unknown[]): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param list - A values of list interpolation * @param plural - A choice number of plural * * @returns translation message */ $t(key: Path, list: unknown[], plural: number): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param list - A values of list interpolation * @param defaultMsg - A default message to return if no translation was found * * @returns translation message */ $t(key: Path, list: unknown[], defaultMsg: string): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param list - A values of list interpolation * @param options - An options, see the {@link TranslateOptions} * * @returns translation message */ $t(key: Path, list: unknown[], options: TranslateOptions): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns translation message */ $t(key: Path, named: NamedValue): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param named - A values of named interpolation * @param plural - A choice number of plural * * @returns translation message */ $t(key: Path, named: NamedValue, plural: number): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param named - A values of named interpolation * @param defaultMsg - A default message to return if no translation was found * * @returns translation message */ $t(key: Path, named: NamedValue, defaultMsg: string): string /** * Locale message translation * * @remarks * Overloaded `$t`. About details, see the {@link $t} remarks. * * @param key - A target locale message key * @param named - A values of named interpolation * @param options - An options, see the {@link TranslateOptions} * * @returns translation message */ $t(key: Path, named: NamedValue, options: TranslateOptions): string /** * Resolve locale message translation * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#rt | `VueI18n#rt`}. * * In {@link I18nMode | Composition API mode}, the `$rt` is injected by `app.config.globalProperties`. * the input / output is the same as for Composer, and it work on **global scope**. About that details, see {@link Composer#rt | `Composer#rt` }. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. * * @returns translated message */ $rt(message: MessageFunction<VueMessageType> | VueMessageType): string /** * Resolve locale message translation for plurals * * @remarks * Overloaded `$rt`. About details, see the {@link $rt} remarks. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. * @param plural - Which plural string to get. 1 returns the first one. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message */ $rt( message: MessageFunction<VueMessageType> | VueMessageType, plural: number, options?: TranslateOptions ): string /** * Resolve locale message translation for list interpolations * * @remarks * Overloaded `$rt`. About details, see the {@link $rt} remarks. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. * @param list - A values of list interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message */ $rt( message: MessageFunction<VueMessageType> | VueMessageType, list: unknown[], options?: TranslateOptions ): string /** * Resolve locale message translation for named interpolations * * @remarks * Overloaded `$rt`. About details, see the {@link $rt} remarks. * * @param message - A target locale message to be resolved. You will need to specify the locale message returned by `$tm`. * @param named - A values of named interpolation. * @param options - Additional {@link TranslateOptions | options} for translation * * @returns Translated message */ $rt( message: MessageFunction<VueMessageType> | VueMessageType, named: NamedValue, options?: TranslateOptions ): string /** * Locale message pluralization * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * The input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#tc | `VueI18n#tc` }. * The value of plural is handled with default `1`. * Supported for Legacy API mode only. * * @param key - A target locale message key * * @returns translation message that is pluraled */ $tc(key: Path): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param locale - A locale, override locale that global scope or local scope * * @returns translation message that is pluraled */ $tc(key: Path, locale: Locale): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns translation message that is pluraled */ $tc(key: Path, list: unknown[]): TranslateResult /** * Locale message pluralization * Supported for Legacy API mode only. * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns translation message that is pluraled */ $tc(key: Path, named: Record<string, unknown>): TranslateResult /** * Locale message pluralization * Supported for Legacy API mode only. * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * * @returns translation message that is pluraled */ $tc(key: Path, choice: number): TranslateResult /** * Locale message pluralization * Supported for Legacy API mode only. * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param locale - A locale, override locale that global scope or local scope * * @returns translation message that is pluraled */ $tc(key: Path, choice: number, locale: Locale): TranslateResult /** * Locale message pluralization * Supported for Legacy API mode only. * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param list - A values of list interpolation * * @returns translation message that is pluraled */ $tc(key: Path, choice: number, list: unknown[]): TranslateResult /** * Locale message pluralization * Supported for Legacy API mode only. * * @remarks * Overloaded `$tc`. About details, see the {@link $tc} remarks. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param named - A values of named interpolation * * @returns translation message that is pluraled */ $tc( key: Path, choice: number, named: Record<string, unknown> ): TranslateResult /** * Translation message exist * * @remarks * The input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#te | `VueI18n.#te` }. * Supported for Legacy API mode only. * * @param key - A target locale message key * @param locale - A locale, optional, override locale that global scope or local scope * * @returns if found locale message, `true`, else `false` */ $te(key: Path, locale?: Locale): boolean /** * Datetime formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#d | `VueI18n#d` }. * * In {@link I18nMode | Composition API mode}, the `$d` is injected by `app.config.globalProperties`. * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#d | `Composer#d` }. * * @param value - A value, timestamp number or `Date` instance * * @returns formatted value */ $d(value: number | Date): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * * @returns formatted value */ $d(value: number | Date, key: string): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * @param locale - A locale, optional, override locale that global scope or local scope * * @returns formatted value */ $d(value: number | Date, key: string, locale: Locale): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param args - An argument values * * @returns formatted value */ $d( value: number | Date, args: { [key: string]: string } ): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * * @returns formatted value */ $d(value: number | Date): string /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * * @returns formatted value */ $d(value: number | Date, key: string): string /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * @param locale - A locale, optional, override locale that global scope or local scope * * @returns formatted value */ $d(value: number | Date, key: string, locale: Locale): string /** * Datetime formatting * * @remarks * Overloaded `$d`. About details, see the {@link $d} remarks. * * @param value - A value, timestamp number or `Date` instance * @param options - An options, see the {@link DateTimeOptions} * * @returns formatted value */ $d(value: number | Date, options: DateTimeOptions): string /** * Number formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#n | `VueI18n.n` }. * * In {@link I18nMode | Composition API mode}, the `$n` is injected by `app.config.globalProperties`. * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#n | `Composer.n` }. * * @param value - A number value * * @returns formatted value */ $n(value: number): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param key - A key of number formats * * @returns formatted value */ $n(value: number, key: string): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param key - A key of number formats * @param locale - A locale, optional, override locale that global scope or local scope * * @returns formatted value */ $n(value: number, key: string, locale: Locale): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param args - An argument values * * @returns formatted value */ $n(value: number, args: { [key: string]: string }): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * * @returns formatted value */ $n(value: number): string /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param key - A key of number formats * * @returns formatted value */ $n(value: number, key: string): string /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param key - A key of number formats * @param locale - A locale, optional, override locale that global scope or local scope * * @returns formatted value */ $n(value: number, key: string, locale: Locale): string /** * Number formatting * * @remarks * Overloaded `$n`. About details, see the {@link $n} remarks. * * @param value - A number value * @param options - An options, see the {@link NumberOptions} * * @returns formatted value */ $n(value: number, options: NumberOptions): string /** * Locale messages getter * * In {@link I18nMode | Legacy API mode}, the input / output is the same as for VueI18n instance. About that details, see {@link VueI18n#tm | `VueI18n#tm` }. * * @remarks * In {@link I18nMode | Composition API mode}, the `$tm` is injected by `app.config.globalProperties`. * the input / output is the same as for Composer instance, and it work on **global scope**. About that details, see {@link Composer#tm | `Composer.tm` }. * Based on the current `locale`, locale messages will be returned from Composer instance messages. * If you change the `locale`, the locale messages returned will also correspond to the locale. * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with fallbacking. * * @param key - A target locale message key * * @returns locale messages */ $tm(key: Path): LocaleMessageValue<VueMessageType> | {} } }
the_stack
import { Connection } from './connection'; export namespace ui { export interface HTMLDatabenchElement extends HTMLElement { databenchUI: UIElement; } /** * Abstract class for user interface elements which provides general helpers * to determine the action name from an HTML tag and a way to modify the message * that is sent with actions of wired elements. * * The constructor adds the variables `actionName` and `wireSignal` using * [[UIElement.determineActionName]] and * [[UIElement.determineWireSignal]] respectively. * It also adds `this` UI element to the DOM node at `databenchUI`. */ export class UIElement { node: HTMLDatabenchElement; static idCounter: number = 0; idCount: number; actionName: string; wireSignal: string | { [x: string]: string; }; /** * @param node An HTML element. */ constructor(node: HTMLElement|HTMLDatabenchElement) { this.node = <HTMLDatabenchElement>node; this.node.databenchUI = this; this.idCount = UIElement.idCounter++; this.actionName = this.determineActionName(node); this.wireSignal = this.determineWireSignal(node); } /** * Formats the payload of an action. * @param value Original payload. * @return Modified payload. */ actionFormat(value: any): any { return value; } /** * Determine whether to skip this element. * * This can be forced by adding a `data-skipwire=true` attribute * to the HTML tag. * * @param node A HTML element. */ static skipWire(node: HTMLElement): boolean { return (node.dataset.skipwire === 'true' || node.dataset.skipwire === 'TRUE' || node.dataset.skipwire === '1'); } /** * Determine the name of the action that should be associated with the node. * * The action name is determined from * the tag's `data-action`, `name` or `id` attribute (in that order). * * @param node A HTML element. * @return Name of action or null. */ determineActionName(node: HTMLElement): string { const dataAction = node.dataset.action; if (dataAction) return dataAction; const attrName = node.getAttribute('name'); if (attrName) return attrName; const attrId = node.getAttribute('id'); if (attrId) return attrId; return 'element' + this.idCount; } /** * Determine the name of the signal that should be listened to from the backend. * * The signal name is determined from the `data-signal`, * `data-action`, `name` or `id` attribute (in that order.) * For all attributes apart from `data-signal`, the value is wrapped in an * object like `{ data: value-of-attribute }`. The `data-signal` value * can contain a `:` which will be used to create an object as well. That means * that `data-signal="data:myvalue"` gives the same result as `data-action="myvalue"`. * * @param node A HTML element. * @return Name of a signal or null. */ determineWireSignal(node: HTMLElement): string | { [x: string]: string; } { const dataSignal = node.dataset.signal; if (dataSignal) { if (dataSignal.indexOf(':') >= 1) { const [key, value] = dataSignal.split(':', 2); return { [key]: value }; } return dataSignal; } const dataAction = node.dataset.action; if (dataAction) return { data: dataAction }; const attrName = node.getAttribute('name'); if (attrName) return { data: attrName }; const attrId = node.getAttribute('id'); if (attrId) return { data: attrId }; return { data: 'element' + this.idCount }; } } /** * Shows all `console.log()` messages and `log` actions from backend. * * Usually wired to a `<pre id="log">` element. */ export class Log extends UIElement { limitNumber: number; limitLength: number; _messages: string[][]; /** * @param node Primary node. * @param limitNumber Maximum number of messages to show. * @param limitLength Maximum length of a message. */ constructor(node: HTMLElement, limitNumber: number = 20, limitLength: number = 250) { super(node); this.limitNumber = limitNumber; this.limitLength = limitLength; this._messages = []; } render(): Log { while (this._messages.length > this.limitNumber) this._messages.shift(); this.node.innerText = this._messages .map(m => m.join('')) .map(m => ((m.length > this.limitLength) ? `${m.substr(0, this.limitLength)} ...` : m)) .join('\n'); return this; } add(message: any, source = 'unknown'): Log { const msg = typeof message === 'string' ? message : JSON.stringify(message); const paddedSource = Array(Math.max(0, 8 - source.length)).join(' ') + source; this._messages.push([`${paddedSource}: ${msg}`]); this.render(); return this; } /** Wire all logs. */ static wire(conn: Connection, id: string = 'log', wireSignals: string[] = ['log', 'warn', 'error'], limitNumber: number = 20, limitLength: number = 250) { const node = document.getElementById(id); if (node == null || UIElement.skipWire(node)) return; const log = new Log(node, limitNumber, limitLength); console.log(`Wiring ${wireSignals} to `, node); wireSignals.forEach(wireSignal => { conn.on(wireSignal, message => { log.add(message, `backend (${wireSignal})`); }); conn.preEmit(wireSignal, message => { log.add(message, `frontend (${wireSignal})`); return message; }); }); return; } } /** * Visual representation of alerts like connection failures. * * Usually wired to a `<div id="databench-alerts">` element. */ export class StatusLog extends UIElement { formatter: (message: string, count: number) => string; _messages: { [message: string]: number }; /** * @param node HTML node. * @param formatter Formats a message and a count to a string. */ constructor(node: HTMLElement, formatter: (message: string, count: number) => string = StatusLog.defaultAlert) { super(node); this.formatter = formatter; this._messages = {}; } /** * The default formatter function * @param message A message. * @param count Count of the message. * @returns HTML formatted version of the inputs. */ static defaultAlert(message: string, count: number): string { const countFormat = count <= 1 ? '' : `<b>(${count})</b> `; return `<div class="alert alert-danger">${countFormat}${message}</div>`; } render(): StatusLog { const formatted = Object.getOwnPropertyNames(this._messages) .map((m: string) => this.formatter(m, this._messages[m])); this.node.innerHTML = formatted.join('\n'); return this; } add(message: any): StatusLog { if (message == null) { this._messages = {}; return this; } const msg = typeof message === 'string' ? message : JSON.stringify(message); if (this._messages[msg] !== undefined) { this._messages[msg] += 1; } else { this._messages[msg] = 1; } this.render(); return this; } /** Wire all status logs. */ static wire(conn: Connection, id: string = 'databench-alerts', formatter: (message: string, count: number) => string = StatusLog.defaultAlert) { const node = document.getElementById(id); if (node == null) return; if (UIElement.skipWire(node)) return; console.log('Wiring status log', node, `to element with id=${id}.`); const l = new StatusLog(node, formatter); conn.errorCB = l.add.bind(l); } } export enum ButtonState { Idle = 1, Active, } /** * A button, and usually wired to any `<button>` with an action name. * * This button also binds to process IDs of the backend. That means * that the button is disabled (using the CSS class `disabled`) while the * backend is processing the action that got started when it was clicked. * A simple example is below. * * In `index.html`: * ```html * <button data-action="run">Run</button> * ``` * * In `analysis.py`: * ```py * @ databench.on * def run(self): * """Run when button is pressed.""" * pass * ``` * * In this form, Databench finds the button automatically and connects it * to the backend. No additional JavaScript code is required. */ export class Button extends UIElement { _state: ButtonState; /** * @param node DOM node to connect. */ constructor(node: HTMLElement) { super(node); this._state = ButtonState.Idle; this.node.addEventListener('click', this.click.bind(this), false); } /** * Called on click events. When a button is wired, this function is overwritten * with the actual function that is triggered on click events. * @param processID a random id for the process that could be started */ clickCB(processID: number) { return console.log(`click on ${this.node} with ${processID}`); } render(): Button { switch (this._state) { case ButtonState.Active: this.node.classList.add('disabled'); break; default: this.node.classList.remove('disabled'); } return this; } click(): Button { if (this._state !== ButtonState.Idle) return this; const processID = Math.floor(Math.random() * 0x100000); this.clickCB(processID); return this; } state(s: ButtonState): Button { if (s !== ButtonState.Idle && s !== ButtonState.Active) return this; this._state = s; this.render(); return this; } /** Wire all buttons. */ static wire(conn: Connection, root?: Document|HTMLElement) { if (root === undefined) root = document; const elements: HTMLDatabenchElement[] = [].slice.call(root.getElementsByTagName('BUTTON'), 0); elements .filter(node => node.databenchUI === undefined) .filter(node => !UIElement.skipWire(node)) .forEach(node => { const b = new Button(node); console.log('Wiring button', node, `to action ${b.actionName}.`); // set up click callback b.clickCB = (processID) => { // set up process callback conn.onProcess(processID, status => b.state( // map process status to state { start: ButtonState.Active, end: ButtonState.Idle }[status] )); conn.emit(b.actionName, b.actionFormat({ __process_id: processID, // eslint-disable-line camelcase })); }; }); } } /** * Data bound text elements. * * Wired to `<span>`, `<p>`, `<div>`, `<i>` and `<b>` tags with a * `data-action` attribute specifying the action name. */ export class Text extends UIElement { /** * Format the value. * * The default implementation returns a `JSON.stringify()` version for values * that are `typeof value == 'object'`. Otherwise it passes the value through. * * @param value Value as represented in the backend. * @return Formatted representation of the value. */ formatFn(value: any): string { if (typeof value === 'object') { return JSON.stringify(value, undefined, 2); } return value; } /** Reads the value. */ getValue() { return this.node.innerHTML; } /** Reads the value. */ setValue(v?: string): Text { this.node.innerHTML = this.formatFn(v || ''); return this; } /** * Wire all text. * @param {Connection} conn Connection to use. */ static wire(conn: Connection, root?: Document|HTMLElement) { if (root === undefined) root = document; const elements: HTMLDatabenchElement[] = [].concat( [].slice.call(root.getElementsByTagName('SPAN'), 0), [].slice.call(root.getElementsByTagName('P'), 0), [].slice.call(root.getElementsByTagName('DIV'), 0), [].slice.call(root.getElementsByTagName('I'), 0), [].slice.call(root.getElementsByTagName('B'), 0), [].slice.call(root.getElementsByTagName('PRE'), 0), ); elements .filter(node => node.databenchUI === undefined) .filter(node => node.dataset['action'] !== undefined) .filter(node => !UIElement.skipWire(node)) .forEach(node => { const t = new Text(node); console.log('Wiring text', node, `to action ${t.actionName}.`); // handle events from backend conn.on(t.wireSignal, message => t.setValue(message)); }); } } /** Make an `<input[type='text']>` with an action name interactive. */ export class TextInput extends UIElement { node: HTMLInputElement & HTMLDatabenchElement; _triggerOnKeyUp: boolean; /** * @param node The node to connect. */ constructor(node: HTMLElement) { super(node); this._triggerOnKeyUp = false; this.node.addEventListener('change', this.change.bind(this), false); } /** * Format the value. * @param value Value as represented in the backend. * @return Formatted representation of the value. */ formatFn(value: any): string { return value; } /** * Callback that is triggered on frontend changes. * @param value A formatted action. */ changeCB(value: any) { return console.log(`change of ${this.node}: ${value}`); } change() { return this.changeCB(this.actionFormat(this.getValue())); } /** * The default is `false`, which means that the callback is only triggered on * `change` events (i.e. pressing enter or unfocusing the element). * Setting this to true will trigger on every `keyup` event of this element. * * @param v Whether to trigger on `keyup` events. Default is true. * @return self */ triggerOnKeyUp(v: boolean): TextInput { if (v !== false && !this._triggerOnKeyUp) { this.node.addEventListener('keyup', this.change.bind(this), false); this._triggerOnKeyUp = true; } if (v === false && this._triggerOnKeyUp) { this.node.removeEventListener('keyup', this.change.bind(this), false); this._triggerOnKeyUp = false; } return this; } /** Reads and sets the value. */ getValue(): string { return this.node.value; } /** Set value */ setValue(v: string): TextInput { this.node.value = this.formatFn(v || ''); return this; } /** Wire all text inputs. */ static wire(conn: Connection, root?: Document|HTMLElement) { if (root === undefined) root = document; const elements: HTMLDatabenchElement[] = [].slice.call(root.getElementsByTagName('INPUT'), 0); elements .filter(node => node.databenchUI === undefined) .filter(node => node.getAttribute('type') === 'text') .filter(node => !UIElement.skipWire(node)) .forEach(node => { const t = new TextInput(node); console.log('Wiring text input', node, `to action ${t.actionName}.`); // handle events from frontend t.changeCB = message => conn.emit(t.actionName, message); // handle events from backend conn.on(t.wireSignal, message => t.setValue(message)); }); } } /** * Make all `<input[type='range']>` with an action name interactive. * * In `index.html`: * ```html * <label for="samples">Samples:</label> * <input type="range" id="samples" value="1000" min="100" max="10000" step="100" /> * ``` * * In `analysis.py`: * ```py * @ databench.on * def samples(self, value): * """Sets the number of samples to generate per run.""" * yield self.set_state(samples=value) * ``` */ export class Slider extends UIElement { node: HTMLInputElement & HTMLDatabenchElement; labelNode: HTMLElement | undefined; labelHtml: string; /** * @param node DOM node to bind. * @param labelNode DOM node label that corresponds to the slider. */ constructor(node: HTMLElement, labelNode?: HTMLElement) { super(node); this.labelNode = labelNode; this.labelHtml = labelNode ? labelNode.innerHTML : ''; this.node.addEventListener('input', this.render.bind(this), false); this.node.addEventListener('change', this.change.bind(this), false); this.render(); } /** * Callback with changes to the slider value. * @param value Value from a sliderToValue() transform. */ changeCB(value: number) { return console.log(`slider value change: ${value}`); } /** * Transform a backend value to a slider value. * @param value Value as stored in backend. * @return Value for the HTML range element. */ valueToSlider(value: number): string { return value.toString(); } /** * Transform a value from the HTML range element to a value that should be stored. * @param s Value from HTML range element. * @return Value to store. */ sliderToValue(s: number): number { return s; } /** * How a value should be represented. * For example, this can add units or convert from radians to degrees. * @param value Input value as it is stored in the backend. * @return Representation of a value. */ formatFn(value: number): string { return value.toString(); } render(): Slider { const v = this.getValue(); if (this.labelNode) { this.labelNode.innerHTML = `${this.labelHtml} ${this.formatFn(v)}`; } return this; } /** Reads the value. */ getValue(): number { return this.sliderToValue(parseFloat(this.node.value)); } /** Set the value. */ setValue(v: number): Slider { const newSliderValue = this.valueToSlider(v); if (this.node.value === newSliderValue) return this; this.node.value = newSliderValue; this.render(); return this; } change() { return this.changeCB(this.actionFormat(this.getValue())); } /** Find all labels for slider elements. */ static labelsForSliders(root: Document|HTMLElement) { let map: { [inputname: string]: HTMLLabelElement } = {}; const elements: HTMLLabelElement[] = [].slice.call(root.getElementsByTagName('LABEL'), 0); elements .filter(label => label.htmlFor) .forEach(label => { map[label.htmlFor] = label; }); return map; } /** Wire all sliders. */ static wire(conn: Connection, root?: Document|HTMLElement) { if (root === undefined) root = document; const lfs = this.labelsForSliders(root); const elements: HTMLDatabenchElement[] = [].slice.call(root.getElementsByTagName('INPUT'), 0); elements .filter(node => node.databenchUI === undefined) .filter(node => node.getAttribute('type') === 'range') .filter(node => !UIElement.skipWire(node)) .forEach(node => { const slider = new Slider(node, lfs[node.id]); console.log('Wiring slider', node, `to action ${slider.actionName}.`); // handle events from frontend slider.changeCB = message => conn.emit(slider.actionName, message); // handle events from backend conn.on(slider.wireSignal, message => slider.setValue(message)); }); } } /** * Connect an `<img>` with a signal name to the backend. * * The signal message is placed directly into the `src` attribute of the image * tag. For matplotlib, that formatting can be done with the utility function * `fig_to_src()` (see example below). * * In `index.html`: * ```html * <img alt="my plot" data-signal="mpl" /> * ``` * * In `analysis.py`: * ```py * import matplotlib.pyplot as plt * ... * fig = plt.figure() * ... * self.emit('mpl', databench.fig_to_src(fig)) * ``` */ export class Image extends UIElement { node: HTMLImageElement & HTMLDatabenchElement; getSrc(): string { return this.node.src; } /** Sets theSrc. */ setSrc(v: string): Image { this.node.src = v; return this; } /** Wire all text inputs. */ static wire(conn: Connection, root?: Document|HTMLElement) { if (root === undefined) root = document; const elements: HTMLDatabenchElement[] = [].slice.call(root.getElementsByTagName('IMG'), 0); elements .filter(node => node.databenchUI === undefined) .filter(node => node.dataset['signal'] !== undefined) .filter(node => !UIElement.skipWire(node)) .forEach(node => { const img = new Image(node); console.log('Wiring image', node, `to signal ${img.wireSignal}.`); // handle events from backend conn.on(img.wireSignal, message => img.setSrc(message)); }); } } /** * Wire all the UI elements to the backend. The action name is determined by * [[UIElement.determineActionName]] and the action message can be modified * by overwriting [[UIElement.actionFormat]]. The signal name is determined by * [[UIElement.determineWireSignal]]. * * @param connection A Databench.Connection instance. * @return The same connection. */ export function wire(connection: Connection, root?: Document|HTMLElement): Connection { StatusLog.wire(connection); Button.wire(connection, root); TextInput.wire(connection, root); Text.wire(connection, root); Slider.wire(connection, root); Image.wire(connection, root); Log.wire(connection); return connection; } } // namespace ui
the_stack
import assert from 'assert'; import Type from './type'; import * as Grammar from './syntax_api'; import TypeChecker from './typecheck'; import { ClassDef } from './ast/class_def'; import { FunctionDef, ArgumentDef, ArgDirection } from './ast/function_def'; import { Library } from './ast/program'; import { Dataset, Example } from './ast/statement'; import Cache from './utils/cache'; function delay(timeout : number) : Promise<void> { return new Promise((resolve, reject) => { setTimeout(resolve, timeout); }); } interface MemoryTable { args : string[]; types : Type[]; } interface TpMixinDeclaration { kind : string; types : string[]; args : string[]; required : boolean[]; is_input : boolean[]; facets : string[]; } interface MixinDeclaration { kind : string; types : Type[]; args : string[]; required : boolean[]; is_input : boolean[]; facets : string[]; } /** * A delegate object to access tables stored in long-term assistant memory. * * @deprecated Long-term memory support in Almond is still experimental and APIs will change */ export interface MemoryClient { /** * Retrieve the type information of a stored table * * @param {string} table - the name of the table to retrieve * @return {Object} */ getSchema(table : string, principal : string|null) : Promise<MemoryTable|null>; } interface EntityTypeRecord { type : string; is_well_known : boolean|number; has_ner_support : boolean|number; // this can be both null and undefined because we don't want it to be // missing/undefined (undefined would be missing when through JSON), // but we have to account for legacy implementations of the API where // it is in fact missing subtype_of ?: string[]|null; } /** * The abstract interface to access Thingpedia. * * This is the minimal interface needed by the ThingTalk library. It is usally * implemented by the Thingpedia SDK. */ export interface AbstractThingpediaClient { get locale() : string; /** * Retrieve the full code of a Thingpedia class. * * @param {string} kind - the Thingpedia class identifier * @return {string} - the raw code of the class */ getDeviceCode(kind : string) : Promise<string>; /** * Retrieve type and metadata information for one or more Thingpedia classes. * * @param {string[]} kinds - the Thingpedia class identifiers to retrieve * @param {boolean} getMeta - whether to retrieve metadata or not * @return {string} - the retrieved type information, as ThingTalk classes */ getSchemas(kinds : string[], getMeta : boolean) : Promise<string>; getMixins() : Promise<{ [key : string] : TpMixinDeclaration }>; /** * Retrieve the {@link Ast.Dataset} associated with one or more Thingpedia classes. * * @param {string[]} kinds - the Thingpedia class identifiers to retrieve */ getExamplesByKinds(kinds : string[]) : Promise<string>; /** * Retrieve the list of all entity types declared in Thingpedia. */ getAllEntityTypes() : Promise<EntityTypeRecord[]>; } class DummyMemoryClient { _tables : Map<string, MemoryTable> constructor() { this._tables = new Map; } getSchema(table : string, principal : string|null) : Promise<MemoryTable|null> { return Promise.resolve(this._tables.get(table) || null); } createTable(table : string, args : string[], types : Type[]) : Promise<void> { this._tables.set(table, { args: args, types: types }); return Promise.resolve(); } } type FunctionType = 'query' | 'action'; type MetadataLevel = 'basic' | 'everything'; type ClassMap = { [key : string] : ClassDef|Error }; type DatasetMap = { [key : string] : Dataset|Error }; /** * Delegate object to retrieve type information and metadata from Thingpedia. * * This class wraps an {@link AbstractThingpediaClient} and provides batching, in-memory * caching, and parsing. */ export default class SchemaRetriever { private _manifestCache : Map<string, Promise<ClassDef>>; private _currentRequest : { basic : Promise<ClassMap>|null; everything : Promise<ClassMap>|null; dataset : Promise<DatasetMap>|null; }; private _pendingRequests : { basic : string[]; everything : string[]; dataset : string[]; }; private _classCache : { basic : Cache<string, ClassDef|null>; everything : Cache<string, ClassDef|null>; dataset : Cache<string, Dataset>; }; private _entityTypeCache : Cache<string, EntityTypeRecord>; private _thingpediaClient : AbstractThingpediaClient; private _memoryClient : MemoryClient; private _silent : boolean; /** * Construct a new schema retriever. * * @param {AbstractThingpediaClient} tpClient - the Thingpedia client interface to wrap * @param {MemoryClient} [mClient] - the client interface to access stored tables * @param {boolean} [silent=false] - whether debugging information should be printed */ constructor(tpClient : AbstractThingpediaClient, mClient ?: MemoryClient|null, silent = false) { this._manifestCache = new Map; // each of the following exists for schema (types only) // and metadata (types and NL annotations) // keyed by isMeta/useMeta this._currentRequest = { basic: null, everything: null, dataset: null, }; this._pendingRequests = { basic: [], everything: [], dataset: [], }; this._classCache = { // expire caches in 24 hours (same as on-disk thingpedia caches) basic: new Cache(24 * 3600 * 1000), everything: new Cache(24 * 3600 * 1000), dataset: new Cache(24 * 3600 * 1000) }; this._entityTypeCache = new Cache(24 * 3600 * 1000); this._thingpediaClient = tpClient; this._memoryClient = mClient || new DummyMemoryClient(); this._silent = !!silent; } /** * Remove all information related to the given Thingpedia class from the cache. * * @param {string} kind - the class identifier */ removeFromCache(kind : string) : void { this._classCache.basic.delete(kind); this._classCache.everything.delete(kind); this._manifestCache.delete(kind); } /** * Remove all information from all caches. */ clearCache() : void { this._classCache.basic.clear(); this._classCache.everything.clear(); this._manifestCache.clear(); } /** * Override cached type information with the passed in class. * * This can be used to ensure the schema retriever is consistent with other * cached information (for example, on disk caching of device implementation). * * @param {Ast.ClassDef} classDef - class definition to inject */ injectClass(classDef : ClassDef) : void { // never expire explicitly injected class this._classCache.basic.set(classDef.kind, classDef, -1); this._classCache.everything.set(classDef.kind, classDef, -1); this._manifestCache.set(classDef.kind, Promise.resolve(classDef)); } private async _getManifestRequest(kind : string) { const code = await this._thingpediaClient.getDeviceCode(kind); const parsed = await Grammar.parse(code, Grammar.SyntaxType.Normal, { locale: this._thingpediaClient.locale, timezone: undefined }).typecheck(this); assert(parsed instanceof Library && parsed.classes.length > 0); return parsed.classes[0]; } private _getManifest(kind : string) : Promise<ClassDef> { if (this._manifestCache.has(kind)) return Promise.resolve(this._manifestCache.get(kind)!); const request = this._getManifestRequest(kind); this._manifestCache.set(kind, request); return request; } async getFormatMetadata(kind : string, query : string) : Promise<unknown[]> { const classDef = await this._getManifest(kind); if (classDef.queries[query]) return (classDef.queries[query].metadata.formatted as unknown[]) || []; return []; } private async _makeRequest(isMeta : MetadataLevel) : Promise<ClassMap> { // delay the actual request so that further requests // in the same event loop iteration will be batched // toghether // batching is important because otherwise we can // make a lot of tiny HTTP requests at the same time // and kill the Thingpedia server just out of overhead await delay(0); const pending = this._pendingRequests[isMeta]; this._pendingRequests[isMeta] = []; this._currentRequest[isMeta] = null; if (pending.length === 0) return {}; if (!this._silent) console.log(`Batched ${isMeta ? 'schema-meta' : 'schema'} request for ${pending}`); const code = await this._thingpediaClient.getSchemas(pending, isMeta === 'everything'); if (code.trim() === '') { // empty reply, this means none of the requested classes was found // add negative cache entry (with small 10 minute timeout) for the missing class for (const kind of pending) { // we add it for both with & without metadata (if the class doesn't exist it doesn't exist) this._classCache.basic.set(kind, null, 600 * 1000); this._classCache.everything.set(kind, null, 600 * 1000); } return {}; } const parsed = Grammar.parse(code, Grammar.SyntaxType.Normal, { locale: this._thingpediaClient.locale, timezone: undefined }) as Library; const result : ClassMap = {}; const missing = new Set<string>(pending); await Promise.all(parsed.classes.map(async (classDef) => { try { const typeChecker = new TypeChecker(this, isMeta === 'everything'); await typeChecker.typeCheckClass(classDef, true); this._classCache[isMeta].set(classDef.kind, classDef); result[classDef.kind] = classDef; missing.delete(classDef.kind); } catch(e) { result[classDef.kind] = e; } })); // add negative cache entry (with small 10 minute timeout) for the missing class for (const kind of missing) { // we add it for both with & without metadata (if the class doesn't exist it doesn't exist) this._classCache.basic.set(kind, null, 600 * 1000); this._classCache.everything.set(kind, null, 600 * 1000); } return result; } private _ensureRequest(isMeta : MetadataLevel) : void { if (this._currentRequest[isMeta] !== null) return; this._currentRequest[isMeta] = this._makeRequest(isMeta); } private async _getClass(kind : string, useMeta : MetadataLevel) : Promise<ClassDef> { if (typeof kind !== 'string') throw new TypeError(); const cached = this._classCache[useMeta].get(kind); if (cached !== undefined) { if (cached === null) // negative cache throw new TypeError('Invalid kind ' + kind); return cached; } if (this._pendingRequests[useMeta].indexOf(kind) < 0) this._pendingRequests[useMeta].push(kind); this._ensureRequest(useMeta); const everything = await this._currentRequest[useMeta]!; if (kind in everything) { const result = everything[kind]; if (result instanceof Error) throw result; else return result; } else { throw new TypeError('Invalid kind ' + kind); } } /** * Return the full type information of the passed in class. * * @param {string} kind - the class identifier * @return {Ast.ClassDef} the corresponding class */ getFullSchema(kind : string) : Promise<ClassDef> { return this._getClass(kind, 'everything'); } /** * Return the full type information and metadata of the passed in class. * * @param {string} kind - the class identifier * @return {Ast.ClassDef} the corresponding class, including metadata */ getFullMeta(kind : string) : Promise<ClassDef> { return this._getClass(kind, 'everything'); } _where(where : FunctionType | 'both') : ('queries'|'actions'|'both') { switch (where) { case 'query': return 'queries'; case 'action': return 'actions'; case 'both': return 'both'; default: throw new TypeError('unexpected function type ' + where); } } // FIXME: this function exists for compatibility with // some really old code in almond-cloud (IIRC) // investigate if it can be removed /** * Return the type signature of the given function. * * This method is deprecated because it returns the types without the * argument names, directions and annotations. * * @param {string} kind - the class identifier * @param {string} functionType - the type of function (either `query` or `action`) * @param {string} name - the function name * @return {Type[]} the list of types in the signature * @deprecated Use {@link SchemaRetriever.getSchemaAndNames} instead */ async getSchema(kind : string, functionType : FunctionType | 'both', name : string) : Promise<Type[]> { return (await this.getSchemaAndNames(kind, functionType, name)).types; } private async _getFunction(kind : string, functionType : FunctionType | 'both', name : string, useMeta : MetadataLevel) : Promise<FunctionDef> { const where = this._where(functionType); const classDef = await this._getClass(kind, useMeta); if (where === 'both') { if (!(name in classDef.queries) && !(name in classDef.actions)) throw new TypeError(`Class ${kind} has no function ${name}`); return classDef.queries[name] || classDef.actions[name]; } else { if (!(name in classDef[where])) throw new TypeError(`Class ${kind} has no ${functionType} ${name}`); return classDef[where][name]; } } /** * Return the type information of the given function. * * This method returns the minimal amount of information necessary to typecheck * a program, but not enough to drive the dialog agent. * This method is preferred to {@link SchemaRetriever.getMeta} when metadata * is not needed, because it reduces the load on the server (which can skip the * localization step) and reduces the amount of transferred data. * * @param {string} kind - the class identifier * @param {string} functionType - the type of function (either `query` or `action`) * @param {string} name - the function name * @return {Ast.FunctionDef} the function definition */ getSchemaAndNames(kind : string, functionType : FunctionType | 'both', name : string) : Promise<FunctionDef> { return this._getFunction(kind, functionType, name, 'basic'); } /** * Return the type information and metadata of the given function. * * This method returns the full amount of information necessary to typecheck * and drive the dialog agent, but might not include implementation only information * (such as loader or configuration mixins). * * @param {string} kind - the class identifier * @param {string} functionType - the type of function (either `query` or `action`) * @param {string} name - the function name * @return {Ast.FunctionDef} the function definition */ getMeta(kind : string, functionType : FunctionType | 'both', name : string) : Promise<FunctionDef> { return this._getFunction(kind, functionType, name, 'everything'); } async getMemorySchema(table : string, getMeta = false) : Promise<FunctionDef> { const resolved = await this._memoryClient.getSchema(table, null); if (!resolved) throw new TypeError(`No such table ${table}`); const { args:argnames, types } = resolved; const args : ArgumentDef[] = []; for (let i = 0; i < types.length; i++) args.push(new ArgumentDef(null, ArgDirection.OUT, argnames[i], Type.fromString(types[i]))); const functionDef = new FunctionDef(null, 'query', null, table, [], { is_list: true, is_monitorable: true }, args, {}); // complete initialization of the function functionDef.setClass(null); assert(functionDef.minimal_projection); return functionDef; } async getMixins(kind : string) : Promise<MixinDeclaration> { const mixins = await this._thingpediaClient.getMixins(); if (!(kind in mixins)) throw new TypeError("Mixin " + kind + " not found."); const resolved = mixins[kind]; const parsed : MixinDeclaration = { kind: resolved.kind, types: resolved.types.map(Type.fromString), args: resolved.args, required: resolved.required, is_input: resolved.is_input, facets: resolved.facets }; return parsed; } private async _makeDatasetRequest() : Promise<DatasetMap> { // delay the actual request so that further requests // in the same event loop iteration will be batched // toghether // batching is important because otherwise we can // make a lot of tiny HTTP requests at the same time // and kill the Thingpedia server just out of overhead await delay(0); const pending = this._pendingRequests.dataset; this._pendingRequests.dataset = []; this._currentRequest.dataset = null; if (pending.length === 0) return {}; if (!this._silent) console.log(`Batched dataset request for ${pending}`); const code = await this._thingpediaClient.getExamplesByKinds(pending); const result : DatasetMap = {}; if (code.trim() === '') { // empty reply, this means none of the requested classes was found, // or all the datasets are empty for (const kind of pending) this._classCache.dataset.set(kind, result[kind] = new Dataset(null, kind, [])); } else { const parsed = Grammar.parse(code, Grammar.SyntaxType.Normal, { locale: this._thingpediaClient.locale, timezone: undefined }) as Library; const examples = new Map<string, Example[]>(); // flatten all examples in all datasets, and then split again by device // this is to account for the HTTP API (which returns one dataset), // developer mode (which returns one per device) and file client, // which returns one or more depending on the content of the files // on disk for (const dataset of parsed.datasets) { for (const example of dataset.examples) { // typecheck each example individually, and ignore those that do not // typecheck // this can occur if the dataset we retrieved from Thingpedia is newer // than the cached manifest and includes new functions or a parameter change try { await example.typecheck(this, true); } catch(e) { console.log(`Failed to load dataset example ${example.id}: ${e.message}`); continue; } const devices = new Set<string>(); for (const [, prim] of example.iteratePrimitives(false)) devices.add(prim.selector.kind); for (const device of devices) { const list = examples.get(device); if (list) list.push(example); else examples.set(device, [example]); } } } for (const kind of pending) { const dataset = new Dataset(null, kind, examples.get(kind) || []); this._classCache.dataset.set(kind, result[kind] = dataset); } } return result; } private _ensureDatasetRequest() : void { if (this._currentRequest.dataset !== null) return; this._currentRequest.dataset = this._makeDatasetRequest(); } async getExamplesByKind(kind : string) : Promise<Dataset> { if (typeof kind !== 'string') throw new TypeError(); const cached = this._classCache.dataset.get(kind); if (cached !== undefined) return cached; if (this._pendingRequests.dataset.indexOf(kind) < 0) this._pendingRequests.dataset.push(kind); this._ensureDatasetRequest(); const everything = await this._currentRequest.dataset!; const result = everything[kind]; assert(result); if (result instanceof Error) throw result; else return result; } private async _getEntityTypeRecord(entityType : string) : Promise<EntityTypeRecord> { const cached = this._entityTypeCache.get(entityType); if (cached) return cached; // first try loading the class and looking for a declaration there // this is to support development of Thingpedia skills without editing // entities.json const [kind, name] = entityType.split(':'); if (kind !== 'tt') { try { const classDef = await this._getClass(kind, 'everything'); let found = null; for (const entity of classDef.entities) { // load all the entities from this class, not just the one // we're retrieving, otherwise we'll fallback to entities.json // for all the entities, and be sad that entity records are // wrong const entityType = classDef.kind + ':' + entity.name; const hasNer = entity.getImplementationAnnotation<boolean>('has_ner'); const subTypeOf = entity.extends.map((e) => e.includes(':') ? e : classDef.kind + ':' + e); const newRecord : EntityTypeRecord = { type: entityType, is_well_known: false, has_ner_support: hasNer === undefined ? true : hasNer, subtype_of : subTypeOf }; this._entityTypeCache.set(entityType, newRecord); if (entity.name === name) found = newRecord; // keep going to more entities } if (found) return found; } catch(e) { // ignore if there is no class with that name } } // then look up in thingpedia const allEntities = await this._thingpediaClient.getAllEntityTypes(); let found = null; for (const record of allEntities) { // to support development of thingpedia skills, we don't want // entities.json to override actual classes, so we can't put // things in the cache unless we're sure about them // so we only put in the cache all the tt: entities (which // don't belong to any class) and the one entity we're looking for // this is a bit wasteful in that it results in multiple queries // to Thingpedia // we should change this back once Thingpedia actually knows // about entity subtyping if (record.type === entityType || record.type.startsWith('tt:')) this._entityTypeCache.set(record.type, record); if (record.type === entityType) found = record; } if (found) return found; // finally, make up a record with default info const newRecord : EntityTypeRecord = { type: entityType, is_well_known: false, has_ner_support: false }; this._entityTypeCache.set(entityType, newRecord); return newRecord; } async getEntityParents(entityType : string) : Promise<string[]> { const record = await this._getEntityTypeRecord(entityType); return record.subtype_of || []; } }
the_stack
import {TEST_ACCOUNTS} from '@statechannels/devtools'; import { AssetOutcome, channelDataToStatus, getChannelId, randomChannelId, TestContractArtifacts, } from '@statechannels/nitro-protocol'; import { Address, BN, makeAddress, makeDestination, simpleEthAllocation, simpleTokenAllocation, State, Uint256, } from '@statechannels/wallet-core'; import {BigNumber, constants, Contract, providers, Wallet} from 'ethers'; import _ from 'lodash'; import { alice, alice as aliceParticipant, bob, bob as bobParticipant, } from '../../engine/__test__/fixtures/participants'; import {alice as aWallet, bob as bWallet} from '../../engine/__test__/fixtures/signing-wallets'; import {stateSignedBy} from '../../engine/__test__/fixtures/states'; import {ChainService} from '../chain-service'; import {AllocationUpdatedArg, ChallengeRegisteredArg, HoldingUpdatedArg} from '../types'; const zeroAddress = makeAddress(constants.AddressZero); /* eslint-disable no-process-env, @typescript-eslint/no-non-null-assertion */ const erc20Address = makeAddress(process.env.ERC20_ADDRESS!); const testAdjudicatorAddress = makeAddress(process.env.NITRO_ADJUDICATOR_ADDRESS!); if (!process.env.RPC_ENDPOINT) throw new Error('RPC_ENDPOINT must be defined'); const rpcEndpoint = process.env.RPC_ENDPOINT; const chainId = process.env.CHAIN_NETWORK_ID || '9002'; /* eslint-enable no-process-env, @typescript-eslint/no-non-null-assertion */ const provider: providers.JsonRpcProvider = new providers.JsonRpcProvider(rpcEndpoint); const defaultNoopListeners = { holdingUpdated: _.noop, allocationUpdated: _.noop, channelFinalized: _.noop, challengeRegistered: _.noop, }; let chainService: ChainService; let channelNonce = 0; async function mineBlock(timestamp?: number) { const param = timestamp ? [timestamp] : []; await provider.send('evm_mine', param); } async function mineBlocks() { for (const _i of _.range(5)) { await mineBlock(); } } jest.setTimeout(20_000); // The test nitro adjudicator allows us to set channel storage const testAdjudicator = new Contract( testAdjudicatorAddress, TestContractArtifacts.TestNitroAdjudicatorArtifact.abi, // We use a separate signer address to avoid nonce issues new providers.JsonRpcProvider(rpcEndpoint).getSigner(1) ); beforeAll(() => { // Try to use a different private key for every chain service instantiation to avoid nonce errors // Using the first account here as that is the one that: // - Deploys the token contract. // - And therefore has tokens allocated to it. /* eslint-disable no-process-env */ chainService = new ChainService({ provider: rpcEndpoint, pk: process.env.CHAIN_SERVICE_PK ?? TEST_ACCOUNTS[0].privateKey, allowanceMode: 'MaxUint', }); /* eslint-enable no-process-env, @typescript-eslint/no-non-null-assertion */ }); afterAll(() => { chainService.destructor(); testAdjudicator.provider.removeAllListeners(); provider.removeAllListeners(); }); function getChannelNonce() { return channelNonce++; } function fundChannel( expectedHeld: number, amount: number, channelId: string = randomChannelId(), asset: Address = zeroAddress ): { channelId: string; requestPromise: Promise<providers.TransactionResponse>; } { const requestPromise = chainService.fundChannel({ channelId, asset, expectedHeld: BN.from(expectedHeld), amount: BN.from(amount), }); return {channelId, requestPromise}; } function fundChannelAndMineBlocks( expectedHeld: number, amount: number, channelId: string = randomChannelId(), asset: Address = zeroAddress ): { channelId: string; requestPromise: Promise<providers.TransactionResponse>; } { const retVal = fundChannel(expectedHeld, amount, channelId, asset); retVal.requestPromise.then(async response => { await response.wait(); mineBlocks(); }); return retVal; } async function waitForChannelFunding( expectedHeld: number, amount: number, channelId: string = randomChannelId(), asset: Address = zeroAddress ): Promise<string> { const request = await fundChannel(expectedHeld, amount, channelId, asset).requestPromise; await request.wait(); return channelId; } async function setUpConclude(isEth = true) { const aEthWallet = Wallet.createRandom(); const bEthWallet = Wallet.createRandom(); const alice = aliceParticipant({destination: makeDestination(aEthWallet.address).toLowerCase()}); const bob = bobParticipant({destination: makeDestination(bEthWallet.address).toLowerCase()}); const outcome = isEth ? simpleEthAllocation([ {destination: alice.destination, amount: BN.from(1)}, {destination: bob.destination, amount: BN.from(3)}, ]) : simpleTokenAllocation(erc20Address, [ {destination: alice.destination, amount: BN.from(1)}, {destination: bob.destination, amount: BN.from(3)}, ]); const newAssetOutcome: AssetOutcome = { asset: isEth ? constants.AddressZero : erc20Address, allocationItems: [ {destination: alice.destination, amount: BN.from(0)}, {destination: bob.destination, amount: BN.from(0)}, ], }; const state1: State = { appData: constants.HashZero, appDefinition: makeAddress(constants.AddressZero), isFinal: true, turnNum: 4, outcome, participants: [alice, bob], channelNonce: getChannelNonce(), chainId, challengeDuration: 9001, }; const channelId = getChannelId({ channelNonce: state1.channelNonce, chainId: state1.chainId, participants: [alice, bob].map(p => p.signingAddress), }); const signatures = [aWallet(), bWallet()].map(sw => sw.signState(state1)); await waitForChannelFunding(0, 4, channelId, isEth ? zeroAddress : erc20Address); return { channelId, aAddress: aEthWallet.address, bAddress: bEthWallet.address, state: state1, signatures, newAssetOutcome, }; } describe('chainid mismatch detection', () => { it('throws an error when the chainid is wrong', async () => { await expect(chainService.checkChainId(987654321)).rejects.toThrow('ChainId mismatch'); }); }); describe('fundChannel', () => { it('Successfully funds channel with 2 participants, rejects invalid 3rd', async () => { const channelId = await waitForChannelFunding(0, 5); await waitForChannelFunding(5, 5, channelId); const {requestPromise: fundChannelPromise} = fundChannel(5, 5, channelId); await expect(fundChannelPromise).rejects.toThrow( 'cannot estimate gas; transaction may fail or may require manual gas limit' ); }); it('Fund erc20', async () => { const channelId = randomChannelId(); await waitForChannelFunding(0, 5, channelId, erc20Address); expect(await testAdjudicator.holdings(erc20Address, channelId)).toEqual(BigNumber.from(5)); }); }); describe('registerChannel', () => { it('registers a channel in the finalizing channel list and fires an event when that channel is finalized', async () => { const channelId = randomChannelId(); const currentTime = (await provider.getBlock(provider.getBlockNumber())).timestamp; const tx = await testAdjudicator.setStatus( channelId, channelDataToStatus({ turnNumRecord: 0, finalizesAt: currentTime + 2, }) ); await tx.wait(); const channelFinalizedHandler = jest.fn(); const channelFinalizedPromise = new Promise<void>(resolve => chainService.registerChannel(channelId, [testAdjudicatorAddress], { ...defaultNoopListeners, channelFinalized: arg => { channelFinalizedHandler(arg); resolve(); }, }) ); await mineBlock(currentTime + 1); await mineBlock(currentTime + 2); await channelFinalizedPromise; expect(channelFinalizedHandler).toHaveBeenCalledWith(expect.objectContaining({channelId})); }); it('Successfully registers channel and receives follow on funding event', async () => { const channelId = randomChannelId(); const wrongChannelId = randomChannelId(); let counter = 0; let resolve: (value: unknown) => void; const p = new Promise(r => (resolve = r)); const holdingUpdated = async (arg: HoldingUpdatedArg): Promise<void> => { switch (counter) { case 0: expect(arg).toMatchObject({ channelId, asset: zeroAddress, amount: BN.from(0), }); counter++; // wait for the transaction to be mined. // Otherwise, it is possible for the correct channel funding transaction to be mined first. // In which case, this test might pass even if the holdingUpdated callback is fired for the wrongChannelId. await (await fundChannel(0, 5, wrongChannelId).requestPromise).wait(); fundChannelAndMineBlocks(0, 5, channelId); break; case 1: expect(arg).toMatchObject({ channelId, asset: zeroAddress, amount: BN.from(5), }); counter++; chainService.unregisterChannel(channelId); resolve(undefined); break; default: throw new Error('Should not reach here'); } }; chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, holdingUpdated, }); await p; }); it('Receives correct initial holding when holdings are confirmed', async () => { const channelId = randomChannelId(); await waitForChannelFunding(0, 5, channelId); await mineBlocks(); // wait for deposit to be confirmed then register channel await new Promise(resolve => chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, holdingUpdated: arg => { expect(arg).toMatchObject({ channelId, asset: zeroAddress, amount: BN.from(5), }); resolve(true); }, }) ); }); it('Channel with multiple assets', async () => { const channelId = randomChannelId(); let resolve: (value: unknown) => void; const p = new Promise(r => (resolve = r)); const objectsToMatch = _.flatten( [0, 5].map(amount => [zeroAddress, erc20Address].map(address => ({ channelId, asset: address, amount: BN.from(amount), })) ) ); const holdingUpdated = (arg: HoldingUpdatedArg): void => { const index = objectsToMatch.findIndex( predicate => predicate.channelId === arg.channelId && predicate.amount === arg.amount && predicate.asset === arg.asset ); expect(index).toBeGreaterThan(-1); // Note, splice mutates the array on which it is called objectsToMatch.splice(index, 1); if (!objectsToMatch.length) resolve(true); }; chainService.registerChannel(channelId, [erc20Address, zeroAddress], { ...defaultNoopListeners, holdingUpdated, }); await waitForChannelFunding(0, 5, channelId, zeroAddress); await waitForChannelFunding(0, 5, channelId, erc20Address); // No need to wait for block mining. The promise below will not resolve until after the 5th block is mined mineBlocks(); await p; }); }); describe('unconfirmedEvents', () => { it('Unconfirmed deposits are not missed', async () => { const channelId = randomChannelId(); for (const expectedHeld of _.range(10)) { await waitForChannelFunding(expectedHeld, 1, channelId); } // Some deposited events are unconfirmed when we register channel, // make sure they're not missed let lastObservedAmount = -1; let numberOfEventsObserved = 0; const p = new Promise(resolve => { chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, holdingUpdated: arg => { const received = parseInt(arg.amount); if (lastObservedAmount >= 0 && numberOfEventsObserved !== 1) { // To understand why duplicate events are possible, consult chain-service getInitialHoldings if (numberOfEventsObserved === 1) { expect([lastObservedAmount, lastObservedAmount + 1]).toContain(received); } else { expect(received).toEqual(lastObservedAmount + 1); } } if (received === 10) { resolve(true); return; } lastObservedAmount = received; numberOfEventsObserved++; mineBlock(); }, }); }); await p; }); }); describe('concludeAndWithdraw', () => { it('triggers a channel finalized event', async () => { const {channelId, state, signatures} = await setUpConclude(); const p = new Promise<void>(resolve => chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, channelFinalized: arg => { expect(arg.channelId).toEqual(channelId); resolve(); }, }) ); const transactionResponse = await chainService.concludeAndWithdraw([{...state, signatures}]); if (!transactionResponse) throw 'Expected transaction response'; await transactionResponse.wait(); mineBlocks(); await p; }); it('Successful concludeAndWithdraw with eth allocation', async () => { const { channelId, aAddress, bAddress, state, signatures, newAssetOutcome, } = await setUpConclude(); const AllocationUpdated: AllocationUpdatedArg = { channelId, asset: zeroAddress, newHoldings: '0x00' as Uint256, externalPayouts: [ { amount: BN.from(1), destination: makeDestination(aAddress).toLowerCase(), }, { amount: BN.from(3), destination: makeDestination(bAddress).toLowerCase(), }, ], internalPayouts: [], newAssetOutcome, }; const p = new Promise<void>(resolve => chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, allocationUpdated: arg => { expect(arg).toMatchObject(AllocationUpdated); resolve(); }, }) ); const transactionResponse = await chainService.concludeAndWithdraw([{...state, signatures}]); if (!transactionResponse) throw 'Expected transaction response'; await transactionResponse.wait(); expect(await provider.getBalance(aAddress)).toEqual(BigNumber.from(1)); expect(await provider.getBalance(bAddress)).toEqual(BigNumber.from(3)); mineBlocks(); await p; }); it('Register channel -> concludeAndWithdraw -> mine confirmation blocks for erc20', async () => { const {channelId, aAddress, bAddress, state, signatures, newAssetOutcome} = await setUpConclude( false ); const AllocationUpdated: AllocationUpdatedArg = { channelId, asset: erc20Address, newHoldings: '0x00' as Uint256, externalPayouts: [ { amount: BN.from(1), destination: makeDestination(aAddress).toLowerCase(), }, { amount: BN.from(3), destination: makeDestination(bAddress).toLowerCase(), }, ], internalPayouts: [], newAssetOutcome, }; const p = new Promise<void>(resolve => chainService.registerChannel(channelId, [erc20Address], { ...defaultNoopListeners, allocationUpdated: arg => { expect(arg).toMatchObject(AllocationUpdated); resolve(); }, }) ); const transactionResponse = await chainService.concludeAndWithdraw([{...state, signatures}]); if (!transactionResponse) throw 'Expected transaction response'; await transactionResponse.wait(); const erc20Contract: Contract = new Contract( erc20Address, TestContractArtifacts.TokenArtifact.abi, provider ); expect(await erc20Contract.balanceOf(aAddress)).toEqual(BigNumber.from(1)); expect(await erc20Contract.balanceOf(bAddress)).toEqual(BigNumber.from(3)); mineBlocks(); await p; }); it('concludeAndWithdraw -> register channel -> mine confirmation blocks for erc20', async () => { const {channelId, aAddress, bAddress, state, signatures, newAssetOutcome} = await setUpConclude( false ); const AllocationUpdated: AllocationUpdatedArg = { channelId, asset: erc20Address, newHoldings: '0x00' as Uint256, externalPayouts: [ { amount: BN.from(1), destination: makeDestination(aAddress).toLowerCase(), }, { amount: BN.from(3), destination: makeDestination(bAddress).toLowerCase(), }, ], internalPayouts: [], newAssetOutcome, }; const p = new Promise<void>(resolve => chainService.registerChannel(channelId, [erc20Address], { ...defaultNoopListeners, allocationUpdated: arg => { expect(arg).toMatchObject(AllocationUpdated); resolve(); }, }) ); const transactionResponse = await chainService.concludeAndWithdraw([{...state, signatures}]); if (!transactionResponse) throw 'Expected transaction response'; await transactionResponse.wait(); const erc20Contract: Contract = new Contract( erc20Address, TestContractArtifacts.TokenArtifact.abi, provider ); expect(await erc20Contract.balanceOf(aAddress)).toEqual(BigNumber.from(1)); expect(await erc20Contract.balanceOf(bAddress)).toEqual(BigNumber.from(3)); mineBlocks(); await p; }); }); describe('challenge', () => { it('two channels are challenged, funds are withdrawn -> final balances are correct', async () => { const aDestinationAddress = Wallet.createRandom().address; const bDestinationAddress = Wallet.createRandom().address; const aDestination = makeDestination(aDestinationAddress); const bDestination = makeDestination(bDestinationAddress); const channelNonces = [0, 1].map(getChannelNonce); const outcome = simpleEthAllocation([ { destination: aDestination, amount: BN.from(1), }, { destination: bDestination, amount: BN.from(3), }, ]); const state0s = channelNonces.map((channelNonce, index) => stateSignedBy()({ chainId, challengeDuration: index + 2, outcome, channelNonce, }) ); const state1s = channelNonces.map((channelNonce, index) => stateSignedBy([bWallet()])({ chainId, turnNum: 1, challengeDuration: index + 2, outcome, channelNonce: channelNonce, }) ); const channelIds = channelNonces.map(channelNonce => getChannelId({ channelNonce: channelNonce, chainId: chainId, participants: state0s[0].participants.map(p => p.signingAddress), }) ); const channelsFinalized = channelIds.map( channelId => new Promise(resolve => chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, channelFinalized: resolve, }) ) ); await Promise.all( channelIds.map(channelId => waitForChannelFunding(0, 4, channelId, zeroAddress)) ); await (await chainService.challenge([state0s[0], state1s[0]], aWallet().privateKey)).wait(); await (await chainService.challenge([state0s[1], state1s[1]], aWallet().privateKey)).wait(); const currentTime = (await provider.getBlock(provider.getBlockNumber())).timestamp; // The longest challenge duration is 3 seconds. // Lets mine a few blocks up to challenge expiration const blockDeltas = [0, 1, 2, 3]; for (const blockDelta of blockDeltas) { await mineBlock(currentTime + blockDelta); } await Promise.all(channelsFinalized); await Promise.all( state1s.map(async state1 => await (await chainService.withdraw(state1)).wait()) ); expect(await provider.getBalance(aDestinationAddress)).toEqual(BigNumber.from(2)); expect(await provider.getBalance(bDestinationAddress)).toEqual(BigNumber.from(6)); }); it('triggers challenge registered when a challenge is raised', async () => { const aDestinationAddress = Wallet.createRandom().address; const bDestinationAddress = Wallet.createRandom().address; const aDestination = makeDestination(aDestinationAddress); const bDestination = makeDestination(bDestinationAddress); const channelNonce = getChannelNonce(); const outcome = simpleEthAllocation([ { destination: aDestination, amount: BN.from(1), }, { destination: bDestination, amount: BN.from(3), }, ]); const state0 = stateSignedBy()({ chainId, challengeDuration: 2, outcome, channelNonce, }); const state1 = stateSignedBy([bWallet()])({ chainId, turnNum: 1, challengeDuration: 2, outcome, channelNonce: channelNonce, }); const channelId = getChannelId({ channelNonce: state1.channelNonce, chainId: state1.chainId, participants: [alice(), bob()].map(p => p.signingAddress), }); const challengeRegistered: Promise<ChallengeRegisteredArg> = new Promise(challengeRegistered => chainService.registerChannel(channelId, [zeroAddress], { ...defaultNoopListeners, challengeRegistered, }) ); await waitForChannelFunding(0, 4, channelId, zeroAddress); await (await chainService.challenge([state0, state1], aWallet().privateKey)).wait(); const result = await challengeRegistered; // TODO: Sort out these inconsistencies // Currently the participants come back slightly different (since the chain only knows the participant's address) // The chainId is returned as hex // We don't care about the signatures expect(result.challengeStates[0]).toMatchObject( _.omit(state0, ['participants', 'chainId', 'signatures']) ); expect(result.challengeStates[1]).toMatchObject( _.omit(state1, ['participants', 'chainId', 'signatures']) ); expect(result.channelId).toEqual(channelId); }); }); describe('getBytecode', () => { it('returns the bytecode for an app definition', async () => { const bytecode = await chainService.fetchBytecode(testAdjudicatorAddress); expect(bytecode).toMatch(/^0x[A-Fa-f0-9]{64,}$/); }); it('rejects when there is no bytecode deployed at the address', async () => { await expect(chainService.fetchBytecode(constants.AddressZero)).rejects.toThrow( 'Bytecode missing' ); }); });
the_stack
import { CdkScrollable } from '@angular/cdk/scrolling'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import { BehaviorSubject, Subscription } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { NovoLabelService } from '../../services/novo-label-service'; import { binarySearch, Helpers } from '../../utils/Helpers'; export type TabbedGroupPickerTab = { typeName: string; typeLabel: string; valueField: string; labelField: string; scrollOffset?: number; icon?: string; } & (ParentTab | ChildTab); export type ParentTab = { childTypeName: string; data: Array<ParentOption>; }; type ParentOption = { selected?: boolean; indeterminate?: boolean; children: Array<{ selected?: boolean }>; } & { [key: string]: any }; export type ChildTab = { data: Array<{ selected?: boolean } & { [key: string]: any }>; }; export type TabbedGroupPickerQuickSelect = { label: string; selected?: boolean; childTypeName?: string; children?: (({ selected?: boolean } & { [key: string]: any }) | (number))[]; all?: boolean; }; export type QuickSelectConfig = { label: string; items: TabbedGroupPickerQuickSelect[] }; export type TabbedGroupPickerButtonConfig = { theme: string; side: string; icon: string; label: string; }; @Component({ selector: 'novo-tabbed-group-picker', templateUrl: './TabbedGroupPicker.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class NovoTabbedGroupPickerElement implements OnDestroy, OnInit { @ViewChild('tabbedGroupPickerVirtualScrollViewport') private scrollableInstance: CdkScrollable; @Input() buttonConfig: TabbedGroupPickerButtonConfig; @Input() tabs: TabbedGroupPickerTab[]; @Input() quickSelectConfig: QuickSelectConfig; @Output() selectionChange: EventEmitter<any> = new EventEmitter<any>(); displayTabs: TabbedGroupPickerTab[]; displayTabIndex: number = 0; filterText: BehaviorSubject<string> = new BehaviorSubject(''); filterTextSubscription: Subscription; loading = true; showClearAll: boolean = false; // Initial height based on 13 px font rendered in chrome. Actual height retrieved onDropdownToggled. scrollViewportHeight: number = 351; virtualScrollItemSize: number = 39; constructor(public labelService: NovoLabelService, private ref: ChangeDetectorRef) { } get displayTab(): TabbedGroupPickerTab { return this.displayTabs[this.displayTabIndex]; } set displayTab(tab: TabbedGroupPickerTab) { this.displayTabIndex = this.tabs.map(({ typeName }) => typeName).indexOf(tab.typeName); } get minBufferPx() { return this.scrollViewportHeight; // render at least 2x the number of items visible (viewport + min buffer) } get maxBufferPx() { return 2 * this.scrollViewportHeight; // render at most 3x the number of items visible (viewport + max buffer) } ngOnInit(): void { this.setupDisplayData(); this.createChildrenReferences(); this.initializeDescendantSelection(); this.updateParentsAndQuickSelect(); this.updateClearAll(); this.loading = false; this.filterTextSubscription = this.filterText.pipe(debounceTime(300)).subscribe({ next: this.filter, }); } ngOnDestroy(): void { if (this.filterTextSubscription) { this.filterTextSubscription.unsubscribe(); } } changeTab(tab: TabbedGroupPickerTab) { this.displayTab = tab; if (this.scrollableInstance) { this.scrollableInstance.scrollTo({ behavior: 'auto', top: 0 }); } } getPixelHeight(element: HTMLElement) { return Number(getComputedStyle(element, '').height.match(/(\d+(\.\d+)?)px$/)[1]); } setupDisplayData(): void { // shallow copy here so that reassigning displayTabs[i].data doesn't mutate tabs[i].data // but both data values point to the same items this.displayTabs = this.tabs.map((tab) => ({ ...tab })); this.displayTab = this.tabs[0]; } // Replace each parent's child object with a reference to the child to avoid // a child lookup for selected status; linking references allows M x N // time complexity instead of M x N^2 createChildrenReferences(): void { this.tabs.forEach((tab) => { // would rather filter but TypeScript still wants a type narrowing here if ('childTypeName' in tab) { const childTab = this.tabs.find(({ typeName }) => typeName === tab.childTypeName); const compareFunction = this.makeCompareFunction(childTab.valueField); const warnFunction = this.makeWarningFunction(tab.typeName, childTab.typeName, childTab.valueField); const sortedChildren = childTab.data.slice().sort(compareFunction); tab.data .filter(({ children }) => children && children.length) .forEach((parent: { children?: any[] }) => this.replaceChildrenWithReferences(parent as ParentOption, sortedChildren, compareFunction, warnFunction), ); } }); if (this.quickSelectConfig) { this.quickSelectConfig.items .filter((parent) => 'all' in parent) .forEach((parent) => { parent.children = this.tabs.find(({ typeName }) => parent.childTypeName === typeName).data; }); this.quickSelectConfig.items .filter((parent) => !('all' in parent)) .forEach((parent) => { const childTab = this.tabs.find(({ typeName }) => typeName === parent.childTypeName); const compareFunction = this.makeCompareFunction(childTab.valueField); const warnFunction = this.makeWarningFunction(parent.label, childTab.typeName, childTab.valueField); const sortedChildren = childTab.data.slice().sort(compareFunction); this.replaceChildrenWithReferences(parent as ParentOption, sortedChildren, compareFunction, warnFunction); }); } } makeCompareFunction<T>(key: string): (a: T | { [key: string]: T }, b: T | { [key: string]: T }) => 1 | -1 | 0 | undefined { return (a: T | { [key: string]: T }, b: T | { [key: string]: T }) => { const aValue: T = (a && a[key]) || a; const bValue: T = (b && b[key]) || b; if (aValue < bValue) { return -1; } else if (aValue > bValue) { return 1; } else if (aValue === bValue) { return 0; } else { return undefined; } }; } replaceChildrenWithReferences( parent: { children: any[] }, sortedData: ChildTab['data'], compareFunction: (a, b) => 1 | -1 | 0, warnFunction: (child) => void, ): void { parent.children = parent.children .map((child) => binarySearch(child, sortedData, compareFunction) || warnFunction(child)) .filter(Boolean); // since map can return undefined, remove undefined elements } makeWarningFunction(parentLabel: string, childLabel: string, childValueField): (child) => void { return (child) => { const childValue = child[childValueField] || child; console.warn(`No ${childLabel} found with value ${childValue} for parent ${parentLabel}`); }; } onDropdownToggle(event) { if (event) { this.scrollViewportHeight = this.getPixelHeight(this.scrollableInstance.getElementRef().nativeElement); this.virtualScrollItemSize = this.getPixelHeight(this.scrollableInstance.getElementRef().nativeElement.querySelector('novo-list-item')); } } onItemToggled(item: { selected?: boolean; children?: Array<{ selected?: boolean; children?: Array<{ selected?: boolean }> }> }) { if (Array.isArray(item.children)) { this.updateDescendants(item.selected, item.children); } this.updateParentsAndQuickSelect(); this.updateClearAll(item.selected); this.emitSelectedValues(); this.ref.markForCheck(); } initializeDescendantSelection() { this.tabs.forEach((tab) => { if ('childTypeName' in tab && tab.data && tab.data.length) { tab.data.forEach((parent) => { if (parent.selected && parent.children && parent.children.length) { parent.children.forEach((child) => { child.selected = true; }); } }); } }); } updateDescendants(parentIsSelected: boolean, children: Array<{ selected?: boolean; children?: Array<{ selected?: boolean }> }>): void { children.forEach((item) => { parentIsSelected ? (item.selected = true) : delete item.selected; if (Array.isArray(item.children)) { this.updateDescendants(item.selected, item.children); } }); } updateClearAll(itemWasJustSelected?: boolean) { this.showClearAll = itemWasJustSelected ? true : this.tabs.some((tab) => { if ((tab as ParentTab).childTypeName) { return tab.data.some(({ selected, indeterminate }) => selected || indeterminate); } else { return tab.data.some(({ selected }) => selected); } }); } updateParentsAndQuickSelect(): void { // mutate here to avoid dereferencing the objects in displayTabs this.tabs .filter((tab) => 'childTypeName' in tab && !!tab.childTypeName) .forEach((tab) => { const parents = tab.data.filter(({ children }: { children?: any[] }) => children && children.length); parents.forEach((parent: { children?: { selected?: boolean }[] }) => { ['indeterminate', 'selected'].forEach((selectedStateOption) => delete parent[selectedStateOption]); const selectedState = this.getSelectedState(parent.children); if (selectedState) { parent[selectedState] = true; } }); }); if (this.quickSelectConfig) { this.quickSelectConfig.items.forEach((quickSelect) => { delete quickSelect.selected; const selectedState = this.getSelectedState(quickSelect.children as ({ selected?: boolean } & { [key: string]: any })[]); if (selectedState) { quickSelect[selectedState] = true; } }); } } getSelectedState = (childArray: { selected?: boolean; indeterminate?: boolean }[]): 'selected' | 'indeterminate' | undefined => { const numberOfSelectedItems = childArray.filter(({ selected }) => selected).length; if (!numberOfSelectedItems) { return undefined; } return numberOfSelectedItems === childArray.length ? 'selected' : 'indeterminate'; }; emitSelectedValues() { const selectedValues: TabbedGroupPickerTab[] = this.tabs.map((tab) => ({ ...tab, data: tab.data.filter(({ selected }) => selected), })); this.selectionChange.emit(selectedValues); } deselectEverything(event) { Helpers.swallowEvent(event); this.showClearAll = false; if (this.quickSelectConfig) { this.quickSelectConfig.items.forEach((quickSelect) => { delete quickSelect.selected; }); } this.tabs.forEach((tab) => { if ((tab as ParentTab).childTypeName) { tab.data.forEach((item) => { delete item.selected; delete item.indeterminate; item.children.forEach((child) => delete child.selected); }); } else { (tab as ChildTab).data.forEach((item) => delete item.selected); } }); this.emitSelectedValues(); this.ref.markForCheck(); } onClearFilter(event) { Helpers.swallowEvent(event); this.filterText.next(''); } onFilter(event: { target: { value: string } }) { this.filterText.next(event.target.value); } filter = (searchTerm: string) => { this.displayTabs.forEach( (displayTab, i) => (displayTab.data = this.tabs[i].data.filter((item) => item[displayTab.labelField].toLowerCase().includes(searchTerm.toLowerCase()), )), ); this.ref.markForCheck(); }; }
the_stack
import { exec, ExecException } from "child_process"; import build from "CLI/commands/build"; import { CLIError } from "CLI/errors/CLIError"; import fs from "fs-extra"; import kleur from "kleur"; import { lookpath } from "lookpath"; import path from "path"; import prompts from "prompts"; import { COMPILER_VERSION, PACKAGE_ROOT, RBXTS_SCOPE } from "Shared/constants"; import { benchmark } from "Shared/util/benchmark"; import ts from "typescript"; import yargs from "yargs"; interface InitOptions { yes?: boolean; git?: boolean; eslint?: boolean; prettier?: boolean; vscode?: boolean; packageManager?: PackageManager; } enum InitMode { None = "none", Game = "game", Place = "place", Model = "model", Plugin = "plugin", Package = "package", } enum PackageManager { NPM = "npm", Yarn = "yarn", PNPM = "pnpm", } interface PackageManagerCommands { init: string; devInstall: string; build: string; } const packageManagerCommands: Record<PackageManager, PackageManagerCommands> = { [PackageManager.NPM]: { init: "npm init -y", devInstall: "npm install --silent -D", build: "npm run build", }, [PackageManager.Yarn]: { init: "yarn init -y", devInstall: "yarn add --silent -D", build: "yarn run build", }, [PackageManager.PNPM]: { init: "pnpm init -y", devInstall: "pnpm install --silent -D", build: "pnpm run build", }, }; function cmd(cmdStr: string) { return new Promise<string>((resolve, reject) => { exec(cmdStr, (error, stdout) => { if (error) { reject(error); } resolve(stdout); }); }).catch((error: ExecException) => { throw new CLIError(`Command "${error.cmd}" exited with code ${error.code}\n\n${error.message}`); }); } function getNonDevCompilerVersion() { return COMPILER_VERSION.match(/^(.+)-dev.+$/)?.[1] ?? COMPILER_VERSION; } const TEMPLATE_DIR = path.join(PACKAGE_ROOT, "templates"); const GIT_IGNORE = ["/node_modules", "/out", "/include", "*.tsbuildinfo"]; async function init(argv: yargs.Arguments<InitOptions>, mode: InitMode) { const cwd = process.cwd(); const paths = { packageJson: path.join(cwd, "package.json"), packageLockJson: path.join(cwd, "package-lock.json"), projectJson: path.join(cwd, "default.project.json"), serveProjectJson: mode === InitMode.Plugin && path.join(cwd, "serve.project.json"), src: path.join(cwd, "src"), tsconfig: path.join(cwd, "tsconfig.json"), gitignore: path.join(cwd, ".gitignore"), eslintrc: path.join(cwd, ".eslintrc.json"), settings: path.join(cwd, ".vscode", "settings.json"), extensions: path.join(cwd, ".vscode", "extensions.json"), }; const existingPaths = new Array<string>(); for (const filePath of Object.values(paths)) { if (filePath && (await fs.pathExists(filePath))) { const stat = await fs.stat(filePath); if (stat.isFile() || (await fs.readdir(filePath)).length > 0) { existingPaths.push(path.relative(cwd, filePath)); } } } if (existingPaths.length > 0) { const pathInfo = existingPaths.map(v => ` - ${kleur.yellow(v)}\n`).join(""); throw new CLIError(`Cannot initialize project, process could overwrite:\n${pathInfo}`); } if (mode === InitMode.None) { mode = ( await prompts({ type: "select", name: "template", message: "Select template", choices: [InitMode.Game, InitMode.Model, InitMode.Plugin, InitMode.Package].map(value => ({ title: value, value, })), initial: 0, }) ).template; // ctrl+c if (mode === undefined) { return; } } // Detect if there is additional package managers // We don't need to prompt the user to use additional package managers if none are installed const packageManagerExistance: Record<PackageManager, boolean> = { [PackageManager.NPM]: true, // NPM is installed by default, skip checking to save time [PackageManager.PNPM]: (await lookpath("pnpm")) ? true : false, [PackageManager.Yarn]: (await lookpath("yarn")) ? true : false, }; const packageManagerCount = Object.values(packageManagerExistance).filter(exists => exists).length; const { git = argv.git ?? argv.yes ?? false, eslint = argv.eslint ?? argv.yes ?? false, prettier = argv.prettier ?? argv.yes ?? false, vscode = argv.vscode ?? argv.yes ?? false, packageManager = argv.packageManager ?? PackageManager.NPM, }: { git: boolean; eslint: boolean; prettier: boolean; vscode: boolean; packageManager: PackageManager; } = await prompts([ { type: () => argv.git === undefined && argv.yes === undefined && "confirm", name: "git", message: "Configure Git", initial: true, }, { type: () => argv.eslint === undefined && argv.yes === undefined && "confirm", name: "eslint", message: "Configure ESLint", initial: true, }, { type: (_, values) => (argv.eslint || values.eslint) && argv.prettier === undefined && argv.yes === undefined && "confirm", name: "prettier", message: "Configure Prettier", initial: true, }, { type: () => argv.vscode === undefined && argv.yes === undefined && "confirm", name: "vscode", message: "Configure VSCode Project Settings", initial: true, }, { type: () => argv.packageManager === undefined && packageManagerCount > 1 && argv.yes === undefined && "select", name: "packageManager", message: "Multiple package managers detected. Select package manager:", choices: Object.entries(PackageManager) .filter(([, packageManager]) => packageManagerExistance[packageManager]) .map(([managerDisplayName, managerEnum]) => ({ title: managerDisplayName, value: managerEnum, })), }, ]); await benchmark("Initializing..", async () => { const selectedPackageManager = packageManagerCommands[packageManager]; await cmd(selectedPackageManager.init); const pkgJson = await fs.readJson(paths.packageJson); pkgJson.scripts = { build: "rbxtsc", watch: "rbxtsc -w", }; if (mode === InitMode.Package) { pkgJson.name = RBXTS_SCOPE + "/" + pkgJson.name; pkgJson.main = "out/init.lua"; pkgJson.types = "out/index.d.ts"; pkgJson.files = ["out"]; pkgJson.publishConfig = { access: "public", }; pkgJson.scripts.prepublishOnly = selectedPackageManager.build; } await fs.outputFile(paths.packageJson, JSON.stringify(pkgJson, null, 2)); // git init if (git) { try { await cmd("git init"); } catch (error) { if (!(error instanceof CLIError)) throw error; throw new CLIError( `${error.diagnostics[0].messageText}\nDo you not have Git installed? Git CLI is required to use Git functionality. If you do not wish to use Git, answer no to "Configure Git".`, ); } await fs.outputFile(paths.gitignore, GIT_IGNORE.join("\n") + "\n"); } // npm install -D const devDependencies = ["@rbxts/types", `@rbxts/compiler-types@compiler-${getNonDevCompilerVersion()}`]; if (eslint) { devDependencies.push( "eslint", "typescript", "@typescript-eslint/eslint-plugin", "@typescript-eslint/parser", "eslint-plugin-roblox-ts", ); if (prettier) { devDependencies.push("prettier", "eslint-config-prettier", "eslint-plugin-prettier"); } } await cmd(`${selectedPackageManager.devInstall} ${devDependencies.join(" ")}`); // create .eslintrc.json if (eslint) { const eslintConfig = { parser: "@typescript-eslint/parser", parserOptions: { jsx: true, useJSXTextNode: true, ecmaVersion: 2018, sourceType: "module", project: "./tsconfig.json", }, plugins: ["@typescript-eslint", "roblox-ts"], extends: ["plugin:@typescript-eslint/recommended", "plugin:roblox-ts/recommended"], rules: ts.identity<{ [index: string]: unknown }>({}), }; if (prettier) { eslintConfig.plugins.push("prettier"); eslintConfig.extends.push("plugin:prettier/recommended"); eslintConfig.rules["prettier/prettier"] = [ "warn", { semi: true, trailingComma: "all", singleQuote: false, printWidth: 120, tabWidth: 4, useTabs: true, }, ]; } await fs.outputFile(paths.eslintrc, JSON.stringify(eslintConfig, undefined, "\t")); } if (vscode) { const extensions = { recommendations: ["roblox-ts.vscode-roblox-ts"], }; if (eslint) { const settings = { "[typescript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint", "editor.formatOnSave": true, }, "[typescriptreact]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint", "editor.formatOnSave": true, }, "eslint.run": "onType", "eslint.format.enable": true, "typescript.tsdk": "node_modules/typescript/lib", }; await fs.outputFile(paths.settings, JSON.stringify(settings, undefined, "\t")); extensions.recommendations.push("dbaeumer.vscode-eslint"); } await fs.outputFile(paths.extensions, JSON.stringify(extensions, undefined, "\t")); } const templateTsConfig = path.join( TEMPLATE_DIR, `tsconfig-${mode === InitMode.Package ? "package" : "default"}.json`, ); await fs.copy(templateTsConfig, paths.tsconfig); await fs.copy(path.join(TEMPLATE_DIR, mode), cwd); }); await benchmark( "Building..", () => build.handler({ logTruthyChanges: false, noInclude: false, project: ".", usePolling: false, verbose: false, watch: false, writeOnlyChanged: false, $0: argv.$0, _: argv._, }) as never, ); } const GAME_DESCRIPTION = "Generate a Roblox place"; const MODEL_DESCRIPTION = "Generate a Roblox model"; const PLUGIN_DESCRIPTION = "Generate a Roblox Studio plugin"; const PACKAGE_DESCRIPTION = "Generate a roblox-ts npm package"; /** * Defines behavior of `rbxtsc init` command. */ // eslint-disable-next-line @typescript-eslint/ban-types export = ts.identity<yargs.CommandModule<{}, InitOptions>>({ command: "init", describe: "Create a project from a template", builder: () => yargs .option("yes", { alias: "y", boolean: true, describe: "recommended options", }) .option("git", { boolean: true, describe: "Configure Git", }) .option("eslint", { boolean: true, describe: "Configure ESLint", }) .option("prettier", { boolean: true, describe: "Configure Prettier", }) .option("vscode", { boolean: true, describe: "Configure VSCode Project Settings", }) .option("packageManager", { choices: Object.values(PackageManager), describe: "Choose an alternative package manager", }) .command([InitMode.Game, InitMode.Place], GAME_DESCRIPTION, {}, argv => init(argv as never, InitMode.Game)) .command(InitMode.Model, MODEL_DESCRIPTION, {}, argv => init(argv as never, InitMode.Model)) .command(InitMode.Plugin, PLUGIN_DESCRIPTION, {}, argv => init(argv as never, InitMode.Plugin)) .command(InitMode.Package, PACKAGE_DESCRIPTION, {}, argv => init(argv as never, InitMode.Package)), handler: argv => init(argv, InitMode.None), });
the_stack
import * as UT from 'utility-types'; /** Caution: TypeScript enum is compatible with number! By convention, we'd better to relax the comparison to only compare Ordering with zero. Ordering > 0 ==> GT; Ordering < 0 ==> LT; */ export const enum Ordering { LT = -1, EQ = 0, GT = 1 } export type Maybe<T> = T | undefined; export type Writable<T> = {-readonly [P in keyof T]-?: T[P]}; /** Union to Intersection */ export type InterU<U> = (U extends any ? (a: U) => 0 : never) extends ((a: infer I) => 0) ? I : never; export type ArrayIndex<T> = Exclude<keyof T, Extract<keyof any[], string>>; export type Equal<A, B> = A extends B ? (B extends A ? true : false) : false; /** Substitude Type A to B in Type Expr E recursively. @param InferInter Whether infer intersection type, only works when A is TypeVar. */ export type Subst<E, A, B, InferInter = false> = InferInter extends true ? (E extends A & infer X ? B & (X extends A ? unknown : X) : SubstIn<E, A, B, true>) : (E extends A ? B : SubstIn<E, A, B, false>); /** SubstIn is same as Subst except it wont replace top E. @example type T = number | {body: T}; let a: SubstIn<T, T, Date>; a = 1; a = {body: new Date()}; let b: Subst<T, T, Date>; b = new Date(); */ export type SubstIn<E, A, B, InferInter = false> = // First check extends Primitive in order to distribute over union types // Subst unknown check if E does not contain type A, then preserve its type name // Thus SubstIn<A[] | X, B> will preserve type name X if X does not contain type A E extends UT.Primitive ? E : SubstInRaw<E, A, unknown, InferInter> extends E ? E : SubstInRaw<E, A, B, InferInter>; export type SubstInRaw<E, A, B, InferInter> = E extends (...a: infer Params) => infer Ret ? (...a: SubstInRaw<Params, A, B, InferInter>) => Subst<Ret, A, B, InferInter> : E extends [any, ...any[]] ? SubstRecord<E, A, B, InferInter> : E extends Array<infer X> ? SubstArray<X, A, B, InferInter> : E extends ReadonlyArray<infer X> ? SubstROArray<X, A, B, InferInter> : SubstRecord<E, A, B, InferInter>; export type SubstRecord<E, A, B, InferInter> = {[K in keyof E]: Subst<E[K], A, B, InferInter>}; /* // This definition will cause error "Type instantiation is excessively deep and possibly infinite" // Use interface extends to defer the type instantiation export type SubstArray<E, A, B, InferInter> = E extends Array<any> ? Array<{[I in keyof E]: Subst<E[I], A, B, InferInter>}[Exclude<keyof E, string>]> : ReadonlyArray<{[I in keyof E]: Subst<E[I], A, B, InferInter>}[Exclude<keyof E, string>]>; */ export interface SubstArray<X, A, B, InferInter> extends Array<Subst<X, A, B, InferInter>> {} export interface SubstROArray<X, A, B, InferInter> extends ReadonlyArray<Subst<X, A, B, InferInter>> {} export interface $<S extends string> { _TypeVar_: S; } export type TypeVar<S extends string> = $<S>; /** TypeFn, use lamda symbol for better show. (Greek Small Letter Lamda) */ export interface λ<Param extends string, Body> { _TypeFn_: { _Param_: Param; _Body_: Body; }; } export type TypeFn<Param extends string, Body> = λ<Param, Body>; export type ParamVarOfTypeFn<F> = F extends TypeFn<infer Param, any> ? $<Param> : never; export type BodyOfTypeFn<F> = F extends TypeFn<any, infer Body> ? Body : never; export type AppF<F, A> = F extends TypeFn<infer Param, infer Body> ? Subst<Body, $<Param>, A, true> : F; /** Identity Type Function λx.x */ export type IdentF = TypeFn<'x', $<'x'>>; /** @deprecated AppF already did the job to act as a const function when apply to non TypeFn, in other words, every type X(X is not TypeFn) is itself a ConstF<X>. */ export type ConstF<X> = TypeFn<'_', X>; /** The structures of FSubst and FSubstIn are same as their non-F counterparts except the third type param B becomes a type function F which recieve the subtype occurrence of A as parameter; */ export type FSubst<E, A, F> = E extends A ? AppF<F, FSubstIn<E, A, F>> : FSubstIn<E, A, F>; export type FSubstIn<E, A, F> = // See `SubstIn` E extends UT.Primitive ? E : SubstIn<E, A, unknown> extends E ? E : FSubstInRaw<E, A, F>; export type FSubstInRaw<E, A, F> = E extends (...a: infer Params) => infer Ret ? (...a: FSubstInRaw<Params, A, F>) => FSubst<Ret, A, F> : E extends [any, ...any[]] ? FSubstRecord<E, A, F> : E extends ReadonlyArray<any> ? FSubstArray<E, A, F> : FSubstRecord<E, A, F>; export type FSubstRecord<E, A, F> = {[K in keyof E]: FSubst<E[K], A, F>}; export type FSubstArray<E, A, F> = E extends Array<any> ? Array<{[I in keyof E]: FSubst<E[I], A, F>}[Exclude<keyof E, string>]> : ReadonlyArray<{[I in keyof E]: FSubst<E[I], A, F>}[Exclude<keyof E, string>]>; /** Data.Fix @deprecated Impractical, use `SubstIn` and `FSubstIn` instead. @example type A = {kind:'A',name:string}; type B = {kind:'B',target:T1}; type T1 = A | B; type C = {kind:'C',items:T1[]}; type T2 = Fix<T1 | C>; */ export type Fix<T> = {unfix: SubstIn<T, T, Fix<T>>}; /** Transform (A => B | A => C) to (A => B|C) */ export type UnionF<F> = [F] extends [Function] ? [F] extends [(...a: infer A) => infer B] ? (...a: A) => B : never : F; /** Index Signature */ export function IndexSig<T>(a: T): {[k: string]: UnionF<T[keyof T]>} { return a as any; } export type OK<T> = {value: T}; export type Err<E> = {error: E}; export type Result<T, E> = OK<T> | Err<E>; export function isResultOK<A>(a: Result<A, any>): a is OK<A> { return (<Err<any>>a).error === undefined; } export function Err<E>(a: E): undefined extends E ? never : Err<E> { return <any>{error: a}; } export function OK<T>(a: T): OK<T> { return {value: a}; } export interface Eq<A> { equals: (x: A, y: A) => boolean; } export interface Comparator<A> { (x: A, y: A): Ordering; } /** Usage: function f<S extends Stream<S>>(s:S):S {return s.slice()} */ export interface Stream<S extends {readonly [index: number]: S[number]}> { readonly [index: number]: S[number]; length: number; slice(): S; slice(start: number): S; slice(start: number, end: number): S; } export function compare<T>(a: T, b: T): Ordering { if (a > b) return Ordering.GT; if (a < b) return Ordering.LT; return Ordering.EQ; } export function compareArray<S extends Stream<S>>(a1: S, a2: S, cmp: Comparator<S[number]> = compare): Ordering { let l1 = a1.length; let l2 = a2.length; if (!l1 && !l2) return Ordering.EQ; for (let i = 0, l = Math.min(l1, l2); i < l; i++) { let ord = cmp(a1[i], a2[i]); if (ord !== Ordering.EQ) return ord; } return compare(l1, l2); } /** Support custom equals method via Eq<T> interface */ export function deepEqual<T>(a: T, b: T): boolean { if (typeof a !== 'object' || a == null) { return a === b; } if (Array.isArray(a) && Array.isArray(b)) { let l1 = a.length; let l2 = b.length; if (l1 !== l2) return false; for (let i = 0; i < l1; i++) { if (!deepEqual(a[i], b[i])) return false; } } else if (typeof (<any>a).equals === 'function') { return (<any>a).equals(b); } else { for (let k in a) { if (!deepEqual(a[k], b[k])) return false; } } return true; } export const _inspect_ = Symbol.for('nodejs.util.inspect.custom'); /** Compare unicode string by their code points string.fromCodePoint(0x1F437) == "🐷" == "\uD83D\uDC37" == "\u{1F437}" let c1 = '\uD83D\uDC37'; let c2 = '\uFA16'; assert(compareFullUnicode(c1,c2) === Ordering.GT) */ export function compareFullUnicode(s1: string, s2: string): Ordering { let a1 = Array.from(s1).map(Char.ord); let a2 = Array.from(s2).map(Char.ord); return compareArray(a1, a2); } export type BSearchResult = {found: boolean; index: number}; /** Binary Search All items greater than `x` are behind BSearchResult.index When `x` lesser than all elements, result index will be startIndex-1. @param cmp { (x,elementInArray) => Ordering } @param startIndex {} */ export function bsearch<T>(a: T[], x: T, cmp?: Comparator<T>, startIndex?: number, endIndex?: number): BSearchResult; export function bsearch<T, X>( a: T[], x: X, cmp: (x: X, e: T) => Ordering, startIndex?: number, endIndex?: number ): BSearchResult; export function bsearch<T>( a: T[], x: T, cmp: Comparator<T> = compare, startIndex: number = 0, endIndex: number = a.length - 1 ): BSearchResult { let result = {found: false, index: -1}; let i = startIndex - 1; for (let lo = startIndex, hi = endIndex; lo <= hi; ) { i = lo + ((hi - lo + 1) >> 1); let middle = a[i]; let ord = cmp(x, middle); if (ord < 0) { // LT hi = --i; } else if (ord > 0) { // GT lo = i + 1; } else { // EQ result.found = true; break; } } result.index = i; return result; } /** Return sorted unique Array. */ export function sortUnique<T>(a: T[], cmp: Comparator<T> = compare): T[] { let n = a.length; if (n <= 1) return a; a = a.slice().sort(cmp); let len = 1; for (let i = 1, last = a[0]; i < n; i++) { let x = a[i]; if (x === last || cmp(x, last) === Ordering.EQ) continue; last = a[len++] = a[i]; } a.length = len; return a; } // chr(0x1F4AA) == "💪" == "\uD83D\uDCAA" function chr(n: number): string { return String.fromCodePoint(n); } function ord(c: string): number { return c.codePointAt(0)!; } const CHAR_MAX_CODE_POINT = 0x10ffff; export const Char = { chr: chr, ord: ord, pred(c: string): string { return chr(ord(c) - 1); }, predSafe(c: string): string { let n = ord(c) - 1; return chr(n < 0 ? 0 : n); }, succ(c: string): string { return chr(ord(c) + 1); }, succSafe(c: string): string { let n = ord(c) + 1; return chr(n > CHAR_MAX_CODE_POINT ? CHAR_MAX_CODE_POINT : n); }, hexEscape(c: string): string { let code = c.charCodeAt(0); return '\\x' + code.toString(16).padStart(2, '0'); }, unicodeEscape(c: string): string { let code = c.charCodeAt(0); return '\\u' + code.toString(16).padStart(4, '0'); }, codePointEscape(c: string): string { let code = c.codePointAt(0)!; return '\\u{' + code.toString(16) + '}'; }, /** Ctrl A-Z */ ctrl(c: string): string { return String.fromCharCode(c.charCodeAt(0) % 32); }, // Max unicode code point MAX_CODE_POINT: CHAR_MAX_CODE_POINT, MIN_CHAR: chr(0), MAX_CHAR: chr(CHAR_MAX_CODE_POINT) }; /** Simple random int i, min <= i <= max. */ export function randInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; } const _hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn(o: any, k: string): boolean { return _hasOwnProperty.call(o, k); } let _guidCount = 0; /** @deprecated Prefer WeakSet or WeakMap */ export function guidOf(obj: any): string { if (hasOwn(obj, '_GUID_')) { return obj._GUID_; } else { let _guid = guid(); // Prohibit from enumerating Object.defineProperty(obj, '_GUID_', {value: _guid}); return _guid; } } /**Alternative to Symbol()*/ export function guid(): string { _guidCount = (_guidCount + 1) | 0; return '_' + (+new Date()).toString(36).slice(2) + _guidCount.toString(36); } export function flat<T>(a: T[][]): T[] { return (<T[]>[]).concat(...a); } export function escapeUnicodes(s: string, codePointSyntax: boolean = true): string { let chars = codePointSyntax ? Array.from(s) : s.split(''); return chars .map(c => { let cp = ord(c); let cps = cp.toString(16).toUpperCase(); if (cp <= 0xff) { return c; } else if (cp > 0xffff) { return '\\u{' + cps + '}'; } else { return '\\u' + cps.padStart(4, '0'); } }) .join(''); } export function escapeNonAlphanum(s: string, codePointSyntax: boolean = true): string { let alphanum = /^[A-Z0-9\-\\]$/i; let chars = codePointSyntax ? Array.from(s) : s.split(''); return chars .map(c => { let cp = ord(c); let cps = cp.toString(16).toUpperCase(); if (alphanum.test(c)) { return c; } else if (cp <= 0xf) { return '\\x0' + cps; } else if (cp <= 0xff) { return '\\x' + cps; } else if (cp <= 0xfff) { return '\\u0' + cps; } else if (cp > 0xffff) { return '\\u{' + cps + '}'; } else { return '\\u' + cps; } }) .join(''); } export function escapeRegex(s: string, inCharClass = false): string { s = s.replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&'); if (inCharClass) { s = s.replace(/-/g, '\\-'); } return s; } export function sum(nums: number[]): number { let total = 0; for (let n of nums) { total += n; } return total; } export function enumNum(begin: number, end: number): number[] { let a = []; while (begin <= end) { a.push(begin++); } return a; } export function invertMap<K, V>(m: Map<K, V>): Map<V, K> { return new Map(Array.from(m).map(kv => kv.reverse() as [V, K])); } type _InvertRecord<M> = InterU<{[K in keyof M]: {[V in M[K] extends keyof any ? M[K] : string]: K}}[keyof M]>; export type InvertRecord<M> = // Ensure values of M are distinct types. // Overlaps will result in intersection type instead of union // which surely not super type of keyof M keyof M extends _InvertRecord<M>[keyof _InvertRecord<M>] ? _InvertRecord<M> : {[k in M[keyof M] extends keyof any ? M[keyof M] : string]: string}; export function invertRecord<M>(m: M): InvertRecord<M>; export function invertRecord(m: any): any { let a = {} as any; for (let k in m) { a[m[k]] = k; } return a; } const _excludeSignCodePoint = 94; //ord('^'); const _hyphenCodePoint = 45; // ord('-'); const _escapeCodePoint = 92; // ord('\\'); /** Math.pow(2,21). */ const B2_21 = 0x200000; /** Math.pow(2,21) - 1. Bits Char.MAX_CODE_POINT used. */ const B2_21_1 = 0x1fffff; /** Inclusive CharRange representation. CharRangeRepr use number to save memory. Number.MAX_SAFE_INTEGER is 0x1fffffffffffff, 53 bit. Char.MAX_CODE_POINT is 0x10ffff, 21 bit. A number is sufficient to pack two char code points. ``` rangeBegin = CharRangeRepr / Math.pow(2,21) & 0x1FFFFF // shift right 21 bit rangeEnd = CharRangeRepr & 0x1FFFFF // retain right 21 bit ``` A single code point use equal rangeBegin and rangeEnd. Use {_nominal_:true} to enforce nominal type check CharRangeRepr. Number can not directly assign to CharRangeRepr. @example: Single char "A" => `0x41 * Math.pow(2,21) + 0x41 === 0x8200041` Single char "Z" => `0x5A * Math.pow(2,21) + 0x5A === 0xB40005A` Range "A" to "Z" => `0x41 * Math.pow(2,21) + 0x5A === 0x820005A` @todo: Use another bit to repr char range with even gap. "\x10\x12\x14\x16\x18" could be repr as range 0x10 to 0x18 but with even gap. */ export type CharRangeRepr = number & {_nominal_: true}; export namespace CharRange { /** Pack char range two chars to CharRangeRepr */ export function fromCharPair(beginChar: string, endChar: string): CharRangeRepr { return pack(ord(beginChar), ord(endChar)); } /** Pack single char to CharRangeRepr */ export function singleChar(c: string): CharRangeRepr { return single(ord(c)); } /** Pack single char code point to CharRangeRepr */ export function single(codePoint: number): CharRangeRepr { return pack(codePoint, codePoint); } /** Pack char range two code points into number CharRangeRepr */ export function pack(begin: number, end: number): CharRangeRepr { return (begin * B2_21 + end) as CharRangeRepr; } export function begin(r: CharRangeRepr): number { return (r / B2_21) & B2_21_1; } export function end(r: CharRangeRepr): number { return r & B2_21_1; } export function getSize(r: CharRangeRepr): number { return end(r) - begin(r) + 1; } export function includeChar(range: CharRangeRepr, c: string): boolean { let cp = ord(c); return includeCodePoint(range, cp); } export function includeCodePoint(range: CharRangeRepr, cp: number): boolean { return begin(range) <= cp && cp <= end(range); } export function isSubsetOf(a: CharRangeRepr, b: CharRangeRepr): boolean { return begin(b) <= begin(a) && end(a) <= end(b); } export function isSingle(r: CharRangeRepr): boolean { return begin(r) === end(r); } export function intersect(a: CharRangeRepr, b: CharRangeRepr): Maybe<CharRangeRepr> { let a1 = begin(a); let a2 = end(a); let b1 = begin(b); let b2 = end(b); if (b2 < a1 || a2 < b1) return; if (a1 <= b1) { if (b2 <= a2) return b; else return pack(b1, a2); } else { if (a2 <= b2) return a; else return pack(a1, b2); } } export function join(a: CharRangeRepr, b: CharRangeRepr): Maybe<CharRangeRepr> { let a1 = begin(a); let a2 = end(a); let b1 = begin(b); let b2 = end(b); if (b2 + 1 < a1 || a2 + 1 < b1) return; return pack(Math.min(a1, b1), Math.max(a2, b2)); } /** Subtract range: a - b === a, if a and b have no overlap a - b === undefined, if a isSubsetof b a - b === range, if a starts with b or a ends with b a - b === [r1,r2], if b isSubsetof a and a.begin < b.begin && b.end < a.end */ export function subtract(a: CharRangeRepr, b: CharRangeRepr): Maybe<CharRangeRepr | [CharRangeRepr, CharRangeRepr]> { let a1 = begin(a); let a2 = end(a); let b1 = begin(b); let b2 = end(b); if (b2 < a1 || a2 < b1) return a; let left = a1 < b1; let right = b2 < a2; if (left && right) return [pack(a1, b1 - 1), pack(b2 + 1, a2)]; if (left) return pack(a1, b1 - 1); if (right) return pack(b2 + 1, a2); // if (!left && !right) return; } /** Coalesce char range list to non-overlapping sorted ranges. */ export function coalesce(ranges: CharRangeRepr[]): CharRangeRepr[] { let newRanges: CharRangeRepr[] = []; ranges = sortUnique(ranges, CharRange.compare); if (ranges.length <= 1) return ranges; let prev = ranges[0]; for (let i = 1, l = ranges.length; i < l; i++) { let a = ranges[i]; let joined = join(a, prev); if (typeof joined === 'undefined') { newRanges.push(prev); prev = a; } else { prev = joined; } } newRanges.push(prev); return newRanges; } export function compare(a: CharRangeRepr, b: CharRangeRepr): Ordering { if (a === b) return Ordering.EQ; if (a < b) return Ordering.LT; else return Ordering.GT; } export function compareIn(x: CharRangeRepr, r: CharRangeRepr): Ordering { if (isSubsetOf(x, r)) return Ordering.EQ; if (x < r) return Ordering.LT; else return Ordering.GT; } /** If char is less than range low bound, return LT, if char is in range, return EQ, and so forth. */ export function compareCharToRange(c: string, range: CharRangeRepr): Ordering { return compareCodePointToRange(ord(c), range); } export function compareCodePointToRange(cp: number, range: CharRangeRepr): Ordering { let r1 = begin(range); let r2 = end(range); if (cp < r1) return Ordering.LT; if (cp > r2) return Ordering.GT; return Ordering.EQ; } /** Convert CharRange to regex char class like pattern string @see `Charset.fromPattern` */ export function toPattern(range: CharRangeRepr): string { let r1 = begin(range); let r2 = end(range); if (r1 === r2) return toChar(r1); if (r1 + 1 === r2) return toChar(r1) + toChar(r2); return toChar(r1) + '-' + toChar(r2); function toChar(cp: number): string { if (cp === _escapeCodePoint || cp === _excludeSignCodePoint || cp === _hyphenCodePoint) { return '\\' + chr(cp); } else { return chr(cp); } } } export function toCodePoints(range: CharRangeRepr, maxCount = Infinity): number[] { let r1 = begin(range); let r2 = end(range); let a = []; while (r1 <= r2 && a.length < maxCount) { a.push(r1++); } return a; } } /** Regex like Charset,support ranges and invertion @example Charset.fromPattern("^a-z0-9") */ export class Charset { static readonly unicode = new Charset([CharRange.pack(0, Char.MAX_CODE_POINT)]); static readonly empty = new Charset([]); readonly ranges: CharRangeRepr[]; /** Regex like char class pattern string like '^a-f123' to Charset: exclude range "a" to "f" and chars "123". Support "^" to indicate invertion. Char "\" only used to escape "-" and "\" itself. Char classes like "\w\s" are not supported! @param {string} re Regex like char class [^a-z0-9_] input as "^a-z0-9_". */ static fromPattern(re: string): Charset { if (!re.length) return Charset.empty; let codePoints = Array.from(re).map(ord); let stack: number[] = []; let ranges: CharRangeRepr[] = []; let exclude = false; let i = 0; if (codePoints[0] === _excludeSignCodePoint && codePoints.length > 1) { i++; exclude = true; } for (let l = codePoints.length; i < l; i++) { let cp = codePoints[i]; if (cp === _escapeCodePoint) { // Identity escape,e.g. "-" and "=" if (++i < l) { stack.push(codePoints[i]); } else { throw new SyntaxError('Invalid end escape'); } } else if (cp === _hyphenCodePoint) { i++; if (stack.length > 0 && i < l) { let rangeBegin = stack.pop()!; let rangeEnd = codePoints[i]; if (rangeEnd === _escapeCodePoint) { if (++i < l) { rangeEnd = codePoints[i]; } else { throw new SyntaxError('Invalid end escape'); } } if (rangeBegin > rangeEnd) { // z-a is invalid throw new RangeError( 'Charset range out of order: ' + escapeNonAlphanum(String.fromCodePoint(rangeBegin, _hyphenCodePoint, rangeEnd)) + ' !\n' + escapeNonAlphanum(re) ); } ranges.push(CharRange.pack(rangeBegin, rangeEnd)); } else { throw new SyntaxError( 'Incomplete char range at ' + i + ': ' + String.fromCodePoint(...codePoints.slice(i - 2, i + 2)) ); } } else { stack.push(cp); } } ranges = ranges.concat(stack.map(CharRange.single)); let charset = new Charset(ranges); if (exclude) { return Charset.unicode.subtract(charset); } else { return charset; } } /** Build from single char list. */ static fromChars(chars: string) { return Charset.fromCodePoints(Array.from(chars).map(ord)); } static fromCodePoints(codePoints: number[]) { return new Charset(codePoints.map(CharRange.single)); } /** Create from CharRange list. */ constructor(ranges: CharRangeRepr[]) { this.ranges = CharRange.coalesce(ranges); } includeChar(c: string): boolean { return this.includeCodePoint(ord(c)); } includeCodePoint(cp: number): boolean { let {found} = bsearch<CharRangeRepr, number>(this.ranges, cp, (cp, range) => { return CharRange.compareCodePointToRange(cp, range); }); return found; } includeRange(range: CharRangeRepr): boolean { let {found} = bsearch(this.ranges, range, (range, x) => { if (CharRange.isSubsetOf(range, x)) return Ordering.EQ; return CharRange.compare(range, x); }); return found; } isSubsetof(parent: Charset): boolean { let a = this.intersect(parent); return a.equals(this); } isEmpty() { return !this.ranges.length; } _size?: number; /** Get Charset total count of chars */ getSize(): number { if (this._size === undefined) { this._size = sum(this.ranges.map(CharRange.getSize)); } return this._size; } getMinCodePoint(): Maybe<number> { if (!this.ranges.length) return; return CharRange.begin(this.ranges[0]); } getMaxCodePoint(): Maybe<number> { if (!this.ranges.length) return; return CharRange.end(this.ranges[this.ranges.length - 1]); } subtract(other: Charset): Charset { let newRanges: CharRangeRepr[] = []; let thisRanges = this.ranges.slice(); let toExcludeRanges = other.ranges; let i = 0; loopNextExclude: for (let ex of toExcludeRanges) { for (; i < thisRanges.length; i++) { let range = thisRanges[i]; let rg = CharRange.subtract(range, ex); if (rg === range) { // no overlap if (range > ex) { continue loopNextExclude; } else { newRanges.push(range); continue; } } else if (typeof rg === 'undefined') { // whole a has been excluded continue; } else if (Array.isArray(rg)) { newRanges.push(rg[0]); thisRanges[i] = rg[1]; continue loopNextExclude; } else { if (rg < ex) { newRanges.push(rg); continue; } else { thisRanges[i] = rg; continue loopNextExclude; } } } break; } let ranges = newRanges.concat(thisRanges.slice(i)); if (!ranges.length) return Charset.empty; return new Charset(ranges); } inverted(): Charset { return Charset.unicode.subtract(this); } union(other: Charset): Charset { return new Charset(this.ranges.concat(other.ranges)); } intersect(other: Charset): Charset { let otherRanges = other.ranges.slice(); let thisRanges = this.ranges; let newRanges: CharRangeRepr[] = []; for (let i = 0, j = 0; i < thisRanges.length && j < otherRanges.length; ) { let r1 = thisRanges[i]; let r2 = otherRanges[j]; let inter = CharRange.intersect(r1, r2); if (typeof inter === 'undefined') { // no overlap if (r1 < r2) i++; else j++; } else { newRanges.push(inter); let end1 = CharRange.end(r1); let end2 = CharRange.end(r2); if (end1 <= end2) i++; if (end2 <= end1) j++; } } if (!newRanges.length) return Charset.empty; return new Charset(newRanges); } equals(other: Charset): boolean { if (this.ranges.length !== other.ranges.length) return false; return compareArray(this.ranges, other.ranges, CharRange.compare) === Ordering.EQ; } toPattern(): string { return this.ranges.map(CharRange.toPattern).join(''); } toString(): string { return escapeNonAlphanum(this.toPattern()); } toRegex(): RegExp { return new RegExp('[' + this.toPattern().replace(/[\[\]]/g, '\\$&') + ']', 'u'); } toCodePoints(maxCount = Infinity): number[] { let a = []; for (let r of this.ranges) { let b = CharRange.toCodePoints(r, maxCount); maxCount -= b.length; a.push(b); } return flat(a); } [_inspect_](): string { return this.toString(); } static compare(a: Charset, b: Charset): Ordering { if (a === b) return Ordering.EQ; return compareArray(a.ranges, b.ranges, CharRange.compare); } static union(a: Charset[]): Charset { return a.reduce((prev, current) => prev.union(current), Charset.empty); } }
the_stack
import * as sourceMapSupport from "source-map-support"; sourceMapSupport.install(); import { ANTLRErrorListener } from "../src/ANTLRErrorListener"; import { ANTLRInputStream } from "../src/ANTLRInputStream"; import { Array2DHashSet } from "../src/misc/Array2DHashSet"; import { ATN } from "../src/atn/ATN"; import { ATNConfig } from "../src/atn/ATNConfig"; import { ATNConfigSet } from "../src/atn/ATNConfigSet"; import { ATNDeserializer } from "../src/atn/ATNDeserializer"; import { BailErrorStrategy } from "../src/BailErrorStrategy"; import { BitSet } from "../src/misc/BitSet"; import { CharStream } from "../src/CharStream"; import { CharStreams } from "../src/CharStreams"; import { CodePointBuffer } from "../src/CodePointBuffer"; import { CodePointCharStream } from "../src/CodePointCharStream"; import { CommonTokenStream } from "../src/CommonTokenStream"; import { DefaultErrorStrategy } from "../src/DefaultErrorStrategy"; import { DFA } from "../src/dfa/DFA"; import { DFAState } from "../src/dfa/DFAState"; import { DiagnosticErrorListener } from "../src/DiagnosticErrorListener"; import { ErrorNode } from "../src/tree/ErrorNode"; import { Interval } from "../src/misc/Interval"; import { JavaUnicodeInputStream } from "./JavaUnicodeInputStream"; import { Lexer } from "../src/Lexer"; import { LexerATNSimulator } from "../src/atn/LexerATNSimulator"; import { MurmurHash } from "../src/misc/MurmurHash"; import { NotNull } from "../src/Decorators"; import { ObjectEqualityComparator } from "../src/misc/ObjectEqualityComparator"; import { Override } from "../src/Decorators"; import { ParseCancellationException } from "../src/misc/ParseCancellationException"; import { Parser } from "../src/Parser"; import { ParserATNSimulator } from "../src/atn/ParserATNSimulator"; import { ParserErrorListener } from "../src/ParserErrorListener"; import { ParserInterpreter } from "../src/ParserInterpreter"; import { ParserRuleContext } from "../src/ParserRuleContext"; import { ParseTree } from "../src/tree/ParseTree"; import { ParseTreeListener } from "../src/tree/ParseTreeListener"; import { ParseTreeWalker } from "../src/tree/ParseTreeWalker"; import { PredictionContextCache } from "../src/atn/PredictionContextCache"; import { PredictionMode } from "../src/atn/PredictionMode"; import { RecognitionException } from "../src/RecognitionException"; import { Recognizer } from "../src/Recognizer"; import { SimulatorState } from "../src/atn/SimulatorState"; import { Stopwatch } from "./Stopwatch"; import { TerminalNode } from "../src/tree/TerminalNode"; import { TimeSpan } from "./TimeSpan"; import { Token } from "../src/Token"; import { TokenSource } from "../src/TokenSource"; import { TokenStream } from "../src/TokenStream"; import * as Utils from "../src/misc/Utils"; import { JavaLexer as JavaLexer } from "./gen/std/JavaLexer"; import { JavaLexer as JavaLexerAtn } from "./gen/std-atn/JavaLexer"; import { JavaLRLexer as JavaLRLexer } from "./gen/lr/JavaLRLexer"; import { JavaLRLexer as JavaLRLexerAtn } from "./gen/lr-atn/JavaLRLexer"; import { JavaParser as JavaParser } from "./gen/std/JavaParser"; import { JavaParser as JavaParserAtn } from "./gen/std-atn/JavaParser"; import { JavaLRParser as JavaLRParser } from "./gen/lr/JavaLRParser"; import { JavaLRParser as JavaLRParserAtn } from "./gen/lr-atn/JavaLRParser"; import * as assert from "assert"; import * as fs from "fs"; import * as path from "path"; type GeneratedJavaLexer = Lexer & { }; type GeneratedJavaParser = Parser & { atn: ATN; compilationUnit(): ParserRuleContext; }; type AnyJavaParser = GeneratedJavaParser | ParserInterpreter; function assertTrue(value: boolean, message?: string) { assert.strictEqual(value, true, message); } /** * Randomize array element order in-place. * Using Durstenfeld shuffle algorithm. */ function shuffleArray<T>(array: T[]) { for (let i = array.length - 1; i > 0; i--) { let j = (Math.random() * (i + 1)) | 0; let temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } function listFilesSync(directory: string, filter: FilenameFilter): string[] { let files = fs.readdirSync(directory); files = files.filter((value: string) => { return filter.accept(directory, path.basename(value)); }); return files.map((value) => path.join(directory, value)); } function writeFileSync(directory: string, name: string, content: string): void { fs.writeFileSync(path.join(directory, name), content, { encoding: "utf8" }); } function forceGC(): boolean { if (!global.gc) { return false; } global.gc(); return true; } export class MurmurHashChecksum { private value: number; private count: number; constructor() { this.value = MurmurHash.initialize(); this.count = 0; } public update(value: number): void { this.value = MurmurHash.update(this.value, value); this.count++; } public getValue(): number { return MurmurHash.finish(this.value, this.count); } } class EmptyListener implements ParseTreeListener { } export class TestPerformance { /** * Parse all java files under this package within the JDK_SOURCE_ROOT * (environment variable or property defined on the Java command line). */ private static readonly TOP_PACKAGE: string = "java.lang"; /** * {@code true} to load java files from sub-packages of * {@link #TOP_PACKAGE}. */ private static readonly RECURSIVE: boolean = true; /** * {@code true} to read all source files from disk into memory before * starting the parse. The default value is {@code true} to help prevent * drive speed from affecting the performance results. This value may be set * to {@code false} to support parsing large input sets which would not * otherwise fit into memory. */ public static readonly PRELOAD_SOURCES: boolean = true; /** * The encoding to use when reading source files. */ public static readonly ENCODING: string = "UTF-8"; /** * The maximum number of files to parse in a single iteration. */ private static readonly MAX_FILES_PER_PARSE_ITERATION: number = 0x7FFFFFFF; /** * {@code true} to call {@link Collections#shuffle} on the list of input * files before the first parse iteration. */ private static readonly SHUFFLE_FILES_AT_START: boolean = false; /** * {@code true} to call {@link Collections#shuffle} before each parse * iteration <em>after</em> the first. */ private static readonly SHUFFLE_FILES_AFTER_ITERATIONS: boolean = false; /** * The instance of {@link Random} passed when calling * {@link Collections#shuffle}. */ // private static readonly RANDOM: Random = new Random(); /** * {@code true} to use the Java grammar with expressions in the v4 * left-recursive syntax (JavaLR.g4). {@code false} to use the standard * grammar (Java.g4). In either case, the grammar is renamed in the * temporary directory to Java.g4 before compiling. */ private static readonly USE_LR_GRAMMAR: boolean = true; /** * {@code true} to specify the {@code -Xforce-atn} option when generating * the grammar, forcing all decisions in {@code JavaParser} to be handled by * {@link ParserATNSimulator#adaptivePredict}. */ private static readonly FORCE_ATN: boolean = false; /** * {@code true} to specify the {@code -atn} option when generating the * grammar. This will cause ANTLR to export the ATN for each decision as a * DOT (GraphViz) file. */ private static readonly EXPORT_ATN_GRAPHS: boolean = true; /** * {@code true} to specify the {@code -XdbgST} option when generating the * grammar. */ private static readonly DEBUG_TEMPLATES: boolean = false; /** * {@code true} to specify the {@code -XdbgSTWait} option when generating the * grammar. */ private static readonly DEBUG_TEMPLATES_WAIT: boolean = TestPerformance.DEBUG_TEMPLATES; /** * {@code true} to delete temporary (generated and compiled) files when the * test completes. */ private static readonly DELETE_TEMP_FILES: boolean = true; /** * {@code true} to use a {@link ParserInterpreter} for parsing instead of * generated parser. */ private static readonly USE_PARSER_INTERPRETER: boolean = false; /** * {@code true} to call {@link System#gc} and then wait for 5 seconds at the * end of the test to make it easier for a profiler to grab a heap dump at * the end of the test run. */ private static readonly PAUSE_FOR_HEAP_DUMP: boolean = false; /** * Parse each file with {@code JavaParser.compilationUnit}. */ private static readonly RUN_PARSER: boolean = true; /** * {@code true} to use {@link BailErrorStrategy}, {@code false} to use * {@link DefaultErrorStrategy}. */ private static readonly BAIL_ON_ERROR: boolean = false; /** * {@code true} to compute a checksum for verifying consistency across * optimizations and multiple passes. */ private static readonly COMPUTE_CHECKSUM: boolean = true; /** * This value is passed to {@link Parser#setBuildParseTree}. */ private static readonly BUILD_PARSE_TREES: boolean = false; /** * Use * {@link ParseTreeWalker#DEFAULT}{@code .}{@link ParseTreeWalker#walk walk} * with the {@code JavaParserBaseListener} to show parse tree walking * overhead. If {@link #BUILD_PARSE_TREES} is {@code false}, the listener * will instead be called during the parsing process via * {@link Parser#addParseListener}. */ private static readonly BLANK_LISTENER: boolean = false; private static readonly EXPORT_LARGEST_CONFIG_CONTEXTS: boolean = false; /** * Shows the number of {@link DFAState} and {@link ATNConfig} instances in * the DFA cache at the end of each pass. If {@link #REUSE_LEXER_DFA} and/or * {@link #REUSE_PARSER_DFA} are false, the corresponding instance numbers * will only apply to one file (the last file if {@link #NUMBER_OF_THREADS} * is 0, otherwise the last file which was parsed on the first thread). */ private static readonly SHOW_DFA_STATE_STATS: boolean = true; /** * If {@code true}, the DFA state statistics report includes a breakdown of * the number of DFA states contained in each decision (with rule names). */ public static readonly DETAILED_DFA_STATE_STATS: boolean = true; private static readonly ENABLE_LEXER_DFA: boolean = true; private static readonly ENABLE_PARSER_DFA: boolean = true; /** * If {@code true}, the DFA will be used for full context parsing as well as * SLL parsing. */ private static readonly ENABLE_PARSER_FULL_CONTEXT_DFA: boolean = false; /** * Specify the {@link PredictionMode} used by the * {@link ParserATNSimulator}. If {@link #TWO_STAGE_PARSING} is * {@code true}, this value only applies to the second stage, as the first * stage will always use {@link PredictionMode#SLL}. */ private static readonly PREDICTION_MODE: PredictionMode = PredictionMode.LL; private static readonly FORCE_GLOBAL_CONTEXT: boolean = false; private static readonly TRY_LOCAL_CONTEXT_FIRST: boolean = true; private static readonly OPTIMIZE_LL1: boolean = true; private static readonly OPTIMIZE_UNIQUE_CLOSURE: boolean = true; private static readonly OPTIMIZE_TAIL_CALLS: boolean = true; private static readonly TAIL_CALL_PRESERVES_SLL: boolean = true; private static readonly TREAT_SLLK1_CONFLICT_AS_AMBIGUITY: boolean = false; private static readonly TWO_STAGE_PARSING: boolean = true; private static readonly SHOW_CONFIG_STATS: boolean = false; /** * If {@code true}, detailed statistics for the number of DFA edges were * taken while parsing each file, as well as the number of DFA edges which * required on-the-fly computation. */ public static readonly COMPUTE_TRANSITION_STATS: boolean = false; private static readonly SHOW_TRANSITION_STATS_PER_FILE: boolean = false; /** * If {@code true}, the transition statistics will be adjusted to a running * total before reporting the final results. */ private static readonly TRANSITION_RUNNING_AVERAGE: boolean = false; /** * If {@code true}, transition statistics will be weighted according to the * total number of transitions taken during the parsing of each file. */ private static readonly TRANSITION_WEIGHTED_AVERAGE: boolean = false; /** * If {@code true}, after each pass a summary of the time required to parse * each file will be printed. */ private static readonly COMPUTE_TIMING_STATS: boolean = false; /** * If {@code true}, the timing statistics for {@link #COMPUTE_TIMING_STATS} * will be cumulative (i.e. the time reported for the <em>n</em>th file will * be the total time required to parse the first <em>n</em> files). */ private static readonly TIMING_CUMULATIVE: boolean = false; /** * If {@code true}, the timing statistics will include the parser only. This * flag allows for targeted measurements, and helps eliminate variance when * {@link #PRELOAD_SOURCES} is {@code false}. * <p/> * This flag has no impact when {@link #RUN_PARSER} is {@code false}. */ private static readonly TIME_PARSE_ONLY: boolean = false; /** * When {@code true}, messages will be printed to {@link System#err} when * the first stage (SLL) parsing resulted in a syntax error. This option is * ignored when {@link #TWO_STAGE_PARSING} is {@code false}. */ private static readonly REPORT_SECOND_STAGE_RETRY: boolean = true; public static readonly REPORT_SYNTAX_ERRORS: boolean = true; public static readonly REPORT_AMBIGUITIES: boolean = false; public static readonly REPORT_FULL_CONTEXT: boolean = false; public static readonly REPORT_CONTEXT_SENSITIVITY: boolean = TestPerformance.REPORT_FULL_CONTEXT; /** * If {@code true}, a single {@code JavaLexer} will be used, and * {@link Lexer#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static readonly REUSE_LEXER: boolean = false; /** * If {@code true}, a single DFA will be used for lexing which is shared * across all threads and files. Otherwise, each file will be lexed with its * own DFA which is accomplished by creating one ATN instance per thread and * clearing its DFA cache before lexing each file. */ private static readonly REUSE_LEXER_DFA: boolean = true; /** * If {@code true}, a single {@code JavaParser} will be used, and * {@link Parser#setInputStream} will be called to initialize it for each * source file. Otherwise, a new instance will be created for each file. */ private static readonly REUSE_PARSER: boolean = false; /** * If {@code true}, a single DFA will be used for parsing which is shared * across all threads and files. Otherwise, each file will be parsed with * its own DFA which is accomplished by creating one ATN instance per thread * and clearing its DFA cache before parsing each file. */ private static readonly REUSE_PARSER_DFA: boolean = true; /** * If {@code true}, the shared lexer and parser are reset after each pass. * If {@code false}, all passes after the first will be fully "warmed up", * which makes them faster and can compare them to the first warm-up pass, * but it will not distinguish bytecode load/JIT time from warm-up time * during the first pass. */ private static readonly CLEAR_DFA: boolean = false; /** * Total number of passes to make over the source. */ private static readonly PASSES: number = 4; /** * This option controls the granularity of multi-threaded parse operations. * If {@code true}, the parsing operation will be parallelized across files; * otherwise the parsing will be parallelized across multiple iterations. */ private static readonly FILE_GRANULARITY: boolean = true; /** * Number of parser threads to use. */ public static readonly NUMBER_OF_THREADS: number = 1; private static readonly sharedLexers: Array<Lexer | undefined> = new Array<Lexer>(TestPerformance.NUMBER_OF_THREADS); private static readonly sharedLexerATNs: Array<ATN | undefined> = new Array<ATN>(TestPerformance.NUMBER_OF_THREADS); private static readonly sharedParsers: Array<AnyJavaParser | undefined> = new Array<AnyJavaParser>(TestPerformance.NUMBER_OF_THREADS); private static readonly sharedParserATNs: Array<ATN | undefined> = new Array<ATN>(TestPerformance.NUMBER_OF_THREADS); private static readonly sharedListeners: Array<ParseTreeListener | undefined> = new Array<ParseTreeListener>(TestPerformance.NUMBER_OF_THREADS); private static readonly totalTransitionsPerFile: Uint32Array[] = new Array<Uint32Array>(TestPerformance.PASSES); private static readonly computedTransitionsPerFile: Uint32Array[] = new Array<Uint32Array>(TestPerformance.PASSES); private static decisionInvocationsPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static fullContextFallbackPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static nonSllPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static totalTransitionsPerDecisionPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static computedTransitionsPerDecisionPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static fullContextTransitionsPerDecisionPerFile: Uint32Array[][] = new Array<Uint32Array[]>(TestPerformance.PASSES); private static readonly timePerFile: Float64Array[] = new Array<Float64Array>(TestPerformance.PASSES); private static readonly tokensPerFile: Int32Array[] = new Array<Int32Array>(TestPerformance.PASSES); private static readonly tokenCount: Int32Array = new Int32Array(TestPerformance.PASSES); public compileJdk(): void { let jdkSourceRoot: string | undefined = this.getSourceRoot("JDK"); assertTrue(jdkSourceRoot != null && jdkSourceRoot.length > 0, "The JDK_SOURCE_ROOT environment variable must be set for performance testing."); jdkSourceRoot = jdkSourceRoot as string; let lexerCtor: {new(input: CharStream): GeneratedJavaLexer} = TestPerformance.USE_LR_GRAMMAR ? JavaLRLexer : JavaLexer; let parserCtor: {new(input: TokenStream): GeneratedJavaParser} = TestPerformance.USE_LR_GRAMMAR ? JavaLRParser : JavaParser; if (TestPerformance.FORCE_ATN) { lexerCtor = TestPerformance.USE_LR_GRAMMAR ? JavaLRLexerAtn : JavaLexerAtn; parserCtor = TestPerformance.USE_LR_GRAMMAR ? JavaLRParserAtn : JavaParserAtn; } else { lexerCtor = TestPerformance.USE_LR_GRAMMAR ? JavaLRLexer : JavaLexer; parserCtor = TestPerformance.USE_LR_GRAMMAR ? JavaLRParser : JavaParser; } let listenerName: string = TestPerformance.USE_LR_GRAMMAR ? "JavaLRBaseListener" : "JavaBaseListener"; let entryPoint: string = "compilationUnit"; let factory: ParserFactory = this.getParserFactory(lexerCtor, parserCtor, EmptyListener, JavaLRParser.prototype.compilationUnit.name, (parser) => parser.compilationUnit()); if (TestPerformance.TOP_PACKAGE.length > 0) { jdkSourceRoot = jdkSourceRoot + "/" + TestPerformance.TOP_PACKAGE.replace(/\./g, "/"); } let directory: string = jdkSourceRoot; assertTrue(fs.lstatSync(directory).isDirectory()); let filesFilter: FilenameFilter = FilenameFilters.extension(".java", false); let directoriesFilter: FilenameFilter = FilenameFilters.ALL_FILES; let sources: InputDescriptor[] = this.loadSources(directory, filesFilter, directoriesFilter, TestPerformance.RECURSIVE); for (let i = 0; i < TestPerformance.PASSES; i++) { if (TestPerformance.COMPUTE_TRANSITION_STATS) { TestPerformance.totalTransitionsPerFile[i] = new Uint32Array(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.computedTransitionsPerFile[i] = new Uint32Array(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); if (TestPerformance.DETAILED_DFA_STATE_STATS) { TestPerformance.decisionInvocationsPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.fullContextFallbackPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.nonSllPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.totalTransitionsPerDecisionPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.computedTransitionsPerDecisionPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.fullContextTransitionsPerDecisionPerFile[i] = new Array<Uint32Array>(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); } } if (TestPerformance.COMPUTE_TIMING_STATS) { TestPerformance.timePerFile[i] = new Float64Array(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); TestPerformance.tokensPerFile[i] = new Int32Array(Math.min(sources.length, TestPerformance.MAX_FILES_PER_PARSE_ITERATION)); } } console.log(`Located ${sources.length} source files.`); process.stdout.write(TestPerformance.getOptionsDescription(TestPerformance.TOP_PACKAGE)); // let executorService: ExecutorService = Executors.newFixedThreadPool(TestPerformance.FILE_GRANULARITY ? 1 : TestPerformance.NUMBER_OF_THREADS, new NumberedThreadFactory()); // let passResults: Promise<any>[] = []; // passResults.add(executorService.submit(new Runnable() { // @Override // run(): void { try { this.parse1(0, factory, sources, TestPerformance.SHUFFLE_FILES_AT_START); } catch (ex) { //Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); console.error(ex); } // } // })); for (let i = 0; i < TestPerformance.PASSES - 1; i++) { let currentPass: number = i + 1; // passResults.add(executorService.submit(new Runnable() { // @Override // run(): void { if (TestPerformance.CLEAR_DFA) { let index: number = TestPerformance.FILE_GRANULARITY ? 0 : 0; if (TestPerformance.sharedLexers.length > 0 && TestPerformance.sharedLexers[index] != null) { let atn: ATN = TestPerformance.sharedLexers[index]!.atn; atn.clearDFA(); } if (TestPerformance.sharedParsers.length > 0 && TestPerformance.sharedParsers[index] != null) { let atn: ATN = TestPerformance.sharedParsers[index]!.atn; atn.clearDFA(); } if (TestPerformance.FILE_GRANULARITY) { TestPerformance.sharedLexers.fill(undefined); TestPerformance.sharedParsers.fill(undefined); } } try { this.parse2(currentPass, factory, sources, TestPerformance.SHUFFLE_FILES_AFTER_ITERATIONS); } catch (ex) { // Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); console.error(ex); } // } // })); } // for (let passResult of passResults) { // passResult.get(); // } // executorService.shutdown(); // executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); if (TestPerformance.COMPUTE_TRANSITION_STATS && TestPerformance.SHOW_TRANSITION_STATS_PER_FILE) { this.computeTransitionStatistics(); } if (TestPerformance.COMPUTE_TIMING_STATS) { this.computeTimingStatistics(); } sources.length = 0; if (TestPerformance.PAUSE_FOR_HEAP_DUMP) { forceGC(); console.log("Pausing before application exit."); // try { // Thread.sleep(4000); // } catch (InterruptedException ex) { // Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); // } } } /** * Compute and print ATN/DFA transition statistics. */ private computeTransitionStatistics(): void { if (TestPerformance.TRANSITION_RUNNING_AVERAGE) { for (let i = 0; i < TestPerformance.PASSES; i++) { let data: Uint32Array = TestPerformance.computedTransitionsPerFile[i]; for (let j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } data = TestPerformance.totalTransitionsPerFile[i]; for (let j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } } } let sumNum: Uint32Array = new Uint32Array(TestPerformance.totalTransitionsPerFile[0].length); let sumDen: Uint32Array = new Uint32Array(TestPerformance.totalTransitionsPerFile[0].length); let sumNormalized: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); for (let i = 0; i < TestPerformance.PASSES; i++) { let num: Uint32Array = TestPerformance.computedTransitionsPerFile[i]; let den: Uint32Array = TestPerformance.totalTransitionsPerFile[i]; for (let j = 0; j < den.length; j++) { sumNum[j] += num[j]; sumDen[j] += den[j]; if (den[j] > 0) { sumNormalized[j] += num[j] / den[j]; } } } let weightedAverage: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); let average: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); for (let i = 0; i < average.length; i++) { if (sumDen[i] > 0) { weightedAverage[i] = sumNum[i] / sumDen[i]; } else { weightedAverage[i] = 0; } average[i] = sumNormalized[i] / TestPerformance.PASSES; } let low95: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); let high95: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); let low67: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); let high67: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); let stddev: Float64Array = new Float64Array(TestPerformance.totalTransitionsPerFile[0].length); for (let i = 0; i < stddev.length; i++) { let points: Float64Array = new Float64Array(TestPerformance.PASSES); for (let j = 0; j < TestPerformance.PASSES; j++) { let totalTransitions: number = TestPerformance.totalTransitionsPerFile[j][i]; if (totalTransitions > 0) { points[j] = TestPerformance.computedTransitionsPerFile[j][i] / TestPerformance.totalTransitionsPerFile[j][i]; } else { points[j] = 0; } } points.sort(); let averageValue: number = TestPerformance.TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; let value: number = 0; for (let j = 0; j < TestPerformance.PASSES; j++) { let diff: number = points[j] - averageValue; value += diff * diff; } let ignoreCount95: number = Math.round(TestPerformance.PASSES * (1 - 0.95) / 2.0) | 0; let ignoreCount67: number = Math.round(TestPerformance.PASSES * (1 - 0.667) / 2.0) | 0; low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / TestPerformance.PASSES); } console.log("File\tAverage\tStd. Dev.\t95%% Low\t95%% High\t66.7%% Low\t66.7%% High"); for (let i = 0; i < stddev.length; i++) { let averageValue: number = TestPerformance.TRANSITION_WEIGHTED_AVERAGE ? weightedAverage[i] : average[i]; console.log(`${i + 1}\t${averageValue}\t${stddev[i]}\t${averageValue - low95[i]}\t${high95[i] - averageValue}\t${averageValue - low67[i]}\t${high67[i] - averageValue}`); } } /** * Compute and print timing statistics. */ private computeTimingStatistics(): void { if (TestPerformance.TIMING_CUMULATIVE) { for (let i = 0; i < TestPerformance.PASSES; i++) { let data: Float64Array = TestPerformance.timePerFile[i]; for (let j = 0; j < data.length - 1; j++) { data[j + 1] += data[j]; } let data2: Int32Array = TestPerformance.tokensPerFile[i]; for (let j = 0; j < data2.length - 1; j++) { data2[j + 1] += data2[j]; } } } let fileCount: number = TestPerformance.timePerFile[0].length; let sum: Float64Array = new Float64Array(fileCount); for (let i = 0; i < TestPerformance.PASSES; i++) { let data: Float64Array = TestPerformance.timePerFile[i]; let tokenData: Int32Array = TestPerformance.tokensPerFile[i]; for (let j = 0; j < data.length; j++) { sum[j] += data[j] / tokenData[j]; } } let average: Float64Array = new Float64Array(fileCount); for (let i = 0; i < average.length; i++) { average[i] = sum[i] / TestPerformance.PASSES; } let low95: Float64Array = new Float64Array(fileCount); let high95: Float64Array = new Float64Array(fileCount); let low67: Float64Array = new Float64Array(fileCount); let high67: Float64Array = new Float64Array(fileCount); let stddev: Float64Array = new Float64Array(fileCount); for (let i = 0; i < stddev.length; i++) { let points: Float64Array = new Float64Array(TestPerformance.PASSES); for (let j = 0; j < TestPerformance.PASSES; j++) { points[j] = TestPerformance.timePerFile[j][i] / TestPerformance.tokensPerFile[j][i]; } points.sort(); let averageValue: number = average[i]; let value: number = 0; for (let j = 0; j < TestPerformance.PASSES; j++) { let diff: number = points[j] - averageValue; value += diff * diff; } let ignoreCount95: number = Math.round(TestPerformance.PASSES * (1 - 0.95) / 2.0) | 0; let ignoreCount67: number = Math.round(TestPerformance.PASSES * (1 - 0.667) / 2.0) | 0; low95[i] = points[ignoreCount95]; high95[i] = points[points.length - 1 - ignoreCount95]; low67[i] = points[ignoreCount67]; high67[i] = points[points.length - 1 - ignoreCount67]; stddev[i] = Math.sqrt(value / TestPerformance.PASSES); } console.log("File\tAverage\tStd. Dev.\t95% Low\t95% High\t66.7% Low\t66.7% High"); for (let i = 0; i < stddev.length; i++) { let averageValue: number = average[i]; console.log(`${i + 1}\t${averageValue}\t${stddev[i]}\t${averageValue - low95[i]}\t${high95[i] - averageValue}\t${averageValue - low67[i]}\t${high67[i] - averageValue}`); } } private getSourceRoot(prefix: string): string | undefined { let sourceRoot = process.env[prefix + "_SOURCE_ROOT"]; // if (sourceRoot == null) { // sourceRoot = System.getProperty(prefix+"_SOURCE_ROOT"); // } return sourceRoot; } // @Override // protected eraseTempDir(): void { // if (TestPerformance.DELETE_TEMP_FILES) { // super.eraseTempDir(); // } // } public static getOptionsDescription(topPackage: string): string { let builder: string = ""; builder += ("Input="); if (topPackage.length === 0) { builder += ("*"); } else { builder += (topPackage) + (".*"); } builder += (", Grammar=") + (TestPerformance.USE_LR_GRAMMAR ? "LR" : "Standard"); builder += (", ForceAtn=") + (TestPerformance.FORCE_ATN); builder += (", Lexer:") + (TestPerformance.ENABLE_LEXER_DFA ? "DFA" : "ATN"); builder += (", Parser:") + (TestPerformance.ENABLE_PARSER_DFA ? "DFA" : "ATN"); builder += ("\n"); builder += ("Op=Lex") + (TestPerformance.RUN_PARSER ? "+Parse" : " only"); builder += (", Strategy=") + (TestPerformance.BAIL_ON_ERROR ? BailErrorStrategy.name : DefaultErrorStrategy.name); builder += (", BuildParseTree=") + (TestPerformance.BUILD_PARSE_TREES); builder += (", WalkBlankListener=") + (TestPerformance.BLANK_LISTENER); builder += ("\n"); builder += ("Lexer=") + (TestPerformance.REUSE_LEXER ? "setInputStream" : "newInstance"); builder += (", Parser=") + (TestPerformance.REUSE_PARSER ? "setInputStream" : "newInstance"); builder += (", AfterPass=") + (TestPerformance.CLEAR_DFA ? "newInstance" : "setInputStream"); builder += ("\n"); builder += ("UniqueClosure=") + (TestPerformance.OPTIMIZE_UNIQUE_CLOSURE ? "optimize" : "complete"); builder += ("\n"); return builder.toString(); } /** * This method is separate from {@link #parse2} so the first pass can be distinguished when analyzing * profiler results. */ protected parse1(currentPass: number, factory: ParserFactory, sources: InputDescriptor[], shuffleSources: boolean): void { if (TestPerformance.FILE_GRANULARITY) { forceGC(); } this.parseSources(currentPass, factory, sources, shuffleSources); } /** * This method is separate from {@link #parse1} so the first pass can be distinguished when analyzing * profiler results. */ protected parse2(currentPass: number, factory: ParserFactory, sources: InputDescriptor[], shuffleSources: boolean): void { if (TestPerformance.FILE_GRANULARITY) { forceGC(); } this.parseSources(currentPass, factory, sources, shuffleSources); } protected loadSources(directory: string, filesFilter: FilenameFilter, directoriesFilter: FilenameFilter, recursive: boolean): InputDescriptor[]; protected loadSources(directory: string, filesFilter: FilenameFilter, directoriesFilter: FilenameFilter, recursive: boolean, result: InputDescriptor[]): void; protected loadSources(directory: string, filesFilter: FilenameFilter, directoriesFilter: FilenameFilter, recursive: boolean, result?: InputDescriptor[]): InputDescriptor[] | void { if (result === undefined) { result = []; this.loadSources(directory, filesFilter, directoriesFilter, recursive, result); return result; } assert(fs.lstatSync(directory).isDirectory()); let sources: string[] = listFilesSync(directory, filesFilter); for (let file of sources) { if (!fs.lstatSync(file).isFile()) { continue; } result.push(new InputDescriptor(fs.realpathSync(file))); } if (recursive) { let children: string[] = listFilesSync(directory, directoriesFilter); for (let child of children) { if (fs.lstatSync(child).isDirectory()) { this.loadSources(child, filesFilter, directoriesFilter, true, result); } } } } public configOutputSize: number = 0; protected parseSources(currentPass: number, factory: ParserFactory, sources: InputDescriptor[], shuffleSources: boolean): void { if (shuffleSources) { let sourcesList: InputDescriptor[] = sources.slice(0); shuffleArray(sourcesList); sources = sourcesList; } let startTime: Stopwatch = Stopwatch.startNew(); TestPerformance.tokenCount[currentPass] = 0; let inputSize: number = 0; let inputCount: number = 0; let results: Array<FileParseResult | undefined> = []; // let executorService: ExecutorService; // if (TestPerformance.FILE_GRANULARITY) { // executorService = Executors.newFixedThreadPool(TestPerformance.FILE_GRANULARITY ? TestPerformance.NUMBER_OF_THREADS : 1, new NumberedThreadFactory()); // } else { // executorService = Executors.newSingleThreadExecutor(new FixedThreadNumberFactory((<NumberedThread>Thread.currentThread()).getThreadNumber())); // } for (let inputDescriptor of sources) { if (inputCount >= TestPerformance.MAX_FILES_PER_PARSE_ITERATION) { break; } let input: CharStream = inputDescriptor.getInputStream(); input.seek(0); inputSize += input.size; inputCount++; let futureChecksum: () => FileParseResult | undefined = () => { // @Override // call(): FileParseResult { // this incurred a great deal of overhead and was causing significant variations in performance results. // console.log(`Parsing file ${input.sourceName}`); try { return factory.parseFile(input, currentPass, 0); } catch (ex) { console.error(ex); } return undefined; // } }; results.push(futureChecksum()); } let checksum = new MurmurHashChecksum(); let currentIndex: number = -1; for (let future of results) { currentIndex++; let fileChecksum: number = 0; // try { let fileResult: FileParseResult | undefined = future; if (fileResult == null) { continue; } if (TestPerformance.COMPUTE_TRANSITION_STATS) { TestPerformance.totalTransitionsPerFile[currentPass][currentIndex] = TestPerformance.sum(fileResult.parserTotalTransitions); TestPerformance.computedTransitionsPerFile[currentPass][currentIndex] = TestPerformance.sum(fileResult.parserComputedTransitions); if (TestPerformance.DETAILED_DFA_STATE_STATS) { TestPerformance.decisionInvocationsPerFile[currentPass][currentIndex] = fileResult.decisionInvocations; TestPerformance.fullContextFallbackPerFile[currentPass][currentIndex] = fileResult.fullContextFallback; TestPerformance.nonSllPerFile[currentPass][currentIndex] = fileResult.nonSll; TestPerformance.totalTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserTotalTransitions; TestPerformance.computedTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserComputedTransitions; TestPerformance.fullContextTransitionsPerDecisionPerFile[currentPass][currentIndex] = fileResult.parserFullContextTransitions; } } if (TestPerformance.COMPUTE_TIMING_STATS) { TestPerformance.timePerFile[currentPass][currentIndex] = fileResult.elapsedTime.totalMilliseconds; TestPerformance.tokensPerFile[currentPass][currentIndex] = fileResult.tokenCount; } fileChecksum = fileResult.checksum; // } catch (ExecutionException ex) { // Logger.getLogger(TestPerformance.class.getName()).log(Level.SEVERE, null, ex); // } if (TestPerformance.COMPUTE_CHECKSUM) { TestPerformance.updateChecksum(checksum, fileChecksum); } } // executorService.shutdown(); // executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); console.log(`${currentPass + 1}. Total parse time for ${inputCount} files (${Math.round(inputSize / 1024)} KiB, ${TestPerformance.tokenCount[currentPass]} tokens${TestPerformance.COMPUTE_CHECKSUM ? `, checksum 0x${(checksum.getValue() >>> 0).toString(16)}` : ""}): ${Math.round(startTime.elapsedMillis())}ms`); if (TestPerformance.sharedLexers.length > 0) { let index: number = TestPerformance.FILE_GRANULARITY ? 0 : 0; let lexer: Lexer = TestPerformance.sharedLexers[index]!; let lexerInterpreter: LexerATNSimulator = lexer.interpreter; let modeToDFA: DFA[] = lexerInterpreter.atn.modeToDFA; if (TestPerformance.SHOW_DFA_STATE_STATS) { let states: number = 0; let configs: number = 0; let uniqueConfigs: Array2DHashSet<ATNConfig> = new Array2DHashSet<ATNConfig>(ObjectEqualityComparator.INSTANCE); for (let dfa of modeToDFA) { if (dfa == null) { continue; } states += dfa.states.size; for (let state of dfa.states) { configs += state.configs.size; uniqueConfigs.addAll(state.configs); } } console.log(`There are ${states} lexer DFAState instances, ${configs} configs (${uniqueConfigs.size} unique), ${lexerInterpreter.atn.contextCacheSize} prediction contexts.`); if (TestPerformance.DETAILED_DFA_STATE_STATS) { console.log("\tMode\tStates\tConfigs\tMode"); for (let i = 0; i < modeToDFA.length; i++) { let dfa: DFA = modeToDFA[i]; if (dfa == null || dfa.states.isEmpty) { continue; } let modeConfigs: number = 0; for (let state of dfa.states) { modeConfigs += state.configs.size; } let modeName: string = lexer.modeNames[i]; console.log(`\t${dfa.decision}\t${dfa.states.size}\t${modeConfigs}\t${modeName}`); } } } } if (TestPerformance.RUN_PARSER && TestPerformance.sharedParsers.length > 0) { let index: number = TestPerformance.FILE_GRANULARITY ? 0 : 0; let parser: Parser = TestPerformance.sharedParsers[index]!; // make sure the individual DFAState objects actually have unique ATNConfig arrays let interpreter: ParserATNSimulator = parser.interpreter; let decisionToDFA: DFA[] = interpreter.atn.decisionToDFA; if (TestPerformance.SHOW_DFA_STATE_STATS) { let states: number = 0; let configs: number = 0; let uniqueConfigs: Array2DHashSet<ATNConfig> = new Array2DHashSet<ATNConfig>(ObjectEqualityComparator.INSTANCE); for (let dfa of decisionToDFA) { if (dfa == null) { continue; } states += dfa.states.size; for (let state of dfa.states) { configs += state.configs.size; uniqueConfigs.addAll(state.configs); } } console.log(`There are ${states} parser DFAState instances, ${configs} configs (${uniqueConfigs.size} unique), ${interpreter.atn.contextCacheSize} prediction contexts.`); if (TestPerformance.DETAILED_DFA_STATE_STATS) { if (TestPerformance.COMPUTE_TRANSITION_STATS) { console.log("\tDecision\tStates\tConfigs\tPredict (ALL)\tPredict (LL)\tNon-SLL\tTransitions\tTransitions (ATN)\tTransitions (LL)\tLA (SLL)\tLA (LL)\tRule"); } else { console.log("\tDecision\tStates\tConfigs\tRule"); } for (let i = 0; i < decisionToDFA.length; i++) { let dfa: DFA = decisionToDFA[i]; if (dfa == null || dfa.states.isEmpty) { continue; } let decisionConfigs: number = 0; for (let state of dfa.states) { decisionConfigs += state.configs.size; } let ruleName: string = parser.ruleNames[parser.atn.decisionToState[dfa.decision].ruleIndex]; let calls: number = 0; let fullContextCalls: number = 0; let nonSllCalls: number = 0; let transitions: number = 0; let computedTransitions: number = 0; let fullContextTransitions: number = 0; let lookahead: number = 0; let fullContextLookahead: number = 0; let formatString: string; if (TestPerformance.COMPUTE_TRANSITION_STATS) { for (let data of TestPerformance.decisionInvocationsPerFile[currentPass]) { calls += data[i]; } for (let data of TestPerformance.fullContextFallbackPerFile[currentPass]) { fullContextCalls += data[i]; } for (let data of TestPerformance.nonSllPerFile[currentPass]) { nonSllCalls += data[i]; } for (let data of TestPerformance.totalTransitionsPerDecisionPerFile[currentPass]) { transitions += data[i]; } for (let data of TestPerformance.computedTransitionsPerDecisionPerFile[currentPass]) { computedTransitions += data[i]; } for (let data of TestPerformance.fullContextTransitionsPerDecisionPerFile[currentPass]) { fullContextTransitions += data[i]; } if (calls > 0) { lookahead = (transitions - fullContextTransitions) / calls; } if (fullContextCalls > 0) { fullContextLookahead = fullContextTransitions / fullContextCalls; } formatString = `\t${dfa.decision}\t${dfa.states.size}\t${decisionConfigs}\t${calls}\t${fullContextCalls}\t${nonSllCalls}\t${transitions}\t${computedTransitions}\t${fullContextTransitions}\t${lookahead}\t${fullContextLookahead}\t${ruleName}`; } else { calls = 0; formatString = `\t${dfa.decision}\t${dfa.states.size}\t${decisionConfigs}\t${ruleName}`; } console.log(formatString); } } } let localDfaCount: number = 0; let globalDfaCount: number = 0; let localConfigCount: number = 0; let globalConfigCount: number = 0; let contextsInDFAState: Int32Array = new Int32Array(0); for (let dfa of decisionToDFA) { if (dfa == null) { continue; } if (TestPerformance.SHOW_CONFIG_STATS) { for (let state of dfa.states) { if (state.configs.size >= contextsInDFAState.length) { let contextsInDFAState2 = new Int32Array(state.configs.size + 1); contextsInDFAState2.set(contextsInDFAState); contextsInDFAState = contextsInDFAState2; } if (state.isAcceptState) { let hasGlobal: boolean = false; for (let config of state.configs) { if (config.reachesIntoOuterContext) { globalConfigCount++; hasGlobal = true; } else { localConfigCount++; } } if (hasGlobal) { globalDfaCount++; } else { localDfaCount++; } } contextsInDFAState[state.configs.size]++; } } if (TestPerformance.EXPORT_LARGEST_CONFIG_CONTEXTS) { for (let state of dfa.states) { for (let config of state.configs) { let configOutput: string = config.toDotString(); if (configOutput.length <= this.configOutputSize) { continue; } this.configOutputSize = configOutput.length; throw new Error("Not implemented"); // writeFileSync(tmpdir, "d" + dfa.decision + ".s" + state.stateNumber + ".a" + config.alt + ".config.dot", configOutput); } } } } if (TestPerformance.SHOW_CONFIG_STATS && currentPass === 0) { console.log(` DFA accept states: ${localDfaCount + globalDfaCount} total, ${localDfaCount} with only local context, ${globalDfaCount} with a global context`); console.log(` Config stats: ${localConfigCount + globalConfigCount} total, ${localConfigCount} local, ${globalConfigCount} global`); if (TestPerformance.SHOW_DFA_STATE_STATS) { for (let i = 0; i < contextsInDFAState.length; i++) { if (contextsInDFAState[i] !== 0) { console.log(` ${i} configs = ${contextsInDFAState[i]}`); } } } } } if (TestPerformance.COMPUTE_TIMING_STATS) { console.log("File\tTokens\tTime"); for (let i = 0; i < TestPerformance.timePerFile[currentPass].length; i++) { console.log(`${i + 1}\t${TestPerformance.tokensPerFile[currentPass][i]}\t${TestPerformance.timePerFile[currentPass][i]}`); } } } private static sum(array: Uint32Array): number { let result: number = 0; for (let value of array) { result += value; } return result; } public static updateChecksum(checksum: MurmurHashChecksum, value: number | Token | undefined): void { if (typeof value === "number") { checksum.update(value); } else { let token: Token | undefined = value; if (token == null) { checksum.update(0); return; } TestPerformance.updateChecksum(checksum, token.startIndex); TestPerformance.updateChecksum(checksum, token.stopIndex); TestPerformance.updateChecksum(checksum, token.line); TestPerformance.updateChecksum(checksum, token.charPositionInLine); TestPerformance.updateChecksum(checksum, token.type); TestPerformance.updateChecksum(checksum, token.channel); } } protected getParserFactory(lexerCtor: {new(input: CharStream): GeneratedJavaLexer}, parserCtor: {new(input: TokenStream): GeneratedJavaParser}, listenerCtor: {new(): ParseTreeListener}, entryPointName: string, entryPoint: (parser: GeneratedJavaParser) => ParserRuleContext): ParserFactory { // try { // let loader: ClassLoader = new URLClassLoader(new URL[] { new File(tmpdir).toURI().toURL() }, ClassLoader.getSystemClassLoader()); // lexerClass: Class<? extends Lexer> = loader.loadClass(lexerName).asSubclass(Lexer.class); // parserClass: Class<? extends Parser> = loader.loadClass(parserName).asSubclass(Parser.class); // listenerClass: Class<? extends ParseTreeListener> = (Class<? extends ParseTreeListener>)loader.loadClass(listenerName).asSubclass(ParseTreeListener.class); // lexerCtor: Constructor<? extends Lexer> = lexerClass.getConstructor(CharStream.class); // parserCtor: Constructor<? extends Parser> = parserClass.getConstructor(TokenStream.class); // construct initial instances of the lexer and parser to deserialize their ATNs let lexerInstance = new lexerCtor(CharStreams.fromString("")); let parserInstance = new parserCtor(new CommonTokenStream(lexerInstance)); if (!TestPerformance.REUSE_LEXER_DFA) { let lexerSerializedATN: string = lexerInstance.serializedATN; for (let i = 0; i < TestPerformance.NUMBER_OF_THREADS; i++) { TestPerformance.sharedLexerATNs[i] = new ATNDeserializer().deserialize(Utils.toCharArray(lexerSerializedATN)); } } if (TestPerformance.RUN_PARSER && !TestPerformance.REUSE_PARSER_DFA) { let parserSerializedATN: string = parserInstance.serializedATN; for (let i = 0; i < TestPerformance.NUMBER_OF_THREADS; i++) { TestPerformance.sharedParserATNs[i] = new ATNDeserializer().deserialize(Utils.toCharArray(parserSerializedATN)); } } return { // @SuppressWarnings("unused") // @Override parseFile(input: CharStream, currentPass: number, thread: number): FileParseResult { let checksum = new MurmurHashChecksum(); let startTime: Stopwatch = Stopwatch.startNew(); assert(thread >= 0 && thread < TestPerformance.NUMBER_OF_THREADS); try { let listener: ParseTreeListener | undefined = TestPerformance.sharedListeners[thread]; if (listener == null) { listener = new listenerCtor(); TestPerformance.sharedListeners[thread] = listener; } let lexer: Lexer | undefined = TestPerformance.sharedLexers[thread]; if (TestPerformance.REUSE_LEXER && lexer != null) { lexer.inputStream = input; } else { let previousLexer: Lexer | undefined = lexer; lexer = new lexerCtor(input); TestPerformance.sharedLexers[thread] = lexer; let atn: ATN = (TestPerformance.FILE_GRANULARITY || previousLexer == null ? lexer : previousLexer).atn; if (!TestPerformance.REUSE_LEXER_DFA || (!TestPerformance.FILE_GRANULARITY && previousLexer == null)) { atn = TestPerformance.sharedLexerATNs[thread]!; } if (!TestPerformance.ENABLE_LEXER_DFA) { lexer.interpreter = new NonCachingLexerATNSimulator(atn, lexer); } else if (!TestPerformance.REUSE_LEXER_DFA || TestPerformance.COMPUTE_TRANSITION_STATS) { lexer.interpreter = new StatisticsLexerATNSimulator(atn, lexer); } } lexer.removeErrorListeners(); lexer.addErrorListener(DescriptiveLexerErrorListener.INSTANCE); lexer.interpreter.optimize_tail_calls = TestPerformance.OPTIMIZE_TAIL_CALLS; if (TestPerformance.ENABLE_LEXER_DFA && !TestPerformance.REUSE_LEXER_DFA) { lexer.interpreter.atn.clearDFA(); } let tokens: CommonTokenStream = new CommonTokenStream(lexer); tokens.fill(); TestPerformance.tokenCount[currentPass] += tokens.size; if (TestPerformance.COMPUTE_CHECKSUM) { for (let token of tokens.getTokens()) { TestPerformance.updateChecksum(checksum, token); } } if (!TestPerformance.RUN_PARSER) { return new FileParseResult(input.sourceName, checksum.getValue(), undefined, tokens.size, startTime, lexer, undefined); } let parseStartTime: Stopwatch = Stopwatch.startNew(); let parser: AnyJavaParser | undefined = TestPerformance.sharedParsers[thread]; if (TestPerformance.REUSE_PARSER && parser != null) { parser.inputStream = tokens; } else { let previousParser: Parser | undefined = parser; if (TestPerformance.USE_PARSER_INTERPRETER) { let referenceParser: Parser = new parserCtor(tokens); parser = new ParserInterpreter(referenceParser.grammarFileName, referenceParser.vocabulary, referenceParser.ruleNames, referenceParser.atn, tokens); } else { parser = new parserCtor(tokens); } let atn: ATN = (TestPerformance.FILE_GRANULARITY || previousParser == null ? parser : previousParser).atn; if (!TestPerformance.REUSE_PARSER_DFA || (!TestPerformance.FILE_GRANULARITY && previousParser == null)) { atn = TestPerformance.sharedParserATNs[thread]!; } if (!TestPerformance.ENABLE_PARSER_DFA) { parser.interpreter = new NonCachingParserATNSimulator(atn, parser); } else if (!TestPerformance.REUSE_PARSER_DFA || TestPerformance.COMPUTE_TRANSITION_STATS) { parser.interpreter = new StatisticsParserATNSimulator(atn, parser); } TestPerformance.sharedParsers[thread] = parser; } parser.removeParseListeners(); parser.removeErrorListeners(); if (!TestPerformance.TWO_STAGE_PARSING) { parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); } if (TestPerformance.ENABLE_PARSER_DFA && !TestPerformance.REUSE_PARSER_DFA) { parser.interpreter.atn.clearDFA(); } parser.interpreter.setPredictionMode(TestPerformance.TWO_STAGE_PARSING ? PredictionMode.SLL : TestPerformance.PREDICTION_MODE); parser.interpreter.force_global_context = TestPerformance.FORCE_GLOBAL_CONTEXT && !TestPerformance.TWO_STAGE_PARSING; parser.interpreter.always_try_local_context = TestPerformance.TRY_LOCAL_CONTEXT_FIRST || TestPerformance.TWO_STAGE_PARSING; parser.interpreter.enable_global_context_dfa = TestPerformance.ENABLE_PARSER_FULL_CONTEXT_DFA; parser.interpreter.optimize_ll1 = TestPerformance.OPTIMIZE_LL1; parser.interpreter.optimize_unique_closure = TestPerformance.OPTIMIZE_UNIQUE_CLOSURE; parser.interpreter.optimize_tail_calls = TestPerformance.OPTIMIZE_TAIL_CALLS; parser.interpreter.tail_call_preserves_sll = TestPerformance.TAIL_CALL_PRESERVES_SLL; parser.interpreter.treat_sllk1_conflict_as_ambiguity = TestPerformance.TREAT_SLLK1_CONFLICT_AS_AMBIGUITY; parser.buildParseTree = TestPerformance.BUILD_PARSE_TREES; if (!TestPerformance.BUILD_PARSE_TREES && TestPerformance.BLANK_LISTENER) { parser.addParseListener(listener); } if (TestPerformance.BAIL_ON_ERROR || TestPerformance.TWO_STAGE_PARSING) { parser.errorHandler = new BailErrorStrategy(); } // let parseMethod: Method = parserClass.getMethod(entryPoint); let parseResult: ParserRuleContext; try { if (TestPerformance.COMPUTE_CHECKSUM && !TestPerformance.BUILD_PARSE_TREES) { parser.addParseListener(new ChecksumParseTreeListener(checksum)); } if (parser instanceof ParserInterpreter) { parseResult = parser.parse(parser.ruleNames.indexOf(entryPointName)); } else { parseResult = entryPoint(parser); } } catch (ex) { if (!TestPerformance.TWO_STAGE_PARSING) { throw ex; } let sourceName: string = tokens.sourceName; sourceName = sourceName != null && sourceName.length > 0 ? sourceName + ": " : ""; if (TestPerformance.REPORT_SECOND_STAGE_RETRY) { console.error(sourceName + "Forced to retry with full context."); } if (!(ex instanceof ParseCancellationException)) { throw ex; } tokens.seek(0); if (TestPerformance.REUSE_PARSER && TestPerformance.sharedParsers[thread] != null) { parser.inputStream = tokens; } else { if (TestPerformance.USE_PARSER_INTERPRETER) { let referenceParser: Parser = new parserCtor(tokens); parser = new ParserInterpreter(referenceParser.grammarFileName, referenceParser.vocabulary, referenceParser.ruleNames, referenceParser.atn, tokens); } else { parser = new parserCtor(tokens); } TestPerformance.sharedParsers[thread] = parser; } parser.removeParseListeners(); parser.removeErrorListeners(); parser.addErrorListener(DescriptiveErrorListener.INSTANCE); parser.addErrorListener(new SummarizingDiagnosticErrorListener()); if (!TestPerformance.ENABLE_PARSER_DFA) { parser.interpreter = new NonCachingParserATNSimulator(parser.atn, parser); } else if (!TestPerformance.REUSE_PARSER_DFA) { parser.interpreter = new StatisticsParserATNSimulator(TestPerformance.sharedParserATNs[thread]!, parser); } else if (TestPerformance.COMPUTE_TRANSITION_STATS) { parser.interpreter = new StatisticsParserATNSimulator(parser.atn, parser); } parser.interpreter.setPredictionMode(TestPerformance.PREDICTION_MODE); parser.interpreter.force_global_context = TestPerformance.FORCE_GLOBAL_CONTEXT; parser.interpreter.always_try_local_context = TestPerformance.TRY_LOCAL_CONTEXT_FIRST; parser.interpreter.enable_global_context_dfa = TestPerformance.ENABLE_PARSER_FULL_CONTEXT_DFA; parser.interpreter.optimize_ll1 = TestPerformance.OPTIMIZE_LL1; parser.interpreter.optimize_unique_closure = TestPerformance.OPTIMIZE_UNIQUE_CLOSURE; parser.interpreter.optimize_tail_calls = TestPerformance.OPTIMIZE_TAIL_CALLS; parser.interpreter.tail_call_preserves_sll = TestPerformance.TAIL_CALL_PRESERVES_SLL; parser.interpreter.treat_sllk1_conflict_as_ambiguity = TestPerformance.TREAT_SLLK1_CONFLICT_AS_AMBIGUITY; parser.buildParseTree = TestPerformance.BUILD_PARSE_TREES; if (TestPerformance.COMPUTE_CHECKSUM && !TestPerformance.BUILD_PARSE_TREES) { parser.addParseListener(new ChecksumParseTreeListener(checksum)); } if (!TestPerformance.BUILD_PARSE_TREES && TestPerformance.BLANK_LISTENER) { parser.addParseListener(listener); } if (TestPerformance.BAIL_ON_ERROR) { parser.errorHandler = new BailErrorStrategy(); } if (parser instanceof ParserInterpreter) { parseResult = parser.parse(parser.ruleNames.indexOf(entryPointName)); } else { parseResult = entryPoint(parser); } } if (TestPerformance.COMPUTE_CHECKSUM && TestPerformance.BUILD_PARSE_TREES) { ParseTreeWalker.DEFAULT.walk(new ChecksumParseTreeListener(checksum), parseResult); } if (TestPerformance.BUILD_PARSE_TREES && TestPerformance.BLANK_LISTENER) { ParseTreeWalker.DEFAULT.walk(listener, parseResult); } return new FileParseResult(input.sourceName, checksum.getValue(), parseResult, tokens.size, TestPerformance.TIME_PARSE_ONLY ? parseStartTime : startTime, lexer, parser); } catch (e) { if (!TestPerformance.REPORT_SYNTAX_ERRORS && e instanceof ParseCancellationException) { return new FileParseResult("unknown", checksum.getValue(), undefined, 0, startTime, undefined, undefined); } // e.printStackTrace(System.out); console.error(e); throw new Error("IllegalStateException: " + e); } }, }; // } catch (Exception e) { // e.printStackTrace(System.out); // Assert.fail(e.getMessage()); // throw new IllegalStateException(e); // } } } export interface ParserFactory { parseFile(input: CharStream, currentPass: number, thread: number): FileParseResult; } export class FileParseResult { public sourceName: string; public checksum: number; public parseTree?: ParseTree; public tokenCount: number; public startTime: Stopwatch; public elapsedTime: TimeSpan; public lexerDFASize: number; public lexerTotalTransitions: number; public lexerComputedTransitions: number; public parserDFASize: number; public decisionInvocations: Uint32Array; public fullContextFallback: Uint32Array; public nonSll: Uint32Array; public parserTotalTransitions: Uint32Array; public parserComputedTransitions: Uint32Array; public parserFullContextTransitions: Uint32Array; constructor(sourceName: string, checksum: number, parseTree: ParseTree | undefined, tokenCount: number, startTime: Stopwatch, lexer: Lexer | undefined, parser: Parser | undefined) { this.sourceName = sourceName; this.checksum = checksum; this.parseTree = parseTree; this.tokenCount = tokenCount; this.startTime = startTime; this.elapsedTime = this.startTime.elapsed(); if (lexer != null) { let interpreter: LexerATNSimulator = lexer.interpreter; if (interpreter instanceof StatisticsLexerATNSimulator) { this.lexerTotalTransitions = interpreter.totalTransitions; this.lexerComputedTransitions = interpreter.computedTransitions; } else { this.lexerTotalTransitions = 0; this.lexerComputedTransitions = 0; } let dfaSize: number = 0; for (let dfa of interpreter.atn.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size; } } this.lexerDFASize = dfaSize; } else { this.lexerDFASize = 0; this.lexerTotalTransitions = 0; this.lexerComputedTransitions = 0; } if (parser != null) { let interpreter: ParserATNSimulator = parser.interpreter; if (interpreter instanceof StatisticsParserATNSimulator) { this.decisionInvocations = interpreter.decisionInvocations; this.fullContextFallback = interpreter.fullContextFallback; this.nonSll = interpreter.nonSll; this.parserTotalTransitions = interpreter.totalTransitions; this.parserComputedTransitions = interpreter.computedTransitions; this.parserFullContextTransitions = interpreter.fullContextTransitions; } else { this.decisionInvocations = new Uint32Array(0); this.fullContextFallback = new Uint32Array(0); this.nonSll = new Uint32Array(0); this.parserTotalTransitions = new Uint32Array(0); this.parserComputedTransitions = new Uint32Array(0); this.parserFullContextTransitions = new Uint32Array(0); } let dfaSize: number = 0; for (let dfa of interpreter.atn.decisionToDFA) { if (dfa != null) { dfaSize += dfa.states.size; } } this.parserDFASize = dfaSize; } else { this.parserDFASize = 0; this.decisionInvocations = new Uint32Array(0); this.fullContextFallback = new Uint32Array(0); this.nonSll = new Uint32Array(0); this.parserTotalTransitions = new Uint32Array(0); this.parserComputedTransitions = new Uint32Array(0); this.parserFullContextTransitions = new Uint32Array(0); } } } class StatisticsLexerATNSimulator extends LexerATNSimulator { public totalTransitions: number; public computedTransitions: number; constructor(atn: ATN); constructor(atn: ATN, recog: Lexer); constructor(atn: ATN, recog?: Lexer) { if (recog === undefined) { super(atn); } else { super(atn, recog); } this.totalTransitions = 0; this.computedTransitions = 0; } @Override protected getExistingTargetState(s: DFAState, t: number): DFAState | undefined { this.totalTransitions++; return super.getExistingTargetState(s, t); } @Override protected computeTargetState(input: CharStream, s: DFAState, t: number): DFAState { this.computedTransitions++; return super.computeTargetState(input, s, t); } } class StatisticsParserATNSimulator extends ParserATNSimulator { public decisionInvocations: Uint32Array; public fullContextFallback: Uint32Array; public nonSll: Uint32Array; public totalTransitions: Uint32Array; public computedTransitions: Uint32Array; public fullContextTransitions: Uint32Array; private decision: number; constructor(atn: ATN, parser: Parser) { super(atn, parser); this.decisionInvocations = new Uint32Array(atn.decisionToState.length); this.fullContextFallback = new Uint32Array(atn.decisionToState.length); this.nonSll = new Uint32Array(atn.decisionToState.length); this.totalTransitions = new Uint32Array(atn.decisionToState.length); this.computedTransitions = new Uint32Array(atn.decisionToState.length); this.fullContextTransitions = new Uint32Array(atn.decisionToState.length); this.decision = -1; } public adaptivePredict(input: TokenStream, decision: number, outerContext: ParserRuleContext): number; public adaptivePredict(input: TokenStream, decision: number, outerContext: ParserRuleContext, useContext: boolean): number; @Override public adaptivePredict(input: TokenStream, decision: number, outerContext: ParserRuleContext, useContext?: boolean): number { if (useContext === undefined) { try { this.decision = decision; this.decisionInvocations[decision]++; return super.adaptivePredict(input, decision, outerContext); } finally { this.decision = -1; } } else { if (useContext) { this.fullContextFallback[decision]++; } return super.adaptivePredict(input, decision, outerContext, useContext); } } @Override protected getExistingTargetState(previousD: DFAState, t: number): DFAState | undefined { this.totalTransitions[this.decision]++; return super.getExistingTargetState(previousD, t); } @Override protected computeTargetState(dfa: DFA, s: DFAState, remainingGlobalContext: ParserRuleContext, t: number, useContext: boolean, contextCache: PredictionContextCache): [DFAState, ParserRuleContext | undefined] { this.computedTransitions[this.decision]++; return super.computeTargetState(dfa, s, remainingGlobalContext, t, useContext, contextCache); } @Override protected computeReachSet(dfa: DFA, previous: SimulatorState, t: number, contextCache: PredictionContextCache): SimulatorState | undefined { if (previous.useContext) { this.totalTransitions[this.decision]++; this.computedTransitions[this.decision]++; this.fullContextTransitions[this.decision]++; } return super.computeReachSet(dfa, previous, t, contextCache); } } class DescriptiveErrorListener implements ParserErrorListener { public static INSTANCE: DescriptiveErrorListener = new DescriptiveErrorListener(); @Override public syntaxError<T extends Token>(recognizer: Recognizer<T, any>, offendingSymbol: T | undefined, line: number, charPositionInLine: number, msg: string, e: RecognitionException | undefined): void { if (!TestPerformance.REPORT_SYNTAX_ERRORS) { return; } let inputStream = recognizer.inputStream; let sourceName: string = inputStream != null ? inputStream.sourceName : ""; if (sourceName.length > 0) { sourceName = `${sourceName}:${line}:${charPositionInLine}: `; } console.error(sourceName + "line " + line + ":" + charPositionInLine + " " + msg); } } class DescriptiveLexerErrorListener implements ANTLRErrorListener<number> { public static INSTANCE: DescriptiveLexerErrorListener = new DescriptiveLexerErrorListener(); @Override public syntaxError<T extends number>(recognizer: Recognizer<T, any>, offendingSymbol: T | undefined, line: number, charPositionInLine: number, msg: string, e: RecognitionException | undefined): void { if (!TestPerformance.REPORT_SYNTAX_ERRORS) { return; } let inputStream = recognizer.inputStream; let sourceName: string = inputStream != null ? inputStream.sourceName : ""; if (sourceName.length > 0) { sourceName = `${sourceName}:${line}:${charPositionInLine}: `; } process.stderr.write(sourceName + "line " + line + ":" + charPositionInLine + " " + msg); } } class SummarizingDiagnosticErrorListener extends DiagnosticErrorListener { private _sllConflict: BitSet | undefined; private _sllConfigs!: ATNConfigSet; @Override public reportAmbiguity(recognizer: Parser, dfa: DFA, startIndex: number, stopIndex: number, exact: boolean, ambigAlts: BitSet | undefined, configs: ATNConfigSet): void { if (TestPerformance.COMPUTE_TRANSITION_STATS && TestPerformance.DETAILED_DFA_STATE_STATS) { let sllPredictions: BitSet = this.getConflictingAlts(this._sllConflict, this._sllConfigs); let sllPrediction: number = sllPredictions.nextSetBit(0); let llPredictions: BitSet = this.getConflictingAlts(ambigAlts, configs); let llPrediction: number = llPredictions.cardinality() === 0 ? ATN.INVALID_ALT_NUMBER : llPredictions.nextSetBit(0); if (sllPrediction !== llPrediction) { (recognizer.interpreter as StatisticsParserATNSimulator).nonSll[dfa.decision]++; } } if (!TestPerformance.REPORT_AMBIGUITIES) { return; } // show the rule name along with the decision let decision: number = dfa.decision; let rule: string = recognizer.ruleNames[dfa.atnStartState.ruleIndex]; let input: string = recognizer.inputStream.getText(Interval.of(startIndex, stopIndex)); recognizer.notifyErrorListeners(`reportAmbiguity d=${decision} (${rule}): ambigAlts=${ambigAlts}, input='${input}'`); } @Override public reportAttemptingFullContext(recognizer: Parser, dfa: DFA, startIndex: number, stopIndex: number, conflictingAlts: BitSet | undefined, conflictState: SimulatorState): void { this._sllConflict = conflictingAlts; this._sllConfigs = conflictState.s0.configs; if (!TestPerformance.REPORT_FULL_CONTEXT) { return; } // show the rule name and viable configs along with the base info let decision: number = dfa.decision; let rule: string = recognizer.ruleNames[dfa.atnStartState.ruleIndex]; let input: string = recognizer.inputStream.getText(Interval.of(startIndex, stopIndex)); let representedAlts: BitSet = this.getConflictingAlts(conflictingAlts, conflictState.s0.configs); recognizer.notifyErrorListeners(`reportAttemptingFullContext d=${decision} (${rule}), input='${input}', viable=${representedAlts}`); } @Override public reportContextSensitivity(recognizer: Parser, dfa: DFA, startIndex: number, stopIndex: number, prediction: number, acceptState: SimulatorState): void { if (TestPerformance.COMPUTE_TRANSITION_STATS && TestPerformance.DETAILED_DFA_STATE_STATS) { let sllPredictions: BitSet = this.getConflictingAlts(this._sllConflict, this._sllConfigs); let sllPrediction: number = sllPredictions.nextSetBit(0); if (sllPrediction !== prediction) { (recognizer.interpreter as StatisticsParserATNSimulator).nonSll[dfa.decision]++; } } if (!TestPerformance.REPORT_CONTEXT_SENSITIVITY) { return; } // show the rule name and viable configs along with the base info let decision: number = dfa.decision; let rule: string = recognizer.ruleNames[dfa.atnStartState.ruleIndex]; let input: string = recognizer.inputStream.getText(Interval.of(startIndex, stopIndex)); recognizer.notifyErrorListeners(`reportContextSensitivity d=${decision} (${rule}), input='${input}', viable={${prediction}}`); } } export interface FilenameFilter { accept(dir: string, name: string): boolean; } namespace FilenameFilters { export const ALL_FILES: FilenameFilter = { // @Override accept(dir: string, name: string): boolean { return true; }, }; export function extension(extension: string): FilenameFilter; export function extension(extension: string, caseSensitive: boolean): FilenameFilter; export function extension(extension: string, caseSensitive: boolean = true): FilenameFilter { return new FileExtensionFilenameFilter(extension, caseSensitive); } export function name(filename: string): FilenameFilter; export function name(filename: string, caseSensitive: boolean): FilenameFilter; export function name(filename: string, caseSensitive: boolean = true): FilenameFilter { return new FileNameFilenameFilter(filename, caseSensitive); } export function all(...filters: FilenameFilter[]): FilenameFilter { return new AllFilenameFilter(filters); } export function any(...filters: FilenameFilter[]): FilenameFilter { return new AnyFilenameFilter(filters); } export function none(...filters: FilenameFilter[]): FilenameFilter { return not(any(...filters)); } export function not(filter: FilenameFilter): FilenameFilter { return new NotFilenameFilter(filter); } } class FileExtensionFilenameFilter implements FilenameFilter { private readonly extension: string; private readonly caseSensitive: boolean; constructor(extension: string, caseSensitive: boolean) { if (!extension.startsWith(".")) { extension = "." + extension; } this.extension = extension; this.caseSensitive = caseSensitive; } @Override public accept(dir: string, name: string): boolean { if (this.caseSensitive) { return name.endsWith(this.extension); } else { return name.toLowerCase().endsWith(this.extension); } } } class FileNameFilenameFilter implements FilenameFilter { private readonly filename: string; private readonly caseSensitive: boolean; constructor(filename: string, caseSensitive: boolean) { this.filename = filename; this.caseSensitive = caseSensitive; } @Override public accept(dir: string, name: string): boolean { if (this.caseSensitive) { return name === this.filename; } else { return name.toLowerCase() === this.filename; } } } class AllFilenameFilter implements FilenameFilter { private readonly filters: FilenameFilter[]; constructor(filters: FilenameFilter[]) { this.filters = filters.slice(0); } @Override public accept(dir: string, name: string): boolean { for (let filter of this.filters) { if (!filter.accept(dir, name)) { return false; } } return true; } } class AnyFilenameFilter implements FilenameFilter { private readonly filters: FilenameFilter[]; constructor(filters: FilenameFilter[]) { this.filters = filters.slice(0); } @Override public accept(dir: string, name: string): boolean { for (let filter of this.filters) { if (filter.accept(dir, name)) { return true; } } return false; } } class NotFilenameFilter implements FilenameFilter { private readonly filter: FilenameFilter; constructor(filter: FilenameFilter) { this.filter = filter; } @Override public accept(dir: string, name: string): boolean { return !this.filter.accept(dir, name); } } class NonCachingLexerATNSimulator extends StatisticsLexerATNSimulator { constructor(atn: ATN, recog: Lexer) { super(atn, recog); } protected addDFAEdge(/*@NotNull*/ p: DFAState, t: number, /*@NotNull*/ q: ATNConfigSet): DFAState; protected addDFAEdge(/*@NotNull*/ p: DFAState, t: number, /*@NotNull*/ q: DFAState): void; protected addDFAEdge(p: DFAState, t: number, q: ATNConfigSet | DFAState): DFAState | void { if (q instanceof ATNConfigSet) { return super.addDFAEdge(p, t, q); } else { // do nothing } } } class NonCachingParserATNSimulator extends StatisticsParserATNSimulator { constructor(atn: ATN, parser: Parser) { super(atn, parser); } @Override protected setDFAEdge(p: DFAState, t: number, q: DFAState): void { // Do not set the edge } } class ChecksumParseTreeListener implements ParseTreeListener { private static VISIT_TERMINAL: number = 1; private static VISIT_ERROR_NODE: number = 2; private static ENTER_RULE: number = 3; private static EXIT_RULE: number = 4; private checksum: MurmurHashChecksum; constructor(checksum: MurmurHashChecksum) { this.checksum = checksum; } @Override public visitTerminal(node: TerminalNode): void { this.checksum.update(ChecksumParseTreeListener.VISIT_TERMINAL); TestPerformance.updateChecksum(this.checksum, node.symbol); } @Override public visitErrorNode(node: ErrorNode): void { this.checksum.update(ChecksumParseTreeListener.VISIT_ERROR_NODE); TestPerformance.updateChecksum(this.checksum, node.symbol); } @Override public enterEveryRule(ctx: ParserRuleContext): void { this.checksum.update(ChecksumParseTreeListener.ENTER_RULE); TestPerformance.updateChecksum(this.checksum, ctx.ruleIndex); TestPerformance.updateChecksum(this.checksum, ctx.start); } @Override public exitEveryRule(ctx: ParserRuleContext): void { this.checksum.update(ChecksumParseTreeListener.EXIT_RULE); TestPerformance.updateChecksum(this.checksum, ctx.ruleIndex); TestPerformance.updateChecksum(this.checksum, ctx.stop); } } export class InputDescriptor { private source: string; private inputStream?: CodePointBuffer; constructor(@NotNull source: string) { this.source = source; if (TestPerformance.PRELOAD_SOURCES) { this.getInputStream(); } } @NotNull public getInputStream(): CharStream { if (this.inputStream === undefined) { this.inputStream = this.bufferFromFileName(this.source, TestPerformance.ENCODING); } return new JavaUnicodeInputStream(CodePointCharStream.fromBuffer(this.inputStream, this.source)); } private bufferFromFileName(source: string, encoding: string): CodePointBuffer { let input = fs.readFileSync(this.source, encoding); let array = new Uint16Array(input.length); for (let i = 0; i < input.length; i++) { array[i] = input.charCodeAt(i); } let builder = CodePointBuffer.builder(input.length); builder.append(array); return builder.build(); } } // Create an instance of the benchmark class and run it let benchmark = new TestPerformance(); benchmark.compileJdk();
the_stack
import debounce from 'lodash/debounce'; import cloneDeep from 'lodash/fp/cloneDeep'; import set from 'lodash/fp/set'; import {ArkhamConstants} from '../constants/ArkhamConstants'; import {FluxFramework} from './Flux'; import {FluxAction, FluxOptions, FluxStore} from './Flux.types'; jest.mock('lodash/debounce'); const initialState = { falsy: false, item: 'default', testAction: 'default', testUpdate: 'default', zeroValue: 0 }; const helloStore = (type: string, data, state = initialState): any => { switch(type) { case 'TEST_EVENT': return set('testAction', data.testVar, state); default: return state; } }; describe('Flux', () => { const consoleError = console.error; const consoleWarn = console.warn; const cfg: FluxOptions = { name: 'arkhamjsTest', stores: [helloStore] }; let Flux; beforeAll(() => { console.error = jest.fn(); console.warn = jest.fn(); }); beforeEach(async () => { Flux = new FluxFramework(); // Configure await Flux.init(cfg, true); }); afterAll(() => { console.error = consoleError; console.warn = consoleWarn; }); describe('#addMiddleware', () => { describe('should apply pre-dispatch middleware', () => { const middleTest: string = 'intercept object'; // Add object middleware const objMiddleware = { name: 'objectMiddleware', preDispatch: (action) => ({...action, testVar: middleTest}) }; afterEach(() => { Flux.clearMiddleware(); }); it('should alter data before sending to stores', async () => { // Method Flux.addMiddleware([objMiddleware]); // Set test data Flux.setState('helloStore.testAction', 'default'); // Dispatch an action const preAction: FluxAction = await Flux.dispatch({testVar: 'hello world', type: 'TEST_EVENT'}); expect(Flux.getState('helloStore.testAction')).toEqual(middleTest); expect(preAction.testVar).toEqual(middleTest); }); it('should handle error for middleware without a name', () => { const fn = () => Flux.addMiddleware([{preDispatch: objMiddleware.preDispatch}]); expect(fn).toThrowError(); }); it('should handle error for incompatible middleware', () => { const fn = () => Flux.addMiddleware(['incorrect']); expect(fn).toThrowError(); }); }); describe('should apply pre-dispatch middleware as promise', () => { const middleTest: string = 'intercept promise'; beforeEach(() => { // Add object middleware const promiseMiddleware = { name: 'promiseMiddleware', preDispatch: (action) => Promise.resolve({...action, testVar: middleTest}) }; Flux.addMiddleware([promiseMiddleware]); }); afterEach(() => { Flux.clearMiddleware(); }); it('should alter data before sending to stores', async () => { // Set test data Flux.setState('helloStore.testAction', 'default'); // Dispatch an action const preAction: FluxAction = await Flux.dispatch({testVar: 'hello world', type: 'TEST_EVENT'}); expect(Flux.getState('helloStore.testAction')).toEqual(middleTest); expect(preAction.testVar).toEqual(middleTest); }); }); describe('should apply post dispatch middleware', () => { const middleTest: string = 'intercept post'; beforeEach(() => { // Add object middleware const postMiddleware = { name: 'postMiddleware', postDispatch: (action) => Promise.resolve({...action, testVar: middleTest}) }; Flux.addMiddleware([postMiddleware]); }); afterEach(() => { Flux.clearMiddleware(); }); it('should alter store data', async () => { // Set test data Flux.setState('helloStore.testAction', 'default'); // Dispatch an action const postAction: FluxAction = await Flux.dispatch({testVar: 'hello world', type: 'TEST_EVENT'}); expect(Flux.getState('helloStore.testAction')).toEqual('hello world'); expect(postAction.testVar).toEqual(middleTest); }); it('should handle no action error', async () => { await expect(Flux.dispatch(null)).rejects.toThrowError(); }); it('should handle pre dispatch error', async () => { const preMiddleware = { name: 'errorMiddleware', preDispatch: () => Promise.reject(new Error('test')) }; Flux.addMiddleware([preMiddleware]); await expect(Flux.dispatch({type: 'test'})).rejects.toThrowError(); }); it('should handle post dispatch error', async () => { const postMiddleware = { name: 'errorMiddleware', postDispatch: () => Promise.reject(new Error('test')) }; Flux.addMiddleware([postMiddleware]); await expect(Flux.dispatch({type: 'test'})).rejects.toThrowError(); }); }); }); describe('#addPlugin', () => { it('should add a plugin', () => { const addPluginKey: string = 'addPlugin'; const plugin = {method: () => {}, name: 'demoPlugin'}; const results = Flux[addPluginKey]('preDispatch', plugin); expect(results).toEqual([plugin]); }); it('should skip plugin if already exists', () => { const addPluginKey: string = 'addPlugin'; const plugin = {method: () => {}, name: 'demoPlugin'}; Flux.middleware.preDispatchList = [plugin]; const results = Flux[addPluginKey]('preDispatch', plugin); expect(results).toEqual([plugin]); }); it('should handle undefined function', () => { const addPluginKey: string = 'addPlugin'; const fn = () => Flux[addPluginKey]('preDispatch', {method: 'object'}); expect(fn).toThrowError(); }); }); describe('#clearAppData', () => { beforeEach(() => { // Set test data Flux.setState('helloStore.item', 'clear'); }); it('should reset the store data', async () => { // Method await Flux.clearAppData(); expect(Flux.getState(['helloStore', 'item'])).toEqual('default'); }); it('should set data in storage', async () => { const retrnedValue = {hello: 'world'}; const setStorageData = jest.fn().mockResolvedValue(retrnedValue); Flux.options.storage = {setStorageData}; // Method const results = await Flux.clearAppData(); expect(setStorageData.mock.calls.length).toEqual(1); expect(results).toEqual(retrnedValue); }); }); describe('#deregister', () => { it('should remove a state and store', () => { Flux.state = {hello: 'world'}; Flux.storeActions = {hello: 'world'}; Flux.deregister('hello'); expect(Flux.state).toEqual({}); expect(Flux.storeActions).toEqual({}); }); it('should use empty string as default', () => { const originalState = cloneDeep(Flux.state); Flux.deregister(); expect(originalState).toEqual(Flux.state); }); }); describe('#dispatch', () => { let eventSpy; beforeEach(() => { // Spy eventSpy = jest.fn(); Flux.on('TEST_EVENT', eventSpy); }); afterEach(() => { Flux.off('TEST_EVENT', eventSpy); }); it('should return an action', async () => { // Method Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}); const action: any = await Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}); expect(action).toEqual({testVar: 'test', type: 'TEST_EVENT'}); }); it('should alter the store data', () => { // Method Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}); const item: string = Flux.getState('helloStore.testAction'); expect(item).toEqual('test'); }); it('should dispatch an event', () => { // Method Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}); expect(eventSpy.mock.calls.length).toEqual(1); }); it('should not dispatch if no type', () => { // Method Flux.dispatch({testVar: 'test'}); expect(eventSpy.mock.calls.length).toEqual(0); }); it('should not dispatch if silent', () => { // Method Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}, true); expect(eventSpy.mock.calls.length).toEqual(0); }); it('should update storage', () => { Flux.updateStorage = jest.fn().mockResolvedValue({}); Flux.options.storage = {}; // Method Flux.dispatch({testVar: 'test', type: 'TEST_EVENT'}); expect(Flux.updateStorage.mock.calls.length).toEqual(1); }); it('should return updated state if action returns null', async () => { // Add null store const nullStore = (type: string, data, state = initialState): any => { switch(type) { case 'TEST_NULL': return null; default: return state; } }; await Flux.addStores([nullStore]); // Method await Flux.dispatch({testVar: 'test', type: 'TEST_NULL'}); expect(Flux.state.nullStore).toEqual(initialState); }); it('should return empty object if store returns null by default', async () => { // Add null store const nullStore = (type: string, data, state): any => { switch(type) { case 'TEST_NULL': return null; default: return state; } }; await Flux.addStores([nullStore]); Flux.state.nullStore = null; // Method await Flux.dispatch({testVar: 'test', type: 'TEST_NULL'}); expect(Flux.state.nullStore).toEqual({}); }); }); describe('#getOptions', () => { it('should get a options object', () => { const options = Flux.getOptions(); const optionsKey: string = 'options'; expect(options).toEqual(Flux[optionsKey]); }); }); describe('#getState', () => { beforeEach(() => { const storeAction = Flux.getStore('helloStore'); Flux.setState('helloStore', storeAction.initialState); }); it('should get a global store', () => { const value = Flux.getState(); expect(value.helloStore.item).toEqual('default'); }); it('should get a specific store returning an object', () => { const value = Flux.getState('helloStore'); expect(value.item).toEqual('default'); }); it('should get a specific item within a store using array', () => { const value: string = Flux.getState(['helloStore', 'item']); expect(value).toEqual('default'); }); it('should get a specific item within a store using dot notation', () => { const value: string = Flux.getState('helloStore.item'); expect(value).toEqual('default'); }); it('should return default value from a null item', () => { const value: string = Flux.getState('helloStore.notDefault', ''); expect(value).toEqual(''); }); it('should return entire store object with empty key', () => { const value: string = Flux.getState(''); expect(value).toEqual({helloStore: initialState}); }); it('should return entire store object with null key', () => { const value: string = Flux.getState(null); expect(value).toEqual({helloStore: initialState}); }); it('should return entire store object with undefined key', () => { const value: string = Flux.getState(); expect(value).toEqual({helloStore: initialState}); }); it('should return empty object if state is null', () => { Flux.state = null; const value: string = Flux.getState(); expect(value).toEqual({}); }); it('should return a false value', () => { const value = Flux.getState('helloStore.falsy'); expect(value).toEqual(false); }); it('should return a zero value', () => { const value = Flux.getState('helloStore.zeroValue'); expect(value).toEqual(0); }); }); describe('#getStore', () => { it('should get a store function', () => { const storeAction = Flux.getStore('helloStore'); expect(storeAction.name).toEqual('helloStore'); }); it('should use empty string as default value', () => { const storeAction = Flux.getStore(); expect(storeAction).toBeUndefined(); }); }); describe('#init', () => { describe('set app name', () => { // Vars const opts: FluxOptions = { name: 'demo' }; it('should update app name if initializing for the first time', async () => { const privateInit: string = 'isInit'; Flux[privateInit] = false; // Method await Flux.init(opts); const optionsKey: string = 'options'; expect(Flux[optionsKey].name).toEqual('demo'); }); it('should not update app name if initializing again', async () => { const privateInit: string = 'isInit'; Flux[privateInit] = true; // Method await Flux.init(opts); const optionsKey: string = 'options'; expect(Flux[optionsKey].name).toEqual('arkhamjsTest'); }); it('should add windows object for debugging', async () => { // Method await Flux.init({...opts, debug: true}); const debugKey: string = 'arkhamjs'; expect(window[debugKey]).toEqual(Flux); }); it('should use default object if undefined', async () => { // Method await Flux.reset(); await Flux.init(); const optionsKey: string = 'options'; const expectedOptions = { name: 'arkhamjs', routerType: 'browser', scrollToTop: true, state: null, storage: null, storageWait: 300, stores: [], title: 'ArkhamJS' }; expect(Flux[optionsKey]).toEqual(expectedOptions); }); }); describe('set app name for initialized app', () => { // Vars const opts: FluxOptions = { name: 'demo' }; it('should set app name', async () => { await Flux.init(opts, true); const privateProperty: string = 'options'; expect(Flux[privateProperty].name).toEqual('demo'); }); }); describe('set initial empty state', () => { // Vars const opts: FluxOptions = { state: {}, stores: [helloStore] }; it('should set state', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Object.keys(Flux[privateProperty]).length).toEqual(1); }); it('should set state branch for store', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Flux[privateProperty].helloStore.item).toEqual('default'); }); }); describe('set null state', () => { // Vars const opts: FluxOptions = { state: null, stores: [helloStore] }; it('should set state', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Object.keys(Flux[privateProperty]).length).toEqual(1); }); it('should set state branch for store', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Flux[privateProperty].helloStore.item).toEqual('default'); }); }); describe('set defined state', () => { // Vars const opts: FluxOptions = { state: {second: 'value', test: {hello: 'world'}}, stores: [helloStore] }; it('should set state', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Object.keys(Flux[privateProperty]).length).toEqual(3); }); it('should set state branch for store', async () => { await Flux.init(opts, true); const privateProperty: string = 'state'; expect(Flux[privateProperty].test.hello).toEqual('world'); }); }); describe('middleware', () => { // Middleware object const objMiddleware = { name: 'objectMiddleware', preDispatch: (action) => ({...action}) }; // Vars const opts: FluxOptions = { middleware: [objMiddleware], name: 'demo', stores: [helloStore] }; it('should add middleware', async () => { await Flux.init(opts, true); const privateProperty: string = 'middleware'; expect(Flux[privateProperty].preDispatchList[0].name).toEqual('objectMiddleware'); }); }); describe('error handling', () => { it('should handle useStorage error', async () => { Flux.useStorage = Promise.reject(new Error('test')); await expect(Flux.init(cfg, true)).rejects.toThrowError(); }); it('should handle addStores error', async () => { Flux.addStores = Promise.reject(new Error('test')); await expect(Flux.init(cfg, true)).rejects.toThrowError(); }); }); }); describe('event listeners', () => { let eventSpy; beforeEach(() => { eventSpy = jest.fn(); Flux.on('test', eventSpy); }); describe('#on', () => { it('should add a listener', async () => { await Flux.dispatch({type: 'test'}); expect(eventSpy.mock.calls.length).toEqual(1); }); }); describe('#off', () => { it('should remove a listener', async () => { Flux.off('test', eventSpy); await Flux.dispatch({type: 'test'}); expect(eventSpy.mock.calls.length).toEqual(0); }); }); }); describe('#addStores', () => { const demo = (type, data, state = {helloStore: 'joker'}) => { if(type === 'DEMO_TEST') { state.helloStore = data.helloStore; } return state; }; it('should create and save a Store class', () => { Flux.addStores([demo]); const privateProperty: string = 'storeActions'; const storeAction: FluxStore = Flux[privateProperty].demo; expect(storeAction.name).toEqual('demo'); }); it('should set initial state', () => { Flux.addStores([demo]); const privateProperty: string = 'storeActions'; const storeAction: FluxStore = Flux[privateProperty].demo; expect(storeAction.initialState).toEqual({helloStore: 'joker'}); }); it('should handle unsupported stores', () => { const optionsKey: string = 'options'; const setStorageData = new Error('test'); Flux[optionsKey].storage = {setStorageData}; Flux.addStores([demo]); const privateProperty: string = 'storeActions'; const storeAction: FluxStore = Flux[privateProperty].demo; expect(storeAction.initialState).toEqual({helloStore: 'joker'}); }); }); describe('#offInit', () => { it('should remove listener after initialization', () => { const listener = jest.fn(); Flux.off = jest.fn(); Flux.offInit(listener); expect(Flux.off.mock.calls.length).toEqual(1); expect(Flux.off.mock.calls[0][0]).toEqual(ArkhamConstants.INIT); }); }); describe('#onInit', () => { it('should add listener after initialization', () => { const listener = jest.fn(); Flux.isInit = false; Flux.on = jest.fn(); Flux.onInit(listener); expect(Flux.on.mock.calls.length).toEqual(1); expect(Flux.on.mock.calls[0][0]).toEqual(ArkhamConstants.INIT); }); it('should dispatch instantly if already initialized', () => { const listener = jest.fn(); Flux.isInit = true; Flux.onInit(listener); expect(listener.mock.calls.length).toEqual(1); }); }); describe('#register', () => { it('should register a store function', () => { const demoStore = (type: string, data, state = initialState): any => { switch(type) { case 'TEST_EVENT': return set('testAction', data.testVar, state); default: return state; } }; const registerKey: string = 'register'; const storeAction = Flux[registerKey](demoStore); const expectedAction = { action: demoStore, initialState, name: 'demoStore' }; expect(storeAction).toEqual(expectedAction); }); it('should register a store function without an initial value', () => { const demoStore = (type: string, data, state): any => { switch(type) { case 'TEST_EVENT': return set('testAction', data.testVar, state); default: return state; } }; const registerKey: string = 'register'; const storeAction = Flux[registerKey](demoStore); const expectedAction = { action: demoStore, initialState: undefined, name: 'demoStore' }; expect(storeAction).toEqual(expectedAction); }); it('should not save a store function without a name', () => { const registerKey: string = 'register'; const storeAction = Flux[registerKey]((type: string, data, state = initialState): any => { switch(type) { case 'TEST_EVENT': return set('testAction', data.testVar, state); default: return state; } }); expect(storeAction).toBeUndefined(); }); it('should handle undefined function', () => { const registerKey: string = 'register'; const fn = () => Flux[registerKey](); expect(fn).toThrowError(); }); it('should handle argument that is not a function', () => { const registerKey: string = 'register'; const fn = () => Flux[registerKey]({}); expect(fn).toThrowError(); }); }); describe('#removeMiddleware', () => { beforeEach(() => { Flux.clearMiddleware(); // Add object middleware const objMiddleware = { name: 'objectMiddleware', preDispatch: (action) => ({...action}) }; Flux.addMiddleware([objMiddleware]); }); it('should alter data before sending to stores', () => { Flux.removeMiddleware(['objectMiddleware']); const privateProperty: string = 'middleware'; expect(Flux[privateProperty].preDispatchList.length).toEqual(0); }); }); describe('#removePlugin', () => { it('should remove an existing plugin', () => { Flux.middleware.preDispatchList = [{name: 'demoPlugin'}, {name: 'noNotRemovePlugin'}]; expect(Flux.removePlugin('preDispatch', 'demoPlugin')).toEqual([{name: 'noNotRemovePlugin'}]); }); it('should get an undefined list', () => { Flux.middleware.preDispatchList = null; expect(Flux.removePlugin('preDispatch', 'demoPlugin')).toEqual([]); }); }); describe('#removeStores', () => { beforeEach(() => { // Method Flux.removeStores(['helloStore']); }); afterEach(() => { Flux.addStores([helloStore]); }); it('should remove class', () => { const privateProperty: string = 'storeActions'; expect(!!Flux[privateProperty].helloStore).toEqual(false); }); it('should remove store data', () => { const privateProperty: string = 'state'; expect(!!Flux[privateProperty].helloStore).toEqual(false); }); }); describe('#reset', () => { it('should handle argument that is not a function', async () => { const optionsKey: string = 'options'; const setStorageData = new Error('test'); Flux[optionsKey].storage = {setStorageData}; await expect(Flux.reset()).rejects.toThrowError(); }); }); describe('#setState', () => { it('should update the property within the store', async () => { await Flux.setState('helloStore.testUpdate', 'test'); const newItem = await Flux.getState('helloStore.testUpdate'); expect(newItem).toEqual('test'); }); it('should empty string as default path', async () => { await Flux.setState(undefined, 'test'); const newItem = await Flux.getState('helloStore'); expect(newItem).toEqual(initialState); }); it('should update storage', async () => { const optionsKey: string = 'options'; const updateStorageKey: string = 'updateStorage'; const updateStorage = jest.fn(); Flux[optionsKey] = {storage: {}}; Flux[updateStorageKey] = updateStorage; await Flux.setState('helloStore.testUpdate', 'test'); expect(updateStorage.mock.calls.length).toEqual(1); }); }); describe('#useStorage', () => { it('should update storage', async () => { const getStorageData = jest.fn(); const optionsKey: string = 'options'; Flux[optionsKey].state = null; Flux[optionsKey].storage = {getStorageData}; const useStorageKey: string = 'useStorage'; await Flux[useStorageKey]('helloStore'); expect(getStorageData.mock.calls.length).toEqual(1); }); it('without storage', async () => { const optionsKey: string = 'options'; Flux[optionsKey].state = {hello: 'world'}; Flux[optionsKey].storage = null; const useStorageKey: string = 'useStorage'; await Flux[useStorageKey]('helloStore'); const stateKey: string = 'state'; expect(Flux[stateKey].hello).toEqual('world'); }); it('should handle storage errors', async () => { const optionsKey: string = 'options'; Flux[optionsKey].state = null; Flux[optionsKey].storage = new Error('test'); const useStorageKey: string = 'useStorage'; await expect(Flux[useStorageKey]('helloStore')).rejects.toThrowError(); }); it('should debounce storage', async () => { const value: string = 'test'; const optionsKey: string = 'options'; Flux[optionsKey].state = {hello: 'world'}; const setStorageData = jest.fn().mockReturnValue(value); Flux[optionsKey].storage = {setStorageData}; const debounceMock: any = debounce; debounceMock.mockImplementation((fn) => fn()); const useStorageKey: string = 'useStorage'; await Flux[useStorageKey]('helloStore'); expect(setStorageData.mock.calls.length).toEqual(1); }); }); });
the_stack
import {isKeyword, splitToken, Token, TokenKind, tokenToString} from "../scanner/scanner"; import {createRange, Log, SourceRange, spanRanges} from "../../utils/log"; import { allFlags, appendFlag, createAlignOf, createAny, createBinary, createBlock, createboolean, createCall, createCast, createClass, createConstants, createDelete, createDot, createDouble, createEmpty, createEnum, createExpression, createExtends, createFloat, createFor, createFunction, createHook, createIf, createImplements, createImport, createImportFrom, createImports, createIndex, createInt, createModule, createName, createNew, createNull, createParameter, createParameters, createParseError, createReturn, createSizeOf, createString, createThis, createUnary, createUndefined, createVariable, createVariables, createWhile, isUnary, Node, NODE_FLAG_ANYFUNC, NODE_FLAG_DECLARE, NODE_FLAG_EXPORT, NODE_FLAG_GET, NODE_FLAG_JAVASCRIPT, NODE_FLAG_OPERATOR, NODE_FLAG_POSITIVE, NODE_FLAG_PRIVATE, NODE_FLAG_PROTECTED, NODE_FLAG_PUBLIC, NODE_FLAG_SET, NODE_FLAG_START, NODE_FLAG_STATIC, NODE_FLAG_UNSAFE, NODE_FLAG_VIRTUAL, NodeFlag, NodeKind } from "../core/node"; import {assert} from "../../utils/assert"; import {Terminal} from "../../utils/terminal"; export enum Precedence { LOWEST, ASSIGN, LOGICAL_OR, LOGICAL_AND, BITWISE_OR, BITWISE_XOR, BITWISE_AND, EQUAL, COMPARE, SHIFT, ADD, MULTIPLY, EXPONENT, UNARY_PREFIX, UNARY_POSTFIX, MEMBER, } function isRightAssociative(precedence: Precedence): boolean { return precedence == Precedence.ASSIGN || precedence == Precedence.EXPONENT; } enum ParseKind { EXPRESSION, TYPE, } enum StatementMode { NORMAL, FILE, UNTERMINATED, } class ParserContext { previous: Token; current: Token; log: Log; // This is used to suppress subsequent errors for the same token lastError: Token; peek(kind: TokenKind): boolean { return this.current.kind == kind; } eat(kind: TokenKind): boolean { if (this.peek(kind)) { this.advance(); return true; } return false; } advance(): void { if (!this.peek(TokenKind.END_OF_FILE)) { this.previous = this.current; this.current = this.current.next; } } unexpectedToken(): void { if (this.lastError != this.current) { this.lastError = this.current; this.log.error(this.current.range, `Unexpected ${tokenToString(this.current.kind)}`); } } expect(kind: TokenKind): boolean { if (!this.peek(kind)) { if (this.lastError != this.current) { this.lastError = this.current; let previousLine = this.previous.range.enclosingLine(); let currentLine = this.current.range.enclosingLine(); // Show missing token errors on the previous line for clarity if (kind != TokenKind.IDENTIFIER && !previousLine.equals(currentLine)) { this.log.error(previousLine.rangeAtEnd(), `Expected ${tokenToString(kind)}`); } else { this.log.error(this.current.range, `Expected ${tokenToString(kind)} but found ${tokenToString(this.current.kind)}`); } } return false; } this.advance(); return true; } parseUnaryPrefix(kind: NodeKind, mode: ParseKind): Node { assert(isUnary(kind)); let token = this.current; this.advance(); let value = this.parseExpression(Precedence.UNARY_PREFIX, mode); if (value == null) { return null; } return createUnary(kind, value).withRange(spanRanges(token.range, value.range)).withInternalRange(token.range); } parseBinary(kind: NodeKind, left: Node, localPrecedence: Precedence, operatorPrecedence: Precedence): Node { if (localPrecedence >= operatorPrecedence) { return left; } let token = this.current; this.advance(); // Reduce the precedence for right-associative operators let precedence = isRightAssociative(operatorPrecedence) ? (operatorPrecedence - 1) as Precedence : operatorPrecedence; let right = this.parseExpression(precedence, ParseKind.EXPRESSION); if (right == null) { return null; } return createBinary(kind, left, right).withRange(spanRanges(left.range, right.range)).withInternalRange(token.range); } parseUnaryPostfix(kind: NodeKind, value: Node, localPrecedence: Precedence): Node { if (localPrecedence >= Precedence.UNARY_POSTFIX) { return value; } let token = this.current; this.advance(); return createUnary(kind, value).withRange(spanRanges(value.range, token.range)).withInternalRange(token.range); } parseQuotedString(range: SourceRange): string { assert(range.end - range.start >= 2); let text = range.source.contents; let end = range.start + 1; let limit = range.end - 1; let start = end; let quotedString = ""; while (end < limit) { let c = text[end]; if (c == '\\') { quotedString += text.slice(start, end); end = end + 1; start = end + 1; c = text[end]; if (c == '0') quotedString += '\0'; else if (c == 't') quotedString += '\t'; else if (c == 'n') quotedString += '\n'; else if (c == 'r') quotedString += '\r'; else if (c == '"' || c == '\'' || c == '`' || c == '\n' || c == '\\') start = end; else { let escape = createRange(range.source, range.start + end - 1, range.start + end + 1); this.log.error(escape, `Invalid escape code '${escape.toString()}'`); return null; } } end = end + 1; } return quotedString + text.slice(start, end); } parsePrefix(mode: ParseKind): Node { let token = this.current; if (this.peek(TokenKind.IDENTIFIER)) { this.advance(); return createName(token.range.toString()).withRange(token.range); } // if (this.peek(TokenKind.ARRAY)) { // this.advance(); // return createArray(token.range.toString()).withRange(token.range); // } if (this.peek(TokenKind.EXPONENT)) { splitToken(this.current, TokenKind.MULTIPLY, TokenKind.MULTIPLY); } if (this.peek(TokenKind.MULTIPLY)) { return this.parseUnaryPrefix(mode == ParseKind.TYPE ? NodeKind.POINTER_TYPE : NodeKind.DEREFERENCE, mode); } if (mode == ParseKind.EXPRESSION) { if (this.eat(TokenKind.NULL)) { return createNull().withRange(token.range); } if (this.eat(TokenKind.UNDEFINED)) { return createUndefined().withRange(token.range); } if (this.eat(TokenKind.THIS)) { return createThis().withRange(token.range); } if (this.peek(TokenKind.CHARACTER)) { let text = this.parseQuotedString(token.range); if (text == null) { return null; } this.advance(); if (text.length != 1) { this.log.error(token.range, "Invalid character literal (strings use double quotes)"); return createParseError().withRange(token.range); } return createInt(text.charCodeAt(0)).withRange(token.range); } if (this.peek(TokenKind.STRING)) { let text = this.parseQuotedString(token.range); if (text == null) { return null; } this.advance(); return createString(text).withRange(token.range); } if (this.peek(TokenKind.INT32)) { let value = createInt(0); if (!this.parseInt(token.range, value)) { value = createParseError(); } this.advance(); return value.withRange(token.range); } if (this.peek(TokenKind.FLOAT32)) { let value = createFloat(0); if (!this.parseFloat(token.range, value)) { value = createParseError(); } this.advance(); return value.withRange(token.range); } if (this.peek(TokenKind.FLOAT64)) { let value = createDouble(0); if (!this.parseDouble(token.range, value)) { value = createParseError(); } this.advance(); return value.withRange(token.range); } if (this.eat(TokenKind.TRUE)) { return createboolean(true).withRange(token.range); } if (this.eat(TokenKind.FALSE)) { return createboolean(false).withRange(token.range); } if (this.eat(TokenKind.NEW)) { let type = this.parseType(); if (type == null) { return null; } if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } type.appendChild(parameters); } return this.parseArgumentList(token.range, createNew(type)); } if (this.eat(TokenKind.ALIGNOF)) { if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } let type = this.parseType(); let close = this.current; if (type == null || !this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } return createAlignOf(type).withRange(spanRanges(token.range, close.range)); } if (this.eat(TokenKind.SIZEOF)) { if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } let type = this.parseType(); let close = this.current; if (type == null || !this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } return createSizeOf(type).withRange(spanRanges(token.range, close.range)); } if (this.eat(TokenKind.LEFT_PARENTHESIS)) { let value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); let close = this.current; if (value == null || !this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } return value.withRange(spanRanges(token.range, close.range)); } // Unary prefix if (this.peek(TokenKind.BITWISE_AND)) return this.parseUnaryPrefix(NodeKind.ADDRESS_OF, ParseKind.EXPRESSION); if (this.peek(TokenKind.COMPLEMENT)) return this.parseUnaryPrefix(NodeKind.COMPLEMENT, ParseKind.EXPRESSION); if (this.peek(TokenKind.MINUS)) return this.parseUnaryPrefix(NodeKind.NEGATIVE, ParseKind.EXPRESSION); if (this.peek(TokenKind.MINUS_MINUS)) return this.parseUnaryPrefix(NodeKind.PREFIX_DECREMENT, ParseKind.EXPRESSION); if (this.peek(TokenKind.NOT)) return this.parseUnaryPrefix(NodeKind.NOT, ParseKind.EXPRESSION); if (this.peek(TokenKind.PLUS)) return this.parseUnaryPrefix(NodeKind.POSITIVE, ParseKind.EXPRESSION); if (this.peek(TokenKind.PLUS_PLUS)) return this.parseUnaryPrefix(NodeKind.PREFIX_INCREMENT, ParseKind.EXPRESSION); } if (this.peek(TokenKind.LEFT_BRACE)) { Terminal.write("Check if its JS"); } this.unexpectedToken(); return null; } parseInfix(precedence: Precedence, node: Node, mode: ParseKind): Node { let token = this.current.range; // Dot if (this.peek(TokenKind.DOT) && precedence < Precedence.MEMBER) { this.advance(); let name = this.current; let range = name.range; // Allow contextual keywords if (isKeyword(name.kind)) { this.advance(); } // Recover from a missing identifier else if (!this.expect(TokenKind.IDENTIFIER)) { range = createRange(range.source, token.end, token.end); } return createDot(node, range.toString()).withRange(spanRanges(node.range, range)).withInternalRange(range); } if (mode == ParseKind.EXPRESSION) { // Binary if (this.peek(TokenKind.ASSIGN)) return this.parseBinary(NodeKind.ASSIGN, node, precedence, Precedence.ASSIGN); if (this.peek(TokenKind.BITWISE_AND)) return this.parseBinary(NodeKind.BITWISE_AND, node, precedence, Precedence.BITWISE_AND); if (this.peek(TokenKind.BITWISE_OR)) return this.parseBinary(NodeKind.BITWISE_OR, node, precedence, Precedence.BITWISE_OR); if (this.peek(TokenKind.BITWISE_XOR)) return this.parseBinary(NodeKind.BITWISE_XOR, node, precedence, Precedence.BITWISE_XOR); if (this.peek(TokenKind.DIVIDE)) return this.parseBinary(NodeKind.DIVIDE, node, precedence, Precedence.MULTIPLY); if (this.peek(TokenKind.EQUAL)) return this.parseBinary(NodeKind.EQUAL, node, precedence, Precedence.EQUAL); if (this.peek(TokenKind.EXPONENT)) return this.parseBinary(NodeKind.EXPONENT, node, precedence, Precedence.EXPONENT); if (this.peek(TokenKind.GREATER_THAN)) return this.parseBinary(NodeKind.GREATER_THAN, node, precedence, Precedence.COMPARE); if (this.peek(TokenKind.GREATER_THAN_EQUAL)) return this.parseBinary(NodeKind.GREATER_THAN_EQUAL, node, precedence, Precedence.COMPARE); if (this.peek(TokenKind.LESS_THAN)) return this.parseBinary(NodeKind.LESS_THAN, node, precedence, Precedence.COMPARE); if (this.peek(TokenKind.LESS_THAN_EQUAL)) return this.parseBinary(NodeKind.LESS_THAN_EQUAL, node, precedence, Precedence.COMPARE); if (this.peek(TokenKind.LOGICAL_AND)) return this.parseBinary(NodeKind.LOGICAL_AND, node, precedence, Precedence.LOGICAL_AND); if (this.peek(TokenKind.LOGICAL_OR)) return this.parseBinary(NodeKind.LOGICAL_OR, node, precedence, Precedence.LOGICAL_OR); if (this.peek(TokenKind.MINUS)) return this.parseBinary(NodeKind.SUBTRACT, node, precedence, Precedence.ADD); if (this.peek(TokenKind.MULTIPLY)) return this.parseBinary(NodeKind.MULTIPLY, node, precedence, Precedence.MULTIPLY); if (this.peek(TokenKind.NOT_EQUAL)) return this.parseBinary(NodeKind.NOT_EQUAL, node, precedence, Precedence.EQUAL); if (this.peek(TokenKind.PLUS)) return this.parseBinary(NodeKind.ADD, node, precedence, Precedence.ADD); if (this.peek(TokenKind.REMAINDER)) return this.parseBinary(NodeKind.REMAINDER, node, precedence, Precedence.MULTIPLY); if (this.peek(TokenKind.SHIFT_LEFT)) return this.parseBinary(NodeKind.SHIFT_LEFT, node, precedence, Precedence.SHIFT); if (this.peek(TokenKind.SHIFT_RIGHT)) return this.parseBinary(NodeKind.SHIFT_RIGHT, node, precedence, Precedence.SHIFT); // Unary postfix if (this.peek(TokenKind.PLUS_PLUS)) return this.parseUnaryPostfix(NodeKind.POSTFIX_INCREMENT, node, precedence); if (this.peek(TokenKind.MINUS_MINUS)) return this.parseUnaryPostfix(NodeKind.POSTFIX_DECREMENT, node, precedence); // Cast if (this.peek(TokenKind.AS) && precedence < Precedence.UNARY_PREFIX) { this.advance(); let type = this.parseType(); if (type == null) { return null; } return createCast(node, type).withRange(spanRanges(node.range, type.range)).withInternalRange(token); } // Call or index let isIndex = this.peek(TokenKind.LEFT_BRACKET); if ((isIndex || this.peek(TokenKind.LEFT_PARENTHESIS)) && precedence < Precedence.UNARY_POSTFIX) { return this.parseArgumentList(node.range, isIndex ? createIndex(node) : createCall(node)); } // Hook if (this.peek(TokenKind.QUESTION_MARK) && precedence < Precedence.ASSIGN) { this.advance(); let middle = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (middle == null || !this.expect(TokenKind.COLON)) { return null; } let right = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (right == null) { return null; } return createHook(node, middle, right).withRange(spanRanges(node.range, right.range)); } } return node; } parseDelete(): Node { let token = this.current; assert(token.kind == TokenKind.DELETE); this.advance(); let value: Node = null; if (!this.peek(TokenKind.SEMICOLON)) { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } } let semicolon = this.current; this.expect(TokenKind.SEMICOLON); return createDelete(value).withRange(spanRanges(token.range, semicolon.range)); } parseArgumentList(start: SourceRange, node: Node): Node { let open = this.current.range; let isIndex = node.kind == NodeKind.INDEX; let left = isIndex ? TokenKind.LEFT_BRACKET : TokenKind.LEFT_PARENTHESIS; let right = isIndex ? TokenKind.RIGHT_BRACKET : TokenKind.RIGHT_PARENTHESIS; if (!this.expect(left)) { return null; } if (!this.peek(right)) { while (true) { let value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } node.appendChild(value); if (!this.eat(TokenKind.COMMA)) { break; } } } let close = this.current.range; if (!this.expect(right)) { return null; } return node.withRange(spanRanges(start, close)).withInternalRange(spanRanges(open, close)); } parseExpression(precedence: Precedence, mode: ParseKind): Node { // Prefix let node = this.parsePrefix(mode); if (node == null) { return null; } assert(node.range != null); // Infix while (true) { let result = this.parseInfix(precedence, node, mode); if (result == null) { return null; } if (result == node) { break; } node = result; assert(node.range != null); } return node; } parseType(): Node { return this.parseExpression(Precedence.UNARY_POSTFIX, ParseKind.TYPE); } parseIf(): Node { let token = this.current; assert(token.kind == TokenKind.IF); this.advance(); if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } let value: Node; // Recover from a missing value if (this.peek(TokenKind.RIGHT_PARENTHESIS)) { this.unexpectedToken(); this.advance(); value = createParseError(); } else { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null || !this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } } let trueBranch = this.parseBody(); if (trueBranch == null) { return null; } let falseBranch: Node = null; if (this.eat(TokenKind.ELSE)) { falseBranch = this.parseBody(); if (falseBranch == null) { return null; } } return createIf(value, trueBranch, falseBranch).withRange(spanRanges( token.range, (falseBranch != null ? falseBranch : trueBranch).range)); } parseWhile(): Node { let token = this.current; assert(token.kind == TokenKind.WHILE); this.advance(); if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } let value: Node; // Recover from a missing value if (this.peek(TokenKind.RIGHT_PARENTHESIS)) { this.unexpectedToken(); this.advance(); value = createParseError(); } else { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null || !this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } } let body = this.parseBody(); if (body == null) { return null; } return createWhile(value, body).withRange(spanRanges(token.range, body.range)); } parseFor(): Node { let token = this.current; assert(token.kind == TokenKind.FOR); this.advance(); if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } let initializationStmt: Node = this.parseStatement(StatementMode.NORMAL); let terminationStmt: Node = this.parseStatement(StatementMode.NORMAL); let updateStmts: Node = new Node(); updateStmts.kind = NodeKind.EXPRESSIONS; let updateStmt: Node = this.parseStatement(StatementMode.UNTERMINATED); while (updateStmt !== null) { updateStmts.appendChild(updateStmt); if (!this.eat(TokenKind.COMMA)) { updateStmt = null; break; } updateStmt = this.parseStatement(StatementMode.UNTERMINATED); } if (!this.expect(TokenKind.RIGHT_PARENTHESIS)) { this.unexpectedToken(); this.advance(); return createParseError(); } let body = this.parseBody(); if (body == null) { return null; } return createFor(initializationStmt, terminationStmt, updateStmts, body).withRange(spanRanges(token.range, body.range)); } parseBody(): Node { let node = this.parseStatement(StatementMode.NORMAL); if (node == null) { return null; } if (node.kind == NodeKind.BLOCK) { return node; } let block = createBlock(); block.appendChild(node); return block.withRange(node.range); } parseBlock(): Node { let open = this.current; if (!this.expect(TokenKind.LEFT_BRACE)) { return null; } let block = createBlock(); if (!this.parseStatements(block)) { return null; } let close = this.current; if (!this.expect(TokenKind.RIGHT_BRACE)) { return null; } return block.withRange(spanRanges(open.range, close.range)); } // parseObject():Node { // // } parseReturn(): Node { let token = this.current; assert(token.kind == TokenKind.RETURN); this.advance(); let value: Node = null; if (!this.peek(TokenKind.SEMICOLON)) { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } } let semicolon = this.current; this.expect(TokenKind.SEMICOLON); return createReturn(value).withRange(spanRanges(token.range, semicolon.range)); } parseEmpty(): Node { let token = this.current; this.advance(); return createEmpty().withRange(token.range); } parseEnum(firstFlag: NodeFlag): Node { let token = this.current; assert(token.kind == TokenKind.ENUM); this.advance(); let name = this.current; if (!this.expect(TokenKind.IDENTIFIER) || !this.expect(TokenKind.LEFT_BRACE)) { return null; } let text = name.range.toString(); let node = createEnum(text); node.firstFlag = firstFlag; node.flags = allFlags(firstFlag); while (!this.peek(TokenKind.END_OF_FILE) && !this.peek(TokenKind.RIGHT_BRACE)) { let member = this.current.range; let value: Node = null; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } if (this.eat(TokenKind.ASSIGN)) { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } } let variable = createVariable(member.toString(), createName(text), value); node.appendChild(variable.withRange(value != null ? spanRanges(member, value.range) : member).withInternalRange(member)); // Recover from a terminating semicolon if (this.peek(TokenKind.SEMICOLON)) { this.expect(TokenKind.COMMA); this.advance(); } // Recover from a missing comma else if (this.peek(TokenKind.IDENTIFIER)) { this.expect(TokenKind.COMMA); } else if (!this.eat(TokenKind.COMMA)) { break; } } let close = this.current; if (!this.expect(TokenKind.RIGHT_BRACE)) { return null; } return node.withRange(spanRanges(token.range, close.range)).withInternalRange(name.range); } parseParameters(): Node { let node = createParameters(); let open = this.current; let close: Token; assert(open.kind == TokenKind.LESS_THAN); this.advance(); while (true) { let name = this.current; if (!this.expect(TokenKind.IDENTIFIER)) { close = this.current; if (this.eat(TokenKind.GREATER_THAN)) { break; } return null; } node.appendChild(createParameter(name.range.toString()).withRange(name.range)); if (!this.eat(TokenKind.COMMA)) { close = this.current; if (!this.expect(TokenKind.GREATER_THAN)) { return null; } break; } } return node.withRange(spanRanges(open.range, close.range)); } parseImports(): Node { let token = this.current; assert(token.kind == TokenKind.IMPORT); this.advance(); let node = createImports(); node.flags = node.flags | TokenKind.IMPORT; if (this.peek(TokenKind.MULTIPLY)) { //check for wildcard '*' import this.log.error(this.current.range, "wildcard '*' import not supported"); assert(this.eat(TokenKind.MULTIPLY)); assert(this.eat(TokenKind.AS)); let importName = this.current; let range = importName.range; let _import = createImport(importName.range.toString()); node.appendChild(_import.withRange(range).withInternalRange(importName.range)); this.advance(); } else { if (!this.expect(TokenKind.LEFT_BRACE)) { return null; } while (!this.peek(TokenKind.END_OF_FILE) && !this.peek(TokenKind.RIGHT_BRACE)) { let importName = this.current; let range = importName.range; let _import = createImport(importName.range.toString()); node.appendChild(_import.withRange(range).withInternalRange(importName.range)); this.advance(); if (!this.eat(TokenKind.COMMA)) { break; } } // this.advance(); // assert(this.expect(TokenKind.RIGHT_BRACE)); this.expect(TokenKind.RIGHT_BRACE); } this.expect(TokenKind.FROM); let importFrom = this.current; let _from = createImportFrom(importFrom.range.toString()); node.appendChild(_from.withRange(importFrom.range).withInternalRange(importFrom.range)); this.advance(); let semicolon = this.current; this.expect(TokenKind.SEMICOLON); return node.withRange(spanRanges(token.range, semicolon.range)); } parseModule(firstFlag: NodeFlag): Node { let token = this.current; assert(token.kind == TokenKind.MODULE); this.advance(); let name = this.current; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let node = createModule(name.range.toString()); node.firstFlag = firstFlag; node.flags = allFlags(firstFlag); // Type parameters if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } node.appendChild(parameters); } if (!this.expect(TokenKind.LEFT_BRACE)) { return null; } while (!this.peek(TokenKind.END_OF_FILE) && !this.peek(TokenKind.RIGHT_BRACE)) { let childFlags = this.parseFlags(); let childName = this.current; let oldKind = childName.kind; // Support contextual keywords if (isKeyword(childName.kind)) { childName.kind = TokenKind.IDENTIFIER; this.advance(); } // The identifier must come first without any keyword if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let text = childName.range.toString(); // Support operator definitions if (text == "operator" && !this.peek(TokenKind.LEFT_PARENTHESIS) && !this.peek(TokenKind.IDENTIFIER)) { childName.kind = TokenKind.OPERATOR; this.current = childName; if (this.parseFunction(childFlags, node) == null) { return null; } continue; } // Is there another identifier after the first one? else if (this.peek(TokenKind.IDENTIFIER)) { let isGet = text == "get"; let isSet = text == "set"; // The "get" and "set" flags are contextual if (isGet || isSet) { childFlags = appendFlag(childFlags, isGet ? NODE_FLAG_GET : NODE_FLAG_SET, childName.range); // Get the real identifier childName = this.current; this.advance(); } // Recover from an extra "function" token else if (oldKind == TokenKind.FUNCTION) { this.log.error(childName.range, "Instance functions don't need the 'function' keyword"); // Get the real identifier childName = this.current; this.advance(); } // Recover from an extra variable tokens else if (oldKind == TokenKind.CONST || oldKind == TokenKind.LET || oldKind == TokenKind.VAR) { this.log.error(childName.range, `Instance variables don't need the '${childName.range.toString()}' keyword`); // Get the real identifier childName = this.current; this.advance(); } } // Function if (this.peek(TokenKind.LEFT_PARENTHESIS) || this.peek(TokenKind.LESS_THAN)) { this.current = childName; if (this.parseFunction(childFlags, node) == null) { return null; } } // Variable else { this.current = childName; if (this.parseVariables(childFlags, node) == null) { return null; } } } let close = this.current; if (!this.expect(TokenKind.RIGHT_BRACE)) { return null; } return node.withRange(spanRanges(token.range, close.range)).withInternalRange(name.range); } parseClass(firstFlag: NodeFlag): Node { let token = this.current; assert(token.kind == TokenKind.CLASS); this.advance(); let name = this.current; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let node = createClass(name.range.toString()); node.firstFlag = firstFlag; node.flags = allFlags(firstFlag); // Type parameters if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } node.appendChild(parameters); } // "extends" clause let extendsToken = this.current; if (this.eat(TokenKind.EXTENDS)) { let type: Node; // Recover from a missing type if (this.peek(TokenKind.LEFT_BRACE) || this.peek(TokenKind.IMPLEMENTS)) { this.unexpectedToken(); type = createParseError(); } else { type = this.parseType(); if (type == null) { return null; } } node.appendChild(createExtends(type).withRange(type.range != null ? spanRanges(extendsToken.range, type.range) : extendsToken.range)); } // "implements" clause let implementsToken = this.current; if (this.eat(TokenKind.IMPLEMENTS)) { let list = createImplements(); let type: Node = null; while (true) { // Recover from a missing type if (this.peek(TokenKind.LEFT_BRACE)) { this.unexpectedToken(); break; } type = this.parseType(); if (type == null) { return null; } list.appendChild(type); if (!this.eat(TokenKind.COMMA)) { break; } } node.appendChild(list.withRange(type != null ? spanRanges(implementsToken.range, type.range) : implementsToken.range)); } if (!this.expect(TokenKind.LEFT_BRACE)) { return null; } while (!this.peek(TokenKind.END_OF_FILE) && !this.peek(TokenKind.RIGHT_BRACE)) { let childFlags = this.parseFlags(); let childName = this.current; let oldKind = childName.kind; // Support contextual keywords if (isKeyword(childName.kind)) { childName.kind = TokenKind.IDENTIFIER; this.advance(); } // The identifier must come first without any keyword if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let text = childName.range.toString(); // Support operator definitions if (text == "operator" && !this.peek(TokenKind.LEFT_PARENTHESIS) && !this.peek(TokenKind.IDENTIFIER)) { childName.kind = TokenKind.OPERATOR; this.current = childName; if (this.parseFunction(childFlags, node) == null) { return null; } continue; } // Is there another identifier after the first one? else if (this.peek(TokenKind.IDENTIFIER)) { let isGet = text == "get"; let isSet = text == "set"; // The "get" and "set" flags are contextual if (isGet || isSet) { childFlags = appendFlag(childFlags, isGet ? NODE_FLAG_GET : NODE_FLAG_SET, childName.range); // Get the real identifier childName = this.current; this.advance(); } // Recover from an extra "function" token else if (oldKind == TokenKind.FUNCTION) { this.log.error(childName.range, "Instance functions don't need the 'function' keyword"); // Get the real identifier childName = this.current; this.advance(); } // Recover from an extra variable tokens else if (oldKind == TokenKind.CONST || oldKind == TokenKind.LET || oldKind == TokenKind.VAR) { this.log.error(childName.range, `Instance variables don't need the '${childName.range.toString()}' keyword`); // Get the real identifier childName = this.current; this.advance(); } } // Function if (this.peek(TokenKind.LEFT_PARENTHESIS) || this.peek(TokenKind.LESS_THAN)) { this.current = childName; if (this.parseFunction(childFlags, node) == null) { return null; } } // Variable else { this.current = childName; if (this.parseVariables(childFlags, node) == null) { return null; } } } let close = this.current; if (!this.expect(TokenKind.RIGHT_BRACE)) { return null; } return node.withRange(spanRanges(token.range, close.range)).withInternalRange(name.range); } parseFunction(firstFlag: NodeFlag, parent: Node): Node { let isOperator = false; let token = this.current; let nameRange: SourceRange; let name: string; // Support custom operators if (parent != null && this.eat(TokenKind.OPERATOR)) { let end = this.current; if (this.eat(TokenKind.LEFT_BRACKET)) { if (!this.expect(TokenKind.RIGHT_BRACKET)) { return null; } if (this.peek(TokenKind.ASSIGN)) { nameRange = spanRanges(token.range, this.current.range); name = "[]="; this.advance(); } else { nameRange = spanRanges(token.range, end.range); name = "[]"; } isOperator = true; } else if ( this.eat(TokenKind.BITWISE_AND) || this.eat(TokenKind.BITWISE_OR) || this.eat(TokenKind.BITWISE_XOR) || this.eat(TokenKind.COMPLEMENT) || this.eat(TokenKind.DIVIDE) || this.eat(TokenKind.EQUAL) || this.eat(TokenKind.EXPONENT) || this.eat(TokenKind.LESS_THAN) || this.eat(TokenKind.GREATER_THAN) || this.eat(TokenKind.MINUS) || this.eat(TokenKind.MINUS_MINUS) || this.eat(TokenKind.MULTIPLY) || this.eat(TokenKind.PLUS) || this.eat(TokenKind.PLUS_PLUS) || this.eat(TokenKind.REMAINDER) || this.eat(TokenKind.SHIFT_LEFT) || this.eat(TokenKind.SHIFT_RIGHT)) { nameRange = end.range; name = nameRange.toString(); isOperator = true; } else if ( this.eat(TokenKind.ASSIGN) || this.eat(TokenKind.GREATER_THAN_EQUAL) || this.eat(TokenKind.LESS_THAN_EQUAL) || this.eat(TokenKind.LOGICAL_AND) || this.eat(TokenKind.LOGICAL_OR) || this.eat(TokenKind.NOT) || this.eat(TokenKind.NOT_EQUAL)) { nameRange = end.range; name = nameRange.toString(); // Recover from an invalid operator name this.log.error(nameRange, `The operator '${name}' cannot be implemented ${ end.kind == TokenKind.NOT_EQUAL ? "(it is automatically derived from '==')" : end.kind == TokenKind.LESS_THAN_EQUAL ? "(it is automatically derived from '>')" : end.kind == TokenKind.GREATER_THAN_EQUAL ? "(it is automatically derived from '<')" : "" }`); } else { this.unexpectedToken(); } } else { // Functions inside class declarations don't use "function" if (parent == null) { assert(token.kind == TokenKind.FUNCTION); this.advance(); } // Remember where the name is for the symbol later nameRange = this.current.range; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } name = nameRange.toString(); } let node = createFunction(name); node.firstFlag = firstFlag; node.flags = allFlags(firstFlag); if (isOperator) { node.flags = node.flags | NODE_FLAG_OPERATOR; } // Type parameters if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } node.appendChild(parameters); } if (!this.expect(TokenKind.LEFT_PARENTHESIS)) { return null; } if (!this.peek(TokenKind.RIGHT_PARENTHESIS)) { while (true) { let firstArgumentFlag = this.parseFlags(); let argument = this.current; ; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let type: Node; let value: Node = null; let range = argument.range; if (this.expect(TokenKind.COLON)) { type = this.parseType(); if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } type.appendChild(parameters); } if (type != null) { range = spanRanges(range, type.range); } // Recover from a missing type else if (this.peek(TokenKind.COMMA) || this.peek(TokenKind.RIGHT_PARENTHESIS)) { type = createParseError(); } else { return null; } } // Recover from a missing colon else if (this.peek(TokenKind.COMMA) || this.peek(TokenKind.RIGHT_PARENTHESIS)) { type = createParseError(); } let firstType = type; //Type alias while (this.eat(TokenKind.BITWISE_OR)) { let aliasType = this.parseType(); if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } aliasType.appendChild(parameters); } if (aliasType != null) { range = spanRanges(range, aliasType.range); } // Recover from a missing type else if (this.peek(TokenKind.COMMA) || this.peek(TokenKind.RIGHT_PARENTHESIS)) { aliasType = createParseError(); } else { return null; } type.appendChild(aliasType); type = aliasType; } if (this.eat(TokenKind.ASSIGN)) { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); } let variable = createVariable(argument.range.toString(), firstType, value); variable.firstFlag = firstArgumentFlag; variable.flags = allFlags(firstArgumentFlag); node.appendChild(variable.withRange(range).withInternalRange(argument.range)); if (!this.eat(TokenKind.COMMA)) { break; } } } if (!this.expect(TokenKind.RIGHT_PARENTHESIS)) { return null; } let returnType: Node; if (node.isAnyfunc()) { returnType = createAny(); } else { if (node.stringValue == "constructor") { returnType = new Node(); returnType.kind = NodeKind.NAME; returnType.stringValue = parent.stringValue; } else if (this.expect(TokenKind.COLON)) { returnType = this.parseType(); if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } returnType.appendChild(parameters); } if (returnType == null) { // Recover from a missing return type if (this.peek(TokenKind.SEMICOLON) || this.peek(TokenKind.LEFT_BRACE)) { returnType = createParseError(); } else { return null; } } let firstType = returnType; //Type alias while (this.eat(TokenKind.BITWISE_OR)) { let aliasType = this.parseType(); if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } aliasType.appendChild(parameters); } if (aliasType == null) { // Recover from a missing return type if (this.peek(TokenKind.SEMICOLON) || this.peek(TokenKind.LEFT_BRACE)) { aliasType = createParseError(); } else { return null; } } firstType.appendChild(aliasType); firstType = aliasType; } } // Recover from a missing colon else if (this.peek(TokenKind.SEMICOLON) || this.peek(TokenKind.LEFT_BRACE)) { returnType = createParseError(); } else { return null; } } node.appendChild(returnType); let block: Node = null; // Is this an import? let semicolon = this.current; if (this.eat(TokenKind.SEMICOLON)) { block = createEmpty().withRange(semicolon.range); } // Normal functions else { block = this.parseBlock(); if (block == null) { return null; } } // Add this to the enclosing class if (parent != null) { parent.appendChild(node); } node.appendChild(block); return node.withRange(spanRanges(token.range, block.range)).withInternalRange(nameRange); } parseVariables(firstFlag: NodeFlag = null, parent: Node = null): Node { let token = this.current; // Variables inside class declarations don't use "var" if (parent == null) { assert(token.kind == TokenKind.CONST || token.kind == TokenKind.LET || token.kind == TokenKind.VAR); this.advance(); } let node = token.kind == TokenKind.CONST ? createConstants() : createVariables(); node.firstFlag = firstFlag; while (true) { let name = this.current; if (!this.expect(TokenKind.IDENTIFIER)) { return null; } let type: Node = null; if (this.eat(TokenKind.COLON)) { type = this.parseType(); if (this.peek(TokenKind.LESS_THAN)) { let parameters = this.parseParameters(); if (parameters == null) { return null; } type.appendChild(parameters); } if (type == null) { return null; } } let value: Node = null; if (this.eat(TokenKind.ASSIGN)) { value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } // TODO: Implement constructors if (parent != null) { //this.log.error(value.range, "Inline initialization of instance variables is not supported yet"); } } let range = value != null ? spanRanges(name.range, value.range) : type != null ? spanRanges(name.range, type.range) : name.range; let variable = createVariable(name.range.toString(), type, value); variable.firstFlag = firstFlag; variable.flags = allFlags(firstFlag); (parent != null ? parent : node).appendChild(variable.withRange(range).withInternalRange(name.range)); if (!this.eat(TokenKind.COMMA)) { break; } } let semicolon = this.current; this.expect(TokenKind.SEMICOLON); return node.withRange(spanRanges(token.range, semicolon.range)); } parseLoopJump(kind: NodeKind): Node { let token = this.current; this.advance(); this.expect(TokenKind.SEMICOLON); let node = new Node(); node.kind = kind; return node.withRange(token.range); } parseFlags(): NodeFlag { let firstFlag: NodeFlag = null; let lastFlag: NodeFlag = null; while (true) { let token = this.current; let flag: int32; if (this.eat(TokenKind.DECLARE)) flag = NODE_FLAG_DECLARE; else if (this.eat(TokenKind.EXPORT)) flag = NODE_FLAG_EXPORT; else if (this.eat(TokenKind.PRIVATE)) flag = NODE_FLAG_PRIVATE; else if (this.eat(TokenKind.PROTECTED)) flag = NODE_FLAG_PROTECTED; else if (this.eat(TokenKind.PUBLIC)) flag = NODE_FLAG_PUBLIC; else if (this.eat(TokenKind.STATIC)) flag = NODE_FLAG_STATIC; else if (this.eat(TokenKind.ANYFUNC)) flag = NODE_FLAG_ANYFUNC; else if (this.eat(TokenKind.UNSAFE)) flag = NODE_FLAG_UNSAFE; else if (this.eat(TokenKind.JAVASCRIPT)) flag = NODE_FLAG_JAVASCRIPT; else if (this.eat(TokenKind.START)) flag = NODE_FLAG_START; else if (this.eat(TokenKind.VIRTUAL)) flag = NODE_FLAG_VIRTUAL; else return firstFlag; let link = new NodeFlag(); link.flag = flag; link.range = token.range; if (firstFlag == null) firstFlag = link; else lastFlag.next = link; lastFlag = link; } } parseUnsafe(): Node { let token = this.current; this.advance(); let node = this.parseBlock(); if (node == null) { return null; } node.flags = node.flags | NODE_FLAG_UNSAFE; return node.withRange(spanRanges(token.range, node.range)); } parseJavaScript(): Node { let token = this.current; this.advance(); let node = this.parseBlock(); if (node == null) { return null; } node.flags = node.flags | NODE_FLAG_JAVASCRIPT; return node.withRange(spanRanges(token.range, node.range)); } parseStart(): Node { let token = this.current; this.advance(); let node = this.parseBlock(); if (node == null) { return null; } node.flags = node.flags | NODE_FLAG_START; return node.withRange(spanRanges(token.range, node.range)); } parseVirtual(firstFlag): Node { let token = this.current; this.advance(); let node = this.parseFunction(firstFlag, null); if (node == null) { return null; } node.flags = node.flags | NODE_FLAG_VIRTUAL; return node.withRange(spanRanges(token.range, node.range)); } parseStatement(mode: StatementMode): Node { let firstFlag = mode == StatementMode.FILE ? this.parseFlags() : null; // if (this.peek(TokenKind.UNSAFE) && firstFlag == null) return this.parseUnsafe(); //disabled for now if (this.peek(TokenKind.IMPORT) && firstFlag == null) return this.parseImports(); // This should handle before parsing if (this.peek(TokenKind.JAVASCRIPT) && firstFlag == null) return this.parseJavaScript(); if (this.peek(TokenKind.START) && firstFlag == null) return this.parseStart(); if (this.peek(TokenKind.CONST) || this.peek(TokenKind.LET) || this.peek(TokenKind.VAR)) return this.parseVariables(firstFlag, null); if (this.peek(TokenKind.FUNCTION)) return this.parseFunction(firstFlag, null); if (this.peek(TokenKind.VIRTUAL)) return this.parseVirtual(firstFlag); if (this.peek(TokenKind.MODULE)) return this.parseModule(firstFlag); if (this.peek(TokenKind.CLASS)) return this.parseClass(firstFlag); if (this.peek(TokenKind.ENUM)) return this.parseEnum(firstFlag); // Definition modifiers need to be attached to a definition if (firstFlag != null) { this.unexpectedToken(); return null; } if (this.peek(TokenKind.LEFT_BRACE)) return this.parseBlock(); if (this.peek(TokenKind.BREAK)) return this.parseLoopJump(NodeKind.BREAK); if (this.peek(TokenKind.CONTINUE)) return this.parseLoopJump(NodeKind.CONTINUE); if (this.peek(TokenKind.IF)) return this.parseIf(); if (this.peek(TokenKind.WHILE)) return this.parseWhile(); if (this.peek(TokenKind.FOR)) return this.parseFor(); if (this.peek(TokenKind.DELETE)) return this.parseDelete(); if (this.peek(TokenKind.RETURN)) return this.parseReturn(); if (this.peek(TokenKind.SEMICOLON)) return this.parseEmpty(); // Parse an expression statement let value = this.parseExpression(Precedence.LOWEST, ParseKind.EXPRESSION); if (value == null) { return null; } let semicolon = this.current; if (mode !== StatementMode.UNTERMINATED) { this.expect(TokenKind.SEMICOLON); } return createExpression(value).withRange(spanRanges(value.range, semicolon.range)); } parseStatements(parent: Node, mode: StatementMode = StatementMode.NORMAL): boolean { while (!this.peek(TokenKind.END_OF_FILE) && !this.peek(TokenKind.RIGHT_BRACE)) { let child = this.parseStatement(parent.kind == NodeKind.FILE ? StatementMode.FILE : mode); if (child == null) { return false; } if (child.kind === NodeKind.RETURN) { parent.returnNode = child; } parent.appendChild(child); } return true; } parseInt(range: SourceRange, node: Node): boolean { let source = range.source; let contents = source.contents; node.intValue = parseInt(contents.substring(range.start, range.end)); node.flags = NODE_FLAG_POSITIVE; return true; } parseFloat(range: SourceRange, node: Node): boolean { let source = range.source; let contents = source.contents; node.floatValue = parseFloat(contents.substring(range.start, range.end)); node.flags = NODE_FLAG_POSITIVE; return true; } parseDouble(range: SourceRange, node: Node): boolean { let source = range.source; let contents = source.contents; node.doubleValue = parseFloat(contents.substring(range.start, range.end)); node.flags = NODE_FLAG_POSITIVE; return true; } } export function parse(firstToken: Token, log: Log): Node { let context = new ParserContext(); context.current = firstToken; context.log = log; let file = new Node(); file.kind = NodeKind.FILE; if (!context.parseStatements(file)) { return null; } return file; }
the_stack
require('module-alias/register'); import * as _ from 'lodash'; import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import * as setProtocolUtils from 'set-protocol-utils'; import { Address } from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { ConstantAuctionPriceCurveContract, CoreMockContract, RebalanceAuctionModuleMockContract, RebalancingSetTokenContract, RebalancingSetTokenFactoryContract, SetTokenContract, SetTokenFactoryContract, TransferProxyContract, VaultContract, WhiteListContract, } from '@utils/contracts'; import { ether } from '@utils/units'; import { DEFAULT_GAS, ONE_DAY_IN_SECONDS, DEFAULT_AUCTION_PRICE_NUMERATOR, DEFAULT_AUCTION_PRICE_DIVISOR, ZERO, } from '@utils/constants'; import { expectRevertError } from '@utils/tokenAssertions'; import { Blockchain } from '@utils/blockchain'; import { getWeb3 } from '@utils/web3Helper'; import { BidPlaced } from '@utils/contract_logs/rebalanceAuctionModule'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { RebalancingHelper } from '@utils/helpers/rebalancingHelper'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const { expect } = chai; const blockchain = new Blockchain(web3); const { SetProtocolTestUtils: SetTestUtils } = setProtocolUtils; const setTestUtils = new SetTestUtils(web3); contract('RebalanceAuctionModule', accounts => { const [ deployerAccount, managerAccount, bidderAccount, nonTrackedSetToken, ] = accounts; let rebalancingSetToken: RebalancingSetTokenContract; let coreMock: CoreMockContract; let transferProxy: TransferProxyContract; let vault: VaultContract; let rebalanceAuctionModuleMock: RebalanceAuctionModuleMockContract; let factory: SetTokenFactoryContract; let rebalancingComponentWhiteList: WhiteListContract; let rebalancingFactory: RebalancingSetTokenFactoryContract; let constantAuctionPriceCurve: ConstantAuctionPriceCurveContract; const coreHelper = new CoreHelper(deployerAccount, deployerAccount); const erc20Helper = new ERC20Helper(deployerAccount); const rebalancingHelper = new RebalancingHelper( deployerAccount, coreHelper, erc20Helper, blockchain ); before(async () => { ABIDecoder.addABI(CoreMockContract.getAbi()); ABIDecoder.addABI(RebalanceAuctionModuleMockContract.getAbi()); }); after(async () => { ABIDecoder.removeABI(CoreMockContract.getAbi()); ABIDecoder.removeABI(RebalanceAuctionModuleMockContract.getAbi()); }); beforeEach(async () => { await blockchain.saveSnapshotAsync(); transferProxy = await coreHelper.deployTransferProxyAsync(); vault = await coreHelper.deployVaultAsync(); coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault); rebalanceAuctionModuleMock = await coreHelper.deployRebalanceAuctionModuleMockAsync(coreMock, vault); await coreHelper.addModuleAsync(coreMock, rebalanceAuctionModuleMock.address); factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address); rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync(); rebalancingFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync( coreMock.address, rebalancingComponentWhiteList.address, ); constantAuctionPriceCurve = await rebalancingHelper.deployConstantAuctionPriceCurveAsync( DEFAULT_AUCTION_PRICE_NUMERATOR, DEFAULT_AUCTION_PRICE_DIVISOR, ); await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory); await coreHelper.addFactoryAsync(coreMock, rebalancingFactory); await rebalancingHelper.addPriceLibraryAsync(coreMock, constantAuctionPriceCurve); }); afterEach(async () => { await blockchain.revertAsync(); }); describe('#bid', async () => { let subjectRebalancingSetToken: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; let subjectExecutePartialQuantity: boolean; let proposalPeriod: BigNumber; let currentSetToken: SetTokenContract; let nextSetToken: SetTokenContract; let rebalancingSetTokenQuantityToIssue: BigNumber; let minBid: BigNumber; beforeEach(async () => { const naturalUnits = [ether(.001), ether(.0001)]; const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2, naturalUnits ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken rebalancingSetTokenQuantityToIssue = ether(8); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await currentSetToken.naturalUnit.callAsync(); const decTwo = await nextSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectCaller = deployerAccount; subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; subjectExecutePartialQuantity = false; }); async function subject(): Promise<string> { return rebalanceAuctionModuleMock.bid.sendTransactionAsync( subjectRebalancingSetToken, subjectQuantity, subjectExecutePartialQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when bid is called by an invalid Set Token', async () => { beforeEach(async () => { subjectRebalancingSetToken = nonTrackedSetToken; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Default state', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Proposal State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToProposeAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Rebalance State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('transfers the correct amount of tokens to the bidder in the Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldReceiverBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); await subject(); const newReceiverBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlow['inflowArray'][index]).sub(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a placeBid event', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlaced( rebalancingSetToken.address, subjectCaller, subjectQuantity, combinedTokenArray, expectedTokenFlow['inflowArray'], expectedTokenFlow['outflowArray'], rebalanceAuctionModuleMock.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('but quantity is more than remainingCurrentSets', async () => { beforeEach(async () => { subjectQuantity = rebalancingSetTokenQuantityToIssue.add(minBid); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('partial fills is true but amount is less than remainingCurrentSets', async () => { beforeEach(async () => { subjectExecutePartialQuantity = true; }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('and quantity is greater than remainingCurrentSets', async () => { const roundedQuantity = ether(8); beforeEach(async () => { subjectQuantity = ether(9); subjectExecutePartialQuantity = true; }); it('transfers the correct amount of tokens to the bidder in the Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldReceiverBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); await subject(); const newReceiverBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlow['inflowArray'][index]).sub(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(roundedQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a placeBid event', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlaced( rebalancingSetToken.address, subjectCaller, roundedQuantity, combinedTokenArray, expectedTokenFlow['inflowArray'], expectedTokenFlow['outflowArray'], rebalanceAuctionModuleMock.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); describe('but quantity is not multiple of minimum Bid', async () => { beforeEach(async () => { subjectQuantity = minBid.add(1); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); }); describe('#bidAndWithdraw', async () => { let subjectRebalancingSetToken: Address; let subjectQuantity: BigNumber; let subjectExecutePartialQuantity: boolean; let subjectCaller: Address; let proposalPeriod: BigNumber; let currentSetToken: SetTokenContract; let nextSetToken: SetTokenContract; let rebalancingSetTokenQuantityToIssue: BigNumber; let minBid: BigNumber; beforeEach(async () => { const naturalUnits = [ether(.001), ether(.0001)]; const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2, naturalUnits ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken rebalancingSetTokenQuantityToIssue = ether(8); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); // Determine minimum bid const decOne = await currentSetToken.naturalUnit.callAsync(); const decTwo = await nextSetToken.naturalUnit.callAsync(); minBid = new BigNumber(Math.max(decOne.toNumber(), decTwo.toNumber()) * 1000); subjectCaller = deployerAccount; subjectQuantity = minBid; subjectRebalancingSetToken = rebalancingSetToken.address; subjectExecutePartialQuantity = false; }); async function subject(): Promise<string> { return rebalanceAuctionModuleMock.bidAndWithdraw.sendTransactionAsync( subjectRebalancingSetToken, subjectQuantity, subjectExecutePartialQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when bid is called by an invalid Set Token', async () => { beforeEach(async () => { subjectRebalancingSetToken = nonTrackedSetToken; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Default state', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Proposal State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToProposeAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when bid is called and token is in Rebalance State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); await subject(); const newReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflowArray'][index]).sub(expectedTokenFlow['inflowArray'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlow['inflowArray'][index]).sub(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a placeBid event', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlaced( rebalancingSetToken.address, subjectCaller, subjectQuantity, combinedTokenArray, expectedTokenFlow['inflowArray'], expectedTokenFlow['outflowArray'], rebalanceAuctionModuleMock.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('but quantity is more than remainingCurrentSets', async () => { beforeEach(async () => { subjectQuantity = rebalancingSetTokenQuantityToIssue.add(minBid); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('partial fills is true but amount is less than remainingCurrentSets', async () => { beforeEach(async () => { subjectExecutePartialQuantity = true; }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); describe('but quantity is zero', async () => { beforeEach(async () => { subjectQuantity = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('and quantity is greater than remainingCurrentSets', async () => { const roundedQuantity = ether(8); beforeEach(async () => { subjectQuantity = ether(9); subjectExecutePartialQuantity = true; }); it("transfers the correct amount of tokens to the bidder's wallet", async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const tokenInstances = await erc20Helper.retrieveTokenInstancesAsync(combinedTokenArray); const oldReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); await subject(); const newReceiverBalances = await erc20Helper.getTokenBalances( tokenInstances, subjectCaller ); const expectedReceiverBalances = _.map(oldReceiverBalances, (balance, index) => balance.add(expectedTokenFlow['outflowArray'][index]).sub(expectedTokenFlow['inflowArray'][index]) ); expect(JSON.stringify(newReceiverBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it('transfers the correct amount of tokens from the bidder to the rebalancing token in Vault', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const oldSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); await subject(); const newSenderBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const expectedSenderBalances = _.map(oldSenderBalances, (balance, index) => balance.add(expectedTokenFlow['inflowArray'][index]).sub(expectedTokenFlow['outflowArray'][index]) ); expect(JSON.stringify(newSenderBalances)).to.equal(JSON.stringify(expectedSenderBalances)); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(roundedQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); it('emits a placeBid event', async () => { const expectedTokenFlow = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, roundedQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = BidPlaced( rebalancingSetToken.address, subjectCaller, roundedQuantity, combinedTokenArray, expectedTokenFlow['inflowArray'], expectedTokenFlow['outflowArray'], rebalanceAuctionModuleMock.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); describe('but quantity is not multiple of natural unit', async () => { beforeEach(async () => { subjectQuantity = minBid.add(1); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); }); describe('#getBidPrice', async () => { let subjectCaller: Address; let subjectQuantity: BigNumber; let proposalPeriod: BigNumber; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); subjectCaller = managerAccount; subjectQuantity = ether(1); }); async function subject(): Promise<any[]> { return rebalancingSetToken.getBidPrice.callAsync( subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when getBidPrice is called from Default State', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when getBidPrice is called from Proposal State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToProposeAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when getBidPrice is called from Rebalance State', async () => { beforeEach(async () => { // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(9), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, ether(7)); await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('returns the correct UnitArrays; using price=1.374', async () => { const expectedFlows = await rebalancingHelper.constructInflowOutflowArraysAsync( rebalancingSetToken, subjectQuantity, DEFAULT_AUCTION_PRICE_NUMERATOR ); const arrays = await subject(); expect(JSON.stringify(arrays[0])).to.equal(JSON.stringify(expectedFlows['inflowArray'])); expect(JSON.stringify(arrays[1])).to.equal(JSON.stringify(expectedFlows['outflowArray'])); }); }); }); describe('#placeBid: Called from RebalanceAuction Module', async () => { let subjectCaller: Address; let subjectQuantity: BigNumber; let amountToIssue: BigNumber; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); amountToIssue = ether(2); await coreMock.issue.sendTransactionAsync(currentSetToken.address, amountToIssue); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, amountToIssue); subjectCaller = bidderAccount; subjectQuantity = ether(1); }); async function subject(): Promise<string> { return rebalanceAuctionModuleMock.placeBid.sendTransactionAsync( rebalancingSetToken.address, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when placeBid is called from Default State', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when placeBid is called from Proposal State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToProposeAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when placeBid is called from Rebalance State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('subtracts the correct amount from remainingCurrentSets', async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const currentRemainingSets = new BigNumber(biddingParameters[1]); await subject(); const expectedRemainingSets = currentRemainingSets.sub(subjectQuantity); const newBiddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const newRemainingSets = new BigNumber(newBiddingParameters[1]); expect(newRemainingSets).to.be.bignumber.equal(expectedRemainingSets); }); describe('and quantity is not a multiple of minimumBid', async () => { beforeEach(async () => { const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const minimumBid = new BigNumber(biddingParameters[0]); subjectQuantity = minimumBid.mul(new BigNumber(1.5)); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('when placeBid is called from Drawdown State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); const defaultTimeToPivot = new BigNumber(100000); await blockchain.increaseTimeAsync(defaultTimeToPivot.add(1)); const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); const minimumBid = biddingParameters[0]; await rebalanceAuctionModuleMock.bid.sendTransactionAsync( rebalancingSetToken.address, minimumBid, false ); await rebalancingHelper.endFailedRebalanceAsync( rebalancingSetToken ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#placeBid: Called on RebalancingSetToken', async () => { let subjectCaller: Address; let subjectQuantity: BigNumber; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); subjectCaller = bidderAccount; subjectQuantity = ether(1); }); async function subject(): Promise<string> { return rebalancingSetToken.placeBid.sendTransactionAsync( subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when placeBid is called from Rebalance State', async () => { beforeEach(async () => { // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(9), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, ether(7)); await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#redeemFromFailedRebalance', async () => { let subjectRebalancingSetToken: Address; let subjectCaller: Address; let proposalPeriod: BigNumber; let currentSetToken: SetTokenContract; let nextSetToken: SetTokenContract; let rebalancingSetTokenQuantityToIssue: BigNumber; beforeEach(async () => { const naturalUnits = [ether(.001), ether(.0001)]; const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2, naturalUnits ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken rebalancingSetTokenQuantityToIssue = ether(8); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetTokenQuantityToIssue); subjectCaller = deployerAccount; subjectRebalancingSetToken = rebalancingSetToken.address; }); async function subject(): Promise<string> { return rebalanceAuctionModuleMock.redeemFromFailedRebalance.sendTransactionAsync( subjectRebalancingSetToken, { from: subjectCaller, gas: DEFAULT_GAS} ); } describe('when redeemFromFailedRebalance is called by an invalid Set Token', async () => { beforeEach(async () => { subjectRebalancingSetToken = nonTrackedSetToken; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when redeemFromFailedRebalance is called and token is in Default state', async () => { it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when redeemFromFailedRebalance is called and token is in Proposal State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToProposeAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when redeemFromFailedRebalance is called and token is in Rebalance State', async () => { beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when redeemFromFailedRebalance is called and token is in Drawdown State', async () => { let minimumBid: BigNumber; beforeEach(async () => { await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); const defaultTimeToPivot = new BigNumber(100000); await blockchain.increaseTimeAsync(defaultTimeToPivot.add(1)); const biddingParameters = await rebalancingSetToken.biddingParameters.callAsync(); minimumBid = biddingParameters[0]; await rebalanceAuctionModuleMock.bid.sendTransactionAsync( rebalancingSetToken.address, minimumBid, false ); await rebalancingHelper.endFailedRebalanceAsync( rebalancingSetToken ); }); it('transfers the correct amount of tokens to the bidder in the Vault', async () => { const combinedTokenArray = await rebalancingSetToken.getCombinedTokenArray.callAsync(); const receiverTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const setTotalSupply = await rebalancingSetToken.totalSupply.callAsync(); const collateralBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, rebalancingSetToken.address ); const oldReceiverVaultBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); await subject(); const newReceiverVaultBalances = await coreHelper.getVaultBalancesForTokensForOwner( combinedTokenArray, vault, deployerAccount ); const expectedReceiverBalances = _.map(collateralBalances, (balance, index) => oldReceiverVaultBalances[index].add( balance.mul(receiverTokenBalance).div(setTotalSupply).round(0, 3) ) ); expect(JSON.stringify(newReceiverVaultBalances)).to.equal(JSON.stringify(expectedReceiverBalances)); }); it("zeros out the caller's balance", async () => { const currentBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(currentBalance).to.be.bignumber.not.equal(ZERO); await subject(); const newBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(newBalance).to.be.bignumber.equal(ZERO); }); it('subtracts the correct amount from the totalSupply', async () => { const userBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const setTotalSupply = await rebalancingSetToken.totalSupply.callAsync(); await subject(); const newTotalSupply = await rebalancingSetToken.totalSupply.callAsync(); const expectedTotalSupply = setTotalSupply.sub(userBalance); expect(newTotalSupply).to.be.bignumber.equal(expectedTotalSupply); }); }); }); describe('#calculateExecutionQuantity', async () => { let subjectCaller: Address; let subjectQuantity: BigNumber; let subjectAllowPartialFill: boolean; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const proposalPeriod = ONE_DAY_IN_SECONDS; rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( coreMock, rebalancingFactory.address, managerAccount, currentSetToken.address, proposalPeriod ); await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(9), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, ether(7)); await rebalancingHelper.defaultTransitionToRebalanceAsync( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, constantAuctionPriceCurve.address, managerAccount ); subjectCaller = bidderAccount; subjectQuantity = ether(1); subjectAllowPartialFill = true; }); async function subject(): Promise<BigNumber> { return rebalanceAuctionModuleMock.calculateExecutionQuantityExternal.callAsync( rebalancingSetToken.address, subjectQuantity, subjectAllowPartialFill, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('should return passed quantity', async () => { const executionQuantity = await subject(); expect(executionQuantity).to.be.bignumber.equal(subjectQuantity); }); describe('when quantity passed is greater than remainingCurrentSets', async () => { beforeEach(async () => { subjectQuantity = ether(9); }); it('should return passed quantity', async () => { const executionQuantity = await subject(); const biddingParams = await rebalancingSetToken.getBiddingParameters.callAsync(); const expectedExecutionQuantity = biddingParams[1]; expect(executionQuantity).to.be.bignumber.equal(expectedExecutionQuantity); }); }); }); });
the_stack
import { Component, OnInit, Input, ViewChild, ElementRef, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core'; import { TokenService } from '../../../../services/token/token.service'; import { EstimateService } from '../../../../services/estimate/estimate.service'; import { DefaultTransactionParams } from '../../../../interfaces'; import { FullyPreparedTransaction, PartiallyPreparedTransaction, PrepareRequest } from '../../../misc/send/interfaces'; import { Account, ImplicitAccount, OriginatedAccount } from '../../../../services/wallet/wallet'; import { TorusService } from '../../../../services/torus/torus.service'; import Big from 'big.js'; import { TranslateService } from '@ngx-translate/core'; import { WalletService } from '../../../../services/wallet/wallet.service'; import { InputValidationService } from '../../../../services/input-validation/input-validation.service'; import assert from 'assert'; import { TezosDomainsService } from '../../../../services/tezos-domains/tezos-domains.service'; import { ModalComponent } from '../../modal.component'; import { TokenBalancesService } from '../../../../services/token-balances/token-balances.service'; const zeroTxParams: DefaultTransactionParams = { gas: 0, storage: 0, fee: 0, burn: 0 }; @Component({ selector: 'app-prepare-send', templateUrl: './prepare-send.component.html', styleUrls: ['../../../../../scss/components/modals/modal.scss'] }) export class PrepareSendComponent extends ModalComponent implements OnInit, OnChanges { @Input() prepareRequest: PrepareRequest = null; @Output() prepareResponse = new EventEmitter(); @ViewChild('destType') public destType: ElementRef; activeAccount: Account = null; tokenTransfer: string = null; token = null; costPerByte: string = this.estimateService.costPerByte; defaultTransactionParams: DefaultTransactionParams = zeroTxParams; active = false; isMultipleDestinations = false; advancedForm = false; hideAmount = false; simSemaphore = 0; isNFT = false accountDropdownIsOpen = false; torusVerifierName = 'Tezos Address'; torusVerifier = ''; torusLookupId = ''; torusLookupAddress = ''; torusTwitterId = ''; torusPendingLookup = false; transactions = []; toMultipleDestinationsString = ''; formInvalid = ''; latestSimError = ''; prevEquiClass = ''; sendMax = null; amount = ''; toPkh = ''; customFee = ''; customGasLimit = ''; customStorageLimit = ''; name = 'prepare-send'; constructor( private tokenService: TokenService, private estimateService: EstimateService, public torusService: TorusService, private translate: TranslateService, private walletService: WalletService, public tezosDomains: TezosDomainsService, private inputValidationService: InputValidationService, private tokenBalancesService: TokenBalancesService ) { super(); } ngOnInit(): void { } ngOnChanges(changes: SimpleChanges): void { if (changes?.prepareRequest?.currentValue) { this.reset(true); this.tokenTransfer = changes.prepareRequest.currentValue.tokenTransfer ?? null; this.token = this.tokenService.getAsset(this.tokenTransfer); this.isNFT = this.tokenBalancesService.isNFT(this.token); this.activeAccount = changes.prepareRequest.currentValue.account; this.amount = !this.token || !(this.token?.isBooleanAmount || this.token?.balance == 1) ? '' : '1'; if (!this.isOpen) { this.openModal(); } } } openModal() { ModalComponent.currentModel.next({ name: this.name, data: null }); this.estimateService.preLoadData(this.activeAccount.pkh, this.activeAccount.pk); } closeModalAction() { this.prepareResponse.emit(null); ModalComponent.currentModel.next({ name: '', data: null }); this.reset(); } reset(init = false) { if (!init) { this.prepareRequest = null; } this.defaultTransactionParams = zeroTxParams; this.active = false; this.isMultipleDestinations = false; this.advancedForm = false; this.hideAmount = false; this.simSemaphore = 0; this.tokenTransfer = null; this.token = null; this.isNFT = null; this.accountDropdownIsOpen = false; this.transactions = []; this.toMultipleDestinationsString = ''; this.formInvalid = ''; this.latestSimError = ''; this.prevEquiClass = ''; this.torusVerifierName = 'Tezos Address'; this.torusVerifier = ''; this.sendMax = null; this.amount = ''; this.toPkh = ''; this.customFee = ''; this.customGasLimit = ''; this.customStorageLimit = ''; this.clearTorus(); } getTitle(): string { return `Send ${this.getAssetName(true)}`; } getAssetName(short = true): string { if (this.tokenTransfer) { return this.token?.symbol ?? this.token?.name ?? 'Unknown'; } else { return !this.prepareRequest.symbol ? 'tez' : this.prepareRequest.symbol; } } getTotalAmount(): string { let totalSent = Big(0); for (const tx of this.transactions) { totalSent = totalSent.add(tx.amount); } return totalSent.toFixed(); } getTotalCost(display: boolean = false): number | string { const totalFee = Big(this.getTotalFee()).plus(Big(this.getTotalBurn())).toString(); if (display && totalFee === '0') { return '-'; } return Number(totalFee); } getTotalFee(): number { if (this.customFee !== '' && Number(this.customFee)) { return Number(this.customFee); } return Number(this.defaultTransactionParams.fee); } getTotalBurn(): number { if (this.customStorageLimit !== '' && Number(this.customStorageLimit)) { return Number(Big(this.customStorageLimit).mul(this.transactions.length).times(this.costPerByte).div(1000000).toString()); } return this.defaultTransactionParams.burn; } burnAmount(): string { const burn = this.customStorageLimit ? Number(Big(this.customStorageLimit).times(this.costPerByte).div(1000000)) : this.defaultTransactionParams.burn; if (burn) { return burn + ' tez'; } return ''; } amountChange(): void { this.estimateFees(); } async estimateFees(): Promise<void> { console.log('estimate..'); const prevSimError = this.latestSimError; this.latestSimError = ''; let txs: PartiallyPreparedTransaction[] = []; try { txs = this.getMinimalPreparedTxs(); this.transactions = txs; } catch (e) { console.log(e); } if (txs?.length) { const equiClass = this.equiClass(this.activeAccount.address, txs); if (this.prevEquiClass !== equiClass || (this.tokenTransfer && this.checkBalance())) { this.latestSimError = ''; this.prevEquiClass = equiClass; this.simSemaphore++; // Put lock on 'Preview and 'Send max' const callback = (res) => { if (res) { if (res.error) { this.formInvalid = res.error; this.latestSimError = res.error; } else { this.defaultTransactionParams = res; this.formInvalid = ''; this.latestSimError = ''; this.updateMaxAmount(); } } else { console.log('no res'); } this.simSemaphore--; }; this.estimateService.estimateTransactions(JSON.parse(JSON.stringify(txs)), this.activeAccount.address, this.tokenTransfer, callback); } else { this.latestSimError = prevSimError; this.formInvalid = this.latestSimError; } } else { this.latestSimError = prevSimError; if (this.isMultipleDestinations ? !this.toMultipleDestinationsString : !this.toPkh) { this.defaultTransactionParams = zeroTxParams; this.updateMaxAmount(); this.prevEquiClass = ''; } } } equiClass(sender: string, transactions: any): string { let data = sender; if (this.tokenTransfer) { data += transactions[0].to + transactions[0].amount.toString(); } else { for (const tx of transactions) { data += tx.to; } } return data; } /* 1. input validation strict checks that 2. create basic transaction array */ sanitizeNumberInput(e, type = ''): void { console.dir(this.token?.decimals, e.target) if (['gas', 'storage'].includes(type) || (type === 'amount' && this.token?.decimals == 0)) { e.target.value = e.target.value.replace(/[^0-9]/g, ''); } else { e.target.value = e.target.value.replace(/[^0-9\.]/g, ''); if ((e.target.value.match(/\./g) || []).length > 1) { const tmp = e.target.value.split(''); tmp.splice(tmp.lastIndexOf('.'), 1); e.target.value = tmp.join(''); } if (e.target.value.charAt(0) === '.') { e.target.value = '0' + e.target.value; } } } updateDefaultValues(e?: any): void { const val = e?.target.value.trim(); if (val && !this.torusVerifier) { if (this.inputValidationService.twitterAccount(val)) { this.torusVerifier = 'twitter'; this.torusVerifierName = 'Twitter'; } else if (this.inputValidationService.tezosDomain(val)) { this.torusVerifier = 'domain'; this.torusVerifierName = 'Tezos Domains'; } e.target.value = e.target.value.trim(); } if (!this.torusVerifier) { this.estimateFees(); if (this.isMultipleDestinations) { this.amount = this.getTotalAmount(); } } } toPkhChange(): void { if (this.torusVerifier) { this.torusLookup(); } } // Will return PartiallyPreparedTransaction or throw an error getMinimalPreparedTxs(finalCheck = false): PartiallyPreparedTransaction[] { if (!this.isMultipleDestinations) { if (this.torusVerifier) { assert(!this.invalidTorusAccount(), this.invalidTorusAccount()); assert(this.torusReady(), 'Pending lookup'); this.checkTx(this.torusLookupAddress, this.amount, finalCheck); const meta: any = { verifier: this.torusVerifier, alias: this.torusLookupId }; if (this.torusTwitterId) { meta.twitterId = this.torusTwitterId; } return [{ kind: 'transaction', destination: this.torusLookupAddress, amount: this.amount ? this.amount : '0', meta }]; } else { this.checkTx(this.toPkh, this.amount, finalCheck); } return [{ kind: 'transaction', destination: this.toPkh, amount: this.amount ? this.amount : '0' }]; //this.checkGasStorageFee(); } else { return this.getBatch(finalCheck); //assert(false, 'not supported yet') } } checkTx(toPkh: string, amount: string, finalCheck: boolean): void { assert(this.torusVerifier || !(!this.inputValidationService.address(toPkh) || toPkh === this.activeAccount.address), this.translate.instant('SENDCOMPONENT.INVALIDRECEIVERADDRESS')); assert(!this.torusVerifier || !(!this.inputValidationService.torusAccount(this.toPkh, this.torusVerifier) || this.torusLookupAddress === this.activeAccount.address), 'Invalid recipient'); assert(!(!this.inputValidationService.amount(amount, this.token ? this.token.decimals : undefined) || (finalCheck && ((amount === '0') || amount === '') && (toPkh.slice(0, 3) !== 'KT1'))), this.translate.instant('SENDCOMPONENT.INVALIDAMOUNT')); } getBatch(finalCheck = false): PartiallyPreparedTransaction[] { const txs: PartiallyPreparedTransaction[] = this.toMultipleDestinationsString.trim().split(';').map((row, i) => { if (row.trim()) { const cols = row.trim().split(' ').map(col => col.trim()).filter(col => col); assert(cols?.length === 2, `Transaction ${i + 1} has invalid number of arguments. Expected 2, but got ${cols?.length}.`); assert(this.inputValidationService.address(cols[0]), `Transaction ${i + 1} contains an invalid destination.`); assert(this.inputValidationService.amount(cols[1]), `Transaction ${i + 1} contains an invalid amount.`); this.checkTx(cols[0], cols[1], finalCheck); const tx: PartiallyPreparedTransaction = { kind: 'transaction', destination: cols[0], amount: cols[1] }; return tx; } }).filter(row => row); return txs; } getFullyPreparedTxs(): FullyPreparedTransaction[] { assert(!this.simSemaphore && (!this.torusVerifier || this.torusReady()), this.formInvalid ? this.formInvalid : 'Awaiting request' ); const minimalTxs = this.getMinimalPreparedTxs(true); this.transactions = minimalTxs; assert(this.inputValidationService.fee(this.customFee), 'Invalid fee'); assert(this.inputValidationService.gas(this.customGasLimit), 'Invalid gas limit'); assert(this.inputValidationService.gas(this.customStorageLimit), 'Invalid storage limit'); assert(!this.checkBalance(), this.checkBalance()); assert(minimalTxs.length === this.defaultTransactionParams.customLimits?.length, 'Simulation error'); return this.opsWithCustomLimits(); } opsWithCustomLimits(): FullyPreparedTransaction[] { let extraGas: number = 0; let extraStorage: number = 0; if (this.customGasLimit && this.customGasLimit !== this.defaultTransactionParams.gas.toString()) { extraGas = Number(this.customGasLimit) - this.defaultTransactionParams.gas; } if (this.customStorageLimit && this.customStorageLimit !== this.defaultTransactionParams.storage.toString()) { extraStorage = Number(this.customStorageLimit) - this.defaultTransactionParams.storage; } const extraGasPerOp: number = Math.round(extraGas / this.transactions.length); const extraStoragePerOp: number = Math.round(extraStorage / this.transactions.length); const txs: FullyPreparedTransaction[] = []; for (let i = 0; i < this.transactions.length; i++) { let gasLimit: string = extraGas ? (Number(this.defaultTransactionParams.customLimits[i].gasLimit) + extraGasPerOp).toString() : this.defaultTransactionParams.customLimits[i].gasLimit.toString(); let storageLimit = extraStorage ? (Number(this.defaultTransactionParams.customLimits[i].storageLimit) + extraStoragePerOp).toString() : this.defaultTransactionParams.customLimits[i].storageLimit.toString(); gasLimit = !(Number(gasLimit) < 0) ? gasLimit : '0'; storageLimit = !(Number(storageLimit) < 0) ? storageLimit : '0'; const fullyTx: FullyPreparedTransaction = { ...this.transactions[i], fee: (i === this.transactions.length - 1) ? this.getTotalFee().toString() : '0', gasLimit, storageLimit, }; txs.push(fullyTx); } return txs; } invalidTorusAccount(): string { const torusError = { google: 'Invalid Google email address', reddit: 'Invalid Reddit username', twitter: 'Invalid Twitter username', domain: 'Tezos Domains must be valid url' }; if (!this.inputValidationService.torusAccount(this.toPkh, this.torusVerifier) && this.toPkh !== '') { return torusError[this.torusVerifier]; } } sendEntireBalance(event: Event) { event.stopPropagation(); this.sendMax = true; this.checkMaxAmount(); this.amountChange(); } toggleDestination(): void { this.defaultTransactionParams = zeroTxParams; this.sendMax = false; this.prevEquiClass = ''; this.isMultipleDestinations = !this.isMultipleDestinations; this.transactions = []; this.toMultipleDestinationsString = ''; this.formInvalid = ''; this.toPkh = ''; this.amount = ''; this.customFee = ''; this.customGasLimit = ''; this.customStorageLimit = ''; this.clearTorus(); this.updateDefaultValues(); } clearTorus(): void { this.torusVerifier = ''; this.torusPendingLookup = false; this.torusLookupAddress = ''; this.torusLookupId = ''; this.torusTwitterId = ''; } checkMaxAmount(): void { if (this.sendMax) { const max = this.maxToSend(this.activeAccount); if (max.length && max.slice(0, 1) !== '-') { this.amount = max; } else { this.amount = '0'; } } } checkBalance(): string { if (this.transactions.length > 0) { if (this.activeAccount && (this.activeAccount instanceof ImplicitAccount)) { const max = Big(this.maxToSend(this.activeAccount)).plus(this.tokenTransfer ? 0 : 0.000001); let amount = Big(0); for (const tx of this.transactions) { amount = amount.plus(Big(tx.amount)); } if (amount.gt(max)) { return this.translate.instant('SENDCOMPONENT.TOOHIGHFEEORAMOUNT'); } } else if (this.activeAccount && (this.activeAccount instanceof OriginatedAccount)) { const maxKt = Big(this.maxToSend(this.activeAccount)); const maxTz = Big(this.maxToSend(this.walletService.wallet.getImplicitAccount(this.activeAccount.pkh))).plus(0.000001); let amount = Big(0); for (const tx of this.transactions) { amount = amount.plus(Big(tx.amount)); } if (amount.gt(maxKt)) { return this.translate.instant('SENDCOMPONENT.TOOHIGHAMOUNT'); } else if ((new Big('0')).gt(maxTz)) { return this.translate.instant('SENDCOMPONENT.TOOHIGHFEE'); } } } return ''; } updateMaxAmount(): void { if (this.sendMax) { const max = this.maxToSend(this.activeAccount); let maxAmount = '0'; if (max.length && max.slice(0, 1) !== '-') { maxAmount = max; } if (this.amount !== maxAmount) { this.amount = maxAmount; } } } maxToSend(account: Account): string { if (account && (account instanceof ImplicitAccount) && !this.tokenTransfer) { let accountBalance = Big(account.balanceXTZ).div(1000000); accountBalance = accountBalance.minus(this.customFee && Number(this.customFee) ? Number(this.customFee) : this.defaultTransactionParams.fee); if (!this.isMultipleDestinations) { accountBalance = accountBalance.minus(this.customStorageLimit && Number(this.customStorageLimit) ? Number(Big(this.customStorageLimit).times(this.costPerByte).div('1000000')) : this.defaultTransactionParams.burn); } else { accountBalance = accountBalance.minus(this.defaultTransactionParams.burn); } accountBalance = accountBalance.minus(0.000001); // dust return accountBalance.toString(); } else { if (this.tokenTransfer) { if (account instanceof ImplicitAccount) { return Big(account.getTokenBalance(this.tokenTransfer)).div(10 ** this.token.decimals).toFixed(); } } else { return Big(account.balanceXTZ).div(1000000).toString(); } } } async verifierChange(): Promise<void> { this.torusLookupAddress = ''; if (this.torusVerifier) { this.torusLookup(); } else { this.formInvalid = ''; this.estimateFees(); } // this.validateReceiverAddress(); // resimulate? } async torusLookup(): Promise<any> { if (!this.torusService.verifierMapKeys.includes(this.torusVerifier) && this.torusVerifier !== 'domain') { this.formInvalid = 'Invalid verifier'; } else if (this.invalidTorusAccount()) { this.formInvalid = this.invalidTorusAccount(); } else if (this.toPkh) { this.torusPendingLookup = true; this.torusLookupId = this.toPkh; const { pkh, twitterId } = this.torusVerifier === 'domain' ? await this.tezosDomains.getAddressFromDomain(this.toPkh).then((ans) => { if (ans?.pkh === '') { this.formInvalid = 'Could not find the domain'; } return ans; }).catch(e => { console.error(e); this.formInvalid = e; return ''; }) : await this.torusService.lookupPkh(this.torusVerifier, this.toPkh).catch(e => { console.error(e); this.formInvalid = e; return ''; }); this.torusPendingLookup = false; if (pkh) { this.torusLookupAddress = pkh; this.torusTwitterId = twitterId ? twitterId : ''; this.estimateFees(); } else { this.torusLookupAddress = ''; } } } batchSpace(txs = 0): boolean | string { if (this.isMultipleDestinations && this.defaultTransactionParams.customLimits && this.defaultTransactionParams.customLimits.length) { const numberOfTxs = txs ? txs : this.defaultTransactionParams.customLimits.length; const txsLimit = 294 + (this.defaultTransactionParams.reveal ? 0 : 2); // Max transactions in a batch is 296 (294 with a reveal) return !txs ? this.numberWithCommas(numberOfTxs + ' / ' + txsLimit) : numberOfTxs <= txsLimit; } return !txs ? '' : true; } numberWithCommas(x: string): string { const parts: Array<string> = x.split('.'); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts.join('.'); } torusReady(): boolean { return (!this.torusPendingLookup && this.torusLookupAddress !== ''); } preview(): void { let txs: FullyPreparedTransaction[]; try { txs = this.getFullyPreparedTxs(); this.prepareResponse.emit(txs); ModalComponent.currentModel.next({ name: 'confirm-send', data: { customFee: this.customFee, customGasLimit: this.customGasLimit, customStorageLimit: this.customStorageLimit } }); this.reset(); } catch (e) { this.formInvalid = e.message; } } dynSize(): string { const size = this.amount ? this.amount.length : 0; if (size < 7) { return '5'; } else if (size < 9) { return '4'; } else if (size < 12) { return '3'; } else if (size < 17) { return '2'; } return '1.5'; } dropdownResponse(data): void { if (data?.torusVerifier !== this.torusVerifier) { console.log(this.torusVerifier + ' -> ' + data.torusVerifier); this.torusVerifier = data.torusVerifier; this.torusVerifierName = data.torusVerifierName; this.verifierChange(); } } }
the_stack
import { mat4, vec3, quat } from 'gl-matrix'; import { getElement, applyCSS, getTransformMatrix, findIndex, getOffsetFromParent, getRotateOffset, assign } from './utils/helper'; import { quatToEuler } from './utils/math'; import * as DEFAULT from './constants/default'; import { Offset, UpdateOption, ValueOf, Options } from './types'; class CSSCamera { private _element: HTMLElement; private _viewportEl: HTMLElement; private _cameraEl: HTMLElement; private _worldEl: HTMLElement; private _position: vec3; private _scale: vec3; private _rotation: vec3; private _perspective: number; private _rotateOffset: number; private _updateTimer: number; /** * Current version of CSSCamera. * @example * console.log(CSSCamera.VERSION); // ex) 1.0.0 * @type {string} */ static get VERSION() { return '#__VERSION__#'; } /** * The element provided in the constructor. * @example * const camera = new CSSCamera(el); * console.log(camera.element === el); // true * @type {HTMLElement} */ public get element() { return this._element; } /** * The reference of viewport DOM element. * @type {HTMLElement} */ public get viewportEl() { return this._viewportEl; } /** * The reference of camera DOM element. * @type {HTMLElement} */ public get cameraEl() { return this._cameraEl; } /** * The reference of world DOM element. * @type {HTMLElement} */ public get worldEl() { return this._worldEl; } /** * The current position as number array([x, y, z]). * @example * const camera = new CSSCamera(el); * console.log(camera.position); // [0, 0, 0]; * camera.position = [0, 0, 300]; * console.log(camera.position); // [0, 0, 300]; * @type {number[]} */ public get position() { return [...this._position]; } /** * The current scale as number array([x, y, z]). * @example * const camera = new CSSCamera(el); * console.log(camera.scale); // [1, 1, 1]; * camera.scale = [5, 1, 1]; * console.log(camera.scale); // [5, 1, 1]; * @type {number[]} */ public get scale() { return [...this._scale]; } /** * The current Euler rotation angles in degree as number array([x, y, z]). * @example * const camera = new CSSCamera(el); * console.log(camera.rotation); // [0, 0, 0]; * camera.rotation = [90, 0, 0]; * console.log(camera.rotation); // [90, 0, 0]; * @type {number[]} */ public get rotation() { return [...this._rotation]; } /** * The current quaternion rotation as number array([x, y, z, w]). * @example * const camera = new CSSCamera(el); * console.log(camera.quaternion); // [0, 0, 0, 1]; * camera.rotation = [90, 0, 0]; * console.log(camera.quaternion); // [0.7071067690849304, 0, 0, 0.7071067690849304]; * camera.quaternion = [0, 0, 0, 1]; * console.log(camera.rotation); // [0, -0, 0]; * @type {number[]} */ public get quaternion() { const r = this._rotation; const quaternion = quat.fromEuler(quat.create(), r[0], r[1], r[2]); return [...quaternion]; } /** * The current perspective value that will be applied to viewport element. * @example * const camera = new CSSCamera(el); * camera.perspective = 300; * console.log(camera.perspective); // 300 * @type {number} */ public get perspective() { return this._perspective; } /** * The current rotate offset value that will be applied to camera element. * The camera will be as far away from the focal point as this value. * |![rot0](https://woodneck.github.io/css-camera/asset/rot0.gif)|![rot150](https://woodneck.github.io/css-camera/asset/rot150.gif)| * |:---:|:---:| * @example * const camera = new CSSCamera(el); * camera.perspective = 300; * console.log(camera.cameraCSS); // scale3d(1, 1, 1) translateZ(300px) rotateX(0deg) rotateY(0deg) rotateZ(0deg); * camera.rotateOffset = 100; * console.log(camera.cameraCSS); // scale3d(1, 1, 1) translateZ(400px) rotateX(0deg) rotateY(0deg) rotateZ(0deg); * @type {number} */ public get rotateOffset() { return this._rotateOffset; } /** * CSS string can be applied to camera element based on current transform. * @example * const camera = new CSSCamera(el); * camera.perspective = 300; * console.log(camera.cameraCSS); // scale3d(1, 1, 1) translateZ(300px) rotateX(0deg) rotateY(0deg) rotateZ(0deg); * @type {string} */ public get cameraCSS() { const perspective = this._perspective; const rotateOffset = this._rotateOffset; const rotation = this._rotation; const scale = this._scale; // Rotate in order of Z - Y - X // tslint:disable-next-line: max-line-length return `scale3d(${scale[0]}, ${scale[1]}, ${scale[2]}) translateZ(${perspective - rotateOffset}px) rotateX(${rotation[0]}deg) rotateY(${rotation[1]}deg) rotateZ(${rotation[2]}deg)`; } /** * CSS string can be applied to world element based on current transform. * ``` * const camera = new CSSCamera(el); * console.log(camera.worldCSS); // "translate3d(0px, 0px, 0px)"; * camera.translate(0, 0, 300); * console.log(camera.worldCSS); // "translate3d(0px, 0px, -300px)"; * ``` * @type {string} */ public get worldCSS() { const position = this._position; return `translate3d(${-position[0]}px, ${-position[1]}px, ${-position[2]}px)`; } public set position(val: number[]) { this._position = vec3.fromValues(val[0], val[1], val[2]); } public set scale(val: number[]) { this._scale = vec3.fromValues(val[0], val[1], val[2]); } public set rotation(val: number[]) { this._rotation = vec3.fromValues(val[0], val[1], val[2]); } public set quaternion(val: number[]) { this._rotation = quatToEuler(quat.fromValues(val[0], val[1], val[2], val[3])); } public set perspective(val: number) { this._perspective = val; } public set rotateOffset(val: number) { this._rotateOffset = val; } /** * Create new CSSCamera with given element / selector. * @param - The element to apply camera. Can be HTMLElement or CSS selector. * @param {Partial<Options>} [options] Camera options * @param {number[]} [options.position=[0, 0, 0]] Initial position of the camera. * @param {number[]} [options.scale=[1, 1, 1]] Initial scale of the camera. * @param {number[]} [options.rotation=[0, 0, 0]] Initial Euler rotation angles(x, y, z) of the camera in degree. * @param {number} [options.perspective=0] Initial perspective of the camera. * @param {number} [options.rotateOffset=0] Initial rotate offset of the camera. * @example * const camera = new CSSCamera("#el", { * position: [0, 0, 150], // Initial pos(x, y, z) * rotation: [90, 0, 0], // Initial rotation(x, y, z, in degree) * perspective: 300 // CSS "perspective" value to apply * }); */ constructor(el: string | HTMLElement, options: Partial<Options> = {}) { this._element = getElement(el); const op = assign(assign({}, DEFAULT.OPTIONS), options) as Options; this._position = vec3.fromValues(op.position[0], op.position[1], op.position[2]); this._scale = vec3.fromValues(op.scale[0], op.scale[1], op.scale[2]); this._rotation = vec3.fromValues(op.rotation[0], op.rotation[1], op.rotation[2]); this._perspective = op.perspective; this._rotateOffset = op.rotateOffset; this._updateTimer = -1; const element = this._element; const viewport = document.createElement('div'); const camera = viewport.cloneNode() as HTMLElement; const world = viewport.cloneNode() as HTMLElement; viewport.className = DEFAULT.CLASS.VIEWPORT; camera.className = DEFAULT.CLASS.CAMERA; world.className = DEFAULT.CLASS.WORLD; applyCSS(viewport, DEFAULT.STYLE.VIEWPORT); applyCSS(camera, DEFAULT.STYLE.CAMERA); applyCSS(world, DEFAULT.STYLE.WORLD); camera.appendChild(world); viewport.appendChild(camera); this._viewportEl = viewport; this._cameraEl = camera; this._worldEl = world; // EL's PARENT -> VIEWPORT -> CAMERA -> WORLD -> EL element.parentElement!.insertBefore(viewport, element); world.appendChild(element); this.update(0); } /** * Focus a camera to given element. * After focus, element will be in front of camera with no rotation applied. * Also, it will have original width / height if neither [scale](#scale) nor [perspectiveOffset](#perspectiveOffset) is applied. * This method won't work if any of element's parent except camera element has scale applied. * @param - The element to focus. Can be HTMLElement or CSS selector. * @return {CSSCamera} The instance itself */ public focus(el: string | HTMLElement): this { const element = getElement(el); const focusMatrix = this._getFocusMatrix(element); const rotation = quat.create(); const translation = vec3.create(); mat4.getRotation(rotation, focusMatrix); mat4.getTranslation(translation, focusMatrix); const eulerAngle = quatToEuler(rotation); vec3.negate(eulerAngle, eulerAngle); this._rotation = eulerAngle; this._position = translation; return this; } /** * Translate a camera in its local coordinate space. * For example, `camera.translateLocal(0, 0, -300)` will always move camera to direction where it's seeing. * @param - Amount of horizontal translation, in px. * @param - Amount of vertical translation, in px. * @param - Amount of translation in view direction, in px. * @return {CSSCamera} The instance itself */ public translateLocal(x: number = 0, y: number = 0, z: number = 0): this { const position = this._position; const rotation = this._rotation; const transVec = vec3.fromValues(x, y, z); const rotQuat = quat.create(); quat.fromEuler(rotQuat, -rotation[0], -rotation[1], -rotation[2]); vec3.transformQuat(transVec, transVec, rotQuat); vec3.add(position, position, transVec); return this; } /** * Translate a camera in world(absolute) coordinate space. * @param - Amount of translation in x axis, in px. * @param - Amount of translation in y axis, in px. * @param - Amount of translation in z axis, in px. * @return {CSSCamera} The instance itself */ public translate(x: number = 0, y: number = 0, z: number = 0): this { vec3.add(this._position, this._position, vec3.fromValues(x, y, z)); return this; } /** * Rotate a camera in world(absolute) coordinate space. * @param - Amount of rotation in x axis, in degree. * @param - Amount of rotation in y axis, in degree. * @param - Amount of rotation in z axis, in degree. * @return {CSSCamera} The instance itself */ public rotate(x: number = 0, y: number = 0, z: number = 0): this { vec3.add(this._rotation, this._rotation, vec3.fromValues(x, y, z)); return this; } /** * Updates a camera CSS with given duration. * Every other camera transforming properties / methods will be batched until this method is called. * @example * const camera = new CSSCamera(el); * console.log(camera.cameraEl.style.transform); // '' * * camera.perspective = 300; * camera.translate(0, 0, 300); * camera.rotate(0, 90, 0); * console.log(camera.cameraEl.style.transform); // '', Not changed! * * await camera.update(1000); // Camera style is updated. * console.log(camera.cameraEl.style.transform); // scale3d(1, 1, 1) translateZ(300px) rotateX(0deg) rotateY(90deg) rotateZ(0deg) * * // When if you want to apply multiple properties * camera.update(1000, { * property: "transform, background-color", * timingFunction: "ease-out, ease-out", // As same with CSS, you should assign values to each property * delay: "0ms, 100ms" * }); * @param - Transition duration in ms. * @param {Partial<UpdateOption>} [options] Transition options. * @param {string} [options.property="transform"] CSS [transition-property](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-property) to apply. * @param {string} [options.timingFunction="ease-out"] CSS [transition-timing-function](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function) to apply. * @param {string} [options.delay="0ms"] CSS [transition-delay](https://developer.mozilla.org/en-US/docs/Web/CSS/transition-delay) to apply. * @return {Promise<CSSCamera>} A promise resolving instance itself */ public async update(duration: number = 0, options: Partial<UpdateOption> = {}): Promise<this> { applyCSS(this._viewportEl, { perspective: `${this.perspective}px` }); applyCSS(this._cameraEl, { transform: this.cameraCSS }); applyCSS(this._worldEl, { transform: this.worldCSS }); const updateOptions = assign(assign({}, DEFAULT.UPDATE_OPTIONS), options) as UpdateOption; if (duration > 0) { if (this._updateTimer > 0) { window.clearTimeout(this._updateTimer); } const transitionDuration = `${duration}ms`; const updateOption = Object.keys(updateOptions).reduce((option: {[key: string]: ValueOf<UpdateOption>}, key) => { option[`transition${key.charAt(0).toUpperCase() + key.slice(1)}`] = updateOptions[key as keyof UpdateOption]!; return option; }, {}); const finalOption = { transitionDuration, ...updateOption, }; [this._viewportEl, this._cameraEl, this._worldEl].forEach(el => { applyCSS(el, finalOption); }); } return new Promise(resolve => { // Make sure to use requestAnimationFrame even if duration is 0 // To make sure DOM is updated, for successive update() calls. if (duration > 0) { this._updateTimer = window.setTimeout(() => { // Reset transition values [this._viewportEl, this._cameraEl, this._worldEl].forEach(el => { applyCSS(el, { transition: '' }); }); this._updateTimer = -1; resolve(); }, duration); } else { requestAnimationFrame(() => { resolve(); }); } }); } private _getFocusMatrix(element: HTMLElement): mat4 { const elements: HTMLElement[] = []; while (element) { elements.push(element); if (element === this._element) break; element = element.parentElement!; } // Order by shallow to deep elements.reverse(); const elStyles = elements.map(el => window.getComputedStyle(el)); // Find first element that transform-style is not preserve-3d // As all childs of that element is affected by its matrix const firstFlatIndex = findIndex(elStyles, style => style.transformStyle !== 'preserve-3d'); if (firstFlatIndex > 0) { // el doesn't have to be preserve-3d'ed elStyles.splice(firstFlatIndex + 1); } let parentOffset: Offset = { left: 0, top: 0, width: this.viewportEl.offsetWidth, height: this.viewportEl.offsetHeight, }; // Accumulated rotation const accRotation = quat.identity(quat.create()); // Assume center of screen as (0, 0, 0) const centerPos = vec3.fromValues(0, 0, 0); elStyles.forEach((style, idx) => { const el = elements[idx]; const currentOffset = { left: el.offsetLeft, top: el.offsetTop, width: el.offsetWidth, height: el.offsetHeight, }; const transformMat = getTransformMatrix(style); const offsetFromParent = getOffsetFromParent(currentOffset, parentOffset); vec3.transformQuat(offsetFromParent, offsetFromParent, accRotation); vec3.add(centerPos, centerPos, offsetFromParent); const rotateOffset = getRotateOffset(style, currentOffset); vec3.transformQuat(rotateOffset, rotateOffset, accRotation); const transformOrigin = vec3.clone(centerPos); vec3.add(transformOrigin, transformOrigin, rotateOffset); const centerFromOrigin = vec3.create(); vec3.sub(centerFromOrigin, centerPos, transformOrigin); const invAccRotation = quat.invert(quat.create(), accRotation); vec3.transformQuat(centerFromOrigin, centerFromOrigin, invAccRotation); vec3.transformMat4(centerFromOrigin, centerFromOrigin, transformMat); vec3.transformQuat(centerFromOrigin, centerFromOrigin, accRotation); const newCenterPos = vec3.add(vec3.create(), transformOrigin, centerFromOrigin); const rotation = mat4.getRotation(quat.create(), transformMat); vec3.copy(centerPos, newCenterPos); quat.mul(accRotation, accRotation, rotation); parentOffset = currentOffset; }); const perspective = vec3.fromValues(0, 0, this.perspective); vec3.transformQuat(perspective, perspective, accRotation); vec3.add(centerPos, centerPos, perspective); const matrix = mat4.create(); mat4.fromRotationTranslation(matrix, accRotation, centerPos); return matrix; } } export default CSSCamera;
the_stack
import { Schema } from './schema' import { IS_INTERNAL_OBJECT } from "./symbols"; import { MakeOptional, IsNever, IsTrue, IsAny, IsUndefinedOrNever, ArrayItemType, IsInvariant } from './util'; /** * A structure stores all information needed to match Joi's validation logic. * `Value` will NEVER exist in runtime. `Value` is used only for type inference. * @see Value.getType - How `Value` is assembled into literal type. */ export interface Value< TBase = never, TAugment = never, TAllowed = never, TDefault = undefined, TPresence extends Value.Presence = never > { /** * The base (initial) type of a schema. * The base type should not be modified once the value type is created. * * @description * The initial type of a schema is the type when a new schema is created. For example: * * | Schema | The initial type | * |:---------------|:-------------------| * | `Joi.any()` | `any` | * | `Joi.array()` | `any[]` | * | `Joi.object()` | `Record<any, any>` | */ base: TBase, /** * The augmented type of a schema. * * @description * The augmented type of a schema is the type when specifying subtypes for an existing schema. For example: * * | Schema | The augmented type | * |:-----------------------------------------|:-------------------| * | `Joi.any().equal("0", 1)` | `"0" | 1` | * | `Joi.array().items(Joi.string())` | `string[]` | * | `Joi.object().keys({ a: Joi.number() })` | `{ a?: number }` | * * Additionally, a schema map of a object schema is stored in the augment type to simplify the process of merging two object schemas. */ augment: TAugment, /** * The extra allowed types of a schema. * * @description * The allowed type is added by `Schema.allow()`, `Schema.valid()`, `Schema.only()`, `Schema.equal()`. * This type will be the part of the final literal type. */ allowed: TAllowed, /** * The default type of a schema. * * @description * The default type is specified by `Schema.default()`. * This type will be the part of the final literal type if `presence` is `Optional` or `never`. */ default: TDefault, /** * The presence of a schema. * * @description * The presence is the same to the presence flag internally defined in joi. * It has 4 valid values: `Optional`, `Required`, `Forbidden`, `never`. * When presense is `never`, it equals to `Optional`. */ presence: TPresence } export namespace Value { export const enum Presence { Optional, Required, Forbidden } // -------------------------------------------------------------------------- // Alias // -------------------------------------------------------------------------- export type AnyValue = Value< /* base */ unknown, /* augment */ unknown, /* allowed */ unknown, /* default */ unknown, /* isRequired */ Value.Presence > export type EmptyValue = Value< /* base */ never, /* augment */ never, /* allowed */ never, /* default */ never, /* isRequired */ never > // -------------------------------------------------------------------------- // Building literal // -------------------------------------------------------------------------- /** * Transform `InternalObjectType` into object literal type. * @private */ export type transformSchemaMap<T extends Schema.InternalObjectType> = IsNever<T, never, MakeOptional<{ [Key in excludeForbiddenKeys<T>]: ( T[Key] extends Schema<infer TValue> ? Value.literal<TValue> : never ) }>> /** * Transform `InternalArrayType` into array literal type. * @private */ export type transformArrayType<T extends Schema.InternalArrayType<any>> = IsNever<T, never, ( T extends Schema.InternalArrayType<infer TIsSparse> & (infer TItem)[] ? (TItem | IsTrue<TIsSparse, undefined, never>)[] : never )> /** Wrap `U` with the presence type. */ export type literalPresence<TValue extends AnyValue, TLiteral> = ( IsNever<TValue['presence'], TLiteral | TValue['default'], IsInvariant<TValue['presence'], Presence.Forbidden, never, TLiteral | IsInvariant<TValue['presence'], Presence.Required, never, TValue['default']> > > ) /** Get the literal type of a `Value`. */ export type literal<TValue extends AnyValue> = ( TValue extends any // force typescript to handle unions one by one ? ( literalPresence<TValue, TValue['allowed'] | IsNever<TValue['augment'], TValue['base'], | transformSchemaMap<Extract<TValue['augment'], Schema.InternalObjectType>> | transformArrayType<Extract<TValue['augment'], Schema.InternalArrayType<any>>> | Exclude<Exclude<TValue['augment'], Schema.InternalObjectType>, Schema.InternalArrayType<any>> > > ) : never ) // -------------------------------------------------------------------------- // Value structure manipulation // -------------------------------------------------------------------------- /** Replace the augment type of `TValue` with `U` */ export type replace<TValue extends AnyValue, U = never> = ( TValue extends any ? Value< /* base */ TValue['base'], /* augment */ isAllowOnly<TValue, never, U>, /* allowed */ TValue['allowed'], /* default */ TValue['default'], /* isRequired */ TValue['presence'] > : never ) /** Set the extra allowed type of a `Value`. */ export type allow<TValue extends AnyValue, U = never> = ( TValue extends any ? Value< /* base */ TValue['base'], /* augment */ TValue['augment'], /* allowed */ TValue['allowed'] | U, /* default */ TValue['default'], /* isRequired */ TValue['presence'] > : never ) /** * Set the only allowed type of a `Value`. * @description This removes the base type and the augment type */ export type allowOnly<TValue extends AnyValue, U = never> = ( TValue extends any ? Value< /* base */ never, /* augment */ never, /* allowed */ TValue['allowed'] | U, /* default */ TValue['default'], /* isRequired */ TValue['presence'] > : never ) /** Remove types from the allowed type. */ export type disallow<TValue extends AnyValue, U = never> = ( TValue extends any ? Value< /* base */ TValue['base'], /* augment */ TValue['augment'], /* allowed */ Exclude<TValue['allowed'], U>, /* default */ TValue['default'], /* isRequired */ TValue['presence'] > : never ) /** Set the default type of a `Value`. */ export type setDefault<TValue extends AnyValue, U = never> = ( TValue extends any ? Value< /* base */ TValue['base'], /* augment */ TValue['augment'], /* allowed */ TValue['allowed'], /* default */ U, /* isRequired */ TValue['presence'] > : never ) /** Set the presence of a `Value`. */ export type presence<TValue extends AnyValue, TIsRequired extends Value.Presence> = ( TValue extends any ? Value< /* base */ TValue['base'], /* augment */ TValue['augment'], /* allowed */ TValue['allowed'], /* default */ TValue['default'], /* isRequired */ TIsRequired > : never ) /** Merge two a value types by adding the rules of one type to another. */ export type concat<T extends AnyValue, U extends AnyValue> = ( T extends any ? Value< /* base */ IsAny<T['base'], IsAny<U['base'], any, U['base']>, T['base']>, /* augment */ ( | Schema.deepConcatSchemaMap<Extract<T['augment'], Schema.InternalObjectType>, Extract<U['augment'], Schema.InternalObjectType>> | mergeArrayOnly<Extract<T['augment'], Schema.InternalArrayType<any>>, ArrayItemType<Extract<U['augment'], Schema.InternalArrayType<any>>>> | Exclude<Exclude<T['augment'], Schema.InternalObjectType>, Schema.InternalArrayType<any>> | Exclude<Exclude<U['augment'], Schema.InternalObjectType>, Schema.InternalArrayType<any>> ), /* allowed */ T['allowed'] | U['allowed'], /* default */ IsUndefinedOrNever<U['default'], T['default'], U['default']>, /* isRequired */ IsNever<U['presence'], T['presence'], U['presence']> > : never ) // -------------------------------------------------------------------------- // Value manipulation // -------------------------------------------------------------------------- /** Make a `Value` required. */ export type required<TValue extends AnyValue> = presence<TValue, Value.Presence.Required> /** Make a `Value` optional. */ export type optional<TValue extends AnyValue> = presence<TValue, Value.Presence.Optional> /** Make a `Value` forbidden. */ export type forbidden<TValue extends AnyValue> = presence<TValue, Value.Presence.Forbidden> /** Replace the augment type with the original augment type unioned with `U` */ export type union<TValue extends AnyValue, U = never> = replace<TValue, TValue['augment'] | U> /** * Add `TNewItem` into the array type of a `Value`. * * @description * This is similar to merge two array types and leaving other types unmodified. * e.g. `mergeArray<A[] | B, C> -> (A | C)[] | B` */ export type mergeArray<TValue extends AnyValue, TNewItem = never> = replace<TValue, ( IsNever<TValue['augment'], Exclude<TNewItem, undefined>[] & Schema.InternalArrayType<false>, ( | mergeArrayOnly<Extract<TValue['augment'], Schema.InternalArrayType<any>>, TNewItem> | Exclude<TValue['augment'], Schema.InternalArrayType<any>> )> )> /** Set the sparse flag of the array type of a `Value` */ export type setArraySparse<TValue extends AnyValue, TIsSparse extends boolean> = replace<TValue, ( IsNever<TValue['augment'], never[] & Schema.InternalArrayType<TIsSparse>, ( | (ArrayItemType<Extract<TValue['augment'], Schema.InternalArrayType<any>>>[] & Schema.InternalArrayType<TIsSparse>) | Exclude<TValue['augment'], Schema.InternalArrayType<any>> )> )> /** * Deeply merge two `Value`s. * * @description * - If `T` and `U` both have `InternalObjectType` type, merge them. * - Otherwise just directly use `U` as the result. */ export type deepMerge<T extends AnyValue, U extends AnyValue> = ( IsNever<T['augment'], 0, T['augment']> extends Schema.InternalObjectType ? IsNever<U['augment'], 0, U['augment']> extends Schema.InternalObjectType ? replace<U, Schema.deepMergeSchemaMap< Extract<T['augment'], Schema.InternalObjectType>, Extract<U['augment'], Schema.InternalObjectType> >> : U : U ) /** Make intersection to the augment type of a `Value` with `InternalObjectType` and `U`. */ export type appendSchemaMap<TValue extends AnyValue, U> = ( replace<TValue, IsNever<TValue['augment'], Schema.InternalObjectType & U, TValue['augment'] & Schema.InternalObjectType & U>> ) /** * Make some keys of the object optional. * If one of the key is an empty string, make the entire object optional. */ export type setOptionalKeys<TValue extends AnyValue, TKeys extends string> = ( IsInvariant<TKeys, string, TValue, TValue['augment'] extends Schema.InternalSchemaMap ? '' extends TKeys ? Value.optional<Value.replace<TValue, setOptionalKeysInternal<TValue['augment'], TKeys>>> : Value.replace<TValue, setOptionalKeysInternal<TValue['augment'], TKeys>> : never > ) /** * Make some keys of the object required. * If one of the key is an empty string, make the entire object required. */ export type setRequiredKeys<TValue extends AnyValue, TKeys extends string> = ( IsInvariant<TKeys, string, TValue, TValue['augment'] extends Schema.InternalSchemaMap ? '' extends TKeys ? Value.required<Value.replace<TValue, setRequiredKeysInternal<TValue['augment'], TKeys>>> : Value.replace<TValue, setOptionalKeysInternal<TValue['augment'], TKeys>> : never > ) /** * Make some keys of the object forbidden. * If one of the key is an empty string, make the entire object forbidden. */ export type setForbiddenKeys<TValue extends AnyValue, TKeys extends string> = ( IsInvariant<TKeys, string, TValue, TValue['augment'] extends Schema.InternalSchemaMap ? '' extends TKeys ? Value.forbidden<Value.replace<TValue, setForbiddenKeysInternal<TValue['augment'], TKeys>>> : Value.replace<TValue, setForbiddenKeysInternal<TValue['augment'], TKeys>> : never > ) // -------------------------------------------------------------------------- // Helpers // -------------------------------------------------------------------------- /** * Test if the base type of a `Value` is `never`. * @private */ export type isAllowOnly<TValue extends AnyValue, TrueType = true, FalseType = false> = ( IsNever<TValue['base'], IsNever<TValue['augment'], TrueType, FalseType>, FalseType> ) /** * Do the real array merge of `mergeArray`. * @private */ export type mergeArrayOnly<TArray extends Schema.InternalArrayType<any>, TNewItem> = ( TArray extends Schema.InternalArrayType<infer TIsSparse> & (infer TItem)[] ? Exclude<TItem | TNewItem, undefined>[] & Schema.InternalArrayType<TIsSparse> : never ) /** * Extract object keys without forbidden keys from an internal object type * @private */ export type excludeForbiddenKeys<T extends Schema.InternalObjectType> = ( { [Key in keyof T]: IsInvariant<Schema.valueType<Extract<T[Key], Schema>>['presence'], Presence.Forbidden, never, Key> }[Exclude<keyof T, typeof IS_INTERNAL_OBJECT>] ) /** * Make some keys of the object optional. * @private */ export type setOptionalKeysInternal<TSchemaMap extends Schema.InternalSchemaMap, TKeys extends string> = ( Schema.InternalObjectType & { [key in Exclude<keyof TSchemaMap, typeof IS_INTERNAL_OBJECT>]: key extends TKeys ? Schema.from<TSchemaMap[key], Value.optional<Schema.valueType<TSchemaMap[key]>>> : TSchemaMap[key] } ) /** * Make some keys of the object forbidden. * @private */ export type setRequiredKeysInternal<TSchemaMap extends Schema.InternalSchemaMap, TKeys extends string> = ( Schema.InternalObjectType & { [key in Exclude<keyof TSchemaMap, typeof IS_INTERNAL_OBJECT>]: key extends TKeys ? Schema.from<TSchemaMap[key], Value.required<Schema.valueType<TSchemaMap[key]>>> : TSchemaMap[key] } ) /** * Make some keys of the object forbidden. * @private */ export type setForbiddenKeysInternal<TSchemaMap extends Schema.InternalSchemaMap, TKeys extends string> = ( Schema.InternalObjectType & { [key in Exclude<keyof TSchemaMap, typeof IS_INTERNAL_OBJECT>]: key extends TKeys ? Schema.from<TSchemaMap[key], Value.forbidden<Schema.valueType<TSchemaMap[key]>>> : TSchemaMap[key] } ) }
the_stack
namespace sprites.castle { //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroFrontAttack1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroFrontAttack2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroFrontAttack3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroFrontAttack4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackLeft3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackLeft4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackRight4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackRight3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackRight2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroSideAttackRight1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkFront3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkFront4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkBack1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkBack2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkBack3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkBack4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldFront3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldFront4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldBack1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldBack2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldBack3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldBack4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideLeft3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideLeft4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideRight4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideRight3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideRight2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkShieldSideRight1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideLeft3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideLeft4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideRight4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideRight3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideRight2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const heroWalkSideRight1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="misc" export const houseRed = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="misc" export const houseBlue = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessFront0 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessLeft0 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessBack0 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessBack1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princessBack2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Front = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkFront3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Back = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkBack1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkBack2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2WalkBack3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Left1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Left2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Right1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="people" export const princess2Right2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const rock0 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const rock1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const rock2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const saplingOak = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const saplingPine = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="?tile misc" export const shrub = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyFront = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkFront3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackFront1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackFront2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackFront3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackFront4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackLeft1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkLeft2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkRight1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackRight1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyAttackRight2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="dungeon" export const skellyWalkRight2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileGrass2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileGrass1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath4 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath5 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath6 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileGrass3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath7 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath8 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tilePath9 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileDarkGrass1 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileDarkGrass2 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._tile //% tags="tile forest" export const tileDarkGrass3 = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="forest" export const treePine = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="forest" export const treeOak = image.ofBuffer(hex``); //% fixedInstance jres blockIdentity=images._image //% tags="forest" export const treeSmallPine = image.ofBuffer(hex``); }
the_stack
import { Trans } from "@lingui/macro"; import classNames from "classnames"; import { routerShape, Link } from "react-router"; import PropTypes from "prop-types"; import * as React from "react"; import { Icon, Tooltip } from "@dcos/ui-kit"; import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum"; import { iconSizeXs, greyLightDarken1, iconSizeXxs, success, error, } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens"; import CheckboxTable from "#SRC/js/components/CheckboxTable"; import DCOSStore from "#SRC/js/stores/DCOSStore"; import ResourceTableUtil from "#SRC/js/utils/ResourceTableUtil"; import TableUtil from "#SRC/js/utils/TableUtil"; import Units from "#SRC/js/utils/Units"; import TaskHealthStates from "../../constants/TaskHealthStates"; import TaskStates from "../../constants/TaskStates"; import TaskTableHeaderLabels from "../../constants/TaskTableHeaderLabels"; import TaskTableUtil from "../../utils/TaskTableUtil"; import TaskUtil from "../../utils/TaskUtil"; import { getResourceLimits } from "../../columns/resourceLimits"; const tableColumnClasses = { checkbox: "task-table-column-checkbox", id: "task-table-column-primary", name: "task-table-column-name", host: "task-table-column-host-address", zone: "task-table-column-zone-address", region: "task-table-column-region-address", status: "task-table-column-status", health: "task-table-column-health", logs: "task-table-column-logs", cpus: "task-table-column-cpus", mem: "task-table-column-mem", gpus: "task-table-column-gpus", updated: "task-table-column-updated", }; const getService = (taskId) => DCOSStore.serviceTree.getServiceFromTaskID(taskId); export default class extends React.Component { static contextTypes = { router: routerShape.isRequired }; static defaultProps = { className: "table table-flush table-borderless-outer table-borderless-inner-columns flush-bottom", tasks: [], }; static propTypes = { checkedItemsMap: PropTypes.object, className: PropTypes.string, onCheckboxChange: PropTypes.func, params: PropTypes.object.isRequired, service: PropTypes.object.isRequired, tasks: PropTypes.array.isRequired, i18n: PropTypes.object, }; getStatValue(task, prop) { return task.resources[prop] || 0; } getStatusValue = (task) => { return this.props.i18n._(TaskStates[task.state].displayName); }; getClassName(prop, sortBy, row) { return classNames(tableColumnClasses[prop], { active: prop === sortBy.prop, clickable: row == null && prop !== "logs", // this is a header }); } getColumns() { const className = this.getClassName; const heading = ResourceTableUtil.renderHeading(TaskTableHeaderLabels); // Sorts the table columns by their value and if the value is the same it sorts by id const sortFunction = TaskTableUtil.getSortFunction("id"); const getHealthSorting = TableUtil.getHealthSortingOrder; return [ { className, headerClassName: className, heading, prop: "id", render: this.renderHeadline({ primary: true }), sortable: true, sortFunction, }, { className, headerClassName: className, heading, prop: "name", render: this.renderHeadline({ secondary: true }), sortable: true, sortFunction, }, { className, headerClassName: className, heading, prop: "host", render: this.renderHost, sortable: true, sortFunction, }, { className, headerClassName: className, heading, prop: "zone", render: this.renderZone, sortable: true, sortFunction, }, { className, headerClassName: className, heading, prop: "region", render: this.renderRegion, sortable: true, sortFunction, }, { cacheCell: false, className, getValue: this.getStatusValue, headerClassName: className, heading, prop: "status", render: this.renderStatus, sortable: true, sortFunction, }, { cacheCell: false, className, getValue: this.getStatusValue, headerClassName: className, heading, prop: "health", render: this.renderHealth, sortable: true, sortFunction: getHealthSorting, }, { cacheCell: false, className, headerClassName: className, heading, prop: "logs", render: this.renderLog, sortable: false, }, { cacheCell: true, className, getValue: this.getStatValue, headerClassName: className, heading, prop: "cpus", render: this.renderCpus, sortable: true, sortFunction, }, { cacheCell: true, className, getValue: this.getStatValue, headerClassName: className, heading, prop: "mem", render: this.renderMem, sortable: true, sortFunction, }, { cacheCell: true, className, getValue: this.getStatValue, headerClassName: className, heading, prop: "gpus", render: this.renderStats, sortable: true, sortFunction, }, { className, headerClassName: className, heading, prop: "updated", render: ResourceTableUtil.renderUpdated, sortable: true, sortFunction, }, ]; } getColGroup() { return ( <colgroup> <col className={tableColumnClasses.checkbox} /> <col /> <col className={tableColumnClasses.name} /> <col className={tableColumnClasses.host} /> <col className={tableColumnClasses.zone} /> <col className={tableColumnClasses.region} /> <col className={tableColumnClasses.status} /> <col className={tableColumnClasses.health} /> <col className={tableColumnClasses.logs} /> <col className={tableColumnClasses.cpus} /> <col className={tableColumnClasses.mem} /> <col className={tableColumnClasses.gpus} /> <col className={tableColumnClasses.updated} /> </colgroup> ); } getDisabledItemsMap(tasks) { return tasks .filter( (task) => task.state !== "TASK_UNREACHABLE" && (TaskStates[task.state].stateTypes.includes("completed") || !task.isStartedByMarathon) ) .reduce((acc, task) => { acc[task.id] = true; return acc; }, {}); } getInactiveItemsMap(tasks) { return tasks.reduce((acc, task) => { if (TaskStates[task.state].stateTypes.includes("completed")) { acc[task.id] = true; } return acc; }, {}); } renderHeadline = (options) => { const anchorClasses = classNames( { "table-cell-link-primary": options.primary, "table-cell-link-secondary": options.secondary, }, "text-overflow" ); return (prop, task) => { const title = task[prop]; const { id, nodeID } = this.props.params; let linkTo = `/services/detail/${encodeURIComponent(id)}/tasks/${ task.id }`; if (nodeID != null) { linkTo = `/nodes/${nodeID}/tasks/${task.id}`; } return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box"> <div className="table-cell-value flex-box flex-box-col"> <Link className={anchorClasses} to={linkTo} title={title}> {title} </Link> </div> </div> ); }; }; renderLog = (prop, task) => { const title = task.name || task.id; const { id, nodeID } = this.props.params; let linkTo = `/services/detail/${encodeURIComponent(id)}/tasks/${ task.id }/logs`; if (nodeID != null) { linkTo = `/nodes/${nodeID}/tasks/${task.id}/logs`; } return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box flex-align-items-center flex-direction-top-to-bottom"> <Tooltip id={`logs${task.id}`} trigger={ <Link to={linkTo} title={title}> <Icon color={greyLightDarken1} shape={SystemIcons.PageDocument} size={iconSizeXs} /> </Link> } > <Trans id="View Logs" /> </Tooltip> </div> ); }; renderHost = (prop, task) => { const taskHostName = TaskUtil.getHostName(task); if (!taskHostName) { return "N/A"; } return ( <Link className="table-cell-link-secondary text-overflow" to={`/nodes/${task.slave_id}`} title={taskHostName} > {taskHostName} </Link> ); }; renderRegion(prop, task) { return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box"> <div className="table-cell-value flex-box flex-box-col"> {TaskUtil.getRegionName(task)} </div> </div> ); } renderZone(prop, task) { return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box"> <div className="table-cell-value flex-box flex-box-col"> {TaskUtil.getZoneName(task)} </div> </div> ); } renderStats = (prop, task) => { return ( <span>{Units.formatResource(prop, this.getStatValue(task, prop))}</span> ); }; renderMem = (_, task) => { const service = getService(task.id); const memLimit = service && getResourceLimits(service).mem; if (memLimit != null && memLimit !== 0) { return ( <Tooltip id={`mem{task.id}`} trigger={`${Units.formatResource( "mem", task.resources.mem )} / ${Units.formatResource("mem", memLimit)}`} maxWidth={150} > <Trans id="{resource} are being guaranteed with a limit of {limit}" render="span" values={{ resource: Units.formatResource("mem", task.resources.mem), limit: Units.formatResource("mem", memLimit), }} /> </Tooltip> ); } return <span>{Units.formatResource("mem", task.resources.mem)}</span>; }; renderCpus = (_, task) => { const service = getService(task.id); const cpusLimit = service && getResourceLimits(service).cpus; if (cpusLimit != null && cpusLimit !== 0) { return ( <Tooltip id={`cpu${task.id}`} trigger={`${Units.formatResource( "cpus", task.resources.cpus )} / ${Units.formatResource("cpus", cpusLimit)}`} maxWidth={150} > <Trans id="{resource} cpus are being guaranteed with a limit of {limit} cpus" render="span" values={{ resource: Units.formatResource("cpus", task.resources.cpus), limit: Units.formatResource("cpus", cpusLimit), }} /> </Tooltip> ); } return ( <span> {Units.formatResource("cpus", task.resources.cpus)}{" "} {cpusLimit ? ` / ${Units.formatResource("cpus", cpusLimit)}` : null} </span> ); }; renderStatus = (prop, task) => { const statusClassName = TaskUtil.getTaskStatusClassName(task); const statusLabelClasses = `${statusClassName} table-cell-value`; return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box"> <Trans id={this.getStatusValue(task)} render="span" className={statusLabelClasses} /> </div> ); }; renderHealth(prop, task) { const { state } = task; const dangerState = TaskStates[state].stateTypes.includes("failure"); const activeState = TaskStates[state].stateTypes.includes("active"); const transitional = [ "TASK_KILLING", "TASK_STARTING", "TASK_STAGING", ].includes(state); const healthy = task.health === TaskHealthStates.HEALTHY; const unhealthy = task.health === TaskHealthStates.UNHEALTHY; const unknown = task.health === TaskHealthStates.UNKNOWN; let tooltipContent = <Trans id={TaskHealthStates.HEALTHY} render="span" />; if (unhealthy) { tooltipContent = <Trans id={TaskHealthStates.UNHEALTHY} render="span" />; } if (!activeState || unknown || transitional) { tooltipContent = <Trans render="span">No health checks available</Trans>; } const failing = ["TASK_ERROR", "TASK_FAILED"].includes(state); const running = ["TASK_RUNNING", "TASK_STARTING"].includes(state); const getStatusIcon = () => { // inactive if (!activeState || transitional) { return <span className="dot flush inactive" />; } // success if (healthy && running) { return ( <Icon shape={SystemIcons.CircleCheck} size={iconSizeXxs} color={success} /> ); } // running if (unknown && running) { return <span className="dot flush running" />; } // danger if (dangerState || unhealthy || failing) { return ( <Icon shape={SystemIcons.CircleClose} size={iconSizeXxs} color={error} /> ); } }; return ( <div className="flex-box flex-box-align-vertical-center table-cell-flex-box flex-align-items-center flex-direction-top-to-bottom"> <div className="table-cell-icon table-cell-task-dot task-status-indicator"> <Tooltip id={`health${task.id}`} trigger={getStatusIcon()}> {tooltipContent} </Tooltip> </div> </div> ); } render() { const { checkedItemsMap, className, onCheckboxChange, tasks } = this.props; return ( <CheckboxTable checkedItemsMap={checkedItemsMap} className={className} columns={this.getColumns()} data={tasks.slice()} disabledItemsMap={this.getDisabledItemsMap(tasks)} inactiveItemsMap={this.getInactiveItemsMap(tasks)} getColGroup={this.getColGroup} onCheckboxChange={onCheckboxChange} sortBy={{ prop: "updated", order: "desc" }} sortOrder="desc" sortProp="updated" uniqueProperty="id" /> ); } }
the_stack
import * as ts from 'typescript'; import * as path from 'path'; import * as fsx from 'fs-extra'; import * as fs from 'fs'; const DEBUG = false; export const options: ts.CompilerOptions = { allowNonTsExtensions: true, module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES5, }; export interface MinifierOptions { failFast?: boolean; basePath?: string; } export class Minifier { static reservedJSKeywords = Minifier.buildReservedKeywordsMap(); // Key: (Eventually fully qualified) original property name // Value: new generated property name private _renameMap: {[name: string]: string} = {}; // Key: Type symbol at actual use sites (from) // Value: A list of the expected type symbol (to) private _typeCasting: Map<ts.Symbol, ts.Symbol[]> = <Map<ts.Symbol, ts.Symbol[]>>(new Map()); private _reverseTypeCasting: Map<ts.Symbol, ts.Symbol[]> = <Map<ts.Symbol, ts.Symbol[]>>(new Map()); private _lastGeneratedPropName: string = ''; private _typeChecker: ts.TypeChecker; private _errors: string[] = []; constructor(private _minifierOptions: MinifierOptions = {}) {} checkForErrors(program: ts.Program) { var errors = []; var emitResult = program.emit(); var allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); allDiagnostics.forEach(diagnostic => { if (diagnostic.file && !diagnostic.file.fileName.match(/\.d\.ts$/)) { var {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); errors.push(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } }); if (errors.length > 0) { throw new Error( 'Malformed TypeScript: Please check your source-files before attempting to use ts-minify.\n' + errors.join('\n')); } } setTypeChecker(typeChecker: ts.TypeChecker) { this._typeChecker = typeChecker; } reportError(n: ts.Node, message: string) { var file = n.getSourceFile(); var fileName = file.fileName; var start = n.getStart(file); var pos = file.getLineAndCharacterOfPosition(start); var fullMessage = `${fileName}:${pos.line + 1}:${pos.character + 1}: ${message}`; this._errors.push(fullMessage); if (this._minifierOptions.failFast) { throw new Error(fullMessage); } } // This method assumes that the user has taken care of getting and setting the TypeChecker for // an instance of the Minifier class. // // Example: // var minifier = new Minifier(); // var typeChecker = program.getTypeChecker(); // var sourceFile = program.getSourceFile(); // minifier.setTypeChecker(typeChecker); renameProgramFromNode(node: ts.Node): string { this._preprocessVisit(node); return this._visit(node); } // Renaming goes through a pre-processing step and an emitting step. renameProgram(fileNames: string[], destination?: string) { var host = ts.createCompilerHost(options); var program = ts.createProgram(fileNames, options, host); this._typeChecker = program.getTypeChecker(); let sourceFiles = program.getSourceFiles().filter((sf) => !sf.fileName.match(/\.d\.ts$/)); sourceFiles.forEach((f) => { this._preprocessVisit(f); }); if (DEBUG) { this._typeCasting.forEach((value, key) => { value.forEach((val) => console.log('cast type from: ' + key.name, 'to: ' + val.name)); }); } sourceFiles.forEach((f) => { var renamedTSCode = this._visit(f); var fileName = this.getOutputPath(f.fileName, destination); if (DEBUG) { console.log(renamedTSCode); } fsx.mkdirsSync(path.dirname(fileName)); fs.writeFileSync(fileName, renamedTSCode); }); } getOutputPath(filePath: string, destination: string = '.'): string { destination = path.resolve(process.cwd(), destination); var absFilePath = path.resolve(process.cwd(), filePath); // no base path, flatten file structure and output to destination if (!this._minifierOptions.basePath) { return path.join(destination, path.basename(filePath)); } this._minifierOptions.basePath = path.resolve(process.cwd(), this._minifierOptions.basePath); // given a base path, preserve file directory structure var subFilePath = absFilePath.replace(this._minifierOptions.basePath, ''); if (subFilePath === absFilePath) { return path.join(destination, filePath); } return path.join(destination, subFilePath); } isExternal(symbol: ts.Symbol): boolean { // TODO: figure out how to deal with undefined symbols // (ie: in case of string literal, or something like true.toString(), // the TypeScript typechecker will give an undefined symbol) if (!symbol) return true; return symbol.declarations.some((decl) => !!(decl.getSourceFile().fileName.match(/\.d\.ts/))); } isRenameable(symbol: ts.Symbol): boolean { if (this.isExternal(symbol)) return false; if (!this._typeCasting.has(symbol) && !this._reverseTypeCasting.has(symbol)) return true; let boolArrTypeCasting: boolean[] = []; let boolRevArrTypeCasting: boolean[] = []; // Three cases to consider: // CANNOT RENAME: Use site passes an internally typed object, expected site wants an externally // typed object OR use site passes externally typed object, but expected site wants an // internally typed object // CAN RENAME: Use site type symbols are internal, expected type symbols are internal // ERROR: Expected symbol is external, use sites are both internal and external // Create boolean array of whether or not actual sites (type to which a symbol is being cast) // are internal if (this._typeCasting.has(symbol)) { for (let castType of this._typeCasting.get(symbol)) { boolArrTypeCasting.push(!this.isExternal(castType)); } // Check if there are both true and false values in boolArrTypeCasting, throw Error if (boolArrTypeCasting.indexOf(true) >= 0 && boolArrTypeCasting.indexOf(false) >= 0) { throw new Error( 'ts-minify does not support accepting both internal and external types at a use site\n' + 'Symbol name: ' + symbol.getName()); } } // REVERSE if (this._reverseTypeCasting.has(symbol)) { for (let castType of this._reverseTypeCasting.get(symbol)) { boolRevArrTypeCasting.push(!this.isExternal(castType)); } // Check if there are both true and false values in boolArrTypeCasting, throw Error if (boolRevArrTypeCasting.indexOf(true) >= 0 && boolRevArrTypeCasting.indexOf(false) >= 0) { throw new Error( 'ts-minify does not support accepting both internal and external types at a use site\n' + 'Symbol name: ' + symbol.getName()); } } if (boolArrTypeCasting.length === 0) { return boolRevArrTypeCasting[0]; } if (boolRevArrTypeCasting.length === 0) { return boolArrTypeCasting[0]; } // Since all values in boolArrayTypeCasting are all the same value, just return the first value return boolArrTypeCasting[0] && boolRevArrTypeCasting[0]; } private _getAncestor(n: ts.Node, kind: ts.SyntaxKind): ts.Node { for (var parent = n; parent; parent = parent.parent) { if (parent.kind === kind) return parent; } return null; } private _preprocessVisitChildren(node: ts.Node) { node.getChildren().forEach((child) => { this._preprocessVisit(child); }); } // Key - To: the expected type symbol // Value - From: the actual type symbol // IE: Coercing from type A to type B private _recordCast(from: ts.Symbol, to: ts.Symbol) { if (!from || !to) return; if (this._typeCasting.has(from)) { this._typeCasting.get(from).push(to); } else { this._typeCasting.set(from, [to]); } if (this._reverseTypeCasting.has(to)) { this._reverseTypeCasting.get(to).push(from); } else { this._reverseTypeCasting.set(to, [from]); } } // The preprocessing step is necessary in order to to find all typecasts (explicit and implicit) // in the given source file(s). During the visit step (where renaming and emitting occurs), // the information gathered from this step are used to figure out which types are internal to the // scope that the minifier is working with and which are external. This allows the minifier to // rename properties more correctly. private _preprocessVisit(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.CallExpression: { var callExpr = <ts.CallExpression>node; var lhsSymbol = this._typeChecker.getSymbolAtLocation(callExpr.expression); let paramSymbols: ts.Symbol[] = []; // TODO: understand cases of multiple declarations, pick first declaration for now if (!lhsSymbol || !((<any>lhsSymbol.declarations[0]).parameters)) { this._preprocessVisitChildren(node); break; } else { (<any>lhsSymbol.declarations[0]) .parameters.forEach((param) => { if (param.type && param.type.typeName) { let paramSymbol = this._typeChecker.getTypeAtLocation( (<ts.TypeReferenceNode>param.type).typeName) .symbol; paramSymbols.push(paramSymbol); } else if (param.type) { let paramSymbol = this._typeChecker.getTypeAtLocation(param).symbol; paramSymbols.push(paramSymbol); } }); let argsSymbols: ts.Symbol[] = []; // right hand side argument has actual type of parameter callExpr.arguments.forEach( (arg) => { argsSymbols.push(this._typeChecker.getTypeAtLocation(arg).symbol); }); // Casting from: Use site symbol, to: expected parameter type paramSymbols.forEach((sym, i) => { this._recordCast(argsSymbols[i], sym); }); this._preprocessVisitChildren(node); break; } } case ts.SyntaxKind.VariableDeclaration: { let varDecl = <ts.VariableDeclaration>node; if (varDecl.initializer && varDecl.type) { let varDeclTypeSymbol = this._typeChecker.getTypeAtLocation(varDecl.type).symbol; let initTypeSymbol = this._typeChecker.getTypeAtLocation(varDecl.initializer).symbol; // Casting from: initializer's type symbol, to: actual variable declaration's annotated // type this._recordCast(initTypeSymbol, varDeclTypeSymbol); } this._preprocessVisitChildren(node); break; } case ts.SyntaxKind.ReturnStatement: { // check if there is an expression on the return statement since it's optional if (node.parent.kind !== ts.SyntaxKind.SourceFile && (<ts.ReturnStatement>node).expression) { let symbolReturn = this._typeChecker.getTypeAtLocation((<ts.ReturnStatement>node).expression).symbol; let methodDeclAncestor = this._getAncestor(node, ts.SyntaxKind.MethodDeclaration); let funcDeclAncestor = this._getAncestor(node, ts.SyntaxKind.FunctionDeclaration); // early exit if no ancestor that is method or function declaration if (!methodDeclAncestor && !funcDeclAncestor) { this._preprocessVisitChildren(node); break; } let funcLikeDecl = <ts.FunctionLikeDeclaration>(methodDeclAncestor || funcDeclAncestor); if (!funcLikeDecl.type) { this._preprocessVisitChildren(node); break; } if (funcLikeDecl.type && (<ts.TypeReferenceNode>funcLikeDecl.type).typeName) { let funcLikeDeclSymbol = this._typeChecker.getSymbolAtLocation( (<ts.TypeReferenceNode>funcLikeDecl.type).typeName); // Casting from: return expression's type symbol, to: actual function/method // declaration's return type this._recordCast(symbolReturn, funcLikeDeclSymbol); } } this._preprocessVisitChildren(node); break; } default: { this._preprocessVisitChildren(node); break; } } } // Recursively visits every child node, emitting text of the sourcefile that is not a part of // a child node. private _visit(node: ts.Node): string { switch (node.kind) { case ts.SyntaxKind.PropertyAccessExpression: { let pae = <ts.PropertyAccessExpression>node; let exprSymbol = this._getExpressionSymbol(pae); let output = ''; let children = pae.getChildren(); output += this._visit(pae.expression); output += pae.dotToken.getFullText(); // if LHS is a module, do not rename property name var lhsTypeSymbol = this._typeChecker.getTypeAtLocation(pae.expression).symbol; var lhsIsModule = lhsTypeSymbol && ts.SymbolFlags.ValueModule === lhsTypeSymbol.flags; // Early exit when exprSymbol is undefined. if (!exprSymbol) { this.reportError(pae.name, 'Symbol information could not be extracted.\n'); return; } var isExternal = this.isExternal(exprSymbol); if (!this.isRenameable(lhsTypeSymbol) || isExternal || lhsIsModule) { return output + this._ident(pae.name); } return output + this._renameIdent(pae.name); } // TODO: A parameter property will need to also be renamed in the // constructor body if the parameter is used there. // Look at Issue #39 for an example. case ts.SyntaxKind.Parameter: { var paramDecl = <ts.ParameterDeclaration>node; // if there are modifiers, then we know this is a declaration and an initialization at once // we need to rename the property if (this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Public) || this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Private) || this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Protected)) { return this.contextEmit(node, true); } return this.contextEmit(node); } case ts.SyntaxKind.PropertySignature: { if (node.parent.kind === ts.SyntaxKind.TypeLiteral || node.parent.kind === ts.SyntaxKind.InterfaceDeclaration) { let parentSymbol = this._typeChecker.getTypeAtLocation(node.parent).symbol; let rename = this.isRenameable(parentSymbol); return this.contextEmit(node, rename); } return this.contextEmit(node); } // All have same wanted behavior. case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.PropertyAssignment: case ts.SyntaxKind.PropertyDeclaration: { let parentTypeSymbol = this._typeChecker.getTypeAtLocation(node.parent).symbol; let renameable = this.isRenameable(parentTypeSymbol); return this.contextEmit(node, renameable); } default: { return this.contextEmit(node); } } } // if renameIdent is true, rename children identifiers in this node private contextEmit(node: ts.Node, renameIdent: boolean = false) { // The indicies of nodeText range from 0 ... nodeText.length - 1. However, the start and end // positions of nodeText that .getStart() and .getEnd() return are relative to // the entire sourcefile. let nodeText = node.getFullText(); let children = node.getChildren(); let output = ''; // prevEnd is used to keep track of how much of nodeText has been copied over. It is updated // within the for loop below, and text from nodeText(0, prevEnd), including children text // that fall within the range, has already been copied over to output. let prevEnd = 0; let nameChildNode = (<any>node).name; // Loop-invariant: prevEnd should always be less than or equal to the start position of // an unvisited child node because the text before a child's text must be copied over to // the new output before anything else. children.forEach((child) => { // The start and end positions of the child's text must be updated so that they // are relative to the indicies of the parent's text range (0 ... nodeText.length - 1), by // off-setting by the value of the parent's start position. Now childStart and childEnd // are relative to the range of (0 ... nodeText.length). let childStart = child.getFullStart() - node.getFullStart(); let childEnd = child.getEnd() - node.getFullStart(); output += nodeText.substring(prevEnd, childStart); let childText = ''; if (renameIdent && child === nameChildNode && child.kind === ts.SyntaxKind.Identifier) { childText = this._renameIdent(child); } else { childText = this._visit(child); } output += childText; prevEnd = childEnd; }); output += nodeText.substring(prevEnd, nodeText.length); return output; } // n: modifiers array, flag: the flag we are looking for private hasFlag(n: {flags: number}, flag: ts.NodeFlags): boolean { return n && (n.flags & flag) !== 0; } private _getExpressionSymbol(node: ts.PropertyAccessExpression) { let exprSymbol = this._typeChecker.getSymbolAtLocation(node.name); // Sometimes the RHS expression does not have a symbol, so use the symbol at the property access // expression if (!exprSymbol) { exprSymbol = this._typeChecker.getSymbolAtLocation(node); } return exprSymbol; } // rename the identifier, but retain comments/spacing since we are using getFullText(); private _renameIdent(node: ts.Node) { let fullText = node.getFullText(); let fullStart = node.getFullStart(); let regStart = node.getStart() - fullStart; let preIdent = fullText.substring(0, regStart); return preIdent + this.renameProperty(node.getText()); } private _ident(node: ts.Node) { return node.getFullText(); } // Alphabet: ['$', '_','0' - '9', 'a' - 'z', 'A' - 'Z']. // Generates the next char in the alphabet, starting from '$', // and ending in 'Z'. If nextChar is passed in 'Z', it will // start over from the beginning of the alphabet and return '$'. private _nextChar(str: string): string { switch (str) { case '$': return '_'; case '_': return '0'; case '9': return 'a'; case 'z': return 'A'; case 'Z': return '$'; default: return String.fromCharCode(str.charCodeAt(0) + 1); } } static buildReservedKeywordsMap(): {[name: string]: boolean} { var map: {[name: string]: boolean} = {}; // From MDN's Lexical Grammar page // (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar) var keywordList = ('break case class catch const continue debugger delete do else export extends finally for' + ' function if import in instanceof let new return super switch this throw try typeof var' + ' void while with yield enum await int byte char goto long final float short double' + ' native throws boolean abstract volatile transient synchronized') .split(' '); for (var i in keywordList) { map[keywordList[i]] = true; } return map; } private _checkReserved(str: string): boolean { return Minifier.reservedJSKeywords.hasOwnProperty(str); } renameProperty(name: string): string { if (!this._renameMap.hasOwnProperty(name)) { this._renameMap[name] = this.generateNextPropertyName(this._lastGeneratedPropName); } return this._renameMap[name]; } // Given the last code, returns a string for the new property name. // ie: given 'a', will return 'b', given 'az', will return 'aA', etc. ... // public so it is visible for testing generateNextPropertyName(code: string): string { var newName = this._generateNextPropertyNameHelper(code); this._lastGeneratedPropName = newName; return newName; } private _generateNextPropertyNameHelper(code: string) { var chars = code.split(''); var len: number = code.length; var firstChar = '$'; var lastChar = 'Z'; var firstAlpha = 'a'; if (len === 0) { return firstChar; } for (var i = len - 1; i >= 0; i--) { if (chars[i] !== lastChar) { chars[i] = this._nextChar(chars[i]); break; } else { chars[i] = firstChar; if (i === 0) { let newName = firstChar + (chars.join('')); return newName; } } } var newName = chars.join(''); if (this._checkReserved(newName)) { return this.generateNextPropertyName(newName); // Property names cannot start with a number. Generate next possible property name that starts // with the first alpha character. } else if (chars[0].match(/[0-9]/)) { return (firstAlpha + Array(len).join(firstChar)); } else { return newName; } } }
the_stack
import { GraphQLScalarType, valueFromASTUntyped } from './graphql'; import { isObject, isString } from './utils/is'; import type { GraphQLScalarTypeConfig, GraphQLScalarSerializer, GraphQLScalarValueParser, GraphQLScalarLiteralParser, } from './graphql'; import type { TypeAsString } from './TypeMapper'; import { SchemaComposer } from './SchemaComposer'; import { ListComposer } from './ListComposer'; import { NonNullComposer } from './NonNullComposer'; import { isTypeNameString } from './utils/typeHelpers'; import type { Extensions, Directive, DirectiveArgs } from './utils/definitions'; import { inspect } from './utils/misc'; import { graphqlVersion } from './utils/graphqlVersion'; import { printScalar, SchemaPrinterOptions } from './utils/schemaPrinter'; import { getScalarTypeDefinitionNode } from './utils/definitionNode'; export type ScalarTypeComposerDefinition = | TypeAsString | Readonly<ScalarTypeComposerAsObjectDefinition> | Readonly<GraphQLScalarType>; export type ScalarTypeComposerAsObjectDefinition = GraphQLScalarTypeConfig<any, any> & { extensions?: Extensions; directives?: Directive[]; }; /** * `ScalarTypeComposer` is a class which helps to create and modify `GraphQLScalarType`. */ export class ScalarTypeComposer<TContext = any> { schemaComposer: SchemaComposer<TContext>; _gqType: GraphQLScalarType; _gqcExtensions: Extensions | undefined; _gqcDirectives: Directive[] | undefined; _gqcIsModified?: boolean; // @ts-ignore due to initialization via setter _gqcSerialize: GraphQLScalarSerializer<any>; // @ts-ignore due to initialization via setter _gqcParseValue: GraphQLScalarValueParser<any>; // @ts-ignore due to initialization via setter _gqcParseLiteral: GraphQLScalarLiteralParser<any>; /** * Create `ScalarTypeComposer` with adding it by name to the `SchemaComposer`. * This type became available in SDL by its name. */ static create<TCtx = any>( typeDef: ScalarTypeComposerDefinition, schemaComposer: SchemaComposer<TCtx> ): ScalarTypeComposer<TCtx> { if (!(schemaComposer instanceof SchemaComposer)) { throw new Error( 'You must provide SchemaComposer instance as a second argument for `ScalarTypeComposer.create(typeDef, schemaComposer)`' ); } if (schemaComposer.hasInstance(typeDef, ScalarTypeComposer)) { return schemaComposer.getSTC(typeDef); } const stc = this.createTemp(typeDef, schemaComposer); schemaComposer.add(stc); return stc; } /** * Create `ScalarTypeComposer` without adding it to the `SchemaComposer`. * This method may be useful in plugins, when you need to create type temporary. */ static createTemp<TCtx = any>( typeDef: ScalarTypeComposerDefinition, schemaComposer?: SchemaComposer<TCtx> ): ScalarTypeComposer<TCtx> { const sc = schemaComposer || new SchemaComposer(); let STC; if (isString(typeDef)) { const typeName: string = typeDef; if (isTypeNameString(typeName)) { STC = new ScalarTypeComposer( new GraphQLScalarType({ name: typeName, serialize: () => {}, }), sc ); } else { STC = sc.typeMapper.convertSDLTypeDefinition(typeName); if (!(STC instanceof ScalarTypeComposer)) { throw new Error( 'You should provide correct GraphQLScalarType type definition. Eg. `scalar UInt`' ); } } } else if (typeDef instanceof GraphQLScalarType) { STC = new ScalarTypeComposer(typeDef, sc); } else if (isObject(typeDef)) { const type = new GraphQLScalarType({ ...(typeDef as any), }); STC = new ScalarTypeComposer(type, sc); STC.setExtensions(typeDef.extensions); if (Array.isArray((typeDef as any)?.directives)) { STC.setDirectives((typeDef as any).directives); } } else { throw new Error( `You should provide GraphQLScalarTypeConfig or string with scalar name or SDL. Provided:\n${inspect( typeDef )}` ); } return STC; } constructor(graphqlType: GraphQLScalarType, schemaComposer: SchemaComposer<TContext>) { if (!(schemaComposer instanceof SchemaComposer)) { throw new Error( 'You must provide SchemaComposer instance as a second argument for `new ScalarTypeComposer(GraphQLScalarType, SchemaComposer)`' ); } if (!(graphqlType instanceof GraphQLScalarType)) { throw new Error('ScalarTypeComposer accept only GraphQLScalarType in constructor'); } this.schemaComposer = schemaComposer; this._gqType = graphqlType; // add itself to TypeStorage on create // it avoids recursive type use errors this.schemaComposer.set(graphqlType, this); this.schemaComposer.set(graphqlType.name, this); let serialize; let parseValue; let parseLiteral; if (graphqlVersion >= 14) { serialize = this._gqType.serialize; parseValue = this._gqType.parseValue; parseLiteral = this._gqType.parseLiteral; } else { serialize = (this._gqType as any)._scalarConfig.serialize; parseValue = (this._gqType as any)._scalarConfig.parseValue; parseLiteral = (this._gqType as any)._scalarConfig.parseLiteral; } this.setSerialize(serialize); this.setParseValue(parseValue); this.setParseLiteral(parseLiteral); // v15.x if ((this._gqType as any).specifiedByUrl) { this.setDirectiveByName('specifiedBy', { url: (this._gqType as any).specifiedByUrl }); } // v16.x see https://github.com/graphql/graphql-js/issues/3156 if ((this._gqType as any).specifiedByURL) { this.setDirectiveByName('specifiedBy', { url: (this._gqType as any).specifiedByURL }); } if (!this._gqType.astNode) { this._gqType.astNode = getScalarTypeDefinitionNode(this); } this._gqcIsModified = false; } // ----------------------------------------------- // Serialize methods // ----------------------------------------------- setSerialize(fn: GraphQLScalarSerializer<any>): this { this._gqcSerialize = fn; this._gqcIsModified = true; return this; } getSerialize(): GraphQLScalarSerializer<any> { return this._gqcSerialize; } setParseValue(fn: GraphQLScalarValueParser<any> | undefined): this { this._gqcParseValue = fn || ((value) => value); this._gqcIsModified = true; return this; } getParseValue(): GraphQLScalarValueParser<any> | undefined { return this._gqcParseValue; } setParseLiteral(fn: GraphQLScalarLiteralParser<any> | undefined): this { this._gqcParseLiteral = fn || valueFromASTUntyped; this._gqcIsModified = true; return this; } getParseLiteral(): GraphQLScalarLiteralParser<any> | undefined { return this._gqcParseLiteral; } // ----------------------------------------------- // Type methods // ----------------------------------------------- getType(): GraphQLScalarType { if (this._gqcIsModified) { this._gqcIsModified = false; this._gqType.astNode = getScalarTypeDefinitionNode(this); if (graphqlVersion >= 14) { (this._gqType as any).specifiedByUrl = this.getSpecifiedByUrl(); // v15.x (this._gqType as any).specifiedByURL = this.getSpecifiedByUrl(); // v16.x see https://github.com/graphql/graphql-js/issues/3156 this._gqType.serialize = this._gqcSerialize; this._gqType.parseValue = this._gqcParseValue; this._gqType.parseLiteral = this._gqcParseLiteral; } else { (this._gqType as any)._scalarConfig = { ...(this._gqType as any)._scalarConfig, serialize: this._gqcSerialize, parseValue: this._gqcParseValue, parseLiteral: this._gqcParseLiteral, }; } } return this._gqType; } getTypePlural(): ListComposer<ScalarTypeComposer<TContext>> { return new ListComposer(this); } getTypeNonNull(): NonNullComposer<ScalarTypeComposer<TContext>> { return new NonNullComposer(this); } /** * Get Type wrapped in List modifier * * @example * const ColorTC = schemaComposer.createScalarTC(`scalar Color`); * schemaComposer.Query.addFields({ * color1: { type: ColorTC.List }, // in SDL: color1: [Color] * color2: { type: ColorTC.NonNull.List }, // in SDL: color2: [Color!] * color3: { type: ColorTC.NonNull.List.NonNull }, // in SDL: color2: [Color!]! * }) */ get List(): ListComposer<ScalarTypeComposer<TContext>> { return new ListComposer(this); } /** * Get Type wrapped in NonNull modifier * * @example * const ColorTC = schemaComposer.createScalarTC(`scalar Color`); * schemaComposer.Query.addFields({ * color1: { type: ColorTC.List }, // in SDL: color1: [Color] * color2: { type: ColorTC.NonNull.List }, // in SDL: color2: [Color!] * color3: { type: ColorTC.NonNull.List.NonNull }, // in SDL: color2: [Color!]! * }) */ get NonNull(): NonNullComposer<ScalarTypeComposer<TContext>> { return new NonNullComposer(this); } getTypeName(): string { return this._gqType.name; } setTypeName(name: string): this { this._gqType.name = name; this._gqcIsModified = true; this.schemaComposer.add(this); return this; } getDescription(): string { return this._gqType.description || ''; } setDescription(description: string): this { this._gqType.description = description; this._gqcIsModified = true; return this; } getSpecifiedByUrl(): string | undefined | null { return this.getDirectiveByName('specifiedBy')?.url; } setSpecifiedByUrl(url: string | undefined | null): this { this.setDirectiveByName('specifiedBy', { url }); return this; } /** * You may clone this type with a new provided name as string. * Or you may provide a new TypeComposer which will get all cloned * settings from this type. */ clone(newTypeNameOrTC: string | ScalarTypeComposer<any>): ScalarTypeComposer<TContext> { if (!newTypeNameOrTC) { throw new Error('You should provide newTypeName:string for ScalarTypeComposer.clone()'); } const cloned = newTypeNameOrTC instanceof ScalarTypeComposer ? newTypeNameOrTC : ScalarTypeComposer.create(newTypeNameOrTC, this.schemaComposer); cloned._gqcSerialize = this._gqcSerialize; cloned._gqcParseValue = this._gqcParseValue; cloned._gqcParseLiteral = this._gqcParseLiteral; cloned._gqcExtensions = { ...this._gqcExtensions }; cloned.setDescription(this.getDescription()); cloned.setDirectives(this.getDirectives()); return cloned; } /** * Copy this scalar type to another SchemaComposer. * * Scalar types cannot be cloned. * It will be very strange if we clone for example Boolean or Date types. * * This methods exists for compatibility with other TypeComposers. */ cloneTo( anotherSchemaComposer: SchemaComposer<any>, cloneMap: Map<any, any> = new Map() ): ScalarTypeComposer<any> { if (!anotherSchemaComposer) { throw new Error('You should provide SchemaComposer for ObjectTypeComposer.cloneTo()'); } if (cloneMap.has(this)) return cloneMap.get(this); // scalar cannot be cloned, so use the same instance cloneMap.set(this, this); // copy same type instance if (!anotherSchemaComposer.has(this.getTypeName())) { anotherSchemaComposer.add(this); } return this; } merge(type: GraphQLScalarType | ScalarTypeComposer<any>): ScalarTypeComposer<TContext> { let tc: ScalarTypeComposer<any> | undefined; if (type instanceof GraphQLScalarType) { tc = ScalarTypeComposer.createTemp(type, this.schemaComposer); } else if (type instanceof ScalarTypeComposer) { tc = type; } if (tc) { this.setSerialize(tc.getSerialize()); this.setParseValue(tc.getParseValue()); this.setParseLiteral(tc.getParseLiteral()); } else { throw new Error( `Cannot merge ${inspect( type )} with ScalarType(${this.getTypeName()}). Provided type should be GraphQLScalarType or ScalarTypeComposer.` ); } return this; } // ----------------------------------------------- // Extensions methods // // `Extensions` is a property on type/field/arg definitions to pass private extra metadata. // It's used only on the server-side with the Code-First approach, // mostly for 3rd party server middlewares & plugins. // Property `extensions` may contain private server metadata of any type (even functions) // and does not available via SDL. // // @see https://github.com/graphql/graphql-js/issues/1527 // @note // If you need to provide public metadata to clients then use `directives` instead. // ----------------------------------------------- getExtensions(): Extensions { if (!this._gqcExtensions) { return {}; } else { return this._gqcExtensions; } } setExtensions(extensions: Extensions | undefined | null): this { this._gqcExtensions = extensions || undefined; this._gqcIsModified = true; return this; } extendExtensions(extensions: Extensions): this { const current = this.getExtensions(); this.setExtensions({ ...current, ...extensions, }); return this; } clearExtensions(): this { this.setExtensions({}); return this; } getExtension(extensionName: string): unknown { const extensions = this.getExtensions(); return extensions[extensionName]; } hasExtension(extensionName: string): boolean { const extensions = this.getExtensions(); return extensionName in extensions; } setExtension(extensionName: string, value: unknown): this { this.extendExtensions({ [extensionName]: value, }); return this; } removeExtension(extensionName: string): this { const extensions = { ...this.getExtensions() }; delete extensions[extensionName]; this.setExtensions(extensions); return this; } // ----------------------------------------------- // Directive methods // // Directives provide the ability to work with public metadata which is available via SDL. // Directives can be used on type/field/arg definitions. The most famous directives are // `@deprecated(reason: "...")` and `@specifiedBy(url: "...")` which are present in GraphQL spec. // GraphQL spec allows to you add any own directives. // // @example // type Article @directive1 { // name @directive2 // comments(limit: Int @directive3) // } // // @note // If you need private metadata then use `extensions` instead. // ----------------------------------------------- getDirectives(): Array<Directive> { return this._gqcDirectives || []; } setDirectives(directives: Array<Directive>): this { this._gqcDirectives = directives; this._gqcIsModified = true; return this; } getDirectiveNames(): string[] { return this.getDirectives().map((d) => d.name); } /** * Returns arguments of first found directive by name. * If directive does not exists then will be returned undefined. */ getDirectiveByName(directiveName: string): DirectiveArgs | undefined { const directive = this.getDirectives().find((d) => d.name === directiveName); if (!directive) return undefined; return directive.args; } /** * Set arguments of first found directive by name. * If directive does not exists then will be created new one. */ setDirectiveByName(directiveName: string, args?: DirectiveArgs): this { const directives = this.getDirectives(); const idx = directives.findIndex((d) => d.name === directiveName); if (idx >= 0) { directives[idx].args = args; } else { directives.push({ name: directiveName, args }); } this.setDirectives(directives); return this; } getDirectiveById(idx: number): DirectiveArgs | undefined { const directive = this.getDirectives()[idx]; if (!directive) return undefined; return directive.args; } // ----------------------------------------------- // Misc methods // ----------------------------------------------- /** * Prints SDL for current type. */ toSDL(opts?: SchemaPrinterOptions): string { return printScalar(this.getType(), opts); } }
the_stack
import runAxeCheck from '@instructure/ui-axe-check' import { elementToString } from './elementToString' import { fireEvent } from './events' import { isElement } from './isElement' import { querySelector, querySelectorAll, matchesSelector } from './selectors' interface Rectangle { bottom: number readonly height: number left: number right: number top: number readonly width: number x?: number y?: number } interface ClientRectangle extends Rectangle { overflow: string | null positioned: boolean } function getOwnerDocument(element: Node) { return element.ownerDocument || document } function getOwnerWindow(element: Node) { const doc = getOwnerDocument(element) return doc.defaultView } function typeIn(element: Element, text: string) { // We could use here generics to make it better? const initialValue = (element as any).value const characterCount = text.length const eventInit = { bubbles: true, cancelable: true, defaultPrevented: false, eventPhase: 2, isTrusted: true } return new Promise<void>((resolve, reject) => { setTimeout(() => { try { for (let i = 0; i < characterCount; ++i) { const code = text.charCodeAt(i) const keyEventData = { altKey: false, charCode: code, ctrlKey: false, keyCode: code, metaKey: false, shiftKey: false, which: code, ...eventInit } const inputEventData = { charCode: code, target: { value: initialValue + text.slice(0, i + 1) }, ...eventInit } fireEvent.keyDown(element, keyEventData) fireEvent.keyPress(element, keyEventData) fireEvent.beforeInput(element, inputEventData) fireEvent.input(element, inputEventData) fireEvent.change(element, inputEventData) fireEvent.keyUp(element, keyEventData) } resolve() } catch (err: any) { reject(err) } }, 0) }) } function getTextContent(element: Element): string | null { if (matchesSelector(element, 'input[type=submit], input[type=button]')) { return (element as any).value } return element.textContent } // aliases: const text = getTextContent function getTagName(element: Element) { return element.tagName.toLowerCase() } // aliases const tagName = getTagName function getComputedStyle(element: Element) { if (isElement(element) && getOwnerWindow(element)) { return getOwnerWindow(element)!.getComputedStyle(element) } else { throw new Error( `[ui-test-queries] cannot get computed style for an invalid Element: ${element}` ) } } function positioned(element: Element) { const style = getComputedStyle(element) const transform = style.getPropertyValue('-webkit-transform') || style.getPropertyValue('-moz-transform') || style.getPropertyValue('-ms-transform') || style.getPropertyValue('-o-transform') || style.getPropertyValue('transform') || 'none' return ( style.position !== 'static' || // initial value of transform can be 'none' or a matrix equivalent (transform !== 'none' && transform !== 'matrix(1, 0, 0, 1, 0, 0)') ) } function getViewportRects(element: Element): ClientRectangle[] { const doc = getOwnerDocument(element) const win = getOwnerWindow(element) const viewport = { width: Math.max( doc.body.scrollWidth, doc.documentElement.scrollWidth, doc.body.offsetWidth, doc.documentElement.offsetWidth, doc.body.clientWidth, doc.documentElement.clientWidth, win?.innerWidth || 0 ), height: Math.max( doc.body.scrollHeight, doc.documentElement.scrollHeight, doc.body.offsetHeight, doc.documentElement.offsetHeight, doc.body.clientHeight, doc.documentElement.clientHeight, win?.innerHeight || 0 ) } return [ { ...viewport, top: 0, right: viewport.width, bottom: viewport.height, left: 0, overflow: null, positioned: false } ] } function getPositionedParents(element: Element) { const parents = [] let parent: (Node & ParentNode) | null = element // eslint-disable-next-line no-cond-assign while ( (parent = parent.parentNode) && parent && isElement(parent) && (parent as Element).tagName.toLowerCase() !== 'body' ) { if (positioned(parent as Element)) { parents.push(parent) } } return parents } function rectToObject(rect: DOMRect): Rectangle { return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.width, height: rect.height, x: rect.x, y: rect.y } } function getClientRects(element: Element): ClientRectangle[] { const props = { overflow: getComputedStyle(element).overflow, positioned: positioned(element) } let rects: ClientRectangle[] = [ { ...rectToObject(element.getBoundingClientRect()), ...props } ] rects = rects.concat( Array.from(element.getClientRects()).map((rect) => { return { ...rectToObject(rect), ...props } }) ) return rects } function visible(element: Element) { if ( !isElement(element) || (element && element.tagName.toLowerCase() === 'html') ) { return true } const style = getComputedStyle(element) if ( style.visibility === 'hidden' || style.display === 'none' || style.opacity === '0' ) { return false } const elementRects = getClientRects(element) const elementWidth = (element as HTMLElement).offsetWidth || elementRects[0].width || 0 const elementHeight = (element as HTMLElement).offsetHeight || elementRects[0].height || 0 const children = Array.from(element.childNodes) // handle inline elements with block children... if ( element.tagName.toLowerCase() !== 'iframe' && style.display === 'inline' && children.length > 0 && children.filter((child) => visible(child as Element)).length === 0 ) { return false } else if (elementWidth <= 0 && elementHeight <= 0) { return false } const rects = [elementRects].concat( getPositionedParents(element).map((parent) => getClientRects(parent as Element) ) ) rects.push(getViewportRects(element)) return rects.reduce((previousIsVisible, childRects, index) => { const parentRects = rects[index + 1] if (!parentRects) { return previousIsVisible } return ( previousIsVisible && parentRects.reduce((visibleInPreviousParent, parentRect) => { return ( visibleInPreviousParent || childRects.reduce((previousChildIsVisible, childRect) => { const childIsPositioned = childRect.positioned && parentRect.overflow === 'visible' const currentChildIsVisible = childIsPositioned || (childRect.top <= parentRect.bottom && childRect.top + parentRect.bottom >= 0 && childRect.bottom > parentRect.top && childRect.left <= parentRect.right && childRect.left + parentRect.right >= 0 && childRect.right > parentRect.left) return previousChildIsVisible || currentChildIsVisible }, false) ) }, false) ) }, true) } function onscreen(element: Element) { return visible(element) } function clickable(element: Element) { const rects = Array.from(element.getClientRects()).concat( element.getBoundingClientRect() ) return ( visible(element) && rects.reduce((onscreen, rect) => { if (onscreen) return true const doc = getOwnerDocument(element) for ( let x = Math.floor(rect.left), maxX = Math.ceil(rect.right); x <= maxX; x++ ) for ( let y = Math.floor(rect.top), maxY = Math.ceil(rect.bottom); y <= maxY; y++ ) { const elementFromPoint = doc.elementFromPoint(x, y) if ( element.contains(elementFromPoint) || element === elementFromPoint ) { return true } } return false }, false) ) } function focusable(element: Element) { const selector = [ 'a[href]:not([disabled])', 'frame', 'iframe', 'object', 'input:not([type=hidden]):not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', '*[tabindex]' ] return ( !(element as any).disabled && visible(element) && matchesSelector(element, selector.join(',')) ) } function tabbable(element: Element) { return focusable(element) && parseInt(getAttribute(element, 'tabindex')!) > 0 } function getAttribute(element: Element, qualifiedName: string) { return element.getAttribute(qualifiedName) } function getParentNode(element: Element) { return element.parentNode } const parent = getParentNode function containsFocus(element: Element) { const activeElement = getOwnerDocument(element).activeElement return ( element && (activeElement === element || element.contains(activeElement)) ) } function focused(element: Element) { return element === getOwnerDocument(element).activeElement } function getDOMNode(element: Element) { return element } const node = getDOMNode function getBoundingClientRect(element: Element) { return element.getBoundingClientRect() } const rect = getBoundingClientRect function hasClass(element: Element, classname: string) { return element.classList.contains(classname) } function getId(element: Element) { return element.id } // aliases: const id = getId function debug( element: Element | Document | DocumentFragment, maxLength = 7000, options = { highlight: false } ) { // eslint-disable-next-line no-console console.log(toString(element, maxLength, options)) } function toString( element: Element | Document | DocumentFragment, maxLength = 7000, options = { highlight: false } ) { return elementToString(element, maxLength, options) } function accessible( element = document.body, options?: Record<string, unknown> ) { if (isElement(element)) { return runAxeCheck(element, options) } else { throw new Error( '[ui-test-queries] accessibility check can only run on a single, valid DOM Element!' ) } } function exists(element: Element) { const doc = getOwnerDocument(element) return doc && doc.body.contains(element) } function empty(element: Element) { if (element && (element as any).value) { return (element as any).value.length === 0 || !(element as any).value.trim() } else if (element && element.children) { return element.children.length === 0 } else { throw new Error( `[ui-test-queries] cannot determine if a non-element is empty: ${toString( element )}` ) } } function contains(element: Element, elementOrSelector?: string | Element) { if (typeof elementOrSelector === 'string') { return querySelector(element, elementOrSelector) } else if (isElement(elementOrSelector)) { return element.contains(elementOrSelector!) } else if ( elementOrSelector && typeof (elementOrSelector as any).getDOMNode === 'function' ) { return element.contains((elementOrSelector as any).getDOMNode()) } else { return false } } function descendants(element: Element, selector: string) { return querySelectorAll(element, selector).filter( (match) => match !== element ) } // aliases: const children = descendants function ancestors(element: Element, selector: string) { const ancestors = [] let parentNode = element.parentNode while (parentNode && parentNode !== document && isElement(parentNode)) { if (matchesSelector(parentNode as Element, selector)) { ancestors.push(parentNode) } parentNode = parentNode.parentNode } return ancestors } // aliases: const parents = ancestors const attribute = getAttribute function style(element: Element, property: string) { return getComputedStyle(element).getPropertyValue(property) } function classNames(element: Element) { return Array.from(element.classList) } function matches(element: Element, selector: string | undefined) { return matchesSelector(element, selector) } //function bounds(element: Element) { // return getBoundingClientRect(element).property //} function checked(element: Element) { return (element as any).checked || getAttribute(element, 'aria-checked') } function selected(element: Element) { return (element as any).selected || getAttribute(element, 'aria-selected') } function disabled(element: Element) { return ( getAttribute(element, 'disabled') || getAttribute(element, 'aria-disabled') ) } function readonly(element: Element) { return (element as any).readonly || getAttribute(element, 'aria-readonly') } function role(element: Element) { return getAttribute(element, 'role') } function value(element: Element): string | null { return (element as any).value } function label(element: Element) { const doc = getOwnerDocument(element) if (matchesSelector(element, '[aria-label]')) { return getAttribute(element, 'aria-label') } else if (matchesSelector(element, '[aria-labelledby]')) { const ids = getAttribute(element, 'aria-labelledby')!.split(/\s+/) const labels = ids.map((id) => doc.getElementById(id)) return labels.map((label) => (label ? label.textContent : '')).join(' ') } else if ( matchesSelector(element, 'button, a[href], [role="button"], [role="link"]') ) { return getTextContent(element) } else if (matchesSelector(element, 'fieldset')) { const legend = querySelector(element, 'legend') if (legend) { return getTextContent(legend) } } else if (matchesSelector(element, '[id]')) { const labels = Array.from( querySelectorAll(doc, `[for="${getAttribute(element, 'id')}"]`) ) return labels.map((label) => (label ? label.textContent : '')).join(' ') } else if (matchesSelector(element, 'input,textarea,select')) { const labels = ancestors(element, 'label') if (labels.length > 0) { return getTextContent(labels[0] as Element) } } return undefined } function title(element: Element) { if (matchesSelector(element, '[title]')) { return getAttribute(element, 'title') } else if (matchesSelector(element, 'svg')) { const title = querySelector(element, 'title') if (title) { return getTextContent(title) } } return undefined } export { toString, getId, getOwnerWindow, getOwnerDocument, getComputedStyle, getTagName, tagName, typeIn, getAttribute, getDOMNode, node, debug, accessible, getTextContent, getParentNode, parent, getBoundingClientRect, rect, hasClass, containsFocus, focused, visible, focusable, tabbable, clickable, onscreen, exists, text, empty, contains, descendants, ancestors, attribute, style, classNames, id, matches, checked, selected, disabled, readonly, role, value, label, title, children, parents }
the_stack
import { OrderedSet } from '../../../mol-data/int'; import { BoundaryHelper } from '../../../mol-math/geometry/boundary-helper'; import { Vec3 } from '../../../mol-math/linear-algebra'; import { PrincipalAxes } from '../../../mol-math/linear-algebra/matrix/principal-axes'; import { EmptyLoci, Loci } from '../../../mol-model/loci'; import { QueryContext, Structure, StructureElement, StructureQuery, StructureSelection } from '../../../mol-model/structure'; import { PluginContext } from '../../../mol-plugin/context'; import { StateObjectRef } from '../../../mol-state'; import { Task } from '../../../mol-task'; import { structureElementStatsLabel } from '../../../mol-theme/label'; import { arrayRemoveAtInPlace } from '../../../mol-util/array'; import { StatefulPluginComponent } from '../../component'; import { StructureSelectionQuery } from '../../helpers/structure-selection-query'; import { PluginStateObject as PSO } from '../../objects'; import { UUID } from '../../../mol-util'; import { StructureRef } from './hierarchy-state'; import { Boundary } from '../../../mol-math/geometry/boundary'; interface StructureSelectionManagerState { entries: Map<string, SelectionEntry>, additionsHistory: StructureSelectionHistoryEntry[], stats?: SelectionStats } const boundaryHelper = new BoundaryHelper('98'); const HISTORY_CAPACITY = 24; export type StructureSelectionModifier = 'add' | 'remove' | 'intersect' | 'set' export class StructureSelectionManager extends StatefulPluginComponent<StructureSelectionManagerState> { readonly events = { changed: this.ev<undefined>(), additionsHistoryUpdated: this.ev<undefined>(), loci: { add: this.ev<StructureElement.Loci>(), remove: this.ev<StructureElement.Loci>(), clear: this.ev<undefined>() } } private referenceLoci: StructureElement.Loci | undefined get entries() { return this.state.entries; } get additionsHistory() { return this.state.additionsHistory; } get stats() { if (this.state.stats) return this.state.stats; this.state.stats = this.calcStats(); return this.state.stats; } private getEntry(s: Structure) { // ignore decorators to get stable ref const cell = this.plugin.helpers.substructureParent.get(s, true); if (!cell) return; const ref = cell.transform.ref; if (!this.entries.has(ref)) { const entry = new SelectionEntry(StructureElement.Loci(s, [])); this.entries.set(ref, entry); return entry; } return this.entries.get(ref)!; } private calcStats(): SelectionStats { let structureCount = 0; let elementCount = 0; const stats = StructureElement.Stats.create(); this.entries.forEach(v => { const { elements } = v.selection; if (elements.length) { structureCount += 1; for (let i = 0, il = elements.length; i < il; ++i) { elementCount += OrderedSet.size(elements[i].indices); } StructureElement.Stats.add(stats, stats, StructureElement.Stats.ofLoci(v.selection)); } }); const label = structureElementStatsLabel(stats, { countsOnly: true }); return { structureCount, elementCount, label }; } private add(loci: Loci): boolean { if (!StructureElement.Loci.is(loci)) return false; const entry = this.getEntry(loci.structure); if (!entry) return false; const sel = entry.selection; entry.selection = StructureElement.Loci.union(entry.selection, loci); this.tryAddHistory(loci); this.referenceLoci = loci; this.events.loci.add.next(loci); return !StructureElement.Loci.areEqual(sel, entry.selection); } private remove(loci: Loci) { if (!StructureElement.Loci.is(loci)) return false; const entry = this.getEntry(loci.structure); if (!entry) return false; const sel = entry.selection; entry.selection = StructureElement.Loci.subtract(entry.selection, loci); // this.addHistory(loci); this.referenceLoci = loci; this.events.loci.remove.next(loci); return !StructureElement.Loci.areEqual(sel, entry.selection); } private intersect(loci: Loci): boolean { if (!StructureElement.Loci.is(loci)) return false; const entry = this.getEntry(loci.structure); if (!entry) return false; const sel = entry.selection; entry.selection = StructureElement.Loci.intersect(entry.selection, loci); // this.addHistory(loci); this.referenceLoci = loci; return !StructureElement.Loci.areEqual(sel, entry.selection); } private set(loci: Loci) { if (!StructureElement.Loci.is(loci)) return false; const entry = this.getEntry(loci.structure); if (!entry) return false; const sel = entry.selection; entry.selection = loci; this.tryAddHistory(loci); this.referenceLoci = undefined; return !StructureElement.Loci.areEqual(sel, entry.selection); } modifyHistory(entry: StructureSelectionHistoryEntry, action: 'remove' | 'up' | 'down', modulus?: number, groupByStructure = false) { const history = this.additionsHistory; const idx = history.indexOf(entry); if (idx < 0) return; let swapWith: number | undefined = void 0; switch (action) { case 'remove': arrayRemoveAtInPlace(history, idx); break; case 'up': swapWith = idx - 1; break; case 'down': swapWith = idx + 1; break; } if (swapWith !== void 0) { const mod = modulus ? Math.min(history.length, modulus) : history.length; while (true) { swapWith = swapWith % mod; if (swapWith < 0) swapWith += mod; if (!groupByStructure || history[idx].loci.structure === history[swapWith].loci.structure) { const t = history[idx]; history[idx] = history[swapWith]; history[swapWith] = t; break; } else { swapWith += action === 'up' ? -1 : +1; } } } this.events.additionsHistoryUpdated.next(void 0); } private tryAddHistory(loci: StructureElement.Loci) { if (Loci.isEmpty(loci)) return; let idx = 0, entry: StructureSelectionHistoryEntry | undefined = void 0; for (const l of this.additionsHistory) { if (Loci.areEqual(l.loci, loci)) { entry = l; break; } idx++; } if (entry) { // move to top arrayRemoveAtInPlace(this.additionsHistory, idx); this.additionsHistory.unshift(entry); this.events.additionsHistoryUpdated.next(void 0); return; } const stats = StructureElement.Stats.ofLoci(loci); const label = structureElementStatsLabel(stats, { reverse: true }); this.additionsHistory.unshift({ id: UUID.create22(), loci, label }); if (this.additionsHistory.length > HISTORY_CAPACITY) this.additionsHistory.pop(); this.events.additionsHistoryUpdated.next(void 0); } private clearHistory() { if (this.state.additionsHistory.length !== 0) { this.state.additionsHistory = []; this.events.additionsHistoryUpdated.next(void 0); } } private clearHistoryForStructure(structure: Structure) { const historyEntryToRemove: StructureSelectionHistoryEntry[] = []; for (const e of this.state.additionsHistory) { if (e.loci.structure.root === structure.root) { historyEntryToRemove.push(e); } } for (const e of historyEntryToRemove) { this.modifyHistory(e, 'remove'); } if (historyEntryToRemove.length !== 0) { this.events.additionsHistoryUpdated.next(void 0); } } private onRemove(ref: string, obj: PSO.Molecule.Structure | undefined) { if (this.entries.has(ref)) { this.entries.delete(ref); if (obj?.data) { this.clearHistoryForStructure(obj.data); } if (this.referenceLoci?.structure === obj?.data) { this.referenceLoci = undefined; } this.state.stats = void 0; this.events.changed.next(void 0); } } private onUpdate(ref: string, oldObj: PSO.Molecule.Structure | undefined, obj: PSO.Molecule.Structure) { // no change to structure if (oldObj === obj || oldObj?.data === obj.data) return; // ignore decorators to get stable ref const cell = this.plugin.helpers.substructureParent.get(obj.data, true); if (!cell) return; ref = cell.transform.ref; if (!this.entries.has(ref)) return; // use structure from last decorator as reference const structure = this.plugin.helpers.substructureParent.get(obj.data)?.obj?.data; if (!structure) return; // oldObj is not defined for inserts (e.g. TransformStructureConformation) if (!oldObj?.data || Structure.areUnitIdsAndIndicesEqual(oldObj.data, obj.data)) { this.entries.set(ref, remapSelectionEntry(this.entries.get(ref)!, structure)); // remap referenceLoci & prevHighlight if needed and possible if (this.referenceLoci?.structure.root === structure.root) { this.referenceLoci = StructureElement.Loci.remap(this.referenceLoci, structure); } // remap history locis if needed and possible let changedHistory = false; for (const e of this.state.additionsHistory) { if (e.loci.structure.root === structure.root) { e.loci = StructureElement.Loci.remap(e.loci, structure); changedHistory = true; } } if (changedHistory) this.events.additionsHistoryUpdated.next(void 0); } else { // clear the selection for ref this.entries.set(ref, new SelectionEntry(StructureElement.Loci(structure, []))); if (this.referenceLoci?.structure.root === structure.root) { this.referenceLoci = undefined; } this.clearHistoryForStructure(structure); this.state.stats = void 0; this.events.changed.next(void 0); } } /** Removes all selections and returns them */ clear() { const keys = this.entries.keys(); const selections: StructureElement.Loci[] = []; while (true) { const k = keys.next(); if (k.done) break; const s = this.entries.get(k.value)!; if (!StructureElement.Loci.isEmpty(s.selection)) selections.push(s.selection); s.selection = StructureElement.Loci(s.selection.structure, []); } this.referenceLoci = undefined; this.state.stats = void 0; this.events.changed.next(void 0); this.events.loci.clear.next(void 0); this.clearHistory(); return selections; } getLoci(structure: Structure) { const entry = this.getEntry(structure); if (!entry) return EmptyLoci; return entry.selection; } getStructure(structure: Structure) { const entry = this.getEntry(structure); if (!entry) return; return entry.structure; } structureHasSelection(structure: StructureRef) { const s = structure.cell?.obj?.data; if (!s) return false; const entry = this.getEntry(s); return !!entry && !StructureElement.Loci.isEmpty(entry.selection); } has(loci: Loci) { if (StructureElement.Loci.is(loci)) { const entry = this.getEntry(loci.structure); if (entry) { return StructureElement.Loci.isSubset(entry.selection, loci); } } return false; } tryGetRange(loci: Loci): StructureElement.Loci | undefined { if (!StructureElement.Loci.is(loci)) return; if (loci.elements.length !== 1) return; const entry = this.getEntry(loci.structure); if (!entry) return; const xs = loci.elements[0]; if (!xs) return; const ref = this.referenceLoci; if (!ref || !StructureElement.Loci.is(ref) || ref.structure !== loci.structure) return; let e: StructureElement.Loci['elements'][0] | undefined; for (const _e of ref.elements) { if (xs.unit === _e.unit) { e = _e; break; } } if (!e) return; if (xs.unit !== e.unit) return; return getElementRange(loci.structure, e, xs); } /** Count of all selected elements */ elementCount() { let count = 0; this.entries.forEach(v => { count += StructureElement.Loci.size(v.selection); }); return count; } getBoundary() { const min = Vec3.create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); const max = Vec3.create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); boundaryHelper.reset(); const boundaries: Boundary[] = []; this.entries.forEach(v => { const loci = v.selection; if (!StructureElement.Loci.isEmpty(loci)) { boundaries.push(StructureElement.Loci.getBoundary(loci)); } }); for (let i = 0, il = boundaries.length; i < il; ++i) { const { box, sphere } = boundaries[i]; Vec3.min(min, min, box.min); Vec3.max(max, max, box.max); boundaryHelper.includePositionRadius(sphere.center, sphere.radius); } boundaryHelper.finishedIncludeStep(); for (let i = 0, il = boundaries.length; i < il; ++i) { const { sphere } = boundaries[i]; boundaryHelper.radiusPositionRadius(sphere.center, sphere.radius); } return { box: { min, max }, sphere: boundaryHelper.getSphere() }; } getPrincipalAxes(): PrincipalAxes { const elementCount = this.elementCount(); const positions = new Float32Array(3 * elementCount); let offset = 0; this.entries.forEach(v => { StructureElement.Loci.toPositionsArray(v.selection, positions, offset); offset += StructureElement.Loci.size(v.selection) * 3; }); return PrincipalAxes.ofPositions(positions); } modify(modifier: StructureSelectionModifier, loci: Loci) { let changed = false; switch (modifier) { case 'add': changed = this.add(loci); break; case 'remove': changed = this.remove(loci); break; case 'intersect': changed = this.intersect(loci); break; case 'set': changed = this.set(loci); break; } if (changed) { this.state.stats = void 0; this.events.changed.next(void 0); } } private get applicableStructures() { return this.plugin.managers.structure.hierarchy.selection.structures .filter(s => !!s.cell.obj) .map(s => s.cell.obj!.data); } private triggerInteraction(modifier: StructureSelectionModifier, loci: Loci, applyGranularity = true) { switch (modifier) { case 'add': this.plugin.managers.interactivity.lociSelects.select({ loci }, applyGranularity); break; case 'remove': this.plugin.managers.interactivity.lociSelects.deselect({ loci }, applyGranularity); break; case 'intersect': this.plugin.managers.interactivity.lociSelects.selectJoin({ loci }, applyGranularity); break; case 'set': this.plugin.managers.interactivity.lociSelects.selectOnly({ loci }, applyGranularity); break; } } fromLoci(modifier: StructureSelectionModifier, loci: Loci, applyGranularity = true) { this.triggerInteraction(modifier, loci, applyGranularity); } fromCompiledQuery(modifier: StructureSelectionModifier, query: StructureQuery, applyGranularity = true) { for (const s of this.applicableStructures) { const loci = query(new QueryContext(s)); this.triggerInteraction(modifier, StructureSelection.toLociWithSourceUnits(loci), applyGranularity); } } fromSelectionQuery(modifier: StructureSelectionModifier, query: StructureSelectionQuery, applyGranularity = true) { this.plugin.runTask(Task.create('Structure Selection', async runtime => { for (const s of this.applicableStructures) { const loci = await query.getSelection(this.plugin, runtime, s); this.triggerInteraction(modifier, StructureSelection.toLociWithSourceUnits(loci), applyGranularity); } })); } fromSelections(ref: StateObjectRef<PSO.Molecule.Structure.Selections>) { const cell = StateObjectRef.resolveAndCheck(this.plugin.state.data, ref); if (!cell || !cell.obj) return; if (!PSO.Molecule.Structure.Selections.is(cell.obj)) { console.warn('fromSelections applied to wrong object type.', cell.obj); return; } this.clear(); for (const s of cell.obj?.data) { this.fromLoci('set', s.loci); } } constructor(private plugin: PluginContext) { super({ entries: new Map(), additionsHistory: [], stats: SelectionStats() }); // listen to events from substructureParent helper to ensure it is updated plugin.helpers.substructureParent.events.removed.subscribe(e => this.onRemove(e.ref, e.obj)); plugin.helpers.substructureParent.events.updated.subscribe(e => this.onUpdate(e.ref, e.oldObj, e.obj)); } } interface SelectionStats { structureCount: number, elementCount: number, label: string } function SelectionStats(): SelectionStats { return { structureCount: 0, elementCount: 0, label: 'Nothing Selected' }; }; class SelectionEntry { private _selection: StructureElement.Loci; private _structure?: Structure = void 0; get selection() { return this._selection; } set selection(value: StructureElement.Loci) { this._selection = value; this._structure = void 0; } get structure(): Structure | undefined { if (this._structure) return this._structure; if (Loci.isEmpty(this._selection)) { this._structure = void 0; } else { this._structure = StructureElement.Loci.toStructure(this._selection); } return this._structure; } constructor(selection: StructureElement.Loci) { this._selection = selection; } } export interface StructureSelectionHistoryEntry { id: UUID, loci: StructureElement.Loci, label: string } /** remap `selection-entry` to be related to `structure` if possible */ function remapSelectionEntry(e: SelectionEntry, s: Structure): SelectionEntry { return new SelectionEntry(StructureElement.Loci.remap(e.selection, s)); } /** * Assumes `ref` and `ext` belong to the same unit in the same structure */ function getElementRange(structure: Structure, ref: StructureElement.Loci['elements'][0], ext: StructureElement.Loci['elements'][0]) { const min = Math.min(OrderedSet.min(ref.indices), OrderedSet.min(ext.indices)); const max = Math.max(OrderedSet.max(ref.indices), OrderedSet.max(ext.indices)); return StructureElement.Loci(structure, [{ unit: ref.unit, indices: OrderedSet.ofRange(min as StructureElement.UnitIndex, max as StructureElement.UnitIndex) }]); }
the_stack
import { bindActionCreators, Dispatch } from 'redux' import { Framebuffer } from './editor' import * as Screens from './screens' import { Toolbar as IToolbar, Transform, RootStateThunk, Coord2, Pixel, BrushRegion, Font, Brush, Tool, Angle360, FramebufUIState, DEFAULT_FB_WIDTH, DEFAULT_FB_HEIGHT } from './types' import * as selectors from './selectors' import * as screensSelectors from '../redux/screensSelectors' import { getSettingsPaletteRemap } from '../redux/settingsSelectors' import * as utils from '../utils' import * as brush from './brush' import { ActionsUnion, createAction, updateField, DispatchPropsFromActions } from './typeUtils' import { FileFormat } from './typesExport'; import * as matrix from '../utils/matrix'; const defaultFramebufUIState: FramebufUIState = { canvasTransform: matrix.ident(), canvasFit: 'fitWidthHeight' }; const emptyTransform: Transform = { mirror: 0, rotate: 0 } function rotate(transform: Transform): Transform { return { ...transform, rotate: ((transform.rotate + 90) % 360) as Angle360 } } function mirror(transform: Transform, mirror: number) { return { ...transform, mirror: transform.mirror ^ mirror } } function dispatchForCurrentFramebuf ( f: (dispatch: Dispatch, framebufIndex: number) => void ): RootStateThunk { return (dispatch, getState) => { const state = getState(); const framebufIndex = screensSelectors.getCurrentScreenFramebufIndex(state); if (framebufIndex === null) { return; } f(dispatch, framebufIndex); } } const initialBrushValue = { brush: null as (Brush|null), brushRegion: null as (BrushRegion|null), brushTransform: emptyTransform } function moveTextCursor(curPos: Coord2, dir: Coord2, width: number, height: number) { const idx = (curPos.row + dir.row)*width + (curPos.col + dir.col) + width*height const wrapped = idx % (width*height) return { row: Math.floor(wrapped / width), col: Math.floor(wrapped % width) } } function asc2int(asc: string) { return asc.charCodeAt(0) } function convertAsciiToScreencode(asc: string) { if (asc.length !== 1) { return null } if (asc >= 'a' && asc <= 'z') { return asc2int(asc) - asc2int('a') + 1 } if (asc >= 'A' && asc <= 'Z') { return asc2int(asc) - asc2int('A') + 0x41 } if (asc >= '0' && asc <= '9') { return asc2int(asc) - asc2int('0') + 0x30 } const otherChars: {[index:string]: number} = { '@': 0, ' ': 0x20, '!': 0x21, '"': 0x22, '#': 0x23, '$': 0x24, '%': 0x25, '&': 0x26, '\'': 0x27, '(': 0x28, ')': 0x29, '*': 0x2a, '+': 0x2b, ',': 0x2c, '-': 0x2d, '.': 0x2e, '/': 0x2f, ':': 0x3a, ';': 0x3b, '<': 0x3c, '=': 0x3d, '>': 0x3e, '?': 0x3f } if (asc in otherChars) { return otherChars[asc] } return null } const SET_SELECTED_CHAR = 'Toolbar/SET_SELECTED_CHAR' const RESET_BRUSH = 'Toolbar/RESET_BRUSH' const CAPTURE_BRUSH = 'Toolbar/CAPTURE_BRUSH' const MIRROR_BRUSH = 'Toolbar/MIRROR_BRUSH' const ROTATE_BRUSH = 'Toolbar/ROTATE_BRUSH' const MIRROR_CHAR = 'Toolbar/MIRROR_CHAR' const ROTATE_CHAR = 'Toolbar/ROTATE_CHAR' const NEXT_CHARCODE = 'Toolbar/NEXT_CHARCODE' const NEXT_COLOR = 'Toolbar/NEXT_COLOR' const INVERT_CHAR = 'Toolbar/INVERT_CHAR' const CLEAR_MOD_KEY_STATE = 'Toolbar/CLEAR_MOD_KEY_STATE' const INC_UNDO_ID = 'Toolbar/INC_UNDO_ID' const SET_FRAMEBUF_UI_STATE = 'Toolbar/SET_FRAMEBUF_UI_STATE' function captureBrush(framebuf: Pixel[][], brushRegion: BrushRegion) { const { min, max } = utils.sortRegion(brushRegion) const h = max.row - min.row + 1 const w = max.col - min.col + 1 const capfb = Array(h) for (var y = 0; y < h; y++) { capfb[y] = framebuf[y + min.row].slice(min.col, max.col+1) } return createAction(CAPTURE_BRUSH, { framebuf: capfb, brushRegion: { min: { row: 0, col: 0 }, max: { row: h-1, col: w-1 } } }) } const actionCreators = { incUndoId: () => createAction(INC_UNDO_ID), resetBrush: () => createAction(RESET_BRUSH), setSelectedChar: (coord: Coord2) => createAction(SET_SELECTED_CHAR, coord), nextCharcodeAction: (dir: Coord2, font: Font) => createAction(NEXT_CHARCODE, { dir, font }), nextColorAction: (dir: number, paletteRemap: number[]) => createAction(NEXT_COLOR, { dir, paletteRemap }), invertCharAction: (font: Font) => createAction(INVERT_CHAR, font), clearModKeyState: () => createAction(CLEAR_MOD_KEY_STATE), captureBrush, mirrorBrush: (axis:number) => createAction(MIRROR_BRUSH, axis), rotateBrush: () => createAction(ROTATE_BRUSH), mirrorChar: (axis: number) => createAction(MIRROR_CHAR, axis), rotateChar: () => createAction(ROTATE_CHAR), setFramebufUIState: (framebufIndex: number, uiState?: FramebufUIState) => createAction(SET_FRAMEBUF_UI_STATE, { framebufIndex, uiState }), setTextColor: (c: number) => createAction('Toolbar/SET_TEXT_COLOR', c), setTextCursorPos: (pos: Coord2|null) => createAction('Toolbar/SET_TEXT_CURSOR_POS', pos), setSelectedTool: (t: Tool) => createAction('Toolbar/SET_SELECTED_TOOL', t), setBrushRegion: (br: BrushRegion) => createAction('Toolbar/SET_BRUSH_REGION', br), setBrush: (b: Brush) => createAction('Toolbar/SET_BRUSH', b), setWorkspaceFilename: (fname: string|null) => createAction('Toolbar/SET_WORKSPACE_FILENAME', fname), setAltKey: (flag: boolean) => createAction('Toolbar/SET_ALT_KEY', flag), setCtrlKey: (flag: boolean) => createAction('Toolbar/SET_CTRL_KEY', flag), setMetaKey: (flag: boolean) => createAction('Toolbar/SET_META_KEY', flag), setShiftKey: (flag: boolean) => createAction('Toolbar/SET_SHIFT_KEY', flag), setSpacebarKey: (flag: boolean) => createAction('Toolbar/SET_SPACEBAR_KEY', flag), setShowSettings: (flag: boolean) => createAction('Toolbar/SET_SHOW_SETTINGS', flag), setShowCustomFonts: (flag: boolean) => createAction('Toolbar/SET_SHOW_CUSTOM_FONTS', flag), setShowExport: (show: {show:boolean, fmt?:FileFormat}) => createAction('Toolbar/SET_SHOW_EXPORT', show), setShowImport: (show: {show:boolean, fmt?:FileFormat}) => createAction('Toolbar/SET_SHOW_IMPORT', show), setSelectedPaletteRemap: (remapIdx: number) => createAction('Toolbar/SET_SELECTED_PALETTE_REMAP', remapIdx), setCanvasGrid: (flag: boolean) => createAction('Toolbar/SET_CANVAS_GRID', flag), setShortcutsActive: (flag: boolean) => createAction('Toolbar/SET_SHORTCUTS_ACTIVE', flag), setNewScreenSize: (dims: { width: number, height: number }) => createAction('Toolbar/SET_NEW_SCREEN_SIZE', dims) }; export type Actions = ActionsUnion<typeof actionCreators>; export type PropsFromDispatch = DispatchPropsFromActions<typeof Toolbar.actions>; export class Toolbar { static MIRROR_X = 1 static MIRROR_Y = 2 static actions = { ...actionCreators, keyDown: (k: string): RootStateThunk => { // Lower-case single keys in case the caps-lock is on. // Doing this for single char keys only to keep the other // keys (like 'ArrowLeft') in their original values. const key = k.length == 1 ? k.toLowerCase() : k; return (dispatch, getState) => { const state = getState() if (!state.toolbar.shortcutsActive) { return } const { shiftKey, altKey, metaKey, ctrlKey, selectedTool, showSettings, showCustomFonts, showExport, showImport } = state.toolbar const noMods = !shiftKey && !metaKey && !ctrlKey const metaOrCtrl = metaKey || ctrlKey const inModal = state.toolbar.showExport.show || state.toolbar.showImport.show || state.toolbar.showSettings || state.toolbar.showCustomFonts; if (inModal) { // These shouldn't early exit this function since we check for other // conditions for Esc later. if (key === 'Escape') { if (showSettings) { dispatch(Toolbar.actions.setShowSettings(false)); } if (showCustomFonts) { dispatch(Toolbar.actions.setShowCustomFonts(false)); } if (showExport) { dispatch(Toolbar.actions.setShowExport({show:false})); } if (showImport) { dispatch(Toolbar.actions.setShowImport({show:false})); } } return; } let width = 1; let height = 1; const framebufIndex = screensSelectors.getCurrentScreenFramebufIndex(state) if (framebufIndex !== null) { const { width: w, height: h } = selectors.getFramebufByIndex(state, framebufIndex)!; width = w; height = h; } let inTextInput = selectedTool === Tool.Text && state.toolbar.textCursorPos !== null // These shortcuts should work regardless of what drawing tool is selected. if (noMods) { if (!inTextInput) { if (!altKey && key === 'ArrowLeft') { dispatch(Screens.actions.nextScreen(-1)) return } else if (!altKey && key === 'ArrowRight') { dispatch(Screens.actions.nextScreen(+1)) return } else if (key === 'q') { dispatch(Toolbar.actions.nextColor(-1)) return } else if (key === 'e') { dispatch(Toolbar.actions.nextColor(+1)) return } else if (key === 'x' || key === '1') { dispatch(Toolbar.actions.setSelectedTool(Tool.Draw)) return } else if (key === 'c' || key === '2') { dispatch(Toolbar.actions.setSelectedTool(Tool.Colorize)) return } else if (key === '3') { dispatch(Toolbar.actions.setSelectedTool(Tool.CharDraw)) return } else if (key === 'b' || key === '4') { dispatch(Toolbar.actions.setSelectedTool(Tool.Brush)) return } else if (key === 't' || key === '5') { dispatch(Toolbar.actions.setSelectedTool(Tool.Text)) return } else if (key === 'z' || key === '6') { dispatch(Toolbar.actions.setSelectedTool(Tool.PanZoom)) return } else if (key === 'g') { return dispatch((dispatch, getState) => { const { canvasGrid } = getState().toolbar dispatch(Toolbar.actions.setCanvasGrid(!canvasGrid)) }) } } } if (selectedTool === Tool.Text) { if (key === 'Escape') { dispatch(Toolbar.actions.setTextCursorPos(null)) } if (state.toolbar.textCursorPos !== null && !metaOrCtrl) { // Don't match shortcuts if we're in "text tool" mode. const { textCursorPos, textColor } = state.toolbar const c = convertAsciiToScreencode(shiftKey ? key.toUpperCase() : key) if (framebufIndex !== null) { if (c !== null) { dispatch(Framebuffer.actions.setPixel({ ...textCursorPos, screencode: c, color: textColor, }, null, framebufIndex)); const newCursorPos = moveTextCursor( textCursorPos, { col: 1, row: 0 }, width, height ) dispatch(Toolbar.actions.setTextCursorPos(newCursorPos)) } if (key === 'Backspace') { const newCursorPos = moveTextCursor( textCursorPos, { col: -1, row: 0 }, width, height ) dispatch(Toolbar.actions.setTextCursorPos(newCursorPos)); dispatch(Framebuffer.actions.setPixel({ ...newCursorPos, screencode: 0x20, // space color: textColor, }, null, framebufIndex)); } } if (key === 'ArrowLeft' || key === 'ArrowRight') { dispatch(Toolbar.actions.setTextCursorPos( moveTextCursor( textCursorPos, { col: key === 'ArrowLeft' ? -1 : 1, row: 0}, width, height ) )) } else if (key === 'ArrowUp' || key === 'ArrowDown') { dispatch(Toolbar.actions.setTextCursorPos( moveTextCursor( textCursorPos, { row: key === 'ArrowUp' ? -1 : 1, col: 0}, width, height ) )) } } } else if (noMods) { if (key === 'Escape') { if (selectedTool === Tool.Brush) { dispatch(Toolbar.actions.resetBrush()) } } else if (key === 'a') { dispatch(Toolbar.actions.nextCharcode({ row: 0, col: -1})) } else if (key === 'd') { dispatch(Toolbar.actions.nextCharcode({ row: 0, col: +1})) } else if (key === 's') { dispatch(Toolbar.actions.nextCharcode({ row: +1, col: 0})) } else if (key === 'w') { dispatch(Toolbar.actions.nextCharcode({ row: -1, col: 0})) } else if (key === 'v' || key === 'h') { let mirror = Toolbar.MIRROR_Y if (key === 'h') { mirror = Toolbar.MIRROR_X } if (selectedTool === Tool.Brush) { dispatch(Toolbar.actions.mirrorBrush(mirror)) } else if (selectedTool === Tool.Draw || selectedTool === Tool.CharDraw) { dispatch(Toolbar.actions.mirrorChar(mirror)) } } else if (key === 'f') { dispatch(Toolbar.actions.invertChar()) } else if (key === 'r') { if (selectedTool === Tool.Brush) { dispatch(Toolbar.actions.rotateBrush()) } else if (selectedTool === Tool.Draw || selectedTool === Tool.CharDraw) { dispatch(Toolbar.actions.rotateChar()) } } } if (key === 'Shift') { dispatch(Toolbar.actions.setShiftKey(true)) } else if (key === 'Meta') { dispatch(Toolbar.actions.setMetaKey(true)) } else if (key === 'Control') { dispatch(Toolbar.actions.setCtrlKey(true)) } else if (key === 'Alt') { dispatch(Toolbar.actions.setAltKey(true)) } else if (key === ' ') { dispatch(Toolbar.actions.setSpacebarKey(true)) } if (metaOrCtrl) { switch(key) { case '1': dispatch(Toolbar.actions.setSelectedPaletteRemap(0)) break case '2': dispatch(Toolbar.actions.setSelectedPaletteRemap(1)) break case '3': dispatch(Toolbar.actions.setSelectedPaletteRemap(2)) break case '4': dispatch(Toolbar.actions.setSelectedPaletteRemap(3)) break default: break; } } } }, keyUp: (key: string): RootStateThunk => { return (dispatch, _getState) => { if (key === 'Shift') { dispatch(Toolbar.actions.setShiftKey(false)) } else if (key === 'Meta') { dispatch(Toolbar.actions.setMetaKey(false)) } else if (key === 'Control') { dispatch(Toolbar.actions.setCtrlKey(false)) } else if (key === 'Alt') { dispatch(Toolbar.actions.setAltKey(false)) } else if (key === ' ') { dispatch(Toolbar.actions.setSpacebarKey(false)) } } }, clearCanvas: (): RootStateThunk => { return dispatchForCurrentFramebuf((dispatch, framebufIndex) => { dispatch(Framebuffer.actions.clearCanvas(framebufIndex)) }); }, nextCharcode: (dir: Coord2): RootStateThunk => { return (dispatch, getState) => { const { font } = selectors.getCurrentFramebufFont(getState()); dispatch(actionCreators.nextCharcodeAction(dir, font)); } }, invertChar: (): RootStateThunk => { return (dispatch, getState) => { const { font } = selectors.getCurrentFramebufFont(getState()); dispatch(actionCreators.invertCharAction(font)); } }, nextColor: (dir: number): RootStateThunk => { return (dispatch, getState) => { const state = getState() dispatch(actionCreators.nextColorAction(dir, getSettingsPaletteRemap(state))); } }, setScreencode: (code: number): RootStateThunk => { return (dispatch, getState) => { const state = getState(); const { font } = selectors.getCurrentFramebufFont(state); const charPos = utils.rowColFromScreencode(font, code); dispatch(Toolbar.actions.setSelectedChar(charPos)); } }, setCurrentColor: (color: number): RootStateThunk => { return (dispatch, getState) => { const state = getState(); dispatch(Toolbar.actions.setTextColor(color)) if (state.toolbar.selectedTool === Tool.Brush || state.toolbar.selectedTool === Tool.PanZoom) { dispatch(Toolbar.actions.setSelectedTool(Tool.Draw)); } } }, setCurrentChar: (charPos: Coord2): RootStateThunk => { return (dispatch, getState) => { const state = getState() dispatch(Toolbar.actions.setSelectedChar(charPos)) if (state.toolbar.selectedTool === Tool.Brush || state.toolbar.selectedTool === Tool.Colorize || state.toolbar.selectedTool === Tool.Text || state.toolbar.selectedTool === Tool.PanZoom) { dispatch(Toolbar.actions.setSelectedTool(Tool.Draw)) } } }, setCurrentScreencodeAndColor: (pix: Pixel): RootStateThunk => { return (dispatch, getState) => { const state = getState() dispatch(Toolbar.actions.setTextColor(pix.color)) dispatch(Toolbar.actions.setScreencode(pix.code)) if (state.toolbar.selectedTool === Tool.Brush || state.toolbar.selectedTool === Tool.Text) { dispatch(Toolbar.actions.setSelectedTool(Tool.Draw)) } } }, shiftHorizontal: (dir: -1|1): RootStateThunk => { return dispatchForCurrentFramebuf((dispatch, framebufIndex) => { dispatch(Framebuffer.actions.shiftHorizontal(dir, framebufIndex)) }); }, shiftVertical: (dir: -1|1) => { return dispatchForCurrentFramebuf((dispatch, framebufIndex) => { dispatch(Framebuffer.actions.shiftVertical(dir, framebufIndex)) }); }, setCurrentFramebufUIState: (uiState: FramebufUIState): RootStateThunk => { return dispatchForCurrentFramebuf((dispatch, framebufIndex) => { dispatch(Toolbar.actions.setFramebufUIState(framebufIndex, uiState)); }); }, } static reducer(state: IToolbar = { ...initialBrushValue, selectedChar: {row: 8, col: 0}, charTransform: emptyTransform, undoId: 0, textColor: 14, textCursorPos: null as (Coord2|null), selectedTool: Tool.Draw, brushRegion: null as (BrushRegion|null), brush: null as (Brush|null), workspaceFilename: null as (string|null), altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, spacebarKey: false, showSettings: false, showCustomFonts: false, showExport: { show: false }, showImport: { show: false }, selectedPaletteRemap: 0, canvasGrid: false, shortcutsActive: true, newScreenSize: { width: DEFAULT_FB_WIDTH, height: DEFAULT_FB_HEIGHT }, framebufUIState: {} }, action: Actions) { switch (action.type) { case RESET_BRUSH: return { ...state, ...initialBrushValue } case CAPTURE_BRUSH: return { ...state, ...initialBrushValue, brush: action.data } case SET_SELECTED_CHAR: const rc = action.data return { ...state, selectedChar: rc, charTransform: emptyTransform } case NEXT_CHARCODE: { const { dir, font } = action.data const rc = selectors.getCharRowColWithTransform(state.selectedChar, font, state.charTransform) return { ...state, selectedChar: { row: Math.max(0, Math.min(15, rc.row + dir.row)), col: Math.max(0, Math.min(15, rc.col + dir.col)), }, charTransform: emptyTransform } } case INVERT_CHAR: { const font = action.data const curScreencode = selectors.getScreencodeWithTransform(state.selectedChar, font, state.charTransform) const inverseRowCol = utils.rowColFromScreencode(font, brush.findInverseChar(font, curScreencode)) return { ...state, selectedChar: inverseRowCol, charTransform: emptyTransform } } case NEXT_COLOR: { const remap = action.data.paletteRemap; const idx = remap.indexOf(state.textColor); const dir = action.data.dir; const nextIdx = Math.max(0, Math.min(15, idx + dir)); return { ...state, textColor: remap[nextIdx] } } case INC_UNDO_ID: return { ...state, undoId: state.undoId+1 } case SET_FRAMEBUF_UI_STATE: { return { ...state, framebufUIState: { ...state.framebufUIState, [action.data.framebufIndex]: action.data.uiState || defaultFramebufUIState } } } case MIRROR_BRUSH: return { ...state, brushTransform: mirror(state.brushTransform, action.data) } case ROTATE_BRUSH: return { ...state, brushTransform: rotate(state.brushTransform) } case MIRROR_CHAR: return { ...state, charTransform: mirror(state.charTransform, action.data) } case ROTATE_CHAR: return { ...state, charTransform: rotate(state.charTransform) } case CLEAR_MOD_KEY_STATE: return { ...state, altKey: false, ctrlKey: false, metaKey: false, shiftKey: false } case 'Toolbar/SET_TEXT_COLOR': return updateField(state, 'textColor', action.data); case 'Toolbar/SET_TEXT_CURSOR_POS': return updateField(state, 'textCursorPos', action.data); case 'Toolbar/SET_SELECTED_TOOL': return updateField(state, 'selectedTool', action.data); case 'Toolbar/SET_BRUSH_REGION': return updateField(state, 'brushRegion', action.data); case 'Toolbar/SET_BRUSH': return updateField(state, 'brush', action.data); case 'Toolbar/SET_WORKSPACE_FILENAME': return updateField(state, 'workspaceFilename', action.data); case 'Toolbar/SET_ALT_KEY': return updateField(state, 'altKey', action.data); case 'Toolbar/SET_CTRL_KEY': return updateField(state, 'ctrlKey', action.data); case 'Toolbar/SET_META_KEY': return updateField(state, 'metaKey', action.data); case 'Toolbar/SET_SHIFT_KEY': return updateField(state, 'shiftKey', action.data); case 'Toolbar/SET_SPACEBAR_KEY': return updateField(state, 'spacebarKey', action.data); case 'Toolbar/SET_SHOW_SETTINGS': return updateField(state, 'showSettings', action.data); case 'Toolbar/SET_SHOW_CUSTOM_FONTS': return updateField(state, 'showCustomFonts', action.data); case 'Toolbar/SET_SHOW_EXPORT': return updateField(state, 'showExport', action.data); case 'Toolbar/SET_SHOW_IMPORT': return updateField(state, 'showImport', action.data); case 'Toolbar/SET_SELECTED_PALETTE_REMAP': return updateField(state, 'selectedPaletteRemap', action.data); case 'Toolbar/SET_CANVAS_GRID': return updateField(state, 'canvasGrid', action.data); case 'Toolbar/SET_SHORTCUTS_ACTIVE': return updateField(state, 'shortcutsActive', action.data); case 'Toolbar/SET_NEW_SCREEN_SIZE': return updateField(state, 'newScreenSize', action.data); default: return state; } } static bindDispatch (dispatch: Dispatch) { return bindActionCreators(Toolbar.actions, dispatch) } }
the_stack
import {AGGREGATION_OPERATION, _BinSorter as BinSorter} from '@deck.gl/aggregation-layers'; import {console as Console} from 'global/window'; import {aggregate} from '../../utils/aggregate-utils'; import {AGGREGATION_TYPES, SCALE_FUNC} from '../../constants/default-settings'; import {RGBAColor} from '../../reducers'; export type UpdaterType = (this: CPUAggregator, step, props, dimensionUpdater) => void; export type BindedUpdaterType = () => void; export type AggregatedUpdaterType = ( this: CPUAggregator, step, props, aggregation, aggregationParams ) => void; export type BindedAggregatedUpdaterType = (aggregationParams) => void; export type UpdateStepsType = { key: string; triggers: { [key: string]: { prop: string; updateTrigger?: string; }; }; onSet?: { props: string; }; updater: UpdaterType; }; export type DimensionType<ValueType = any> = { key: string; accessor: string; getPickingInfo: (dimensionState, cell, layerProps?) => any; nullValue: ValueType; updateSteps: UpdateStepsType[]; getSubLayerAccessor; }; export type AggregationUpdateStepsType = { key: string; triggers: { [key: string]: { prop: string; updateTrigger?: string; }; }; updater: AggregatedUpdaterType; }; export type AggregationType = { key: string; updateSteps: AggregationUpdateStepsType[]; }; export const DECK_AGGREGATION_MAP = { [AGGREGATION_OPERATION.SUM]: AGGREGATION_TYPES.sum, [AGGREGATION_OPERATION.MEAN]: AGGREGATION_TYPES.average, [AGGREGATION_OPERATION.MIN]: AGGREGATION_TYPES.minimum, [AGGREGATION_OPERATION.MAX]: AGGREGATION_TYPES.maximum }; export function getValueFunc(aggregation, accessor) { if (!aggregation || !AGGREGATION_OPERATION[aggregation.toUpperCase()]) { Console.warn(`Aggregation ${aggregation} is not supported`); } const op = AGGREGATION_OPERATION[aggregation.toUpperCase()] || AGGREGATION_OPERATION.SUM; const keplerOp = DECK_AGGREGATION_MAP[op]; return pts => aggregate(pts.map(accessor), keplerOp); } export function getScaleFunctor(scaleType) { if (!scaleType || !SCALE_FUNC[scaleType]) { Console.warn(`Scale ${scaleType} is not supported`); } return SCALE_FUNC[scaleType] || SCALE_FUNC.quantize; } function nop() {} export function getGetValue(this: CPUAggregator, step, props, dimensionUpdater) { const {key} = dimensionUpdater; const {value, weight, aggregation} = step.triggers; let getValue = props[value.prop]; if (getValue === null) { // If `getValue` is not provided from props, build it with aggregation and weight. getValue = getValueFunc(props[aggregation.prop], props[weight.prop]); } if (getValue) { this._setDimensionState(key, {getValue}); } } export function getDimensionSortedBins(this: CPUAggregator, step, props, dimensionUpdater) { const {key} = dimensionUpdater; const {getValue} = this.state.dimensions[key]; // @ts-expect-error const sortedBins = new BinSorter(this.state.layerData.data || [], { getValue, filterData: props._filterData }); this._setDimensionState(key, {sortedBins}); } export function getDimensionValueDomain(this: CPUAggregator, step, props, dimensionUpdater) { const {key} = dimensionUpdater; const { triggers: {lowerPercentile, upperPercentile, scaleType} } = step; if (!this.state.dimensions[key].sortedBins) { // the previous step should set sortedBins, if not, something went wrong return; } // for log and sqrt scale, returns linear domain by default // TODO: support other scale function domain in bin sorter const valueDomain = this.state.dimensions[key].sortedBins.getValueDomainByScale( props[scaleType.prop], [props[lowerPercentile.prop], props[upperPercentile.prop]] ); this._setDimensionState(key, {valueDomain}); } export function getDimensionScale(this: CPUAggregator, step, props, dimensionUpdater) { const {key} = dimensionUpdater; const {domain, range, scaleType} = step.triggers; const {onSet} = step; if (!this.state.dimensions[key].valueDomain) { // the previous step should set valueDomain, if not, something went wrong return; } const dimensionRange = props[range.prop]; const dimensionDomain = props[domain.prop] || this.state.dimensions[key].valueDomain; const scaleFunctor = getScaleFunctor(scaleType && props[scaleType.prop])(); const scaleFunc = scaleFunctor.domain(dimensionDomain).range(dimensionRange); if (typeof onSet === 'object' && typeof props[onSet.props] === 'function') { props[onSet.props](scaleFunc.domain()); } this._setDimensionState(key, {scaleFunc}); } function normalizeResult(result: {hexagons?; layerData?} = {}) { // support previous hexagonAggregator API if (result.hexagons) { return Object.assign({data: result.hexagons}, result); } else if (result.layerData) { return Object.assign({data: result.layerData}, result); } return result; } export function getAggregatedData( this: CPUAggregator, step, props, aggregation, aggregationParams ) { const { triggers: {aggregator: aggr} } = step; const aggregator = props[aggr.prop]; // result should contain a data array and other props // result = {data: [], ...other props} const result = aggregator(props, aggregationParams); this.setState({ layerData: normalizeResult(result) }); } export const defaultAggregation: AggregationType = { key: 'position', updateSteps: [ { key: 'aggregate', triggers: { cellSize: { prop: 'cellSize' }, position: { prop: 'getPosition', updateTrigger: 'getPosition' }, aggregator: { prop: 'gridAggregator' } }, updater: getAggregatedData } ] }; function getSubLayerAccessor(dimensionState, dimension, layerProps) { return cell => { const {sortedBins, scaleFunc} = dimensionState; const bin = sortedBins.binMap[cell.index]; if (bin && bin.counts === 0) { // no points left in bin after filtering return dimension.nullValue; } const cv = bin && bin.value; const domain = scaleFunc.domain(); const isValueInDomain = cv >= domain[0] && cv <= domain[domain.length - 1]; // if cell value is outside domain, set alpha to 0 return isValueInDomain ? scaleFunc(cv) : dimension.nullValue; }; } export const defaultColorDimension: DimensionType<RGBAColor> = { key: 'fillColor', accessor: 'getFillColor', getPickingInfo: (dimensionState, cell) => { const {sortedBins} = dimensionState; const colorValue = sortedBins.binMap[cell.index] && sortedBins.binMap[cell.index].value; return {colorValue}; }, nullValue: [0, 0, 0, 0], updateSteps: [ { key: 'getValue', triggers: { value: { prop: 'getColorValue', updateTrigger: 'getColorValue' }, weight: { prop: 'getColorWeight', updateTrigger: 'getColorWeight' }, aggregation: { prop: 'colorAggregation' } }, updater: getGetValue }, { key: 'getBins', triggers: { _filterData: { prop: '_filterData', updateTrigger: '_filterData' } }, updater: getDimensionSortedBins }, { key: 'getDomain', triggers: { lowerPercentile: { prop: 'lowerPercentile' }, upperPercentile: { prop: 'upperPercentile' }, scaleType: {prop: 'colorScaleType'} }, updater: getDimensionValueDomain }, { key: 'getScaleFunc', triggers: { domain: {prop: 'colorDomain'}, range: {prop: 'colorRange'}, scaleType: {prop: 'colorScaleType'} }, onSet: { props: 'onSetColorDomain' }, updater: getDimensionScale } ], getSubLayerAccessor }; export const defaultElevationDimension: DimensionType<number> = { key: 'elevation', accessor: 'getElevation', getPickingInfo: (dimensionState, cell) => { const {sortedBins} = dimensionState; const elevationValue = sortedBins.binMap[cell.index] && sortedBins.binMap[cell.index].value; return {elevationValue}; }, nullValue: -1, updateSteps: [ { key: 'getValue', triggers: { value: { prop: 'getElevationValue', updateTrigger: 'getElevationValue' }, weight: { prop: 'getElevationWeight', updateTrigger: 'getElevationWeight' }, aggregation: { prop: 'elevationAggregation' } }, updater: getGetValue }, { key: 'getBins', triggers: { _filterData: { prop: '_filterData', updateTrigger: '_filterData' } }, updater: getDimensionSortedBins }, { key: 'getDomain', triggers: { lowerPercentile: { prop: 'elevationLowerPercentile' }, upperPercentile: { prop: 'elevationUpperPercentile' }, scaleType: {prop: 'elevationScaleType'} }, updater: getDimensionValueDomain }, { key: 'getScaleFunc', triggers: { domain: {prop: 'elevationDomain'}, range: {prop: 'elevationRange'}, scaleType: {prop: 'elevationScaleType'} }, onSet: { props: 'onSetElevationDomain' }, updater: getDimensionScale } ], getSubLayerAccessor }; export const defaultDimensions = [defaultColorDimension, defaultElevationDimension]; export type CPUAggregatorState = {layerData: {data?}; dimensions: {}}; export default class CPUAggregator { static getDimensionScale: any; state: CPUAggregatorState; dimensionUpdaters: {[key: string]: DimensionType}; aggregationUpdater: AggregationType; constructor( opts: { initialState?: CPUAggregatorState; dimensions?: DimensionType[]; aggregation?: AggregationType; } = {} ) { this.state = { layerData: {}, dimensions: { // color: { // getValue: null, // domain: null, // sortedBins: null, // scaleFunc: nop // }, // elevation: { // getValue: null, // domain: null, // sortedBins: null, // scaleFunc: nop // } }, ...opts.initialState }; this.dimensionUpdaters = {}; this.aggregationUpdater = opts.aggregation || defaultAggregation; this._addDimension(opts.dimensions || defaultDimensions); } static defaultDimensions() { return defaultDimensions; } updateAllDimensions(props) { let dimensionChanges: BindedUpdaterType[] = []; // update all dimensions for (const dim in this.dimensionUpdaters) { const updaters = this._accumulateUpdaters(0, props, this.dimensionUpdaters[dim]); dimensionChanges = dimensionChanges.concat(updaters); } dimensionChanges.forEach(f => typeof f === 'function' && f()); } updateAggregation(props, aggregationParams) { const updaters = this._accumulateUpdaters(0, props, this.aggregationUpdater); updaters.forEach(f => typeof f === 'function' && f(aggregationParams)); } updateState(opts, aggregationParams) { const {oldProps, props, changeFlags} = opts; let dimensionChanges: BindedUpdaterType[] = []; if (changeFlags.dataChanged) { // if data changed update everything this.updateAggregation(props, aggregationParams); this.updateAllDimensions(props); return this.state; } const aggregationChanges = this._getAggregationChanges(oldProps, props, changeFlags); if (aggregationChanges && aggregationChanges.length) { // get aggregatedData aggregationChanges.forEach(f => typeof f === 'function' && f(aggregationParams)); this.updateAllDimensions(props); } else { // only update dimensions dimensionChanges = this._getDimensionChanges(oldProps, props, changeFlags) || []; dimensionChanges.forEach(f => typeof f === 'function' && f()); } return this.state; } // Update private state setState(updateObject) { this.state = Object.assign({}, this.state, updateObject); } // Update private state.dimensions _setDimensionState(key, updateObject) { this.setState({ dimensions: Object.assign({}, this.state.dimensions, { [key]: Object.assign({}, this.state.dimensions[key], updateObject) }) }); } _addAggregation(aggregation: AggregationType) { this.aggregationUpdater = aggregation; } _addDimension(dimensions: DimensionType[] = []) { dimensions.forEach(dimension => { const {key} = dimension; this.dimensionUpdaters[key] = dimension; }); } _needUpdateStep( dimensionStep: UpdateStepsType | AggregationUpdateStepsType, oldProps, props, changeFlags ) { // whether need to update current dimension step // dimension step is the value, domain, scaleFunction of each dimension // each step is an object with properties links to layer prop and whether the prop is // controlled by updateTriggers return Object.values(dimensionStep.triggers).some(item => { if (item.updateTrigger) { // check based on updateTriggers change first return ( changeFlags.updateTriggersChanged && (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged[item.updateTrigger]) ); } // fallback to direct comparison return oldProps[item.prop] !== props[item.prop]; }); } _accumulateUpdaters<UpdaterObjectType extends DimensionType | AggregationType>( step, props, dimension: UpdaterObjectType ) { type UpdaterType = UpdaterObjectType extends DimensionType ? BindedUpdaterType : BindedAggregatedUpdaterType; const updaters: UpdaterType[] = []; for (let i = step; i < dimension.updateSteps.length; i++) { const updater = dimension.updateSteps[i].updater; if (typeof updater === 'function') { updaters.push( updater.bind(this, dimension.updateSteps[i], props, dimension) as UpdaterType ); } } return updaters; } _getAllUpdaters<UpdaterObjectType extends DimensionType | AggregationType>( dimension: UpdaterObjectType, oldProps, props, changeFlags ) { type UpdaterType = UpdaterObjectType extends DimensionType ? BindedUpdaterType : BindedAggregatedUpdaterType; let updaters: UpdaterType[] = []; const needUpdateStep = dimension.updateSteps.findIndex(step => this._needUpdateStep(step, oldProps, props, changeFlags) ); if (needUpdateStep > -1) { updaters = updaters.concat(this._accumulateUpdaters(needUpdateStep, props, dimension)); } return updaters; } _getAggregationChanges(oldProps, props, changeFlags) { const updaters = this._getAllUpdaters(this.aggregationUpdater, oldProps, props, changeFlags); return updaters.length ? updaters : null; } _getDimensionChanges(oldProps, props, changeFlags) { let updaters: BindedUpdaterType[] = []; // get dimension to be updated for (const key in this.dimensionUpdaters) { // return the first triggered updater for each dimension const dimension = this.dimensionUpdaters[key]; const dimensionUpdaters = this._getAllUpdaters(dimension, oldProps, props, changeFlags); updaters = updaters.concat(dimensionUpdaters); } return updaters.length ? updaters : null; } getUpdateTriggers(props) { const _updateTriggers = props.updateTriggers || {}; const updateTriggers = {}; for (const key in this.dimensionUpdaters) { const { accessor, updateSteps }: {accessor; updateSteps: UpdateStepsType[]} = this.dimensionUpdaters[key]; // fold dimension triggers into each accessor updateTriggers[accessor] = {}; updateSteps.forEach(step => { Object.values(step.triggers || []).forEach(({prop, updateTrigger}) => { if (updateTrigger) { // if prop is based on updateTrigger e.g. getColorValue, getColorWeight // and updateTriggers is passed in from layer prop // fold the updateTriggers into accessor const fromProp = _updateTriggers[updateTrigger]; if (typeof fromProp === 'object' && !Array.isArray(fromProp)) { // if updateTrigger is an object spread it Object.assign(updateTriggers[accessor], fromProp); } else if (fromProp !== undefined) { updateTriggers[accessor][prop] = fromProp; } } else { // if prop is not based on updateTrigger updateTriggers[accessor][prop] = props[prop]; } }); }); } return updateTriggers; } getPickingInfo({info}, layerProps) { const isPicked = info.picked && info.index > -1; let object = null; if (isPicked) { const cell = this.state.layerData.data[info.index]; let binInfo = {}; for (const key in this.dimensionUpdaters) { const {getPickingInfo} = this.dimensionUpdaters[key]; if (typeof getPickingInfo === 'function') { binInfo = Object.assign( {}, binInfo, getPickingInfo(this.state.dimensions[key], cell, layerProps) ); } } object = Object.assign(binInfo, cell, { points: cell.filteredPoints || cell.points }); } // add bin and to info return Object.assign(info, { picked: Boolean(object), // override object with picked cell object }); } getAccessor(dimensionKey, layerProps) { if (!this.dimensionUpdaters.hasOwnProperty(dimensionKey)) { return nop; } return this.dimensionUpdaters[dimensionKey].getSubLayerAccessor( this.state.dimensions[dimensionKey], this.dimensionUpdaters[dimensionKey], layerProps ); } } CPUAggregator.getDimensionScale = getDimensionScale;
the_stack
import { NonModelTypeConstructor, PersistentModelConstructor } from '../src'; import { DataStore as DataStoreType, initSchema as initSchemaType, } from '../src/datastore/datastore'; import { default as AsyncStorageAdapterType } from '../src/storage/adapter/AsyncStorageAdapter'; import { DATASTORE, USER } from '../src/util'; import { Author as AuthorType, Blog as BlogType, BlogOwner as BlogOwnerType, Comment as CommentType, Nested as NestedType, Post as PostType, PostAuthorJoin as PostAuthorJoinType, PostMetadata as PostMetadataType, Person as PersonType, } from './model'; import { newSchema } from './schema'; import { SortDirection } from '../src/types'; let AsyncStorageAdapter: typeof AsyncStorageAdapterType; let initSchema: typeof initSchemaType; let DataStore: typeof DataStoreType; let Author: PersistentModelConstructor<InstanceType<typeof AuthorType>>; let Blog: PersistentModelConstructor<InstanceType<typeof BlogType>>; let BlogOwner: PersistentModelConstructor<InstanceType<typeof BlogOwnerType>>; let Comment: PersistentModelConstructor<InstanceType<typeof CommentType>>; let Nested: NonModelTypeConstructor<InstanceType<typeof NestedType>>; let Post: PersistentModelConstructor<InstanceType<typeof PostType>>; let Person: PersistentModelConstructor<InstanceType<typeof PersonType>>; let PostAuthorJoin: PersistentModelConstructor<InstanceType< typeof PostAuthorJoinType >>; let PostMetadata: NonModelTypeConstructor<InstanceType< typeof PostMetadataType >>; const inmemoryMap = new Map<string, string>(); // ! We have to mock the same storage interface the AsyncStorageDatabase depends on // ! as a singleton so that new instances all share the same underlying data structure. jest.mock('../src/storage/adapter/InMemoryStore', () => { class InMemoryStore { getAllKeys = async () => { return Array.from(inmemoryMap.keys()); }; multiGet = async (keys: string[]) => { return keys.reduce( (res, k) => (res.push([k, inmemoryMap.get(k)]), res), [] ); }; multiRemove = async (keys: string[]) => { return keys.forEach(k => inmemoryMap.delete(k)); }; setItem = async (key: string, value: string) => { return inmemoryMap.set(key, value); }; removeItem = async (key: string) => { return inmemoryMap.delete(key); }; getItem = async (key: string) => { return inmemoryMap.get(key); }; } return { createInMemoryStore() { return new InMemoryStore(); }, InMemoryStore, }; }); jest.mock('../src/storage/adapter/getDefaultAdapter/index', () => () => AsyncStorageAdapter ); /** * Sets up the schema for the tests * * @param beforeSetUp Executed after reseting modules but before re-requiring the schema initialization */ function setUpSchema(beforeSetUp?: Function) { jest.resetModules(); if (typeof beforeSetUp === 'function') { beforeSetUp(); } ({ default: AsyncStorageAdapter, } = require('../src/storage/adapter/AsyncStorageAdapter')); ({ initSchema, DataStore } = require('../src/datastore/datastore')); ({ Author, Blog, BlogOwner, Comment, Nested, Post, Person, PostAuthorJoin, PostMetadata, } = < { Author: typeof Author; Blog: typeof Blog; BlogOwner: typeof BlogOwner; Comment: typeof Comment; Nested: typeof Nested; Post: typeof Post; Person: typeof Person; PostAuthorJoin: typeof PostAuthorJoin; PostMetadata: typeof PostMetadata; } >initSchema(newSchema)); } describe('AsyncStorage tests', () => { const { InMemoryStore } = require('../src/storage/adapter/InMemoryStore'); const AsyncStorage = new InMemoryStore(); let blog: InstanceType<typeof Blog>, blog2: InstanceType<typeof Blog>, blog3: InstanceType<typeof Blog>, owner: InstanceType<typeof BlogOwner>, owner2: InstanceType<typeof BlogOwner>; beforeEach(async () => { setUpSchema(); owner = new BlogOwner({ name: 'Owner 1' }); owner2 = new BlogOwner({ name: 'Owner 2' }); blog = new Blog({ name: 'Avatar: Last Airbender', owner, }); blog2 = new Blog({ name: 'blog2', owner: owner2, }); blog3 = new Blog({ name: 'Avatar 101', owner: new BlogOwner({ name: 'owner 3' }), }); await DataStore.start(); }); test('setup function', async () => { const allKeys = await AsyncStorage.getAllKeys(); expect(allKeys).not.toHaveLength(0); // At leaset the settings entry should be present expect(allKeys[0]).toMatch( new RegExp( `@AmplifyDatastore::${DATASTORE}_Setting::Data::\\w{26}::\\w{26}` ) ); }); test('save function 1:1 insert', async () => { await DataStore.save(blog); await DataStore.save(owner); const get1 = JSON.parse( await AsyncStorage.getItem( getKeyForAsyncStorage(USER, Blog.name, blog.id) ) ); expect({ ...blog, blogOwnerId: owner.id }).toMatchObject(get1); expect(get1['blogOwnerId']).toBe(owner.id); const get2 = JSON.parse( await AsyncStorage.getItem( getKeyForAsyncStorage(USER, BlogOwner.name, owner.id) ) ); expect(owner).toMatchObject(get2); await DataStore.save(blog2); const get3 = JSON.parse( await AsyncStorage.getItem( getKeyForAsyncStorage(USER, Blog.name, blog2.id) ) ); expect({ ...blog2, blogOwnerId: owner2.id }).toMatchObject(get3); }); test('save stores non-model types along the item (including nested)', async () => { const p = new Post({ title: 'Avatar', blog, metadata: new PostMetadata({ rating: 3, tags: ['a', 'b', 'c'], nested: new Nested({ aField: 'Some value', }), }), }); await DataStore.save(p); const postFromDB = JSON.parse( await AsyncStorage.getItem(getKeyForAsyncStorage(USER, Post.name, p.id)) ); expect(postFromDB.metadata).toMatchObject({ rating: 3, tags: ['a', 'b', 'c'], nested: new Nested({ aField: 'Some value', }), }); }); test('save update', async () => { await DataStore.save(blog); await DataStore.save(owner); const get1 = JSON.parse( await AsyncStorage.getItem( getKeyForAsyncStorage(USER, Blog.name, blog.id) ) ); expect(get1['blogOwnerId']).toBe(owner.id); const updated = Blog.copyOf(blog, draft => { draft.name = 'Avatar: The Last Airbender'; }); await DataStore.save(updated); const get2 = JSON.parse( await AsyncStorage.getItem( getKeyForAsyncStorage(USER, Blog.name, blog.id) ) ); expect(get2.name).toEqual(updated.name); }); test('query function 1:1', async () => { const res = await DataStore.save(blog); await DataStore.save(owner); const query = await DataStore.query(Blog, blog.id); expect(query).toEqual(res); await DataStore.save(blog3); const query1 = await DataStore.query(Blog); query1.forEach(item => { if (item.owner) { expect(item.owner).toHaveProperty('name'); } }); }); test('query M:1 eager load', async () => { const p = new Post({ title: 'Avatar', blog, }); const c1 = new Comment({ content: 'comment 1', post: p }); const c2 = new Comment({ content: 'comment 2', post: p }); await DataStore.save(p); await DataStore.save(c1); await DataStore.save(c2); const q1 = await DataStore.query(Comment, c1.id); expect(q1.post.id).toEqual(p.id); }); test('query with sort on a single field', async () => { const p1 = new Person({ firstName: 'John', lastName: 'Snow', }); const p2 = new Person({ firstName: 'Clem', lastName: 'Fandango', }); const p3 = new Person({ firstName: 'Beezus', lastName: 'Fuffoon', }); const p4 = new Person({ firstName: 'Meow Meow', lastName: 'Fuzzyface', }); await DataStore.save(p1); await DataStore.save(p2); await DataStore.save(p3); await DataStore.save(p4); const sortedPersons = await DataStore.query(Person, null, { page: 0, limit: 20, sort: s => s.firstName(SortDirection.DESCENDING), }); expect(sortedPersons[0].firstName).toEqual('Meow Meow'); expect(sortedPersons[1].firstName).toEqual('John'); expect(sortedPersons[2].firstName).toEqual('Clem'); expect(sortedPersons[3].firstName).toEqual('Beezus'); }); test('query with sort on multiple fields', async () => { const p1 = new Person({ firstName: 'John', lastName: 'Snow', username: 'johnsnow', }); const p2 = new Person({ firstName: 'John', lastName: 'Umber', username: 'smalljohnumber', }); const p3 = new Person({ firstName: 'John', lastName: 'Umber', username: 'greatjohnumber', }); await DataStore.save(p1); await DataStore.save(p2); await DataStore.save(p3); const sortedPersons = await DataStore.query( Person, c => c.username('ne', undefined), { page: 0, limit: 20, sort: s => s .firstName(SortDirection.ASCENDING) .lastName(SortDirection.ASCENDING) .username(SortDirection.ASCENDING), } ); expect(sortedPersons[0].username).toEqual('johnsnow'); expect(sortedPersons[1].username).toEqual('greatjohnumber'); expect(sortedPersons[2].username).toEqual('smalljohnumber'); }); test('delete 1:1 function', async () => { await DataStore.save(blog); await DataStore.save(owner); await DataStore.delete(Blog, blog.id); await DataStore.delete(BlogOwner, owner.id); expect(await DataStore.query(BlogOwner, owner.id)).toBeUndefined(); expect(await DataStore.query(Blog, blog.id)).toBeUndefined(); await DataStore.save(owner); await DataStore.save(owner2); await DataStore.save( Blog.copyOf(blog, draft => { draft; }) ); await DataStore.save(blog2); await DataStore.save(blog3); await DataStore.delete(Blog, c => c.name('beginsWith', 'Avatar')); expect(await DataStore.query(Blog, blog.id)).toBeUndefined(); expect(await DataStore.query(Blog, blog2.id)).toBeDefined(); expect(await DataStore.query(Blog, blog3.id)).toBeUndefined(); }); test('delete M:1 function', async () => { const post = new Post({ title: 'Avatar', blog, }); const c1 = new Comment({ content: 'c1', post }); const c2 = new Comment({ content: 'c2', post }); await DataStore.save(post); await DataStore.save(c1); await DataStore.save(c2); await DataStore.delete(Comment, c1.id); expect(await DataStore.query(Comment, c1.id)).toBeUndefined; expect((await DataStore.query(Comment, c2.id)).id).toEqual(c2.id); }); test('delete 1:M function', async () => { const post = new Post({ title: 'Avatar 1', blog, }); const post2 = new Post({ title: 'Avatar 2', blog, }); await DataStore.save(post); await DataStore.save(post2); const c1 = new Comment({ content: 'c1', post }); const c2 = new Comment({ content: 'c2', post }); const c3 = new Comment({ content: 'c3', post: post2 }); await DataStore.save(c1); await DataStore.save(c2); await DataStore.save(c3); await DataStore.delete(Post, post.id); expect(await DataStore.query(Comment, c1.id)).toBeUndefined(); expect(await DataStore.query(Comment, c2.id)).toBeUndefined(); expect((await DataStore.query(Comment, c3.id)).id).toEqual(c3.id); expect(await DataStore.query(Post, post.id)).toBeUndefined(); }); test('delete M:M function', async () => { const a1 = new Author({ name: 'author1' }); const a2 = new Author({ name: 'author2' }); const a3 = new Author({ name: 'author3' }); const blog = new Blog({ name: 'B1', owner: new BlogOwner({ name: 'O1' }) }); const post = new Post({ title: 'Avatar', blog, }); const post2 = new Post({ title: 'Avatar 2', blog, }); await DataStore.save(post); await DataStore.save(post2); await DataStore.delete(Post, post.id); const postAuthorJoins = await DataStore.query(PostAuthorJoin); expect(postAuthorJoins).toHaveLength(0); await DataStore.delete(Post, c => c); await DataStore.delete(Author, c => c); }); test('delete cascade', async () => { const a1 = await DataStore.save(new Author({ name: 'author1' })); const a2 = await DataStore.save(new Author({ name: 'author2' })); const blog = new Blog({ name: 'The Blog', owner, }); const p1 = new Post({ title: 'Post 1', blog, }); const p2 = new Post({ title: 'Post 2', blog, }); const c1 = await DataStore.save(new Comment({ content: 'c1', post: p1 })); const c2 = await DataStore.save(new Comment({ content: 'c2', post: p1 })); await DataStore.save(p1); await DataStore.save(p2); await DataStore.save(blog); await DataStore.delete(BlogOwner, owner.id); expect(await DataStore.query(Blog, blog.id)).toBeUndefined(); expect(await DataStore.query(BlogOwner, owner.id)).toBeUndefined(); expect(await DataStore.query(Post, p1.id)).toBeUndefined(); expect(await DataStore.query(Post, p2.id)).toBeUndefined(); expect(await DataStore.query(Comment, c1.id)).toBeUndefined(); expect(await DataStore.query(Comment, c2.id)).toBeUndefined(); expect(await DataStore.query(Author, a1.id)).toEqual(a1); expect(await DataStore.query(Author, a2.id)).toEqual(a2); const postAuthorJoins = await DataStore.query(PostAuthorJoin); expect(postAuthorJoins).toHaveLength(0); }); test('delete non existent', async () => { const author = new Author({ name: 'author1' }); const deleted = await DataStore.delete(author); expect(deleted).toStrictEqual(author); const fromDB = await AsyncStorage.getItem( getKeyForAsyncStorage(USER, Author.name, author.id) ); expect(fromDB).toBeUndefined(); }); describe('Internal AsyncStorage key schema changes', () => { test('Keys are migrated to the new format with ulid', async () => { setUpSchema(() => { /** * This section makes sure that generated ulids are seeded so they always match the snapshot */ // Small seedable pseudo-random number generator, taken from https://stackoverflow.com/a/19303725/194974 let seed = 1; function random() { const x = Math.sin(seed++) * 10000; return x - Math.floor(x); } const ulid = require('ulid'); const simulatedSeed = 1589482924218; const oldMonotonicFactory = ulid.monotonicFactory; ulid.monotonicFactory = () => () => { return oldMonotonicFactory(random)(simulatedSeed); }; }); const oldData: [ string, string[] ] = require('./AsyncStorage.migration.data.json'); inmemoryMap.clear(); oldData.forEach(([k, v]) => inmemoryMap.set(k, v)); await DataStore.query(Post); const newKeys = await AsyncStorage.getAllKeys(); expect(newKeys).toMatchSnapshot(); }); }); }); function getKeyForAsyncStorage( namespaceName: string, modelName: string, id: string ) { const collectionInMemoryIndex: Map<string, Map<string, string>> = (<any>( AsyncStorageAdapter )).db._collectionInMemoryIndex; const storeName = `${namespaceName}_${modelName}`; const ulid = collectionInMemoryIndex.get(storeName).get(id); return `@AmplifyDatastore::${storeName}::Data::${ulid}::${id}`; }
the_stack
import {parse as parseMDL} from '../../mdl/parse'; import {parse as parseMDX} from '../../mdx/parse'; import {vec3, mat4, quat} from 'gl-matrix'; import {Model, TextureFlags} from '../../model'; import {ModelRenderer} from '../../renderer/modelRenderer'; import {vec3RotateZ} from '../../renderer/util'; import {decode, getImageData} from '../../blp/decode'; import '../common/shim'; let model: Model; let modelRenderer: ModelRenderer; let canvas: HTMLCanvasElement; let gl: WebGLRenderingContext; const pMatrix = mat4.create(); const mvMatrix = mat4.create(); let loadedTextures = 0; let totalTextures = 0; const cleanupNameRegexp = /.*?([^\\/]+)\.\w+$/; let cameraTheta = Math.PI / 4; let cameraPhi = 0; let cameraDistance = 500; let cameraTargetZ = 50; const cameraBasePos: vec3 = vec3.create(); const cameraPos: vec3 = vec3.create(); const cameraTarget: vec3 = vec3.create(); const cameraUp: vec3 = vec3.fromValues(0, 0, 1); const cameraQuat: quat = quat.create(); let start; function updateModel (timestamp: number) { if (!start) { start = timestamp; } const delta = timestamp - start; // delta /= 10; start = timestamp; modelRenderer.update(delta); } function initGL () { if (gl) { return; } try { gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl') as WebGLRenderingContext; gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); } catch (err) { alert(err); } } const cameraPosProjected: vec3 = vec3.create(); const verticalQuat: quat = quat.create(); const fromCameraBaseVec: vec3 = vec3.fromValues(1, 0, 0); function calcCameraQuat () { vec3.set(cameraPosProjected, cameraPos[0], cameraPos[1], 0); vec3.subtract(cameraPos, cameraPos, cameraTarget); vec3.normalize(cameraPosProjected, cameraPosProjected); vec3.normalize(cameraPos, cameraPos); quat.rotationTo(cameraQuat, fromCameraBaseVec, cameraPosProjected); quat.rotationTo(verticalQuat, cameraPosProjected, cameraPos); quat.mul(cameraQuat, verticalQuat, cameraQuat); } function drawScene () { gl.viewport(0, 0, canvas.width, canvas.height); gl.depthMask(true); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(pMatrix, Math.PI / 4 , canvas.width / canvas.height, 0.1, 10000.0); vec3.set( cameraBasePos, Math.cos(cameraTheta) * Math.cos(cameraPhi) * cameraDistance, Math.cos(cameraTheta) * Math.sin(cameraPhi) * cameraDistance, Math.sin(cameraTheta) * cameraDistance ); cameraTarget[2] = cameraTargetZ; // tslint:disable-next-line vec3RotateZ(cameraPos, cameraBasePos, window['angle'] || 0); mat4.lookAt(mvMatrix, cameraPos, cameraTarget, cameraUp); calcCameraQuat(); modelRenderer.setCamera(cameraPos, cameraQuat); modelRenderer.render(mvMatrix, pMatrix); } function tick(timestamp: number) { requestAnimationFrame(tick); updateModel(timestamp); drawScene(); } function loadTexture (src: string, textureName: string, flags: TextureFlags) { const img = new Image(); img.onload = () => { modelRenderer.setTextureImage(textureName, img, flags); handleLoadedTexture(); }; img.src = src; } function handleLoadedTexture (): void { if (++loadedTextures === totalTextures) { requestAnimationFrame(tick); } } /* function parseModel(isBinary: boolean, xhr: XMLHttpRequest): Model { if (isBinary) { return parseMDX(xhr.response as ArrayBuffer); } else { return parseMDL(xhr.responseText); } } */ function processModelLoading () { console.log(model); loadedTextures = totalTextures = 0; modelRenderer = new ModelRenderer(model); initGL(); modelRenderer.initGL(gl); setAnimationList(); } /* function setSampleTextures () { for (let texture of model.Textures) { if (texture.Image) { ++totalTextures; loadTexture(texture.Image, texture.Image, texture.Flags); } } } */ /* function loadModel () { const xhr = new XMLHttpRequest(); const file = 'preview/Footman.mdl'; const isBinary = file.indexOf('.mdx') > -1; if (isBinary) { xhr.responseType = 'arraybuffer'; } xhr.open('GET', file, true); xhr.onreadystatechange = () => { if (xhr.status === 200 && xhr.readyState === XMLHttpRequest.DONE) { model = parseModel(isBinary, xhr); processModelLoading(); setSampleTextures(); } }; xhr.send(); } */ function init() { canvas = document.getElementById('canvas') as HTMLCanvasElement; initControls(); initCameraMove(); initDragDrop(); // loadModel(); updateCanvasSize(); window.addEventListener('resize', updateCanvasSize); } function initControls () { const inputColor = document.getElementById('color') as HTMLInputElement; inputColor.addEventListener('input', () => { const val = inputColor.value.slice(1); const arr = vec3.fromValues( parseInt(val.slice(0, 2), 16) / 255, parseInt(val.slice(2, 4), 16) / 255, parseInt(val.slice(4, 6), 16) / 255 ); modelRenderer.setTeamColor(arr); }); const select = document.getElementById('select') as HTMLSelectElement; select.addEventListener('input', () => { modelRenderer.setSequence(parseInt(select.value, 10)); }); const inputZ = document.getElementById('targetZ') as HTMLInputElement; inputZ.addEventListener('input', () => { cameraTargetZ = parseInt(inputZ.value, 10); }); const inputDistance = document.getElementById('distance') as HTMLInputElement; inputDistance.addEventListener('input', () => { cameraDistance = parseInt(inputDistance.value, 10); }); } function initCameraMove () { let down = false; let downX, downY; function coords (event) { const list = (event.changedTouches && event.changedTouches.length ? event.changedTouches : event.touches) || [event]; return [list[0].pageX, list[0].pageY]; } function updateCameraDistance (distance: number): void { cameraDistance = distance; if (cameraDistance > 1000) { cameraDistance = 1000; } if (cameraDistance < 100) { cameraDistance = 100; } (document.getElementById('distance') as HTMLInputElement).value = String(cameraDistance); } function pointerDown (event) { if (event.target !== canvas) { return; } down = true; [downX, downY] = coords(event); } function pointerMove (event) { if (!down) { return; } if (event.type === 'touchmove') { event.preventDefault(); } if (event.changedTouches && event.changedTouches.length > 1 || event.touches && event.touches.length > 1) { return; } const [x, y] = coords(event); cameraPhi += -1 * (x - downX) * 0.01; cameraTheta += (y - downY) * 0.01; if (cameraTheta > Math.PI / 2 * 0.98) { cameraTheta = Math.PI / 2 * 0.98; } if (cameraTheta < 0) { cameraTheta = 0; } downX = x; downY = y; } function pointerUp () { down = false; } function wheel (event) { updateCameraDistance(cameraDistance * (1 - event.deltaY / 30)); } let startCameraDistance: number; function gestureStart () { startCameraDistance = cameraDistance; } function gestureChange (event) { updateCameraDistance(startCameraDistance * (1 / event.scale)); } document.addEventListener('mousedown', pointerDown); document.addEventListener('touchstart', pointerDown); document.addEventListener('mousemove', pointerMove); document.addEventListener('touchmove', pointerMove); document.addEventListener('mouseup', pointerUp); document.addEventListener('touchend', pointerUp); document.addEventListener('touchcancel', pointerUp); document.addEventListener('wheel', wheel); document.addEventListener('gesturestart', gestureStart); document.addEventListener('gesturechange', gestureChange); } function updateCanvasSize () { const width = canvas.parentElement.offsetWidth; const height = canvas.parentElement.offsetHeight; const dpr = window.devicePixelRatio || 1; canvas.width = width * dpr; canvas.height = height * dpr; } function encode (html) { return html.replace(/</g, '&lt;').replace(/>/g, '&gt;'); } function setAnimationList () { let list: any[] = model.Sequences.map(seq => seq.Name); if (list.length === 0) { list = ['None']; } const select = document.getElementById('select') as HTMLSelectElement; select.innerHTML = list.map((item, index) => `<option value="${index}">${encode(item)}</option>`).join(''); } function setDragDropTextures () { const texturesContainer = document.querySelector('.drag-textures'); texturesContainer.innerHTML = ''; for (const texture of model.Textures) { if (texture.Image) { const row = document.createElement('div'); row.className = 'drag'; row.textContent = texture.Image; row.setAttribute('data-texture', texture.Image); row.setAttribute('data-texture-flags', String(texture.Flags)); texturesContainer.appendChild(row); } } } function initDragDrop () { const container = document.querySelector('.container'); let dropTarget; container.addEventListener('dragenter', function onDragEnter (event) { let target = event.target as HTMLElement; if (dropTarget && dropTarget !== event.target && dropTarget.classList) { dropTarget.classList.remove('drag_hovered'); } if (!target.classList) { target = target.parentElement; } dropTarget = target; if (target && target.classList && target.classList.contains('drag')) { target.classList.add('drag_hovered'); } container.classList.add('container_drag'); event.preventDefault(); }); container.addEventListener('dragleave', function onDragLeave (event) { if (event.target === dropTarget) { container.classList.remove('container_drag'); if (dropTarget && dropTarget.classList) { dropTarget.classList.remove('drag_hovered'); } } }); container.addEventListener('dragover', function onDragLeave (event: DragEvent) { event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; }); const dropModel = (file, textures) => { const reader = new FileReader(); const isMDX = file.name.indexOf('.mdx') > -1; reader.onload = () => { try { if (isMDX) { model = parseMDX(reader.result as ArrayBuffer); } else { model = parseMDL(reader.result as string); } } catch (err) { console.error(err); // showError(err); return; } processModelLoading(); setTextures(textures); setDragDropTextures(); }; if (isMDX) { reader.readAsArrayBuffer(file); } else { reader.readAsText(file); } }; const dropTexture = (file, textureName: string, textureFlags: TextureFlags) => { const reader = new FileReader(); const isBLP = file.name.indexOf('.blp') > -1; reader.onload = () => { if (isBLP) { const blp = decode(reader.result as ArrayBuffer); console.log(file.name, blp); modelRenderer.setTextureImageData( textureName, blp.mipmaps.map((_mipmap, i) => getImageData(blp, i)), textureFlags ); } else { const img = new Image(); img.onload = () => { console.log(file.name, img); modelRenderer.setTextureImage(textureName, img, textureFlags); }; img.src = reader.result as string; } handleLoadedTexture(); }; if (isBLP) { reader.readAsArrayBuffer(file); } else { reader.readAsDataURL(file); } }; container.addEventListener('drop', function onDrop (event: DragEvent) { event.preventDefault(); container.classList.remove('container_drag'); container.classList.add('container_custom'); if (!dropTarget) { return; } dropTarget.classList.remove('drag_hovered'); const files = event.dataTransfer.files; if (!files || !files.length) { return; } if (dropTarget.getAttribute('data-texture')) { dropTexture(files[0], dropTarget.getAttribute('data-texture'), Number(dropTarget.getAttribute('data-texture-flags'))); } else { let modelFile; for (let i = 0; i < files.length; ++i) { const file = files[i]; if (file.name.indexOf('.mdl') > -1 || file.name.indexOf('.mdx') > -1) { modelFile = file; break; } } if (modelFile) { const textures = {}; for (let i = 0; i < files.length; ++i) { const file = files[i], name = file.name.replace(cleanupNameRegexp, '$1'); if (file.name.indexOf('.mdl') > -1 || file.name.indexOf('.mdx') > -1) { continue; } textures[name] = file; } dropModel(modelFile, textures); } } }); function setTextures (textures) { for (const texture of model.Textures) { if (texture.Image) { ++totalTextures; const cleanupName = texture.Image.replace(cleanupNameRegexp, '$1'); if (cleanupName in textures) { dropTexture(textures[cleanupName], texture.Image, texture.Flags); } else { loadTexture('empty.png', texture.Image, 0); } } } } } document.addEventListener('DOMContentLoaded', init);
the_stack
import Client from '../Client'; import MaxToolbar from '../gui/MaxToolbar'; import Geometry from '../view/geometry/Geometry'; import { convertPoint } from '../util/styleUtils'; import InternalEvent from '../view/event/InternalEvent'; import { getClientX, getClientY } from '../util/EventUtils'; import { makeDraggable } from '../util/gestureUtils'; import Editor from './Editor'; import Cell from '../view/cell/Cell'; import CellArray from '../view/cell/CellArray'; import { Graph } from '../view/Graph'; import EventObject from '../view/event/EventObject'; import ObjectCodec from '../serialization/ObjectCodec'; import CodecRegistry from '../serialization/CodecRegistry'; import { getChildNodes, getTextContent } from '../util/domUtils'; import { NODETYPE } from '../util/Constants'; import Translations from '../util/Translations'; import MaxLog from '../gui/MaxLog'; import Codec from '../serialization/Codec'; import { DropHandler } from 'src/view/other/DragSource'; /** * Toolbar for the editor. This modifies the state of the graph * or inserts new cells upon mouse clicks. * * @Example: * * Create a toolbar with a button to copy the selection into the clipboard, * and a combo box with one action to paste the selection from the clipboard * into the graph. * * ``` * var toolbar = new EditorToolbar(container, editor); * toolbar.addItem('Copy', null, 'copy'); * * var combo = toolbar.addActionCombo('More actions...'); * toolbar.addActionOption(combo, 'Paste', 'paste'); * ``` * * @Codec: * * This class uses the {@link DefaultToolbarCodec} to read configuration * data into an existing instance. See {@link DefaultToolbarCodec} for a * description of the configuration format. */ export class EditorToolbar { constructor(container: HTMLElement | null=null, editor: Editor | null=null) { this.editor = editor; if (container != null && editor != null) { this.init(container); } } /** * Reference to the enclosing {@link Editor}. */ editor: Editor | null; /** * Holds the internal {@link MaxToolbar}. */ toolbar: MaxToolbar | null = null; /** * Reference to the function used to reset the {@link toolbar}. */ resetHandler: Function | null = null; /** * Defines the spacing between existing and new vertices in gridSize units when a new vertex is dropped on an existing cell. Default is 4 (40 pixels). * * @Default is 4 */ spacing: number = 4; /** * Specifies if elements should be connected if new cells are dropped onto connectable elements. * * @Default is false. */ connectOnDrop: boolean = false; /** * Constructs the {@link toolbar} for the given container and installs a listener that updates the {@link Editor.insertFunction} on {@link editor} if an item is selected in the toolbar. This assumes that {@link editor} is not null. */ init(container: HTMLElement): void { if (container != null) { this.toolbar = new MaxToolbar(container); // Installs the insert function in the editor if an item is // selected in the toolbar this.toolbar.addListener(InternalEvent.SELECT, (sender: Element, evt: EventObject) => { const funct = evt.getProperty('function'); if (funct != null) { (<Editor>this.editor).insertFunction = () => { funct.apply(this, [container]); (<MaxToolbar>this.toolbar).resetMode(); }; } else { (<Editor>this.editor).insertFunction = null; } }); // Resets the selected tool after a doubleclick or escape keystroke this.resetHandler = () => { if (this.toolbar != null) { this.toolbar.resetMode(true); } }; (<Editor>this.editor).graph.addListener(InternalEvent.DOUBLE_CLICK, this.resetHandler); (<Editor>this.editor).addListener(InternalEvent.ESCAPE, this.resetHandler); } } /** * Adds a new item that executes the given action in {@link editor}. The title, * icon and pressedIcon are used to display the toolbar item. * * @param title - String that represents the title (tooltip) for the item. * @param icon - URL of the icon to be used for displaying the item. * @param action - Name of the action to execute when the item is clicked. * @param pressed - Optional URL of the icon for the pressed state. */ addItem(title: string, icon: string, action: string, pressed?: string): any { const clickHandler = () => { if (action != null && action.length > 0) { (<Editor>this.editor).execute(action); } }; return (<MaxToolbar>this.toolbar).addItem(title, icon, clickHandler, pressed); } /** * Adds a vertical separator using the optional icon. * * @param icon - Optional URL of the icon that represents the vertical separator. Default is {@link Client.imageBasePath} + ‘/separator.gif’. */ addSeparator(icon?: string): void { icon = icon || `${Client.imageBasePath}/separator.gif`; (<MaxToolbar>this.toolbar).addSeparator(icon); } /** * Helper method to invoke {@link MaxToolbar.addCombo} on toolbar and return the resulting DOM node. */ addCombo(): HTMLElement { return (<MaxToolbar>this.toolbar).addCombo(); } /** * Helper method to invoke <MaxToolbar.addActionCombo> on <toolbar> using * the given title and return the resulting DOM node. * * @param title String that represents the title of the combo. */ addActionCombo(title: string) { return (<MaxToolbar>this.toolbar).addActionCombo(title); } /** * Binds the given action to a option with the specified label in the given combo. Combo is an object returned from an earlier call to {@link addCombo} or {@link addActionCombo}. * * @param combo - DOM node that represents the combo box. * @param title - String that represents the title of the combo. * @param action - Name of the action to execute in {@link editor}. */ addActionOption(combo: HTMLSelectElement, title: string, action: string): void { const clickHandler = () => { (<Editor>this.editor).execute(action); }; this.addOption(combo, title, clickHandler); } /** * Helper method to invoke {@link MaxToolbar.addOption} on {@link toolbar} and return the resulting DOM node that represents the option. * * @param combo - DOM node that represents the combo box. * @param title - String that represents the title of the combo. * @param value - Object that represents the value of the option. */ addOption(combo: HTMLSelectElement, title: string, value: string | ((evt: any) => void) | null): HTMLElement { return (<MaxToolbar>this.toolbar).addOption(combo, title, value); } /** * Creates an item for selecting the given mode in the {@link editor}'s graph. * Supported modenames are select, connect and pan. * * @param title - String that represents the title of the item. * @param icon - URL of the icon that represents the item. * @param mode - String that represents the mode name to be used in {@link Editor.setMode}. * @param pressed - Optional URL of the icon that represents the pressed state. * @param funct - Optional JavaScript function that takes the {@link Editor} as the first and only argument that is executed after the mode has been selected. */ addMode( title: string, icon: string, mode: string, pressed: string | null=null, funct: Function | null=null ): any { const clickHandler = () => { (<Editor>this.editor).setMode(mode); if (funct != null) { funct((<Editor>this.editor)); } }; return (<MaxToolbar>this.toolbar).addSwitchMode(title, icon, clickHandler, pressed); } /** * Creates an item for inserting a clone of the specified prototype cell into * the <editor>'s graph. The ptype may either be a cell or a function that * returns a cell. * * @param title String that represents the title of the item. * @param icon URL of the icon that represents the item. * @param ptype Function or object that represents the prototype cell. If ptype * is a function then it is invoked with no arguments to create new * instances. * @param pressed Optional URL of the icon that represents the pressed state. * @param insert Optional JavaScript function that handles an insert of the new * cell. This function takes the <Editor>, new cell to be inserted, mouse * event and optional <Cell> under the mouse pointer as arguments. * @param toggle Optional boolean that specifies if the item can be toggled. * Default is true. */ addPrototype( title: string, icon: string, ptype: Function | Cell, pressed: string, insert: (editor: Editor, cell: Cell, me: MouseEvent, cellUnderMousePointer?: Cell | null) => void, toggle: boolean=true ): HTMLImageElement | HTMLButtonElement { // Creates a wrapper function that is in charge of constructing // the new cell instance to be inserted into the graph const factory = () => { if (typeof ptype === 'function') { return ptype(); } if (ptype != null) { return (<Editor>this.editor).graph.cloneCell(ptype); } return null; }; // Defines the function for a click event on the graph // after this item has been selected in the toolbar const clickHandler = (evt: MouseEvent, cell: Cell | null) => { if (typeof insert === 'function') { insert((<Editor>this.editor), factory(), evt, cell); } else { this.drop(factory(), evt, cell); } (<MaxToolbar>this.toolbar).resetMode(); InternalEvent.consume(evt); }; const img = (<MaxToolbar>this.toolbar).addMode(title, icon, clickHandler, pressed, null, toggle); // Creates a wrapper function that calls the click handler without // the graph argument const dropHandler: DropHandler = (graph: Graph, evt: MouseEvent, cell: Cell | null) => { clickHandler(evt, cell); }; this.installDropHandler(img, dropHandler); return img; } /** * Handles a drop from a toolbar item to the graph. The given vertex * represents the new cell to be inserted. This invokes {@link insert} or * {@link connect} depending on the given target cell. * * @param vertex - {@link Cell} to be inserted. * @param evt - Mouse event that represents the drop. * @param target - Optional {@link Cell} that represents the drop target. */ drop(vertex: Cell, evt: MouseEvent, target: Cell | null=null): void { const { graph } = (<Editor>this.editor); const model = graph.getDataModel(); if ( target == null || target.isEdge() || !this.connectOnDrop || !target.isConnectable() ) { while (target != null && !graph.isValidDropTarget(target, new CellArray(vertex), evt)) { target = target.getParent(); } this.insert(vertex, evt, target); } else { this.connect(vertex, evt, target); } } /** * Handles a drop by inserting the given vertex into the given parent cell * or the default parent if no parent is specified. * * @param vertex - {@link Cell} to be inserted. * @param evt - Mouse event that represents the drop. * @param target - Optional {@link Cell} that represents the parent. */ insert(vertex: Cell, evt: MouseEvent, target: Cell | null=null): any { const { graph } = (<Editor>this.editor); if (graph.canImportCell(vertex)) { const x = getClientX(evt); const y = getClientY(evt); const pt = convertPoint(graph.container, x, y); // Splits the target edge or inserts into target group if (target && graph.isSplitEnabled() && graph.isSplitTarget(target, new CellArray(vertex), evt)) { return graph.splitEdge(target, new CellArray(vertex), null, pt.x, pt.y); } return (<Editor>this.editor).addVertex(target, vertex, pt.x, pt.y); } return null; } /** * Handles a drop by connecting the given vertex to the given source cell. * * @param vertex - {@link Cell} to be inserted. * @param evt - Mouse event that represents the drop. * @param source - Optional {@link Cell} that represents the source terminal. */ connect(vertex: Cell, evt: MouseEvent, source: Cell | null=null): void { const { graph } = <Editor>this.editor; const model = graph.getDataModel(); if ( source != null && vertex.isConnectable() && graph.isEdgeValid(null, source, vertex) ) { let edge = null; model.beginUpdate(); try { const geo = <Geometry>source.getGeometry(); const g = (<Geometry>vertex.getGeometry()).clone(); // Moves the vertex away from the drop target that will // be used as the source for the new connection g.x = geo.x + (geo.width - g.width) / 2; g.y = geo.y + (geo.height - g.height) / 2; const step = this.spacing * graph.gridSize; const dist = source.getDirectedEdgeCount(true) * 20; if ((<Editor>this.editor).horizontalFlow) { g.x += (g.width + geo.width) / 2 + step + dist; } else { g.y += (g.height + geo.height) / 2 + step + dist; } vertex.setGeometry(g); // Fires two add-events with the code below - should be fixed // to only fire one add event for both inserts const parent = source.getParent(); graph.addCell(vertex, parent); graph.constrainChild(vertex); // Creates the edge using the editor instance and calls // the second function that fires an add event edge = (<Editor>this.editor).createEdge(source, vertex); if (edge.getGeometry() == null) { const edgeGeometry = new Geometry(); edgeGeometry.relative = true; model.setGeometry(edge, edgeGeometry); } graph.addEdge(edge, parent, source, vertex); } finally { model.endUpdate(); } graph.setSelectionCells(new CellArray(vertex, edge)); graph.scrollCellToVisible(vertex); } } /** * Makes the given img draggable using the given function for handling a drop event. * * @param img - DOM node that represents the image. * @param dropHandler - Function that handles a drop of the image. */ installDropHandler(img: HTMLElement, dropHandler: DropHandler): void { const sprite = document.createElement('img'); sprite.setAttribute('src', <string>img.getAttribute('src')); // Handles delayed loading of the images const loader = (evt: InternalEvent) => { // Preview uses the image node with double size. Later this can be // changed to use a separate preview and guides, but for this the // dropHandler must use the additional x- and y-arguments and the // dragsource which makeDraggable returns much be configured to // use guides via mxDragSource.isGuidesEnabled. sprite.style.width = `${2 * img.offsetWidth}px`; sprite.style.height = `${2 * img.offsetHeight}px`; makeDraggable(img, (<Editor>this.editor).graph, dropHandler, sprite); InternalEvent.removeListener(sprite, 'load', loader); }; } /** * Destroys the {@link toolbar} associated with this object and removes all installed listeners. * This does normally not need to be called, the {@link toolbar} is destroyed automatically when the window unloads (in IE) by {@link Editor}. */ destroy(): void { if (this.resetHandler != null) { (<Editor>this.editor).graph.removeListener(this.resetHandler); (<Editor>this.editor).removeListener(this.resetHandler); this.resetHandler = null; } if (this.toolbar != null) { this.toolbar.destroy(); this.toolbar = null; } } } /** * Custom codec for configuring <EditorToolbar>s. This class is created * and registered dynamically at load time and used implicitly via * <Codec> and the <CodecRegistry>. This codec only reads configuration * data for existing toolbars handlers, it does not encode or create toolbars. */ export class EditorToolbarCodec extends ObjectCodec { constructor() { super(new EditorToolbar()); } /** * Returns null. */ encode(enc: any, obj: any) { return null; } /** * Reads a sequence of the following child nodes * and attributes: * * Child Nodes: * * add - Adds a new item to the toolbar. See below for attributes. * separator - Adds a vertical separator. No attributes. * hr - Adds a horizontal separator. No attributes. * br - Adds a linefeed. No attributes. * * Attributes: * * as - Resource key for the label. * action - Name of the action to execute in enclosing editor. * mode - Modename (see below). * template - Template name for cell insertion. * style - Optional style to override the template style. * icon - Icon (relative/absolute URL). * pressedIcon - Optional icon for pressed state (relative/absolute URL). * id - Optional ID to be used for the created DOM element. * toggle - Optional 0 or 1 to disable toggling of the element. Default is * 1 (true). * * The action, mode and template attributes are mutually exclusive. The * style can only be used with the template attribute. The add node may * contain another sequence of add nodes with as and action attributes * to create a combo box in the toolbar. If the icon is specified then * a list of the child node is expected to have its template attribute * set and the action is ignored instead. * * Nodes with a specified template may define a function to be used for * inserting the cloned template into the graph. Here is an example of such * a node: * * ```javascript * <add as="Swimlane" template="swimlane" icon="images/swimlane.gif"><![CDATA[ * function (editor, cell, evt, targetCell) * { * let pt = mxUtils.convertPoint( * editor.graph.container, mxEvent.getClientX(evt), * mxEvent.getClientY(evt)); * return editor.addVertex(targetCell, cell, pt.x, pt.y); * } * ]]></add> * ``` * * In the above function, editor is the enclosing <Editor> instance, cell * is the clone of the template, evt is the mouse event that represents the * drop and targetCell is the cell under the mousepointer where the drop * occurred. The targetCell is retrieved using {@link Graph#getCellAt}. * * Futhermore, nodes with the mode attribute may define a function to * be executed upon selection of the respective toolbar icon. In the * example below, the default edge style is set when this specific * connect-mode is activated: * * ```javascript * <add as="connect" mode="connect"><![CDATA[ * function (editor) * { * if (editor.defaultEdge != null) * { * editor.defaultEdge.style = 'straightEdge'; * } * } * ]]></add> * ``` * * Both functions require <DefaultToolbarCodec.allowEval> to be set to true. * * Modes: * * select - Left mouse button used for rubberband- & cell-selection. * connect - Allows connecting vertices by inserting new edges. * pan - Disables selection and switches to panning on the left button. * * Example: * * To add items to the toolbar: * * ```javascript * <EditorToolbar as="toolbar"> * <add as="save" action="save" icon="images/save.gif"/> * <br/><hr/> * <add as="select" mode="select" icon="images/select.gif"/> * <add as="connect" mode="connect" icon="images/connect.gif"/> * </EditorToolbar> * ``` */ decode(dec: Codec, _node: Element, into: any) { if (into != null) { const editor: Editor = into.editor; let node: Element | null = <Element | null>_node.firstChild; while (node != null) { if (node.nodeType === NODETYPE.ELEMENT) { if (!this.processInclude(dec, node, into)) { if (node.nodeName === 'separator') { into.addSeparator(); } else if (node.nodeName === 'br') { into.toolbar.addBreak(); } else if (node.nodeName === 'hr') { into.toolbar.addLine(); } else if (node.nodeName === 'add') { let as = <string>node.getAttribute('as'); as = Translations.get(as) || as; const icon = node.getAttribute('icon'); const pressedIcon = node.getAttribute('pressedIcon'); const action = node.getAttribute('action'); const mode = node.getAttribute('mode'); const template = node.getAttribute('template'); const toggle = node.getAttribute('toggle') != '0'; const text = getTextContent(<Text><unknown>node); let elt = null; let funct: any; if (action != null) { elt = into.addItem(as, icon, action, pressedIcon); } else if (mode != null) { funct = EditorToolbarCodec.allowEval ? eval(text) : null; elt = into.addMode(as, icon, mode, pressedIcon, funct); } else if ( template != null || (text != null && text.length > 0) ) { let cell = template ? editor.templates[template] : null; const style = node.getAttribute('style'); if (cell != null && style != null) { cell = editor.graph.cloneCell(cell); cell.setStyle(style); } let insertFunction = null; if ( text != null && text.length > 0 && EditorToolbarCodec.allowEval ) { insertFunction = eval(text); } elt = into.addPrototype( as, icon, cell, pressedIcon, insertFunction, toggle ); } else { const children = getChildNodes(node); if (children.length > 0) { if (icon == null) { const combo = into.addActionCombo(as); for (let i = 0; i < children.length; i += 1) { const child = <Element>children[i]; if (child.nodeName === 'separator') { into.addOption(combo, '---'); } else if (child.nodeName === 'add') { const lab = child.getAttribute('as'); const act = child.getAttribute('action'); into.addActionOption(combo, lab, act); } } } else { let select: HTMLSelectElement; const create = () => { const template = editor.templates[select.value]; if (template != null) { const clone = template.clone(); // @ts-ignore const style = select.options[select.selectedIndex].cellStyle; if (style != null) { clone.setStyle(style); } return clone; } MaxLog.warn(`Template ${template} not found`); return null; }; const img = into.addPrototype( as, icon, create, null, null, toggle ); select = into.addCombo(); // Selects the toolbar icon if a selection change // is made in the corresponding combobox. InternalEvent.addListener(select, 'change', () => { into.toolbar.selectMode(img, (evt: MouseEvent) => { const pt = convertPoint( editor.graph.container, getClientX(evt), getClientY(evt) ); return editor.addVertex(null, funct(), pt.x, pt.y); }); into.toolbar.noReset = false; }); // Adds the entries to the combobox for (let i = 0; i < children.length; i += 1) { const child = <Element>children[i]; if (child.nodeName === 'separator') { into.addOption(select, '---'); } else if (child.nodeName === 'add') { const lab = child.getAttribute('as'); const tmp = child.getAttribute('template'); const option = into.addOption( select, lab, tmp || template ); option.cellStyle = child.getAttribute('style'); } } } } } // Assigns an ID to the created element to access it later. if (elt != null) { const id = node.getAttribute('id'); if (id != null && id.length > 0) { elt.setAttribute('id', id); } } } } } node = <Element | null>node.nextSibling; } } return into; } } CodecRegistry.register(new EditorToolbarCodec()); export default EditorToolbar;
the_stack
import { AuthStatus, Base, ClerkBackendAPI, ClerkFetcher, createGetToken, createSignedOutState, JWTPayload, } from '@clerk/backend-core'; import { ServerGetToken } from '@clerk/types'; import { Crypto, CryptoKey } from '@peculiar/webcrypto'; import Cookies from 'cookies'; import deepmerge from 'deepmerge'; import type { NextFunction, Request, Response } from 'express'; import got, { OptionsOfUnknownResponseBody } from 'got'; import jwt from 'jsonwebtoken'; import jwks, { JwksClient } from 'jwks-rsa'; import querystring from 'querystring'; import { SupportMessages } from './constants/SupportMessages'; import { LIB_NAME, LIB_VERSION } from './info'; import { decodeBase64, toSPKIDer } from './utils/crypto'; import { ClerkServerError } from './utils/Errors'; // utils import Logger from './utils/Logger'; const defaultApiKey = process.env.CLERK_API_KEY || ''; const defaultJWTKey = process.env.CLERK_JWT_KEY; const defaultApiVersion = process.env.CLERK_API_VERSION || 'v1'; const defaultServerApiUrl = process.env.CLERK_API_URL || 'https://api.clerk.dev'; const JWKS_MAX_AGE = 3600000; // 1 hour const packageRepo = 'https://github.com/clerkinc/clerk-sdk-node'; export type MiddlewareOptions = { onError?: Function; authorizedParties?: string[]; jwtKey?: string; }; export type WithAuthProp<T> = T & { auth: { sessionId: string | null; userId: string | null; getToken: ServerGetToken; claims: Record<string, unknown> | null; }; }; export type RequireAuthProp<T> = T & { auth: { sessionId: string; userId: string; getToken: ServerGetToken; claims: Record<string, unknown>; }; }; const crypto = new Crypto(); const importKey = async (jwk: JsonWebKey, algorithm: Algorithm) => { return await crypto.subtle.importKey('jwk', jwk, algorithm, true, ['verify']); }; const verifySignature = async ( algorithm: Algorithm, key: CryptoKey, signature: Uint8Array, data: Uint8Array ) => { return await crypto.subtle.verify(algorithm, key, signature, data); }; export default class Clerk extends ClerkBackendAPI { base: Base; jwtKey?: string; httpOptions: OptionsOfUnknownResponseBody; _jwksClient: JwksClient; // singleton instance static _instance: Clerk; constructor({ apiKey = defaultApiKey, jwtKey = defaultJWTKey, serverApiUrl = defaultServerApiUrl, apiVersion = defaultApiVersion, httpOptions = {}, jwksCacheMaxAge = JWKS_MAX_AGE, }: { apiKey?: string; jwtKey?: string; serverApiUrl?: string; apiVersion?: string; httpOptions?: OptionsOfUnknownResponseBody; jwksCacheMaxAge?: number; } = {}) { const fetcher: ClerkFetcher = ( url, { method, authorization, contentType, userAgent, body } ) => { const finalHTTPOptions = deepmerge(this.httpOptions, { method, responseType: contentType === 'text/html' ? 'text' : 'json', headers: { authorization, 'Content-Type': contentType, 'User-Agent': userAgent, 'X-Clerk-SDK': `node/${LIB_VERSION}`, }, // @ts-ignore ...(body && { body: querystring.stringify(body) }), }) as OptionsOfUnknownResponseBody; return got(url, finalHTTPOptions).then((data) => data.body); }; super({ apiKey, apiVersion, serverApiUrl, libName: LIB_NAME, libVersion: LIB_VERSION, packageRepo, fetcher, }); if (!apiKey) { throw Error(SupportMessages.API_KEY_NOT_FOUND); } this.httpOptions = httpOptions; this.jwtKey = jwtKey; this._jwksClient = jwks({ jwksUri: `${serverApiUrl}/${apiVersion}/jwks`, requestHeaders: { Authorization: `Bearer ${apiKey}`, }, timeout: 5000, cache: true, cacheMaxAge: jwksCacheMaxAge, }); const loadCryptoKey = async (token: string) => { const decoded = jwt.decode(token, { complete: true }); if (!decoded) { throw new Error(`Failed to decode token: ${token}`); } const signingKey = await this._jwksClient.getSigningKey( decoded.header.kid ); const pubKey = signingKey.getPublicKey(); return await crypto.subtle.importKey( 'spki', toSPKIDer(pubKey), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256', }, true, ['verify'] ); }; /** Base initialization */ // TODO: More comprehensive base initialization this.base = new Base( importKey, verifySignature, decodeBase64, loadCryptoKey ); } async verifyToken( token: string, authorizedParties?: string[] ): Promise<JWTPayload> { const decoded = jwt.decode(token, { complete: true }); if (!decoded) { throw new Error(`Failed to verify token: ${token}`); } const key = await this._jwksClient.getSigningKey(decoded.header.kid); const verified = jwt.verify(token, key.getPublicKey(), { algorithms: ['RS256'], }) as JWTPayload; if (typeof verified === 'string') { throw new Error('Malformed token'); } if (!verified.iss || !verified.iss.startsWith('https://clerk')) { throw new Error(`Issuer is invalid: ${verified.iss}`); } if (verified.azp && authorizedParties && authorizedParties.length > 0) { if (!authorizedParties.includes(verified.azp)) { throw new Error(`Authorized party is invalid: ${verified.azp}`); } } return verified; } // For use as singleton, always returns the same instance static getInstance(): Clerk { if (!this._instance) { this._instance = new Clerk(); } return this._instance; } // Middlewares // defaultOnError swallows the error defaultOnError(error: Error & { data: any }) { Logger.warn(error.message); (error.data || []).forEach((serverError: ClerkServerError) => { Logger.warn(serverError.longMessage); }); } // strictOnError returns the error so that Express will halt the request chain strictOnError(error: Error & { data: any }) { Logger.error(error.message); (error.data || []).forEach((serverError: ClerkServerError) => { Logger.error(serverError.longMessage); }); return error; } expressWithAuth( { onError, authorizedParties, jwtKey }: MiddlewareOptions = { onError: this.defaultOnError, } ): (req: Request, res: Response, next: NextFunction) => Promise<void> { function signedOut() { throw new Error('Unauthenticated'); } async function authenticate( this: Clerk, req: Request, res: Response, next: NextFunction ): Promise<any> { try { const cookies = new Cookies(req, res); const cookieToken = cookies.get('__session') as string; const headerToken = req.headers.authorization?.replace('Bearer ', ''); const { status, interstitial, sessionClaims, errorReason } = await this.base.getAuthState({ cookieToken, headerToken, clientUat: cookies.get('__client_uat') as string, origin: req.headers.origin, host: req.headers.host as string, forwardedPort: req.headers['x-forwarded-port'] as string, forwardedHost: req.headers['x-forwarded-host'] as string, referrer: req.headers.referer, userAgent: req.headers['user-agent'] as string, authorizedParties, jwtKey: jwtKey || this.jwtKey, fetchInterstitial: () => this.fetchInterstitial(), }); errorReason && res.setHeader('Auth-Result', errorReason); if (status === AuthStatus.SignedOut) { return signedOut(); } if (status === AuthStatus.SignedIn) { // @ts-expect-error req.auth = { sessionId: sessionClaims?.sid, userId: sessionClaims?.sub, getToken: createGetToken({ headerToken, cookieToken, sessionId: sessionClaims?.sid, fetcher: (...args) => this.sessions.getToken(...args), }), claims: sessionClaims, }; return next(); } res.writeHead(401, { 'Content-Type': 'text/html' }); res.write(interstitial); res.end(); } catch (error) { // Auth object will be set to the signed out auth state // @ts-expect-error req.auth = { userId: null, sessionId: null, getToken: createSignedOutState().getToken, claims: null, }; // Call onError if provided if (!onError) { return next(); } const err = await onError(error); if (err) { next(err); } else { next(); } } } return authenticate.bind(this); } expressRequireAuth( options: MiddlewareOptions = { onError: this.strictOnError, } ) { return this.expressWithAuth(options); } // Credits to https://nextjs.org/docs/api-routes/api-middlewares // Helper method to wait for a middleware to execute before continuing // And to throw an error when an error happens in a middleware // @ts-ignore private _runMiddleware(req, res, fn) { return new Promise((resolve, reject) => { // @ts-ignore fn(req, res, (result) => { if (result instanceof Error) { return reject(result); } return resolve(result); }); }); } // Set the session on the request and then call provided handler withAuth( handler: Function, options: MiddlewareOptions = { onError: this.defaultOnError, } ) { return async ( req: WithAuthProp<Request>, res: Response, next?: NextFunction ) => { try { await this._runMiddleware(req, res, this.expressWithAuth(options)); return handler(req, res, next); } catch (error) { // @ts-ignore const errorData = error.data || { error: error.message }; // @ts-ignore res.statusCode = error.statusCode || 401; /** * Res.json is available in express-like environments. * Res.send is available in express-like but also Fastify. */ res.json ? res.json(errorData) : res.send(errorData); res.end(); } }; } // Stricter version, short-circuits if session can't be determined requireAuth( handler: Function, options: MiddlewareOptions = { onError: this.strictOnError, } ) { return this.withAuth(handler, options); } }
the_stack
import Unit from './unit.js'; import { curry1, isVoid, safeToString } from '../-private/utils.js'; /** Discriminant for {@linkcode Ok} and {@linkcode Err} variants of the {@linkcode Result} type. You can use the discriminant via the `variant` property of `Result` instances if you need to match explicitly on it. */ export const Variant = { Ok: 'Ok', Err: 'Err', } as const; export type Variant = keyof typeof Variant; export interface OkJSON<T> { variant: 'Ok'; value: T; } export interface ErrJSON<E> { variant: 'Err'; error: E; } export type ResultJSON<T, E> = OkJSON<T> | ErrJSON<E>; type Repr<T, E> = [tag: 'Ok', value: T] | [tag: 'Err', error: E]; // Defines the *implementation*, but not the *types*. See the exports below. class ResultImpl<T, E> { private constructor(private repr: Repr<T, E>) {} /** Create an instance of {@linkcode Ok}. Note: While you *may* create the {@linkcode Result} type via normal JavaScript class construction, it is not recommended for the functional style for which the library is intended. Instead, use {@linkcode ok}. ```ts // Avoid: const aString = new Result.Ok('characters'); // Prefer: const aString = Result.ok('characters); ``` Note that you may explicitly pass {@linkcode Unit.Unit Unit} to the {@linkcode Ok} constructor to create a `Result<Unit, E>`. However, you may *not* call the `Ok` constructor with `null` or `undefined` to get that result (the type system won't allow you to construct it that way). Instead, for convenience, you can simply call {@linkcode ok}, which will construct the type correctly. @param value The value to wrap in an `Ok`. */ static ok<T, E>(): Result<Unit, E>; static ok<T, E>(value: T): Result<T, E>; static ok<T, E>(value?: T): Result<Unit, E> | Result<T, E> { return isVoid(value) ? (new ResultImpl<Unit, E>(['Ok', Unit]) as Result<Unit, E>) : (new ResultImpl<T, E>(['Ok', value]) as Result<T, E>); } /** Create an instance of {@linkcode Err}. Note: While you *may* create the {@linkcode Result} type via normal JavaScript class construction, it is not recommended for the functional style for which the library is intended. Instead, use {@linkcode err}. ```ts // Avoid: const anErr = new Result.Err('alas, failure'); // Prefer: const anErr = Result.err('alas, failure'); ``` @param error The value to wrap in an `Err`. */ static err<T, E>(): Result<T, Unit>; static err<T, E>(error: E): Result<T, E>; static err<T, E>(error?: E): Result<T, Unit> | Result<T, E> { return isVoid(error) ? (new ResultImpl<T, Unit>(['Err', Unit]) as Result<T, Unit>) : (new ResultImpl<T, E>(['Err', error]) as Result<T, E>); } /** Distinguish between the {@linkcode Variant.Ok} and {@linkcode Variant.Err} {@linkcode Variant variants}. */ get variant(): Variant { return this.repr[0]; } /** The wrapped value. @throws if you access when the {@linkcode Result} is not {@linkcode Ok} */ get value(): T | never { if (this.repr[0] === Variant.Err) { throw new Error('Cannot get the value of Err'); } return this.repr[1]; } /** The wrapped error value. @throws if you access when the {@linkcode Result} is not {@linkcode Err} */ get error(): E | never { if (this.repr[0] === Variant.Ok) { throw new Error('Cannot get the error of Ok'); } return this.repr[1]; } /** Is the {@linkcode Result} an {@linkcode Ok}? */ get isOk() { return this.repr[0] === Variant.Ok; } /** Is the `Result` an `Err`? */ get isErr() { return this.repr[0] === Variant.Err; } /** Method variant for {@linkcode map} */ map<U>(mapFn: (t: T) => U): Result<U, E> { return (this.repr[0] === 'Ok' ? Result.ok(mapFn(this.repr[1])) : this) as Result<U, E>; } /** Method variant for {@linkcode mapOr} */ mapOr<U>(orU: U, mapFn: (t: T) => U): U { return this.repr[0] === 'Ok' ? mapFn(this.repr[1]) : orU; } /** Method variant for {@linkcode mapOrElse} */ mapOrElse<U>(orElseFn: (err: E) => U, mapFn: (t: T) => U): U { return this.repr[0] === 'Ok' ? mapFn(this.repr[1]) : orElseFn(this.repr[1]); } /** Method variant for {@linkcode match} */ match<U>(matcher: Matcher<T, E, U>): U { return this.repr[0] === 'Ok' ? matcher.Ok(this.repr[1]) : matcher.Err(this.repr[1]); } /** Method variant for {@linkcode mapErr} */ mapErr<F>(mapErrFn: (e: E) => F): Result<T, F> { return (this.repr[0] === 'Ok' ? this : Result.err(mapErrFn(this.repr[1]))) as Result<T, F>; } /** Method variant for {@linkcode or} */ or<F>(orResult: Result<T, F>): Result<T, F> { return (this.repr[0] === 'Ok' ? this : orResult) as Result<T, F>; } /** Method variant for {@linkcode orElse} */ orElse<F>(orElseFn: (err: E) => Result<T, F>): Result<T, F> { return (this.repr[0] === 'Ok' ? this : orElseFn(this.repr[1])) as Result<T, F>; } /** Method variant for {@linkcode and} */ and<U>(mAnd: Result<U, E>): Result<U, E> { // (r.isOk ? andResult : err<U, E>(r.error)) return (this.repr[0] === 'Ok' ? mAnd : this) as Result<U, E>; } /** Method variant for {@linkcode andThen} */ andThen<U>(andThenFn: (t: T) => Result<U, E>): Result<U, E> { return (this.repr[0] === 'Ok' ? andThenFn(this.repr[1]) : this) as Result<U, E>; } /** Method variant for {@linkcode unwrapOr} */ unwrapOr<U = T>(defaultValue: U): T | U { return this.repr[0] === 'Ok' ? this.repr[1] : defaultValue; } /** Method variant for {@linkcode unwrapOrElse} */ unwrapOrElse<U>(elseFn: (error: E) => U): T | U { return this.repr[0] === 'Ok' ? this.repr[1] : elseFn(this.repr[1]); } /** Method variant for {@linkcode toString} */ toString(): string { return `${this.repr[0]}(${safeToString(this.repr[1])})`; } /** Method variant for {@linkcode toJSON} */ toJSON(): ResultJSON<T, E> { const variant = this.repr[0]; return variant === 'Ok' ? { variant, value: this.repr[1] } : { variant, error: this.repr[1] }; } /** Method variant for {@linkcode equals} */ equals(comparison: Result<T, E>): boolean { // SAFETY: these casts are stripping away the `Ok`/`Err` distinction and // simply testing what `comparison` *actually* is, which is always an // instance of `ResultImpl` (the same as this method itself). return ( this.repr[0] === (comparison as ResultImpl<T, E>).repr[0] && this.repr[1] === (comparison as ResultImpl<T, E>).repr[1] ); } /** Method variant for {@linkcode ap} */ ap<A, B>(this: Result<(a: A) => B, E>, r: Result<A, E>): Result<B, E> { return r.andThen((val) => this.map((fn) => fn(val))); } } /** An `Ok` instance is the *successful* variant instance of the {@linkcode Result} type, representing a successful outcome from an operation which may fail. For a full discussion, see the module docs. @typeparam T The type wrapped in this `Ok` variant of `Result`. @typeparam E The type which would be wrapped in an `Err` variant of `Result`. */ export interface Ok<T, E> extends Omit<ResultImpl<T, E>, 'error'> { /** `Ok` is always [`Variant.Ok`](../enums/_result_.variant#ok). */ readonly variant: 'Ok'; isOk: true; isErr: false; /** The wrapped value */ value: T; } /** An `Err` instance is the *failure* variant instance of the {@linkcode Result} type, representing a failure outcome from an operation which may fail. For a full discussion, see the module docs. @typeparam T The type which would be wrapped in an `Ok` variant of `Result`. @typeparam E The type wrapped in this `Err` variant of `Result`. */ export interface Err<T, E> extends Omit<ResultImpl<T, E>, 'value'> { /** `Err` is always [`Variant.Err`](../enums/_result_.variant#err). */ readonly variant: 'Err'; isOk: false; isErr: true; /** The wrapped error value. */ error: E; } /** Execute the provided callback, wrapping the return value in {@linkcode Ok} or {@linkcode Err Err(error)} if there is an exception. ```ts const aSuccessfulOperation = () => 2 + 2; const anOkResult = Result.tryOr('Oh noes!!1', () => { aSuccessfulOperation() }); // => Ok(4) const thisOperationThrows = () => throw new Error('Bummer'); const anErrResult = Result.tryOr('Oh noes!!1', () => { thisOperationThrows(); }); // => Err('Oh noes!!1') ``` @param error The error value in case of an exception @param callback The callback to try executing */ export function tryOr<T, E>(error: E, callback: () => T): Result<T, E>; export function tryOr<T, E>(error: E): (callback: () => T) => Result<T, E>; export function tryOr<T, E>( error: E, callback?: () => T ): Result<T, E> | ((callback: () => T) => Result<T, E>) { const op = (cb: () => T) => { try { return ok<T, E>(cb()); } catch { return err<T, E>(error); } }; return curry1(op, callback); } /** Create an instance of {@linkcode Ok}. If you need to create an instance with a specific type (as you do whenever you are not constructing immediately for a function return or as an argument to a function), you can use a type parameter: ```ts const yayNumber = Result.ok<number, string>(12); ``` Note: passing nothing, or passing `null` or `undefined` explicitly, will produce a `Result<Unit, E>`, rather than producing the nonsensical and in practice quite annoying `Result<null, string>` etc. See {@linkcode Unit} for more. ```ts const normalResult = Result.ok<number, string>(42); const explicitUnit = Result.ok<Unit, string>(Unit); const implicitUnit = Result.ok<Unit, string>(); ``` In the context of an immediate function return, or an arrow function with a single expression value, you do not have to specify the types, so this can be quite convenient. ```ts type SomeData = { //... }; const isValid = (data: SomeData): boolean => { // true or false... } const arrowValidate = (data: SomeData): Result<Unit, string> => isValid(data) ? Result.ok() : Result.err('something was wrong!'); function fnValidate(data: someData): Result<Unit, string> { return isValid(data) ? Result.ok() : Result.err('something was wrong'); } ``` @typeparam T The type of the item contained in the `Result`. @param value The value to wrap in a `Result.Ok`. */ export const ok = ResultImpl.ok; /** Is the {@linkcode Result} an {@linkcode Ok}? @typeparam T The type of the item contained in the `Result`. @param result The `Result` to check. @returns A type guarded `Ok`. */ export function isOk<T, E>(result: Result<T, E>): result is Ok<T, E> { return result.isOk; } /** Is the {@linkcode Result} an {@linkcode Err}? @typeparam T The type of the item contained in the `Result`. @param result The `Result` to check. @returns A type guarded `Err`. */ export function isErr<T, E>(result: Result<T, E>): result is Err<T, E> { return result.isErr; } /** Create an instance of {@linkcode Err}. If you need to create an instance with a specific type (as you do whenever you are not constructing immediately for a function return or as an argument to a function), you can use a type parameter: ```ts const notString = Result.err<number, string>('something went wrong'); ``` Note: passing nothing, or passing `null` or `undefined` explicitly, will produce a `Result<T, Unit>`, rather than producing the nonsensical and in practice quite annoying `Result<null, string>` etc. See {@linkcode Unit} for more. ```ts const normalResult = Result.err<number, string>('oh no'); const explicitUnit = Result.err<number, Unit>(Unit); const implicitUnit = Result.err<number, Unit>(); ``` In the context of an immediate function return, or an arrow function with a single expression value, you do not have to specify the types, so this can be quite convenient. ```ts type SomeData = { //... }; const isValid = (data: SomeData): boolean => { // true or false... } const arrowValidate = (data: SomeData): Result<number, Unit> => isValid(data) ? Result.ok(42) : Result.err(); function fnValidate(data: someData): Result<number, Unit> { return isValid(data) ? Result.ok(42) : Result.err(); } ``` @typeparam T The type of the item contained in the `Result`. @param E The error value to wrap in a `Result.Err`. */ export const err = ResultImpl.err; /** Execute the provided callback, wrapping the return value in {@linkcode Ok}. If there is an exception, return a {@linkcode Err} of whatever the `onError` function returns. ```ts const aSuccessfulOperation = () => 2 + 2; const anOkResult = Result.tryOrElse( (e) => e, aSuccessfulOperation ); // => Ok(4) const thisOperationThrows = () => throw 'Bummer' const anErrResult = Result.tryOrElse((e) => e, () => { thisOperationThrows(); }); // => Err('Bummer') ``` @param onError A function that takes `e` exception and returns what will be wrapped in a `Result.Err` @param callback The callback to try executing */ export function tryOrElse<T, E>(onError: (e: unknown) => E, callback: () => T): Result<T, E>; export function tryOrElse<T, E>(onError: (e: unknown) => E): (callback: () => T) => Result<T, E>; export function tryOrElse<T, E>( onError: (e: unknown) => E, callback?: () => T ): Result<T, E> | ((callback: () => T) => Result<T, E>) { const op = (cb: () => T) => { try { return ok<T, E>(cb()); } catch (e) { return err<T, E>(onError(e)); } }; return curry1(op, callback); } /** Map over a {@linkcode Result} instance: apply the function to the wrapped value if the instance is {@linkcode Ok}, and return the wrapped error value wrapped as a new {@linkcode Err} of the correct type (`Result<U, E>`) if the instance is `Err`. `map` works a lot like `Array.prototype.map`, but with one important difference. Both `Result` and `Array` are containers for other kinds of items, but where `Array.prototype.map` has 0 to _n_ items, a `Result` always has exactly one item, which is *either* a success or an error instance. Where `Array.prototype.map` will apply the mapping function to every item in the array (if there are any), `Result.map` will only apply the mapping function to the (single) element if an `Ok` instance, if there is one. If you have no items in an array of numbers named `foo` and call `foo.map(x => x + 1)`, you'll still some have an array with nothing in it. But if you have any items in the array (`[2, 3]`), and you call `foo.map(x => x + 1)` on it, you'll get a new array with each of those items inside the array "container" transformed (`[3, 4]`). With this `map`, the `Err` variant is treated *by the `map` function* kind of the same way as the empty array case: it's just ignored, and you get back a new `Result` that is still just the same `Err` instance. But if you have an `Ok` variant, the map function is applied to it, and you get back a new `Result` with the value transformed, and still wrapped in an `Ok`. #### Examples ```ts import { ok, err, map, toString } from 'true-myth/result'; const double = n => n * 2; const anOk = ok(12); const mappedOk = map(double, anOk); console.log(toString(mappedOk)); // Ok(24) const anErr = err("nothing here!"); const mappedErr = map(double, anErr); console.log(toString(mappedOk)); // Err(nothing here!) ``` @typeparam T The type of the value wrapped in an `Ok` instance, and taken as the argument to the `mapFn`. @typeparam U The type of the value wrapped in the new `Ok` instance after applying `mapFn`, that is, the type returned by `mapFn`. @typeparam E The type of the value wrapped in an `Err` instance. @param mapFn The function to apply the value to if `result` is `Ok`. @param result The `Result` instance to map over. @returns A new `Result` with the result of applying `mapFn` to the value in an `Ok`, or else the original `Err` value wrapped in the new instance. */ export function map<T, U, E>(mapFn: (t: T) => U, result: Result<T, E>): Result<U, E>; export function map<T, U, E>(mapFn: (t: T) => U): (result: Result<T, E>) => Result<U, E>; export function map<T, U, E>( mapFn: (t: T) => U, result?: Result<T, E> ): Result<U, E> | ((result: Result<T, E>) => Result<U, E>) { const op = (r: Result<T, E>) => r.map(mapFn); return curry1(op, result); } /** Map over a {@linkcode Result} instance as in [`map`](#map) and get out the value if `result` is an {@linkcode Ok}, or return a default value if `result` is an {@linkcode Err}. #### Examples ```ts import { ok, err, mapOr } from 'true-myth/result'; const length = (s: string) => s.length; const anOkString = ok('a string'); const theStringLength = mapOr(0, anOkString); console.log(theStringLength); // 8 const anErr = err('uh oh'); const anErrMapped = mapOr(0, anErr); console.log(anErrMapped); // 0 ``` @param orU The default value to use if `result` is an `Err`. @param mapFn The function to apply the value to if `result` is an `Ok`. @param result The `Result` instance to map over. */ export function mapOr<T, U, E>(orU: U, mapFn: (t: T) => U, result: Result<T, E>): U; export function mapOr<T, U, E>(orU: U, mapFn: (t: T) => U): (result: Result<T, E>) => U; export function mapOr<T, U, E>(orU: U): (mapFn: (t: T) => U) => (result: Result<T, E>) => U; export function mapOr<T, U, E>( orU: U, mapFn?: (t: T) => U, result?: Result<T, E> ): U | ((result: Result<T, E>) => U) | ((mapFn: (t: T) => U) => (result: Result<T, E>) => U) { function fullOp(fn: (t: T) => U, r: Result<T, E>): U { return r.mapOr(orU, fn); } function partialOp(fn: (t: T) => U): (maybe: Result<T, E>) => U; function partialOp(fn: (t: T) => U, curriedResult: Result<T, E>): U; function partialOp( fn: (t: T) => U, curriedResult?: Result<T, E> ): U | ((maybe: Result<T, E>) => U) { return curriedResult !== undefined ? fullOp(fn, curriedResult) : (extraCurriedResult: Result<T, E>) => fullOp(fn, extraCurriedResult); } return mapFn === undefined ? partialOp : result === undefined ? partialOp(mapFn) : partialOp(mapFn, result); } /** Map over a {@linkcode Result} instance as in {@linkcode map} and get out the value if `result` is {@linkcode Ok}, or apply a function (`orElseFn`) to the value wrapped in the {@linkcode Err} to get a default value. Like {@linkcode mapOr} but using a function to transform the error into a usable value instead of simply using a default value. #### Examples ```ts import { ok, err, mapOrElse } from 'true-myth/result'; const summarize = (s: string) => `The response was: '${s}'`; const getReason = (err: { code: number, reason: string }) => err.reason; const okResponse = ok("Things are grand here."); const mappedOkAndUnwrapped = mapOrElse(getReason, summarize, okResponse); console.log(mappedOkAndUnwrapped); // The response was: 'Things are grand here.' const errResponse = err({ code: 500, reason: 'Nothing at this endpoint!' }); const mappedErrAndUnwrapped = mapOrElse(getReason, summarize, errResponse); console.log(mappedErrAndUnwrapped); // Nothing at this endpoint! ``` @typeparam T The type of the wrapped `Ok` value. @typeparam U The type of the resulting value from applying `mapFn` to the `Ok` value or `orElseFn` to the `Err` value. @typeparam E The type of the wrapped `Err` value. @param orElseFn The function to apply to the wrapped `Err` value to get a usable value if `result` is an `Err`. @param mapFn The function to apply to the wrapped `Ok` value if `result` is an `Ok`. @param result The `Result` instance to map over. */ export function mapOrElse<T, U, E>( orElseFn: (err: E) => U, mapFn: (t: T) => U, result: Result<T, E> ): U; export function mapOrElse<T, U, E>( orElseFn: (err: E) => U, mapFn: (t: T) => U ): (result: Result<T, E>) => U; export function mapOrElse<T, U, E>( orElseFn: (err: E) => U ): (mapFn: (t: T) => U) => (result: Result<T, E>) => U; export function mapOrElse<T, U, E>( orElseFn: (err: E) => U, mapFn?: (t: T) => U, result?: Result<T, E> ): U | ((result: Result<T, E>) => U) | ((mapFn: (t: T) => U) => (result: Result<T, E>) => U) { function fullOp(fn: (t: T) => U, r: Result<T, E>) { return r.mapOrElse(orElseFn, fn); } function partialOp(fn: (t: T) => U): (result: Result<T, E>) => U; function partialOp(fn: (t: T) => U, curriedResult: Result<T, E>): U; function partialOp( fn: (t: T) => U, curriedResult?: Result<T, E> ): U | ((maybe: Result<T, E>) => U) { return curriedResult !== undefined ? fullOp(fn, curriedResult) : (extraCurriedResult: Result<T, E>) => fullOp(fn, extraCurriedResult); } return mapFn === undefined ? partialOp : result === undefined ? partialOp(mapFn) : partialOp(mapFn, result); } /** Map over a {@linkcode Ok}, exactly as in {@linkcode map}, but operating on the value wrapped in an {@linkcode Err} instead of the value wrapped in the {@linkcode Ok}. This is handy for when you need to line up a bunch of different types of errors, or if you need an error of one shape to be in a different shape to use somewhere else in your codebase. #### Examples ```ts import { ok, err, mapErr, toString } from 'true-myth/result'; const reason = (err: { code: number, reason: string }) => err.reason; const anOk = ok(12); const mappedOk = mapErr(reason, anOk); console.log(toString(mappedOk)); // Ok(12) const anErr = err({ code: 101, reason: 'bad file' }); const mappedErr = mapErr(reason, anErr); console.log(toString(mappedErr)); // Err(bad file) ``` @typeparam T The type of the value wrapped in the `Ok` of the `Result`. @typeparam E The type of the value wrapped in the `Err` of the `Result`. @typeparam F The type of the value wrapped in the `Err` of a new `Result`, returned by the `mapErrFn`. @param mapErrFn The function to apply to the value wrapped in `Err` if `result` is an `Err`. @param result The `Result` instance to map over an error case for. */ export function mapErr<T, E, F>(mapErrFn: (e: E) => F, result: Result<T, E>): Result<T, F>; export function mapErr<T, E, F>(mapErrFn: (e: E) => F): (result: Result<T, E>) => Result<T, F>; export function mapErr<T, E, F>( mapErrFn: (e: E) => F, result?: Result<T, E> ): Result<T, F> | ((result: Result<T, E>) => Result<T, F>) { const op = (r: Result<T, E>) => r.mapErr(mapErrFn); return curry1(op, result); } /** You can think of this like a short-circuiting logical "and" operation on a {@linkcode Result} type. If `result` is {@linkcode Ok}, then the result is the `andResult`. If `result` is {@linkcode Err}, the result is the `Err`. This is useful when you have another `Result` value you want to provide if and *only if* you have an `Ok` – that is, when you need to make sure that if you `Err`, whatever else you're handing a `Result` to *also* gets that `Err`. Notice that, unlike in [`map`](#map) or its variants, the original `result` is not involved in constructing the new `Result`. #### Examples ```ts import { and, ok, err, toString } from 'true-myth/result'; const okA = ok('A'); const okB = ok('B'); const anErr = err({ so: 'bad' }); console.log(toString(and(okB, okA))); // Ok(B) console.log(toString(and(okB, anErr))); // Err([object Object]) console.log(toString(and(anErr, okA))); // Err([object Object]) console.log(toString(and(anErr, anErr))); // Err([object Object]) ``` @typeparam T The type of the value wrapped in the `Ok` of the `Result`. @typeparam U The type of the value wrapped in the `Ok` of the `andResult`, i.e. the success type of the `Result` present if the checked `Result` is `Ok`. @typeparam E The type of the value wrapped in the `Err` of the `Result`. @param andResult The `Result` instance to return if `result` is `Err`. @param result The `Result` instance to check. */ export function and<T, U, E>(andResult: Result<U, E>, result: Result<T, E>): Result<U, E>; export function and<T, U, E>(andResult: Result<U, E>): (result: Result<T, E>) => Result<U, E>; export function and<T, U, E>( andResult: Result<U, E>, result?: Result<T, E> ): Result<U, E> | ((result: Result<T, E>) => Result<U, E>) { const op = (r: Result<T, E>) => r.and(andResult); return curry1(op, result); } /** Apply a function to the wrapped value if {@linkcode Ok} and return a new `Ok` containing the resulting value; or if it is {@linkcode Err} return it unmodified. This differs from `map` in that `thenFn` returns another {@linkcode Result}. You can use `andThen` to combine two functions which *both* create a `Result` from an unwrapped type. You may find the `.then` method on an ES6 `Promise` helpful for comparison: if you have a `Promise`, you can pass its `then` method a callback which returns another `Promise`, and the result will not be a *nested* promise, but a single `Promise`. The difference is that `Promise#then` unwraps *all* layers to only ever return a single `Promise` value, whereas `Result.andThen` will not unwrap nested `Result`s. This is is sometimes also known as `bind`, but *not* aliased as such because [`bind` already means something in JavaScript][bind]. [bind]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind #### Examples ```ts import { ok, err, andThen, toString } from 'true-myth/result'; const toLengthAsResult = (s: string) => ok(s.length); const anOk = ok('just a string'); const lengthAsResult = andThen(toLengthAsResult, anOk); console.log(toString(lengthAsResult)); // Ok(13) const anErr = err(['srsly', 'whatever']); const notLengthAsResult = andThen(toLengthAsResult, anErr); console.log(toString(notLengthAsResult)); // Err(srsly,whatever) ``` @typeparam T The type of the value wrapped in the `Ok` of the `Result`. @typeparam U The type of the value wrapped in the `Ok` of the `Result` returned by the `thenFn`. @typeparam E The type of the value wrapped in the `Err` of the `Result`. @param thenFn The function to apply to the wrapped `T` if `maybe` is `Just`. @param result The `Maybe` to evaluate and possibly apply a function to. */ export function andThen<T, U, E>( thenFn: (t: T) => Result<U, E>, result: Result<T, E> ): Result<U, E>; export function andThen<T, U, E>( thenFn: (t: T) => Result<U, E> ): (result: Result<T, E>) => Result<U, E>; export function andThen<T, U, E>( thenFn: (t: T) => Result<U, E>, result?: Result<T, E> ): Result<U, E> | ((result: Result<T, E>) => Result<U, E>) { const op = (r: Result<T, E>) => r.andThen(thenFn); return curry1(op, result); } /** Provide a fallback for a given {@linkcode Result}. Behaves like a logical `or`: if the `result` value is an {@linkcode Ok}, returns that `result`; otherwise, returns the `defaultResult` value. This is useful when you want to make sure that something which takes a `Result` always ends up getting an `Ok` variant, by supplying a default value for the case that you currently have an {@linkcode Err}. ```ts import { ok, err, Result, or } from 'true-utils/result'; const okA = ok<string, string>('a'); const okB = ok<string, string>('b'); const anErr = err<string, string>(':wat:'); const anotherErr = err<string, string>(':headdesk:'); console.log(or(okB, okA).toString()); // Ok(A) console.log(or(anErr, okA).toString()); // Ok(A) console.log(or(okB, anErr).toString()); // Ok(B) console.log(or(anotherErr, anErr).toString()); // Err(:headdesk:) ``` @typeparam T The type wrapped in the `Ok` case of `result`. @typeparam E The type wrapped in the `Err` case of `result`. @typeparam F The type wrapped in the `Err` case of `defaultResult`. @param defaultResult The `Result` to use if `result` is an `Err`. @param result The `Result` instance to check. @returns `result` if it is an `Ok`, otherwise `defaultResult`. */ export function or<T, E, F>(defaultResult: Result<T, F>, result: Result<T, E>): Result<T, F>; export function or<T, E, F>(defaultResult: Result<T, F>): (result: Result<T, E>) => Result<T, F>; export function or<T, E, F>( defaultResult: Result<T, F>, result?: Result<T, E> ): Result<T, F> | ((result: Result<T, E>) => Result<T, F>) { const op = (r: Result<T, E>) => r.or(defaultResult); return curry1(op, result); } /** Like {@linkcode or}, but using a function to construct the alternative {@linkcode Result}. Sometimes you need to perform an operation using other data in the environment to construct the fallback value. In these situations, you can pass a function (which may be a closure) as the `elseFn` to generate the fallback `Result<T>`. It can then transform the data in the `Err` to something usable as an {@linkcode Ok}, or generate a new {@linkcode Err} instance as appropriate. Useful for transforming failures to usable data. @param elseFn The function to apply to the contents of the `Err` if `result` is an `Err`, to create a new `Result`. @param result The `Result` to use if it is an `Ok`. @returns The `result` if it is `Ok`, or the `Result` returned by `elseFn` if `result` is an `Err. */ export function orElse<T, E, F>( elseFn: (err: E) => Result<T, F>, result: Result<T, E> ): Result<T, F>; export function orElse<T, E, F>( elseFn: (err: E) => Result<T, F> ): (result: Result<T, E>) => Result<T, F>; export function orElse<T, E, F>( elseFn: (err: E) => Result<T, F>, result?: Result<T, E> ): Result<T, F> | ((result: Result<T, E>) => Result<T, F>) { const op = (r: Result<T, E>) => r.orElse(elseFn); return curry1(op, result); } /** Safely get the value out of the {@linkcode Ok} variant of a {@linkcode Result}. This is the recommended way to get a value out of a `Result` most of the time. ```ts import { ok, err, unwrapOr } from 'true-myth/result'; const anOk = ok<number, string>(12); console.log(unwrapOr(0, anOk)); // 12 const anErr = err<number, string>('nooooo'); console.log(unwrapOr(0, anErr)); // 0 ``` @typeparam T The value wrapped in the `Ok`. @typeparam E The value wrapped in the `Err`. @param defaultValue The value to use if `result` is an `Err`. @param result The `Result` instance to unwrap if it is an `Ok`. @returns The content of `result` if it is an `Ok`, otherwise `defaultValue`. */ export function unwrapOr<T, U, E>(defaultValue: U, result: Result<T, E>): U | T; export function unwrapOr<T, U, E>(defaultValue: U): (result: Result<T, E>) => U | T; export function unwrapOr<T, U, E>( defaultValue: U, result?: Result<T, E> ): (T | U) | ((result: Result<T, E>) => T | U) { const op = (r: Result<T, E>) => r.unwrapOr(defaultValue); return curry1(op, result); } /** Safely get the value out of a {@linkcode Result} by returning the wrapped value if it is {@linkcode Ok}, or by applying `orElseFn` to the value in the {@linkcode Err}. This is useful when you need to *generate* a value (e.g. by using current values in the environment – whether preloaded or by local closure) instead of having a single default value available (as in {@linkcode unwrapOr}). ```ts import { ok, err, unwrapOrElse } from 'true-myth/result'; // You can imagine that someOtherValue might be dynamic. const someOtherValue = 2; const handleErr = (errValue: string) => errValue.length + someOtherValue; const anOk = ok<number, string>(42); console.log(unwrapOrElse(handleErr, anOk)); // 42 const anErr = err<number, string>('oh teh noes'); console.log(unwrapOrElse(handleErr, anErr)); // 13 ``` @typeparam T The value wrapped in the `Ok`. @typeparam E The value wrapped in the `Err`. @param orElseFn A function applied to the value wrapped in `result` if it is an `Err`, to generate the final value. @param result The `result` to unwrap if it is an `Ok`. @returns The value wrapped in `result` if it is `Ok` or the value returned by `orElseFn` applied to the value in `Err`. */ export function unwrapOrElse<T, U, E>(orElseFn: (error: E) => U, result: Result<T, E>): T | U; export function unwrapOrElse<T, U, E>(orElseFn: (error: E) => U): (result: Result<T, E>) => T | U; export function unwrapOrElse<T, U, E>( orElseFn: (error: E) => U, result?: Result<T, E> ): (T | U) | ((result: Result<T, E>) => T | U) { const op = (r: Result<T, E>) => r.unwrapOrElse(orElseFn); return curry1(op, result); } /** Create a `String` representation of a {@linkcode Result} instance. An {@linkcode Ok} instance will be `Ok(<representation of the value>)`, and an {@linkcode Err} instance will be `Err(<representation of the error>)`, where the representation of the value or error is simply the value or error's own `toString` representation. For example: call | output --------------------------------- | ---------------------- `toString(ok(42))` | `Ok(42)` `toString(ok([1, 2, 3]))` | `Ok(1,2,3)` `toString(ok({ an: 'object' }))` | `Ok([object Object])`n `toString(err(42))` | `Err(42)` `toString(err([1, 2, 3]))` | `Err(1,2,3)` `toString(err({ an: 'object' }))` | `Err([object Object])` @typeparam T The type of the wrapped value; its own `.toString` will be used to print the interior contents of the `Just` variant. @param result The value to convert to a string. @returns The string representation of the `Maybe`. */ export const toString = <T, E>(result: Result<T, E>): string => { return result.toString(); }; /** * Create an `Object` representation of a {@linkcode Result} instance. * * Useful for serialization. `JSON.stringify()` uses it. * * @param result The value to convert to JSON * @returns The JSON representation of the `Result` */ export const toJSON = <T, E>(result: Result<T, E>): ResultJSON<T, E> => { return result.toJSON(); }; /** A lightweight object defining how to handle each variant of a {@linkcode Result}. */ export type Matcher<T, E, A> = { Ok: (value: T) => A; Err: (error: E) => A; }; /** Performs the same basic functionality as {@linkcode unwrapOrElse}, but instead of simply unwrapping the value if it is {@linkcode Ok} and applying a value to generate the same default type if it is {@linkcode Err}, lets you supply functions which may transform the wrapped type if it is `Ok` or get a default value for `Err`. This is kind of like a poor man's version of pattern matching, which JavaScript currently lacks. Instead of code like this: ```ts import Result, { isOk, match } from 'true-myth/result'; const logValue = (mightBeANumber: Result<number, string>) => { console.log( mightBeANumber.isOk ? mightBeANumber.value.toString() : `There was an error: ${unsafelyGetErr(mightBeANumber)}` ); }; ``` ...we can write code like this: ```ts import Result, { match } from 'true-myth/result'; const logValue = (mightBeANumber: Result<number, string>) => { const value = match( { Ok: n => n.toString(), Err: e => `There was an error: ${e}`, }, mightBeANumber ); console.log(value); }; ``` This is slightly longer to write, but clearer: the more complex the resulting expression, the hairer it is to understand the ternary. Thus, this is especially convenient for times when there is a complex result, e.g. when rendering part of a React component inline in JSX/TSX. @param matcher A lightweight object defining what to do in the case of each variant. @param maybe The `maybe` instance to check. */ export function match<T, E, A>(matcher: Matcher<T, E, A>, result: Result<T, E>): A; export function match<T, E, A>(matcher: Matcher<T, E, A>): (result: Result<T, E>) => A; export function match<T, E, A>( matcher: Matcher<T, E, A>, result?: Result<T, E> ): A | ((result: Result<T, E>) => A) { const op = (r: Result<T, E>) => r.mapOrElse(matcher.Err, matcher.Ok); return curry1(op, result); } /** Allows quick triple-equal equality check between the values inside two {@linkcode Result}s without having to unwrap them first. ```ts const a = Result.of(3) const b = Result.of(3) const c = Result.of(null) const d = Result.nothing() Result.equals(a, b) // true Result.equals(a, c) // false Result.equals(c, d) // true ``` @param resultB A `maybe` to compare to. @param resultA A `maybe` instance to check. */ export function equals<T, E>(resultB: Result<T, E>, resultA: Result<T, E>): boolean; export function equals<T, E>(resultB: Result<T, E>): (resultA: Result<T, E>) => boolean; export function equals<T, E>( resultB: Result<T, E>, resultA?: Result<T, E> ): boolean | ((a: Result<T, E>) => boolean) { const op = (rA: Result<T, E>) => rA.equals(resultB); return curry1(op, resultA); } /** Allows you to *apply* (thus `ap`) a value to a function without having to take either out of the context of their {@linkcode Result}s. This does mean that the transforming function is itself within a `Result`, which can be hard to grok at first but lets you do some very elegant things. For example, `ap` allows you to do this (using the method form, since nesting `ap` calls is awkward): ```ts import { ap, ok, err } from 'true-myth/result'; const one = ok<number, string>(1); const five = ok<number, string>(5); const whoops = err<number, string>('oh no'); const add = (a: number) => (b: number) => a + b; const resultAdd = ok<typeof add, string>(add); resultAdd.ap(one).ap(five); // Ok(6) resultAdd.ap(one).ap(whoops); // Err('oh no') resultAdd.ap(whoops).ap(five) // Err('oh no') ``` Without `ap`, you'd need to do something like a nested `match`: ```ts import { ok, err } from 'true-myth/result'; const one = ok<number, string>(1); const five = ok<number, string>(5); const whoops = err<number, string>('oh no'); one.match({ Ok: n => five.match({ Ok: o => ok<number, string>(n + o), Err: e => err<number, string>(e), }), Err: e => err<number, string>(e), }); // Ok(6) one.match({ Ok: n => whoops.match({ Ok: o => ok<number, string>(n + o), Err: e => err<number, string>(e), }), Err: e => err<number, string>(e), }); // Err('oh no') whoops.match({ Ok: n => five.match({ Ok: o => ok(n + o), Err: e => err(e), }), Err: e => err(e), }); // Err('oh no') ``` And this kind of thing comes up quite often once you're using `Result` to handle errors throughout your application. For another example, imagine you need to compare the equality of two ImmutableJS data structures, where a `===` comparison won't work. With `ap`, that's as simple as this: ```ts import { ok } from 'true-myth/result'; import { is as immutableIs, Set } from 'immutable'; const is = (first: unknown) => (second: unknown) => immutableIs(first, second); const x = ok(Set.of(1, 2, 3)); const y = ok(Set.of(2, 3, 4)); ok(is).ap(x).ap(y); // Ok(false) ``` Without `ap`, we're back to that gnarly nested `match`: ```ts import Result, { ok, err } from 'true-myth/result'; import { is, Set } from 'immutable'; const x = ok(Set.of(1, 2, 3)); const y = ok(Set.of(2, 3, 4)); x.match({ Ok: iX => y.match({ Ok: iY => Result.of(is(iX, iY)), Err: (e) => ok(false), }) Err: (e) => ok(false), }); // Ok(false) ``` In summary: anywhere you have two `Result` instances and need to perform an operation that uses both of them, `ap` is your friend. Two things to note, both regarding *currying*: 1. All functions passed to `ap` must be curried. That is, they must be of the form (for add) `(a: number) => (b: number) => a + b`, *not* the more usual `(a: number, b: number) => a + b` you see in JavaScript more generally. (Unfortunately, these do not currently work with lodash or Ramda's `curry` helper functions. A future update to the type definitions may make that work, but the intermediate types produced by those helpers and the more general function types expected by this function do not currently align.) 2. You will need to call `ap` as many times as there are arguments to the function you're dealing with. So in the case of this `add3` function, which has the "arity" (function argument count) of 3 (`a` and `b`), you'll need to call `ap` twice: once for `a`, and once for `b`. To see why, let's look at what the result in each phase is: ```ts const add3 = (a: number) => (b: number) => (c: number) => a + b + c; const resultAdd = ok(add); // Ok((a: number) => (b: number) => (c: number) => a + b + c) const resultAdd1 = resultAdd.ap(ok(1)); // Ok((b: number) => (c: number) => 1 + b + c) const resultAdd1And2 = resultAdd1.ap(ok(2)) // Ok((c: number) => 1 + 2 + c) const final = maybeAdd1.ap(ok(3)); // Ok(4) ``` So for `toString`, which just takes a single argument, you would only need to call `ap` once. ```ts const toStr = (v: { toString(): string }) => v.toString(); ok(toStr).ap(12); // Ok("12") ``` One other scenario which doesn't come up *quite* as often but is conceivable is where you have something that may or may not actually construct a function for handling a specific `Result` scenario. In that case, you can wrap the possibly-present in `ap` and then wrap the values to apply to the function to in `Result` themselves. Because `Result` often requires you to type out the full type parameterization on a regular basis, it's convenient to use TypeScript's `typeof` operator to write out the type of a curried function. For example, if you had a function that simply merged three strings, you might write it like this: ```ts import Result from 'true-myth/result'; import { curry } from 'lodash'; const merge3Strs = (a: string, b: string, c: string) => string; const curriedMerge = curry(merge3Strs); const fn = Result.ok<typeof curriedMerge, string>(curriedMerge); ``` The alternative is writing out the full signature long-form: ```ts const fn = Result.ok<(a: string) => (b: string) => (c: string) => string, string>(curriedMerge); ``` **Aside:** `ap` is not named `apply` because of the overlap with JavaScript's existing [`apply`] function – and although strictly speaking, there isn't any direct overlap (`Result.apply` and `Function.prototype.apply` don't intersect at all) it's useful to have a different name to avoid implying that they're the same. [`apply`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply @param resultFn result of a function from T to U @param result result of a T to apply to `fn` */ export function ap<A, B, E>(resultFn: Result<(a: A) => B, E>, result: Result<A, E>): Result<B, E>; export function ap<A, B, E>( resultFn: Result<(a: A) => B, E> ): (result: Result<A, E>) => Result<B, E>; export function ap<A, B, E>( resultFn: Result<(a: A) => B, E>, result?: Result<A, E> ): Result<B, E> | ((val: Result<A, E>) => Result<B, E>) { const op = (r: Result<A, E>) => resultFn.ap(r); return curry1(op, result); } /** Determine whether an item is an instance of {@linkcode Result}. @param item The item to check. */ export function isInstance<T, E>(item: unknown): item is Result<T, E> { return item instanceof ResultImpl; } // The public interface for the {@linkcode Result} class *as a value*: a constructor and the // single associated static property. export interface ResultConstructor { ok: typeof ResultImpl.ok; err: typeof ResultImpl.err; } /** A value which may ({@linkcode Ok}) or may not ({@linkcode Err}) be present. The behavior of this type is checked by TypeScript at compile time, and bears no runtime overhead other than the very small cost of the container object. */ export type Result<T, E> = Ok<T, E> | Err<T, E>; export const Result = ResultImpl as ResultConstructor; export default Result;
the_stack
import mxClient from '../mxClient'; import { ALIGN_BOTTOM, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_TOP, DEFAULT_FONTFAMILY, DEFAULT_FONTSIZE, DIRECTION_EAST, DIRECTION_MASK_EAST, DIRECTION_MASK_NONE, DIRECTION_MASK_NORTH, DIRECTION_MASK_SOUTH, DIRECTION_MASK_WEST, DIRECTION_NORTH, DIRECTION_SOUTH, DIRECTION_WEST, FONT_BOLD, FONT_ITALIC, FONT_STRIKETHROUGH, FONT_UNDERLINE, LINE_HEIGHT, NODETYPE_ELEMENT, NONE, PAGE_FORMAT_A4_PORTRAIT, } from './Constants'; import Point from '../view/geometry/Point'; import Dictionary from './Dictionary'; import CellPath from '../view/cell/datatypes/CellPath'; import Rectangle from '../view/geometry/Rectangle'; import { getFunctionName } from './StringUtils'; import { getOuterHtml } from './DomUtils'; import CellState from '../view/cell/datatypes/CellState'; import Cell from '../view/cell/datatypes/Cell'; import Model from '../view/model/Model'; import CellArray from '../view/cell/datatypes/CellArray'; import { Graph } from 'src/view/Graph'; import type { CellStateStyles, Properties, StyleValue } from '../types'; /** * Class: mxUtils * * A singleton class that provides cross-browser helper methods. * This is a global functionality. To access the functions in this * class, use the global classname appended by the functionname. * You may have to load chrome://global/content/contentAreaUtils.js * to disable certain security restrictions in Mozilla for the <open>, * <save>, <saveAs> and <copy> function. * * For example, the following code displays an error message: * * (code) * mxUtils.error('Browser is not supported!', 200, false); * (end) */ const utils = { /* Variable: errorResource * * Specifies the resource key for the title of the error window. If the * resource for this key does not exist then the value is used as * the title. Default is 'error'. */ errorResource: 'error', /** * Variable: closeResource * * Specifies the resource key for the label of the close button. If the * resource for this key does not exist then the value is used as * the label. Default is 'close'. */ closeResource: 'close', /** * Variable: errorImage * * Defines the image used for error dialogs. */ errorImage: '/error.gif', // mxClient.imageBasePath + '/error.gif', }; /** * Function: removeCursors * * Removes the cursors from the style of the given DOM node and its * descendants. * * Parameters: * * element - DOM node to remove the cursor style from. */ export const removeCursors = (element: HTMLElement) => { if (element.style) { element.style.cursor = ''; } const children = element.children; if (children) { const childCount = children.length; for (let i = 0; i < childCount; i += 1) { removeCursors(children[i] as HTMLElement); } } }; /** * Function: getCurrentStyle * * Returns the current style of the specified element. * * Parameters: * * element - DOM node whose current style should be returned. */ export const getCurrentStyle = (element: HTMLElement) => { return element ? window.getComputedStyle(element, '') : null; }; /** * Function: parseCssNumber * * Parses the given CSS numeric value adding handling for the values thin, * medium and thick (2, 4 and 6). */ export const parseCssNumber = (value: string) => { if (value === 'thin') { value = '2'; } else if (value === 'medium') { value = '4'; } else if (value === 'thick') { value = '6'; } let n = parseFloat(value); if (Number.isNaN(n)) { n = 0; } return n; }; /** * Function: setPrefixedStyle * * Adds the given style with the standard name and an optional vendor prefix for the current * browser. * * (code) * mxUtils.setPrefixedStyle(node.style, 'transformOrigin', '0% 0%'); * (end) */ export const setPrefixedStyle = ( style: CSSStyleDeclaration, name: string, value: string ) => { let prefix = null; if (mxClient.IS_SF || mxClient.IS_GC) { prefix = 'Webkit'; } else if (mxClient.IS_MT) { prefix = 'Moz'; } style.setProperty(name, value); if (prefix !== null && name.length > 0) { name = prefix + name.substring(0, 1).toUpperCase() + name.substring(1); style.setProperty(name, value); } }; /** * Function: hasScrollbars * * Returns true if the overflow CSS property of the given node is either * scroll or auto. * * Parameters: * * node - DOM node whose style should be checked for scrollbars. */ export const hasScrollbars = (node: HTMLElement) => { const style = getCurrentStyle(node); return !!style && (style.overflow === 'scroll' || style.overflow === 'auto'); }; /** * Function: findNode * * Returns the first node where attr equals value. * This implementation does not use XPath. */ export const findNode = ( node: Element, attr: string, value: StyleValue ): Element | null => { if (node.nodeType === NODETYPE_ELEMENT) { const tmp = node.getAttribute(attr); if (tmp && tmp === value) { return node; } } node = node.firstChild as Element; while (node) { const result = findNode(node, attr, value); if (result) { return result; } node = node.nextSibling as Element; } return null; }; /** * Function: remove * * Removes all occurrences of the given object in the given array or * object. If there are multiple occurrences of the object, be they * associative or as an array entry, all occurrences are removed from * the array or deleted from the object. By removing the object from * the array, all elements following the removed element are shifted * by one step towards the beginning of the array. * * The length of arrays is not modified inside this function. * * Parameters: * * obj - Object to find in the given array. * array - Array to check for the given obj. */ export const remove = (obj: object, array: object[]) => { let result = null; if (typeof array === 'object') { let index = array.indexOf(obj); while (index >= 0) { array.splice(index, 1); result = obj; index = array.indexOf(obj); } } for (const key in array) { if (array[key] == obj) { delete array[key]; result = obj; } } return result; }; /** * Function: getDocumentSize * * Returns the client size for the current document as an <mxRectangle>. */ export const getDocumentSize = () => { const b = document.body; const d = document.documentElement; try { return new Rectangle( 0, 0, b.clientWidth ?? d.clientWidth, Math.max(b.clientHeight ?? 0, d.clientHeight) ); } catch (e) { return new Rectangle(); } }; /** * Function: fit * * Makes sure the given node is inside the visible area of the window. This * is done by setting the left and top in the style. */ export const fit = (node: HTMLElement) => { const ds = getDocumentSize(); const left = node.offsetLeft; const width = node.offsetWidth; const offset = getDocumentScrollOrigin(node.ownerDocument); const sl = offset.x; const st = offset.y; const right = sl + ds.width; if (left + width > right) { node.style.left = `${Math.max(sl, right - width)}px`; } const top = node.offsetTop; const height = node.offsetHeight; const bottom = st + ds.height; if (top + height > bottom) { node.style.top = `${Math.max(st, bottom - height)}px`; } }; /** * Function: getValue * * Returns the value for the given key in the given associative array or * the given default value if the value is null. * * Parameters: * * array - Associative array that contains the value for the key. * key - Key whose value should be returned. * defaultValue - Value to be returned if the value for the given * key is null. */ export const getValue = (array: any, key: string, defaultValue?: any) => { let value = array != null ? array[key] : null; if (value == null) { value = defaultValue; } return value; }; export const getStringValue = (array: any, key: string, defaultValue: string) => { let value = array != null ? array[key] : null; if (value == null) { value = defaultValue; } return value == null ? null : String(value); }; /** * Function: getNumber * * Returns the numeric value for the given key in the given associative * array or the given default value (or 0) if the value is null. The value * is converted to a numeric value using the Number function. * * Parameters: * * array - Associative array that contains the value for the key. * key - Key whose value should be returned. * defaultValue - Value to be returned if the value for the given * key is null. Default is 0. */ export const getNumber = (array: any, key: string, defaultValue: number) => { let value = array != null ? array[key] : null; if (value == null) { value = defaultValue || 0; } return Number(value); }; /** * Function: getColor * * Returns the color value for the given key in the given associative * array or the given default value if the value is null. If the value * is <mxConstants.NONE> then null is returned. * * Parameters: * * array - Associative array that contains the value for the key. * key - Key whose value should be returned. * defaultValue - Value to be returned if the value for the given * key is null. Default is null. */ export const getColor = (array: any, key: string, defaultValue: any) => { let value = array != null ? array[key] : null; if (value == null) { value = defaultValue; } else if (value === NONE) { value = null; } return value; }; /** * Function: equalPoints * * Compares all mxPoints in the given lists. * * Parameters: * * a - Array of <mxPoints> to be compared. * b - Array of <mxPoints> to be compared. */ export const equalPoints = (a: (Point | null)[] | null, b: (Point | null)[] | null) => { if ((!a && b) || (a && !b) || (a && b && a.length != b.length)) { return false; } if (a && b) { for (let i = 0; i < a.length; i += 1) { const p = a[i]; if (!p || (p && !p.equals(b[i]))) return false; } } return true; }; /** * Function: equalEntries * * Returns true if all properties of the given objects are equal. Values * with NaN are equal to NaN and unequal to any other value. * * Parameters: * * a - First object to be compared. * b - Second object to be compared. */ export const equalEntries = (a: Properties | null, b: Properties | null) => { // Counts keys in b to check if all values have been compared let count = 0; if ((!a && b) || (a && !b) || (a && b && a.length != b.length)) { return false; } if (a && b) { for (var key in b) { count++; } for (var key in a) { count--; if ((!Number.isNaN(a[key]) || !Number.isNaN(b[key])) && a[key] !== b[key]) { return false; } } } return count === 0; }; /** * Function: removeDuplicates * * Removes all duplicates from the given array. */ export const removeDuplicates = (arr: any) => { const dict = new Dictionary(); const result = []; for (let i = 0; i < arr.length; i += 1) { if (!dict.get(arr[i])) { result.push(arr[i]); dict.put(arr[i], true); } } return result; }; /** * Function: toString * * Returns a textual representation of the specified object. * * Parameters: * * obj - Object to return the string representation for. */ export const toString = (obj: Properties) => { let output = ''; for (const i in obj) { try { if (obj[i] == null) { output += `${i} = [null]\n`; } else if (typeof obj[i] === 'function') { output += `${i} => [Function]\n`; } else if (typeof obj[i] === 'object') { const ctor = getFunctionName(obj[i].constructor); output += `${i} => [${ctor}]\n`; } else { output += `${i} = ${obj[i]}\n`; } } catch (e) { output += `${i}=${e.message}`; } } return output; }; /** * Function: toRadians * * Converts the given degree to radians. */ export const toRadians = (deg: number) => { return (Math.PI * deg) / 180; }; /** * Function: toDegree * * Converts the given radians to degree. */ export const toDegree = (rad: number) => { return (rad * 180) / Math.PI; }; /** * Function: arcToCurves * * Converts the given arc to a series of curves. */ export const arcToCurves = ( x0: number, y0: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean, x: number, y: number ) => { x -= x0; y -= y0; if (r1 === 0 || r2 === 0) { return []; } const fS = sweepFlag; const psai = angle; r1 = Math.abs(r1); r2 = Math.abs(r2); const ctx = -x / 2; const cty = -y / 2; const cpsi = Math.cos((psai * Math.PI) / 180); const spsi = Math.sin((psai * Math.PI) / 180); const rxd = cpsi * ctx + spsi * cty; const ryd = -1 * spsi * ctx + cpsi * cty; const rxdd = rxd * rxd; const rydd = ryd * ryd; const r1x = r1 * r1; const r2y = r2 * r2; const lamda = rxdd / r1x + rydd / r2y; let sds; if (lamda > 1) { r1 = Math.sqrt(lamda) * r1; r2 = Math.sqrt(lamda) * r2; sds = 0; } else { let seif = 1; if (largeArcFlag === fS) { seif = -1; } sds = seif * Math.sqrt((r1x * r2y - r1x * rydd - r2y * rxdd) / (r1x * rydd + r2y * rxdd)); } const txd = (sds * r1 * ryd) / r2; const tyd = (-1 * sds * r2 * rxd) / r1; const tx = cpsi * txd - spsi * tyd + x / 2; const ty = spsi * txd + cpsi * tyd + y / 2; let rad = Math.atan2((ryd - tyd) / r2, (rxd - txd) / r1) - Math.atan2(0, 1); let s1 = rad >= 0 ? rad : 2 * Math.PI + rad; rad = Math.atan2((-ryd - tyd) / r2, (-rxd - txd) / r1) - Math.atan2((ryd - tyd) / r2, (rxd - txd) / r1); let dr = rad >= 0 ? rad : 2 * Math.PI + rad; if (!fS && dr > 0) { dr -= 2 * Math.PI; } else if (fS && dr < 0) { dr += 2 * Math.PI; } const sse = (dr * 2) / Math.PI; const seg = Math.ceil(sse < 0 ? -1 * sse : sse); const segr = dr / seg; const t = ((8 / 3) * Math.sin(segr / 4) * Math.sin(segr / 4)) / Math.sin(segr / 2); const cpsir1 = cpsi * r1; const cpsir2 = cpsi * r2; const spsir1 = spsi * r1; const spsir2 = spsi * r2; let mc = Math.cos(s1); let ms = Math.sin(s1); let x2 = -t * (cpsir1 * ms + spsir2 * mc); let y2 = -t * (spsir1 * ms - cpsir2 * mc); let x3 = 0; let y3 = 0; let result = []; for (let n = 0; n < seg; ++n) { s1 += segr; mc = Math.cos(s1); ms = Math.sin(s1); x3 = cpsir1 * mc - spsir2 * ms + tx; y3 = spsir1 * mc + cpsir2 * ms + ty; const dx = -t * (cpsir1 * ms + spsir2 * mc); const dy = -t * (spsir1 * ms - cpsir2 * mc); // CurveTo updates x0, y0 so need to restore it const index = n * 6; result[index] = Number(x2 + x0); result[index + 1] = Number(y2 + y0); result[index + 2] = Number(x3 - dx + x0); result[index + 3] = Number(y3 - dy + y0); result[index + 4] = Number(x3 + x0); result[index + 5] = Number(y3 + y0); x2 = x3 + dx; y2 = y3 + dy; } return result; }; /** * Function: getBoundingBox * * Returns the bounding box for the rotated rectangle. * * Parameters: * * rect - <mxRectangle> to be rotated. * angle - Number that represents the angle (in degrees). * cx - Optional <mxPoint> that represents the rotation center. If no * rotation center is given then the center of rect is used. */ export const getBoundingBox = ( rect: Rectangle | null, rotation: number, cx: Point | null = null ) => { let result = null; if (rect && rotation !== 0) { const rad = toRadians(rotation); const cos = Math.cos(rad); const sin = Math.sin(rad); cx = cx != null ? cx : new Point(rect.x + rect.width / 2, rect.y + rect.height / 2); let p1 = new Point(rect.x, rect.y); let p2 = new Point(rect.x + rect.width, rect.y); let p3 = new Point(p2.x, rect.y + rect.height); let p4 = new Point(rect.x, p3.y); p1 = getRotatedPoint(p1, cos, sin, cx); p2 = getRotatedPoint(p2, cos, sin, cx); p3 = getRotatedPoint(p3, cos, sin, cx); p4 = getRotatedPoint(p4, cos, sin, cx); result = new Rectangle(p1.x, p1.y, 0, 0); result.add(new Rectangle(p2.x, p2.y, 0, 0)); result.add(new Rectangle(p3.x, p3.y, 0, 0)); result.add(new Rectangle(p4.x, p4.y, 0, 0)); } return result; }; /** * Function: getRotatedPoint * * Rotates the given point by the given cos and sin. */ export const getRotatedPoint = (pt: Point, cos: number, sin: number, c = new Point()) => { const x = pt.x - c.x; const y = pt.y - c.y; const x1 = x * cos - y * sin; const y1 = y * cos + x * sin; return new Point(x1 + c.x, y1 + c.y); }; /** * Returns an integer mask of the port constraints of the given map * @param dict the style map to determine the port constraints for * @param defaultValue Default value to return if the key is undefined. * @return the mask of port constraint directions * * Parameters: * * terminal - <mxCelState> that represents the terminal. * edge - <mxCellState> that represents the edge. * source - Boolean that specifies if the terminal is the source terminal. * defaultValue - Default value to be returned. */ export const getPortConstraints = ( terminal: CellState, edge: CellState, source: boolean, defaultValue: any ) => { const value = getValue( terminal.style, 'portConstraint', getValue(edge.style, source ? 'sourcePortConstraint' : 'targetPortConstraint', null) ); if (isNullish(value)) { return defaultValue; } const directions = value.toString(); let returnValue = DIRECTION_MASK_NONE; const constraintRotationEnabled = getValue(terminal.style, 'portConstraintRotation', 0); let rotation = 0; if (constraintRotationEnabled == 1) { rotation = terminal.style.rotation ?? 0; } let quad = 0; if (rotation > 45) { quad = 1; if (rotation >= 135) { quad = 2; } } else if (rotation < -45) { quad = 3; if (rotation <= -135) { quad = 2; } } if (directions.indexOf(DIRECTION_NORTH) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK_NORTH; break; case 1: returnValue |= DIRECTION_MASK_EAST; break; case 2: returnValue |= DIRECTION_MASK_SOUTH; break; case 3: returnValue |= DIRECTION_MASK_WEST; break; } } if (directions.indexOf(DIRECTION_WEST) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK_WEST; break; case 1: returnValue |= DIRECTION_MASK_NORTH; break; case 2: returnValue |= DIRECTION_MASK_EAST; break; case 3: returnValue |= DIRECTION_MASK_SOUTH; break; } } if (directions.indexOf(DIRECTION_SOUTH) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK_SOUTH; break; case 1: returnValue |= DIRECTION_MASK_WEST; break; case 2: returnValue |= DIRECTION_MASK_NORTH; break; case 3: returnValue |= DIRECTION_MASK_EAST; break; } } if (directions.indexOf(DIRECTION_EAST) >= 0) { switch (quad) { case 0: returnValue |= DIRECTION_MASK_EAST; break; case 1: returnValue |= DIRECTION_MASK_SOUTH; break; case 2: returnValue |= DIRECTION_MASK_WEST; break; case 3: returnValue |= DIRECTION_MASK_NORTH; break; } } return returnValue; }; /** * Function: reversePortConstraints * * Reverse the port constraint bitmask. For example, north | east * becomes south | west */ export const reversePortConstraints = (constraint: number) => { let result = 0; result = (constraint & DIRECTION_MASK_WEST) << 3; result |= (constraint & DIRECTION_MASK_NORTH) << 1; result |= (constraint & DIRECTION_MASK_SOUTH) >> 1; result |= (constraint & DIRECTION_MASK_EAST) >> 3; return result; }; /** * Function: findNearestSegment * * Finds the index of the nearest segment on the given cell state for * the specified coordinate pair. */ export const findNearestSegment = (state: CellState, x: number, y: number) => { let index = -1; if (state.absolutePoints.length > 0) { let last = state.absolutePoints[0]; let min = null; for (let i = 1; i < state.absolutePoints.length; i += 1) { const current = state.absolutePoints[i]; if (!last || !current) continue; const dist = ptSegDistSq(last.x, last.y, current.x, current.y, x, y); if (min == null || dist < min) { min = dist; index = i - 1; } last = current; } } return index; }; /** * Function: getDirectedBounds * * Adds the given margins to the given rectangle and rotates and flips the * rectangle according to the respective styles in style. */ export const getDirectedBounds = ( rect: Rectangle, m: Rectangle, style: CellStateStyles | null, flipH: boolean, flipV: boolean ) => { const d = getValue(style, 'direction', DIRECTION_EAST); flipH = flipH != null ? flipH : getValue(style, 'flipH', false); flipV = flipV != null ? flipV : getValue(style, 'flipV', false); m.x = Math.round(Math.max(0, Math.min(rect.width, m.x))); m.y = Math.round(Math.max(0, Math.min(rect.height, m.y))); m.width = Math.round(Math.max(0, Math.min(rect.width, m.width))); m.height = Math.round(Math.max(0, Math.min(rect.height, m.height))); if ( (flipV && (d === DIRECTION_SOUTH || d === DIRECTION_NORTH)) || (flipH && (d === DIRECTION_EAST || d === DIRECTION_WEST)) ) { const tmp = m.x; m.x = m.width; m.width = tmp; } if ( (flipH && (d === DIRECTION_SOUTH || d === DIRECTION_NORTH)) || (flipV && (d === DIRECTION_EAST || d === DIRECTION_WEST)) ) { const tmp = m.y; m.y = m.height; m.height = tmp; } const m2 = Rectangle.fromRectangle(m); if (d === DIRECTION_SOUTH) { m2.y = m.x; m2.x = m.height; m2.width = m.y; m2.height = m.width; } else if (d === DIRECTION_WEST) { m2.y = m.height; m2.x = m.width; m2.width = m.x; m2.height = m.y; } else if (d === DIRECTION_NORTH) { m2.y = m.width; m2.x = m.y; m2.width = m.height; m2.height = m.x; } return new Rectangle( rect.x + m2.x, rect.y + m2.y, rect.width - m2.width - m2.x, rect.height - m2.height - m2.y ); }; /** * Function: getPerimeterPoint * * Returns the intersection between the polygon defined by the array of * points and the line between center and point. */ export const getPerimeterPoint = (pts: Point[], center: Point, point: Point) => { let min = null; for (let i = 0; i < pts.length - 1; i += 1) { const pt = intersection( pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, center.x, center.y, point.x, point.y ); if (pt != null) { const dx = point.x - pt.x; const dy = point.y - pt.y; const ip = { p: pt, distSq: dy * dy + dx * dx }; if (ip != null && (min == null || min.distSq > ip.distSq)) { min = ip; } } } return min != null ? min.p : null; }; /** * Function: rectangleIntersectsSegment * * Returns true if the given rectangle intersects the given segment. * * Parameters: * * bounds - <mxRectangle> that represents the rectangle. * p1 - <mxPoint> that represents the first point of the segment. * p2 - <mxPoint> that represents the second point of the segment. */ export const rectangleIntersectsSegment = (bounds: Rectangle, p1: Point, p2: Point) => { const top = bounds.y; const left = bounds.x; const bottom = top + bounds.height; const right = left + bounds.width; // Find min and max X for the segment let minX = p1.x; let maxX = p2.x; if (p1.x > p2.x) { minX = p2.x; maxX = p1.x; } // Find the intersection of the segment's and rectangle's x-projections if (maxX > right) { maxX = right; } if (minX < left) { minX = left; } if (minX > maxX) { // If their projections do not intersect return false return false; } // Find corresponding min and max Y for min and max X we found before let minY = p1.y; let maxY = p2.y; const dx = p2.x - p1.x; if (Math.abs(dx) > 0.0000001) { const a = (p2.y - p1.y) / dx; const b = p1.y - a * p1.x; minY = a * minX + b; maxY = a * maxX + b; } if (minY > maxY) { const tmp = maxY; maxY = minY; minY = tmp; } // Find the intersection of the segment's and rectangle's y-projections if (maxY > bottom) { maxY = bottom; } if (minY < top) { minY = top; } if (minY > maxY) { // If Y-projections do not intersect return false return false; } return true; }; /** * Function: contains * * Returns true if the specified point (x, y) is contained in the given rectangle. * * Parameters: * * bounds - <mxRectangle> that represents the area. * x - X-coordinate of the point. * y - Y-coordinate of the point. */ export const contains = (bounds: Rectangle, x: number, y: number) => { return ( bounds.x <= x && bounds.x + bounds.width >= x && bounds.y <= y && bounds.y + bounds.height >= y ); }; /** * Function: intersects * * Returns true if the two rectangles intersect. * * Parameters: * * a - <mxRectangle> to be checked for intersection. * b - <mxRectangle> to be checked for intersection. */ export const intersects = (a: Rectangle, b: Rectangle) => { let tw = a.width; let th = a.height; let rw = b.width; let rh = b.height; if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { return false; } const tx = a.x; const ty = a.y; const rx = b.x; const ry = b.y; rw += rx; rh += ry; tw += tx; th += ty; return ( (rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry) ); }; /** * Function: intersectsHotspot * * Returns true if the state and the hotspot intersect. * * Parameters: * * state - <mxCellState> * x - X-coordinate. * y - Y-coordinate. * hotspot - Optional size of the hostpot. * min - Optional min size of the hostpot. * max - Optional max size of the hostpot. */ export const intersectsHotspot = ( state: CellState, x: number, y: number, hotspot: number, min: number, max: number ) => { hotspot = hotspot != null ? hotspot : 1; min = min != null ? min : 0; max = max != null ? max : 0; if (hotspot > 0) { let cx = state.getCenterX(); let cy = state.getCenterY(); let w = state.width; let h = state.height; const start = getValue(state.style, 'startSize') * state.view.scale; if (start > 0) { if (getValue(state.style, 'horizontal', true)) { cy = state.y + start / 2; h = start; } else { cx = state.x + start / 2; w = start; } } w = Math.max(min, w * hotspot); h = Math.max(min, h * hotspot); if (max > 0) { w = Math.min(w, max); h = Math.min(h, max); } const rect = new Rectangle(cx - w / 2, cy - h / 2, w, h); const alpha = toRadians(getValue(state.style, 'rotation') || 0); if (alpha != 0) { const cos = Math.cos(-alpha); const sin = Math.sin(-alpha); const cx = new Point(state.getCenterX(), state.getCenterY()); const pt = getRotatedPoint(new Point(x, y), cos, sin, cx); x = pt.x; y = pt.y; } return contains(rect, x, y); } return true; }; /** * Function: getOffset * * Returns the offset for the specified container as an <mxPoint>. The * offset is the distance from the top left corner of the container to the * top left corner of the document. * * Parameters: * * container - DOM node to return the offset for. * scollOffset - Optional boolean to add the scroll offset of the document. * Default is false. */ export const getOffset = (container: HTMLElement, scrollOffset = false) => { let offsetLeft = 0; let offsetTop = 0; // Ignores document scroll origin for fixed elements let fixed = false; let node: HTMLElement | null = container; const b = document.body; const d = document.documentElement; while (node != null && node != b && node != d && !fixed) { const style = getCurrentStyle(node); if (style != null) { fixed = fixed || style.position == 'fixed'; } node = node.parentNode as HTMLElement; } if (!scrollOffset && !fixed) { const offset = getDocumentScrollOrigin(container.ownerDocument); offsetLeft += offset.x; offsetTop += offset.y; } const r = container.getBoundingClientRect(); if (r != null) { offsetLeft += r.left; offsetTop += r.top; } return new Point(offsetLeft, offsetTop); }; /** * Function: getDocumentScrollOrigin * * Returns the scroll origin of the given document or the current document * if no document is given. */ export const getDocumentScrollOrigin = (doc: Document) => { // @ts-ignore 'parentWindow' is an unknown property. const wnd = doc.defaultView || doc.parentWindow; const x = wnd != null && window.pageXOffset !== undefined ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body) .scrollLeft; const y = wnd != null && window.pageYOffset !== undefined ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; return new Point(x, y); }; /** * Function: getScrollOrigin * * Returns the top, left corner of the viewrect as an <mxPoint>. * * Parameters: * * node - DOM node whose scroll origin should be returned. * includeAncestors - Whether the scroll origin of the ancestors should be * included. Default is false. * includeDocument - Whether the scroll origin of the document should be * included. Default is true. */ export const getScrollOrigin = ( node: HTMLElement | null = null, includeAncestors = false, includeDocument = true ) => { const doc = node != null ? node.ownerDocument : document; const b = doc.body; const d = doc.documentElement; const result = new Point(); let fixed = false; while (node != null && node != b && node != d) { if (!Number.isNaN(node.scrollLeft) && !Number.isNaN(node.scrollTop)) { result.x += node.scrollLeft; result.y += node.scrollTop; } const style = getCurrentStyle(node); if (style != null) { fixed = fixed || style.position == 'fixed'; } node = includeAncestors ? (node.parentNode as HTMLElement) : null; } if (!fixed && includeDocument) { const origin = getDocumentScrollOrigin(doc); result.x += origin.x; result.y += origin.y; } return result; }; /** * Function: convertPoint * * Converts the specified point (x, y) using the offset of the specified * container and returns a new <mxPoint> with the result. * * (code) * let pt = mxUtils.convertPoint(graph.container, * mxEvent.getClientX(evt), mxEvent.getClientY(evt)); * (end) * * Parameters: * * container - DOM node to use for the offset. * x - X-coordinate of the point to be converted. * y - Y-coordinate of the point to be converted. */ export const convertPoint = (container: HTMLElement, x: number, y: number) => { const origin = getScrollOrigin(container, false); const offset = getOffset(container); offset.x -= origin.x; offset.y -= origin.y; return new Point(x - offset.x, y - offset.y); }; /** * Function: isNumeric * * Returns true if the specified value is numeric, that is, if it is not * null, not an empty string, not a HEX number and isNaN returns false. * * Parameters: * * n - String representing the possibly numeric value. */ export const isNumeric = (n: any) => { return ( !Number.isNaN(parseFloat(n)) && isFinite(+n) && (typeof n !== 'string' || n.toLowerCase().indexOf('0x') < 0) ); }; /** * Function: isInteger * * Returns true if the given value is an valid integer number. * * Parameters: * * n - String representing the possibly numeric value. */ export const isInteger = (n: string) => { return String(parseInt(n)) === String(n); }; /** * Function: mod * * Returns the remainder of division of n by m. You should use this instead * of the built-in operation as the built-in operation does not properly * handle negative numbers. */ export const mod = (n: number, m: number) => { return ((n % m) + m) % m; }; /** * Function: intersection * * Returns the intersection of two lines as an <mxPoint>. * * Parameters: * * x0 - X-coordinate of the first line's startpoint. * y0 - X-coordinate of the first line's startpoint. * x1 - X-coordinate of the first line's endpoint. * y1 - Y-coordinate of the first line's endpoint. * x2 - X-coordinate of the second line's startpoint. * y2 - Y-coordinate of the second line's startpoint. * x3 - X-coordinate of the second line's endpoint. * y3 - Y-coordinate of the second line's endpoint. */ export const intersection = ( x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number ) => { const denom = (y3 - y2) * (x1 - x0) - (x3 - x2) * (y1 - y0); const nume_a = (x3 - x2) * (y0 - y2) - (y3 - y2) * (x0 - x2); const nume_b = (x1 - x0) * (y0 - y2) - (y1 - y0) * (x0 - x2); const ua = nume_a / denom; const ub = nume_b / denom; if (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0) { // Get the intersection point const x = x0 + ua * (x1 - x0); const y = y0 + ua * (y1 - y0); return new Point(x, y); } // No intersection return null; }; /** * Function: ptSegDistSq * * Returns the square distance between a segment and a point. To get the * distance between a point and a line (with infinite length) use * <mxUtils.ptLineDist>. * * Parameters: * * x1 - X-coordinate of the startpoint of the segment. * y1 - Y-coordinate of the startpoint of the segment. * x2 - X-coordinate of the endpoint of the segment. * y2 - Y-coordinate of the endpoint of the segment. * px - X-coordinate of the point. * py - Y-coordinate of the point. */ export const ptSegDistSq = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { x2 -= x1; y2 -= y1; px -= x1; py -= y1; let dotprod = px * x2 + py * y2; let projlenSq; if (dotprod <= 0.0) { projlenSq = 0.0; } else { px = x2 - px; py = y2 - py; dotprod = px * x2 + py * y2; if (dotprod <= 0.0) { projlenSq = 0.0; } else { projlenSq = (dotprod * dotprod) / (x2 * x2 + y2 * y2); } } let lenSq = px * px + py * py - projlenSq; if (lenSq < 0) { lenSq = 0; } return lenSq; }; /** * Function: ptLineDist * * Returns the distance between a line defined by two points and a point. * To get the distance between a point and a segment (with a specific * length) use <mxUtils.ptSeqDistSq>. * * Parameters: * * x1 - X-coordinate of point 1 of the line. * y1 - Y-coordinate of point 1 of the line. * x2 - X-coordinate of point 1 of the line. * y2 - Y-coordinate of point 1 of the line. * px - X-coordinate of the point. * py - Y-coordinate of the point. */ export const ptLineDist = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { return ( Math.abs((y2 - y1) * px - (x2 - x1) * py + x2 * y1 - y2 * x1) / Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)) ); }; /** * Function: relativeCcw * * Returns 1 if the given point on the right side of the segment, 0 if its * on the segment, and -1 if the point is on the left side of the segment. * * Parameters: * * x1 - X-coordinate of the startpoint of the segment. * y1 - Y-coordinate of the startpoint of the segment. * x2 - X-coordinate of the endpoint of the segment. * y2 - Y-coordinate of the endpoint of the segment. * px - X-coordinate of the point. * py - Y-coordinate of the point. */ export const relativeCcw = ( x1: number, y1: number, x2: number, y2: number, px: number, py: number ) => { x2 -= x1; y2 -= y1; px -= x1; py -= y1; let ccw = px * y2 - py * x2; if (ccw == 0.0) { ccw = px * x2 + py * y2; if (ccw > 0.0) { px -= x2; py -= y2; ccw = px * x2 + py * y2; if (ccw < 0.0) { ccw = 0.0; } } } return ccw < 0.0 ? -1 : ccw > 0.0 ? 1 : 0; }; /** * Function: setOpacity * * Sets the opacity of the specified DOM node to the given value in %. * * Parameters: * * node - DOM node to set the opacity for. * value - Opacity in %. Possible values are between 0 and 100. */ export const setOpacity = (node: HTMLElement | SVGElement, value: number) => { node.style.opacity = String(value / 100); }; /** * Function: createImage * * Creates and returns an image (IMG node) or VML image (v:image) in IE6 in * quirks mode. * * Parameters: * * src - URL that points to the image to be displayed. */ export const createImage = (src: string) => { let imageNode = null; imageNode = document.createElement('img'); imageNode.setAttribute('src', src); imageNode.setAttribute('border', '0'); return imageNode; }; /** * Function: sortCells * * Sorts the given cells according to the order in the cell hierarchy. * Ascending is optional and defaults to true. */ export const sortCells = (cells: CellArray, ascending = true): CellArray => { const lookup = new Dictionary<Cell, string[]>(); cells.sort((o1, o2) => { let p1 = lookup.get(o1); if (p1 == null) { p1 = CellPath.create(o1).split(CellPath.PATH_SEPARATOR); lookup.put(o1, p1); } let p2 = lookup.get(o2); if (p2 == null) { p2 = CellPath.create(o2).split(CellPath.PATH_SEPARATOR); lookup.put(o2, p2); } const comp = CellPath.compare(p1, p2); return comp == 0 ? 0 : comp > 0 == ascending ? 1 : -1; }); return cells; }; /** * Function: getStylename * * Returns the stylename in a style of the form [(stylename|key=value);] or * an empty string if the given style does not contain a stylename. * * Parameters: * * style - String of the form [(stylename|key=value);]. */ export const getStylename = (style: string) => { const pairs = style.split(';'); const stylename = pairs[0]; if (stylename.indexOf('=') < 0) { return stylename; } return ''; }; /** * Function: getStylenames * * Returns the stylenames in a style of the form [(stylename|key=value);] * or an empty array if the given style does not contain any stylenames. * * Parameters: * * style - String of the form [(stylename|key=value);]. */ export const getStylenames = (style: string) => { const result = []; const pairs = style.split(';'); for (let i = 0; i < pairs.length; i += 1) { if (pairs[i].indexOf('=') < 0) { result.push(pairs[i]); } } return result; }; /** * Function: indexOfStylename * * Returns the index of the given stylename in the given style. This * returns -1 if the given stylename does not occur (as a stylename) in the * given style, otherwise it returns the index of the first character. */ export const indexOfStylename = (style: string, stylename: string) => { const tokens = style.split(';'); let pos = 0; for (let i = 0; i < tokens.length; i += 1) { if (tokens[i] == stylename) { return pos; } pos += tokens[i].length + 1; } return -1; }; /** * Function: addStylename * * Adds the specified stylename to the given style if it does not already * contain the stylename. */ export const addStylename = (style: string, stylename: string) => { if (indexOfStylename(style, stylename) < 0) { if (style == null) { style = ''; } else if (style.length > 0 && style.charAt(style.length - 1) != ';') { style += ';'; } style += stylename; } return style; }; /** * Function: removeStylename * * Removes all occurrences of the specified stylename in the given style * and returns the updated style. Trailing semicolons are not preserved. */ export const removeStylename = (style: string, stylename: string) => { const result = []; const tokens = style.split(';'); for (let i = 0; i < tokens.length; i += 1) { if (tokens[i] != stylename) { result.push(tokens[i]); } } return result.join(';'); }; /** * Function: removeAllStylenames * * Removes all stylenames from the given style and returns the updated * style. */ export const removeAllStylenames = (style: string) => { const result = []; const tokens = style.split(';'); for (let i = 0; i < tokens.length; i += 1) { // Keeps the key, value assignments if (tokens[i].indexOf('=') >= 0) { result.push(tokens[i]); } } return result.join(';'); }; /** * Function: setCellStyles * * Assigns the value for the given key in the styles of the given cells, or * removes the key from the styles if the value is null. * * Parameters: * * model - <Transactions> to execute the transaction in. * cells - Array of <mxCells> to be updated. * key - Key of the style to be changed. * value - New value for the given key. */ export const setCellStyles = ( model: Model, cells: CellArray, key: string, value: any ) => { if (cells.length > 0) { model.beginUpdate(); try { for (let i = 0; i < cells.length; i += 1) { const cell = cells[i]; if (cell) { const style = setStyle(cell.getStyle(), key, value); model.setStyle(cell, style); } } } finally { model.endUpdate(); } } }; /** * Function: setStyle * * Adds or removes the given key, value pair to the style and returns the * new style. If value is null or zero length then the key is removed from * the style. This is for cell styles, not for CSS styles. * * Parameters: * * style - String of the form [(stylename|key=value);]. * key - Key of the style to be changed. * value - New value for the given key. */ export const setStyle = (style: string | null, key: string, value: any) => { const isValue = value != null && (typeof value.length === 'undefined' || value.length > 0); if (style == null || style.length == 0) { if (isValue) { style = `${key}=${value};`; } } else if (style.substring(0, key.length + 1) == `${key}=`) { const next = style.indexOf(';'); if (isValue) { style = `${key}=${value}${next < 0 ? ';' : style.substring(next)}`; } else { style = next < 0 || next == style.length - 1 ? '' : style.substring(next + 1); } } else { const index = style.indexOf(`;${key}=`); if (index < 0) { if (isValue) { const sep = style.charAt(style.length - 1) == ';' ? '' : ';'; style = `${style + sep + key}=${value};`; } } else { const next = style.indexOf(';', index + 1); if (isValue) { style = `${style.substring(0, index + 1) + key}=${value}${ next < 0 ? ';' : style.substring(next) }`; } else { style = style.substring(0, index) + (next < 0 ? ';' : style.substring(next)); } } } return style; }; /** * Function: setCellStyleFlags * * Sets or toggles the flag bit for the given key in the cell's styles. * If value is null then the flag is toggled. * * Example: * * (code) * let cells = graph.getSelectionCells(); * mxUtils.setCellStyleFlags(graph.model, * cells, * mxConstants.STYLE_FONTSTYLE, * mxConstants.FONT_BOLD); * (end) * * Toggles the bold font style. * * Parameters: * * model - <Transactions> that contains the cells. * cells - Array of <mxCells> to change the style for. * key - Key of the style to be changed. * flag - Integer for the bit to be changed. * value - Optional boolean value for the flag. */ export const setCellStyleFlags = ( model: Model, cells: CellArray, key: string, flag: number, value: boolean ) => { if (cells.length > 0) { model.beginUpdate(); try { for (let i = 0; i < cells.length; i += 1) { const cell = cells[i]; if (cell) { const style = setStyleFlag(cell.getStyle(), key, flag, value); model.setStyle(cell, style); } } } finally { model.endUpdate(); } } }; /** * Function: setStyleFlag * * Sets or removes the given key from the specified style and returns the * new style. If value is null then the flag is toggled. * * Parameters: * * style - String of the form [(stylename|key=value);]. * key - Key of the style to be changed. * flag - Integer for the bit to be changed. * value - Optional boolean value for the given flag. */ export const setStyleFlag = ( style: string | null, key: string, flag: number, value: boolean ) => { if (style == null || style.length == 0) { if (value || value == null) { style = `${key}=${flag}`; } else { style = `${key}=0`; } } else { const index = style.indexOf(`${key}=`); if (index < 0) { const sep = style.charAt(style.length - 1) == ';' ? '' : ';'; if (value || value == null) { style = `${style + sep + key}=${flag}`; } else { style = `${style + sep + key}=0`; } } else { const cont = style.indexOf(';', index); let tmp = ''; if (cont < 0) { tmp = style.substring(index + key.length + 1); } else { tmp = style.substring(index + key.length + 1, cont); } if (value == null) { tmp = String(parseInt(tmp) ^ flag); } else if (value) { tmp = String(parseInt(tmp) | flag); } else { tmp = String(parseInt(tmp) & ~flag); } style = `${style.substring(0, index) + key}=${tmp}${ cont >= 0 ? style.substring(cont) : '' }`; } } return style; }; /** * Function: getAlignmentAsPoint * * Returns an <mxPoint> that represents the horizontal and vertical alignment * for numeric computations. X is -0.5 for center, -1 for right and 0 for * left alignment. Y is -0.5 for middle, -1 for bottom and 0 for top * alignment. Default values for missing arguments is top, left. */ export const getAlignmentAsPoint = (align: string, valign: string) => { let dx = -0.5; let dy = -0.5; // Horizontal alignment if (align === ALIGN_LEFT) { dx = 0; } else if (align === ALIGN_RIGHT) { dx = -1; } // Vertical alignment if (valign === ALIGN_TOP) { dy = 0; } else if (valign === ALIGN_BOTTOM) { dy = -1; } return new Point(dx, dy); }; /** * Function: getSizeForString * * Returns an <mxRectangle> with the size (width and height in pixels) of * the given string. The string may contain HTML markup. Newlines should be * converted to <br> before calling this method. The caller is responsible * for sanitizing the HTML markup. * * Example: * * (code) * let label = graph.getLabel(cell).replace(/\n/g, "<br>"); * let size = graph.getSizeForString(label); * (end) * * Parameters: * * text - String whose size should be returned. * fontSize - Integer that specifies the font size in pixels. Default is * <mxConstants.DEFAULT_FONTSIZE>. * fontFamily - String that specifies the name of the font family. Default * is <mxConstants.DEFAULT_FONTFAMILY>. * textWidth - Optional width for text wrapping. * fontStyle - Optional font style. */ export const getSizeForString = ( text: string, fontSize = DEFAULT_FONTSIZE, fontFamily = DEFAULT_FONTFAMILY, textWidth: number | null = null, fontStyle: number | null = null ) => { const div = document.createElement('div'); // Sets the font size and family div.style.fontFamily = fontFamily; div.style.fontSize = `${Math.round(fontSize)}px`; div.style.lineHeight = `${Math.round(fontSize * LINE_HEIGHT)}px`; // Sets the font style if (fontStyle !== null) { if ((fontStyle & FONT_BOLD) === FONT_BOLD) { div.style.fontWeight = 'bold'; } if ((fontStyle & FONT_ITALIC) === FONT_ITALIC) { div.style.fontStyle = 'italic'; } const txtDecor = []; if ((fontStyle & FONT_UNDERLINE) == FONT_UNDERLINE) { txtDecor.push('underline'); } if ((fontStyle & FONT_STRIKETHROUGH) == FONT_STRIKETHROUGH) { txtDecor.push('line-through'); } if (txtDecor.length > 0) { div.style.textDecoration = txtDecor.join(' '); } } // Disables block layout and outside wrapping and hides the div div.style.position = 'absolute'; div.style.visibility = 'hidden'; div.style.display = 'inline-block'; if (textWidth !== null) { div.style.width = `${textWidth}px`; div.style.whiteSpace = 'normal'; } else { div.style.whiteSpace = 'nowrap'; } // Adds the text and inserts into DOM for updating of size div.innerHTML = text; document.body.appendChild(div); // Gets the size and removes from DOM const size = new Rectangle(0, 0, div.offsetWidth, div.offsetHeight); document.body.removeChild(div); return size; }; /** * Function: getScaleForPageCount * * Returns the scale to be used for printing the graph with the given * bounds across the specifies number of pages with the given format. The * scale is always computed such that it given the given amount or fewer * pages in the print output. See <mxPrintPreview> for an example. * * Parameters: * * pageCount - Specifies the number of pages in the print output. * graph - <mxGraph> that should be printed. * pageFormat - Optional <mxRectangle> that specifies the page format. * Default is <mxConstants.PAGE_FORMAT_A4_PORTRAIT>. * border - The border along each side of every page. */ export const getScaleForPageCount = ( pageCount: number, graph: Graph, pageFormat?: Rectangle, border = 0 ) => { if (pageCount < 1) { // We can't work with less than 1 page, return no scale // change return 1; } pageFormat = pageFormat != null ? pageFormat : new Rectangle(...PAGE_FORMAT_A4_PORTRAIT); const availablePageWidth = pageFormat.width - border * 2; const availablePageHeight = pageFormat.height - border * 2; // Work out the number of pages required if the // graph is not scaled. const graphBounds = graph.getGraphBounds().clone(); const sc = graph.getView().getScale(); graphBounds.width /= sc; graphBounds.height /= sc; const graphWidth = graphBounds.width; const graphHeight = graphBounds.height; let scale = 1; // The ratio of the width/height for each printer page const pageFormatAspectRatio = availablePageWidth / availablePageHeight; // The ratio of the width/height for the graph to be printer const graphAspectRatio = graphWidth / graphHeight; // The ratio of horizontal pages / vertical pages for this // graph to maintain its aspect ratio on this page format const pagesAspectRatio = graphAspectRatio / pageFormatAspectRatio; // Factor the square root of the page count up and down // by the pages aspect ratio to obtain a horizontal and // vertical page count that adds up to the page count // and has the correct aspect ratio const pageRoot = Math.sqrt(pageCount); const pagesAspectRatioSqrt = Math.sqrt(pagesAspectRatio); let numRowPages = pageRoot * pagesAspectRatioSqrt; let numColumnPages = pageRoot / pagesAspectRatioSqrt; // These value are rarely more than 2 rounding downs away from // a total that meets the page count. In cases of one being less // than 1 page, the other value can be too high and take more iterations // In this case, just change that value to be the page count, since // we know the other value is 1 if (numRowPages < 1 && numColumnPages > pageCount) { const scaleChange = numColumnPages / pageCount; numColumnPages = pageCount; numRowPages /= scaleChange; } if (numColumnPages < 1 && numRowPages > pageCount) { const scaleChange = numRowPages / pageCount; numRowPages = pageCount; numColumnPages /= scaleChange; } let currentTotalPages = Math.ceil(numRowPages) * Math.ceil(numColumnPages); let numLoops = 0; // Iterate through while the rounded up number of pages comes to // a total greater than the required number while (currentTotalPages > pageCount) { // Round down the page count (rows or columns) that is // closest to its next integer down in percentage terms. // i.e. Reduce the page total by reducing the total // page area by the least possible amount let roundRowDownProportion = Math.floor(numRowPages) / numRowPages; let roundColumnDownProportion = Math.floor(numColumnPages) / numColumnPages; // If the round down proportion is, work out the proportion to // round down to 1 page less if (roundRowDownProportion == 1) { roundRowDownProportion = Math.floor(numRowPages - 1) / numRowPages; } if (roundColumnDownProportion == 1) { roundColumnDownProportion = Math.floor(numColumnPages - 1) / numColumnPages; } // Check which rounding down is smaller, but in the case of very small roundings // try the other dimension instead let scaleChange = 1; // Use the higher of the two values if (roundRowDownProportion > roundColumnDownProportion) { scaleChange = roundRowDownProportion; } else { scaleChange = roundColumnDownProportion; } numRowPages *= scaleChange; numColumnPages *= scaleChange; currentTotalPages = Math.ceil(numRowPages) * Math.ceil(numColumnPages); numLoops++; if (numLoops > 10) { break; } } // Work out the scale from the number of row pages required // The column pages will give the same value const posterWidth = availablePageWidth * numRowPages; scale = posterWidth / graphWidth; // Allow for rounding errors return scale * 0.99999; }; /** * Function: show * * Copies the styles and the markup from the graph's container into the * given document and removes all cursor styles. The document is returned. * * This function should be called from within the document with the graph. * If you experience problems with missing stylesheets in IE then try adding * the domain to the trusted sites. * * Parameters: * * graph - <mxGraph> to be copied. * doc - Document where the new graph is created. * x0 - X-coordinate of the graph view origin. Default is 0. * y0 - Y-coordinate of the graph view origin. Default is 0. * w - Optional width of the graph view. * h - Optional height of the graph view. */ export const show = ( graph: Graph, doc: Document, x0 = 0, y0 = 0, w?: number, h?: number ) => { x0 = x0 != null ? x0 : 0; y0 = y0 != null ? y0 : 0; if (doc == null) { const wnd = window.open() as Window; doc = wnd.document; } else { doc.open(); } const bounds = graph.getGraphBounds(); const dx = Math.ceil(x0 - bounds.x); const dy = Math.ceil(y0 - bounds.y); if (w == null) { w = Math.ceil(bounds.width + x0) + Math.ceil(Math.ceil(bounds.x) - bounds.x); } if (h == null) { h = Math.ceil(bounds.height + y0) + Math.ceil(Math.ceil(bounds.y) - bounds.y); } doc.writeln('<html><head>'); const base = document.getElementsByTagName('base'); for (let i = 0; i < base.length; i += 1) { doc.writeln(getOuterHtml(base[i])); } const links = document.getElementsByTagName('link'); for (let i = 0; i < links.length; i += 1) { doc.writeln(getOuterHtml(links[i])); } const styles = document.getElementsByTagName('style'); for (let i = 0; i < styles.length; i += 1) { doc.writeln(getOuterHtml(styles[i])); } doc.writeln('</head><body style="margin:0px;"></body></html>'); doc.close(); const outer = doc.createElement('div'); outer.style.position = 'absolute'; outer.style.overflow = 'hidden'; outer.style.width = `${w}px`; outer.style.height = `${h}px`; // Required for HTML labels if foreignObjects are disabled const div = doc.createElement('div'); div.style.position = 'absolute'; div.style.left = `${dx}px`; div.style.top = `${dy}px`; if (graph.container && graph.view.drawPane) { let node = graph.container.firstChild; let svg: SVGElement | null = null; while (node != null) { const clone = node.cloneNode(true); if (node == graph.view.drawPane.ownerSVGElement) { outer.appendChild(clone); svg = clone as SVGElement; } else { div.appendChild(clone); } node = node.nextSibling; } doc.body.appendChild(outer); if (div.firstChild != null) { doc.body.appendChild(div); } if (svg != null) { svg.style.minWidth = ''; svg.style.minHeight = ''; if (svg.firstChild) (svg.firstChild as HTMLElement).setAttribute( 'transform', `translate(${dx},${dy})` ); } removeCursors(doc.body); } return doc; }; /** * Function: printScreen * * Prints the specified graph using a new window and the built-in print * dialog. * * This function should be called from within the document with the graph. * * Parameters: * * graph - <mxGraph> to be printed. */ export const printScreen = (graph: Graph) => { const wnd = window.open(); if (!wnd) return; const bounds = graph.getGraphBounds(); show(graph, wnd.document); const print = () => { wnd.focus(); wnd.print(); wnd.close(); }; // Workaround for Google Chrome which needs a bit of a // delay in order to render the SVG contents if (mxClient.IS_GC) { wnd.setTimeout(print, 500); } else { print(); } }; export const isNullish = (v: string | object | null | undefined | number) => v === null || v === undefined; export const isNotNullish = (v: string | object | null | undefined | number) => !isNullish(v); // Merge a mixin into the destination export const mixInto = (dest: any) => (mixin: any) => { const keys = Reflect.ownKeys(mixin); try { for (const key of keys) { Object.defineProperty(dest.prototype, key, { value: mixin[key], writable: true, }); } } catch (e) { console.error('Error while mixing', e); } };
the_stack
import "jest"; import JKFPlayer from "../jkfplayer"; /* tslint:disable:object-literal-sort-keys max-line-length no-unused-expression */ // TODO Fix type errors function p(x, y) { return {x, y}; } describe("class Player", () => { it("new", () => { new JKFPlayer({ header: {}, moves: [{}], }); }); describe("parse", () => { it("kif", () => { JKFPlayer.parseKIF("1 7六歩\n"); JKFPlayer.parse("1 7六歩\n"); JKFPlayer.parse("1 7六歩\n", "hoge.kif"); }); it("ki2", () => { JKFPlayer.parseKI2("▲7六歩"); JKFPlayer.parse("▲7六歩"); JKFPlayer.parse("▲7六歩", "./hoge.ki2"); }); it("csa", () => { JKFPlayer.parseCSA("PI\n+\n"); JKFPlayer.parse("PI\n+\n"); JKFPlayer.parse("PI\n+\n", "http://shogitter.com/kifu/hoge.csa"); }); it("jkf", () => { JKFPlayer.parseJKF('{"header":{},"moves":[]}'); JKFPlayer.parse('{"header":{},"moves":[]}'); JKFPlayer.parse('{"header":{},"moves":[]}', "hoge.jkf"); }); it("illegal", () => { expect(() => { JKFPlayer.parse("ふが"); }).toThrow(); }); }); describe("forward", () => { it("normal", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {move: {from: p(8, 9), to: p(7, 7), color: 0, piece: "KE"}}, { move: { from: p(2, 2), to: p(7, 7), color: 1, piece: "KA", capture: "KE", promote: true, same: true, }, }, {move: {from: p(8, 8), to: p(7, 7), color: 0, piece: "KA", capture: "UM", same: true}}, {move: {to: p(3, 3), color: 1, piece: "KE", relative: "H"}}, ], }); expect(player.shogi.toCSAString()).toBe("\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * * * * * * * * \n\ P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ P+\n\ P-\n\ +"); expect(player.forward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe("\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * -KA * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P4 * * * * * * * * * \n\ P5 * * * * * * * * * \n\ P6 * * +FU * * * * * * \n\ P7+FU+FU * +FU+FU+FU+FU+FU+FU\n\ P8 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ P+\n\ P-\n\ -"); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); const sixth = "\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\ P2 * -HI * * * * * * * \n\ P3-FU-FU-FU-FU-FU-FU-KE-FU-FU\n\ P4 * * * * * * -FU * * \n\ P5 * * * * * * * * * \n\ P6 * * +FU * * * * * * \n\ P7+FU+FU+KA+FU+FU+FU+FU+FU+FU\n\ P8 * * * * * * * +HI * \n\ P9+KY * +GI+KI+OU+KI+GI+KE+KY\n\ P+00KA\n\ P-\n\ +"; expect(player.shogi.toCSAString()).toBe(sixth); expect(player.forward()).toBeFalsy(); expect(player.shogi.toCSAString()).toBe(sixth); }); it("with special", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {special: "CHUDAN"}, ], }); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); const second = player.shogi.toCSAString(); expect(player.forward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(second); expect(player.forward()).toBe(false); expect(player.shogi.toCSAString()).toBe(second); }); }); describe("backward", () => { it("normal", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {special: "CHUDAN"}, ], }); const first = player.shogi.toCSAString(); player.forward(); expect(player.backward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(first); expect(player.backward()).toBeFalsy(); }); }); it("goto, go", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {special: "CHUDAN"}, ], }); const initial = player.shogi.toCSAString(); expect(player.tesuu).toBe(0); expect(player.forward()).toBeTruthy(); expect(player.tesuu).toBe(1); expect(player.forward()); expect(player.tesuu).toBe(2); const second = player.shogi.toCSAString(); expect(player.forward()); expect(player.tesuu).toBe(3); expect(player.forward()).toBeFalsy(); expect(player.tesuu).toBe(3); player.goto(0); expect(player.tesuu).toBe(0); expect(player.shogi.toCSAString()).toBe(initial); expect(player.backward()).toBeFalsy(); expect(player.tesuu).toBe(0); player.go(2); expect(player.tesuu).toBe(2); expect(player.shogi.toCSAString()).toBe(second); }); it("goto, go with string and invalid values", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {special: "CHUDAN"}, ], }); expect(player.tesuu).toBe(0); player.goto("2"); expect(player.tesuu).toBe(2); player.goto("foo"); expect(player.tesuu).toBe(2); player.go("-1"); expect(player.tesuu).toBe(1); player.go("bar"); expect(player.tesuu).toBe(1); player.go("Infinity"); expect(player.tesuu).toBe(3); player.go("-Infinity"); expect(player.tesuu).toBe(0); }); it("goto Infinity", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, {special: "CHUDAN"}, ], }); const first = player.shogi.toCSAString(); expect(player.tesuu).toBe(0); player.goto(Infinity); // goto last expect(player.tesuu).toBe(3); player.goto(-1); expect(player.tesuu).toBe(0); expect(player.shogi.toCSAString()).toBe(first); }); describe("forkAndForward", () => { it("new", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, { move: {from: p(8, 9), to: p(7, 7), color: 0, piece: "KE"}, forks: [ [ { move: { from: p(8, 8), to: p(2, 2), color: 0, piece: "KA", capture: "KA", promote: false, }, }, {move: {from: p(3, 1), to: p(2, 2), color: 1, piece: "GI", capture: "KA", same: true}}, {move: {to: p(4, 5), color: 0, piece: "KA"}}, ], ], }, { move: { from: p(2, 2), to: p(7, 7), color: 1, piece: "KA", capture: "KE", promote: true, same: true, }, }, {move: {from: p(8, 8), to: p(7, 7), color: 0, piece: "KA", capture: "UM", same: true}}, {move: {to: p(3, 3), color: 1, piece: "KE", relative: "H"}}, ], }); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); const beforeFork = player.shogi.toCSAString(); expect(player.forkAndForward(1)).toBe(false); expect(player.shogi.toCSAString()).toBe(beforeFork); expect(player.forkAndForward(0)).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.forward()).toBe(false); expect(player.backward()).toBeTruthy(); expect(player.backward()).toBeTruthy(); expect(player.backward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(beforeFork); expect(player.forkAndForward("0")).toBeTruthy(); }); }); describe("forkPointers, forks, currentStream", () => { function duplicate(obj) { return JSON.parse(JSON.stringify(obj)); } it("one fork", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}}, { move: {from: p(8, 9), to: p(7, 7), color: 0, piece: "KE"}, forks: [ [ { move: { from: p(8, 8), to: p(2, 2), color: 0, piece: "KA", capture: "KA", promote: false, }, }, {move: {from: p(3, 1), to: p(2, 2), color: 1, piece: "GI", capture: "KA", same: true}}, {move: {to: p(4, 5), color: 0, piece: "KA"}}, ], ], }, { move: { from: p(2, 2), to: p(7, 7), color: 1, piece: "KA", capture: "KE", promote: true, same: true, }, }, {move: {from: p(8, 8), to: p(7, 7), color: 0, piece: "KA", capture: "UM", same: true}}, {move: {to: p(3, 3), color: 1, piece: "KE", relative: "H"}}, ], }); expect(player.forkPointers.length).toBe(0); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(1); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream).toMatchSnapshot("currentStream"); expect(player.currentStream.length).toBe(7); const firstForkPointers = duplicate(player.forkPointers); const firstForks = duplicate(player.forks); const firstCurrentStream = duplicate(player.currentStream); player.goto(2); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream).toMatchSnapshot("currentStream"); expect(player.forkPointers).toEqual(firstForkPointers); expect(player.forks).toEqual(firstForks); expect(player.currentStream).toEqual(firstCurrentStream); player.forkAndForward(0); expect(player.forkPointers.length).toBe(1); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(2); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream.length).toBe(6); expect(player.currentStream).toMatchSnapshot("currentStream"); const secondForkPointers = duplicate(player.forkPointers); const secondForks = duplicate(player.forks); const secondCurrentStream = duplicate(player.currentStream); player.goto(Infinity); expect(player.forkPointers).toEqual(secondForkPointers); expect(player.forks).toEqual(secondForks); expect(player.currentStream).toEqual(secondCurrentStream); }); it("nested fork", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, { move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}, forks: [ [ {move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}}, { move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 3), to: p(8, 4), color: 1, piece: "FU"}}, ], ], }, ], ], }, { move: {from: p(5, 3), to: p(5, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 3), to: p(8, 4), color: 1, piece: "FU"}}, {move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}}, { move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 4), to: p(8, 5), color: 1, piece: "FU"}}, {move: {from: p(8, 8), to: p(7, 7), color: 1, piece: "KA"}}, ], ], }, ], ], }, { move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}, forks: [ [ { move: { from: p(8, 8), to: p(2, 2), color: 0, piece: "KA", capture: "KA", promote: false, }, }, ], ], }, ], }); const firstForkPointers = duplicate(player.forkPointers); const firstForks = duplicate(player.forks); const firstCurrentStream = duplicate(player.currentStream); expect(player.forkPointers.length).toBe(0); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(1); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream).toMatchSnapshot("currentStream"); expect(player.currentStream.length).toBe(4); // +2726FU player.forkAndForward(0); expect(player.forkPointers.length).toBe(1); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(2); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream.length).toBe(3); expect(player.currentStream).toMatchSnapshot("currentStream"); // -8384FU player.forkAndForward(0); expect(player.forkPointers.length).toBe(2); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(3); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream.length).toBe(3); expect(player.currentStream).toMatchSnapshot("currentStream"); player.goto(0); expect(player.forkPointers).toEqual(firstForkPointers); expect(player.forks).toEqual(firstForks); expect(player.currentStream).toEqual(firstCurrentStream); // +7776FU player.goto(1); expect(player.forkPointers).toEqual(firstForkPointers); expect(player.forks).toEqual(firstForks); expect(player.currentStream).toEqual(firstCurrentStream); // -8384FU player.forkAndForward(0); expect(player.forkPointers.length).toBe(1); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(2); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream.length).toBe(5); expect(player.currentStream).toMatchSnapshot("currentStream"); // +2726FU player.goto(3); // -8485FU player.forkAndForward(0); expect(player.forkPointers.length).toBe(2); expect(player.forkPointers).toMatchSnapshot("forkPointers"); expect(player.forks.length).toBe(3); expect(player.forks).toMatchSnapshot("forks"); expect(player.currentStream.length).toBe(6); expect(player.currentStream).toMatchSnapshot("currentStream"); }); it("goto fork", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, { move: {from: p(7, 7), to: p(7, 6), color: 0, piece: "FU"}, forks: [ [ {move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}}, { move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 3), to: p(8, 4), color: 1, piece: "FU"}}, ], ], }, ], ], }, { move: {from: p(5, 3), to: p(5, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 3), to: p(8, 4), color: 1, piece: "FU"}}, {move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}}, { move: {from: p(3, 3), to: p(3, 4), color: 1, piece: "FU"}, forks: [ [ {move: {from: p(8, 4), to: p(8, 5), color: 1, piece: "FU"}}, {move: {from: p(8, 8), to: p(7, 7), color: 1, piece: "KA"}}, ], ], }, ], ], }, { move: {from: p(2, 7), to: p(2, 6), color: 1, piece: "FU"}, forks: [ [ { move: { from: p(8, 8), to: p(2, 2), color: 0, piece: "KA", capture: "KA", promote: false, }, }, ], ], }, ], }); // first -> +7776FU // |- +2726FU (branched) -> -3334FU (branchedMain) // |- -8384FU (branchedBranched) const first = player.getTesuuPointer(); // Move +2726FU in branch expect(player.forkAndForward(0)).toBe(true); const branched = player.getTesuuPointer(); // Move -8384FU in branch in branch player.forkAndForward(0); const branchedBranched = player.getTesuuPointer(); player.goto(1); player.goto(2); const branchedMain = player.getTesuuPointer(); expect(branchedMain).not.toEqual(branchedBranched); // Verify go to first player.goto(first); expect(player.getTesuuPointer()).toEqual(first); // Verify go to a branch player.goto(first); gotoAndVerifyPointer(branched); // Verify go to a branch recursively player.goto(first); gotoAndVerifyPointer(branchedBranched); // Verify pointer can be taken by giving tesuu // TODO: JSON can be different. Provide a equal function? expect(player.getTesuuPointer(2)).toEqual(branchedBranched); expect(player.getTesuuPointer(1)).toEqual(branched); // Verify go to sibling (branch to main) under branch gotoAndVerifyPointer(branchedMain); // Verify pointer can be taken by giving tesuu (again) expect(player.getTesuuPointer(2)).toEqual(branchedMain); expect(player.getTesuuPointer(1)).toEqual(branched); // Verify go to sibling (main to branch) under branch gotoAndVerifyPointer(branchedBranched); // Verify go to a node under the same branch // player.goto(branched); gotoAndVerifyPointer(branchedBranched); function gotoAndVerifyPointer(pointer: string) { player.goto(pointer); expect(player.getTesuuPointer()).toEqual(pointer); } }); }); describe("inputMove", () => { it("new input", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, ], }); const first = player.shogi.toCSAString(); // @ts-ignore expect(player.inputMove({from: p(7, 7), to: p(7, 6)})).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(3, 3), to: p(3, 4)})).toBeTruthy(); expect(player.backward()).toBeTruthy(); expect(player.backward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(first); }); it("same with existing one", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, ], }); // @ts-ignore expect(player.inputMove({from: p(7, 7), to: p(7, 6)})).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(3, 3), to: p(3, 4)})).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(2, 7), to: p(2, 6)})).toBeTruthy(); const leaf = player.shogi.toCSAString(); player.goto(1); // @ts-ignore expect(player.inputMove({from: p(3, 3), to: p(3, 4)})).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(leaf); player.goto(1); expect(player.forkAndForward(0)).toBe(false); }); it("same with existing fork", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, ], }); // @ts-ignore expect(player.inputMove({from: p(7, 7), to: p(7, 6)})).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(3, 3), to: p(3, 4)})).toBeTruthy(); expect(player.backward()).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(1, 3), to: p(1, 4)})).toBeTruthy(); expect(player.backward()).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(8, 3), to: p(8, 4)})).toBeTruthy(); // @ts-ignore expect(player.inputMove({from: p(2, 7), to: p(2, 6)})).toBeTruthy(); const leaf = player.shogi.toCSAString(); player.goto(1); // @ts-ignore expect(player.inputMove({from: p(8, 3), to: p(8, 4)})).toBeTruthy(); expect(player.forward()).toBeTruthy(); expect(player.shogi.toCSAString()).toBe(leaf); player.goto(1); expect(player.forkAndForward(2)).toBe(false); }); it("can't add fork to special", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {special: "CHUDAN"}, ], }); expect(() => { player.forward(); // @ts-ignore player.inputMove({from: p(7, 7), to: p(7, 6)}); }).toThrow(); }); it("possibility of promotion", () => { const player = new JKFPlayer({ header: {}, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU", color: 1}}, ], }); player.goto(2); // @ts-ignore expect(player.inputMove({from: p(8, 8), to: p(2, 2)})).toBe(false); // @ts-ignore expect(player.inputMove({from: p(8, 8), to: p(2, 2), promote: true})).toBeTruthy(); player.backward(); // @ts-ignore expect(player.inputMove({from: p(8, 8), to: p(2, 2), promote: false})).toBeTruthy(); }); }); it("numToZen", () => { expect(JKFPlayer.numToZen(7)).toBe("7"); expect(JKFPlayer.numToZen(9)).toBe("9"); }); it("numToKan", () => { expect(JKFPlayer.numToKan(7)).toBe("七"); expect(JKFPlayer.numToKan(9)).toBe("九"); }); it("moveToReadableKifu", () => { expect(JKFPlayer.moveToReadableKifu({ move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}, })).toBe("☗7六歩"); expect(JKFPlayer.moveToReadableKifu({ move: {from: p(2, 3), to: p(2, 4), piece: "FU", color: 1, same: true}, })).toBe("☖同 歩"); expect(JKFPlayer.moveToReadableKifu({ move: {from: p(3, 3), to: p(2, 4), piece: "GI", color: 0, promote: true}, })).toBe("☗2四銀成"); expect(JKFPlayer.moveToReadableKifu({ move: {from: p(3, 3), to: p(2, 4), piece: "GI", color: 0, promote: false}, })).toBe("☗2四銀不成"); expect(JKFPlayer.moveToReadableKifu({ move: {from: p(6, 8), to: p(5, 7), piece: "GI", color: 0, relative: "RU"}, })).toBe("☗5七銀右上"); expect(JKFPlayer.moveToReadableKifu({ special: "TORYO", })).toBe("投了"); }); describe("wrappers", () => { let player; beforeEach(() => { player = new JKFPlayer({ header: {}, moves: [ {comments: ["hoge"]}, { move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}, forks: [ [{move: {from: p(2, 7), to: p(2, 6), piece: "FU", color: 0}}], ], }, {move: {from: p(3, 3), to: p(3, 4), piece: "FU", color: 1}}, ], }); }); it("getBoard", () => { expect(player.getBoard(7, 7)).toEqual({color: 0, kind: "FU"}); expect(player.getBoard(7, 6)).toBeNull(); }); it("getComments", () => { expect(player.getComments()).toEqual(["hoge"]); expect(player.getComments(2)).toEqual([]); }); it("getMove", () => { expect(player.getMove()).toBeUndefined(); expect(player.getMove(2)).toEqual({from: p(3, 3), to: p(3, 4), piece: "FU", color: 1}); }); it("getReadableKifu", () => { expect(player.getReadableKifu()).toBe("開始局面"); expect(player.getReadableKifu(2)).toBe("☖3四歩"); }); it("getState", () => { expect(player.getState()).toEqual({ board: [ [{ color: 1, kind: "KY" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "KY" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "KA" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "GI" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "HI" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "KY" }, { }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { }, { color: 0, kind: "KY" }], ], color: 0, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }); }); it("getReadableKifuState", () => { expect(player.getReadableKifuState()).toEqual([ {kifu: "開始局面", forks: [], comments: ["hoge"]}, {kifu: "☗7六歩", forks: ["☗2六歩"], comments: []}, {kifu: "☖3四歩", forks: [], comments: []}, ]); }); it("getReadableForkKifu", () => { expect(player.getReadableForkKifu(1)).toEqual([]); expect(player.getReadableForkKifu()).toEqual(["☗2六歩"]); }); it("getNextFork", () => { expect(player.getNextFork(1)).toEqual([]); expect(player.getNextFork()).toEqual([ [{move: {color: 0, from: p(2, 7), piece: "FU", to: p(2, 6)}}], ]); }); it("toJKF", () => { const jkf = JSON.parse(player.toJKF()); const player2 = new JKFPlayer(jkf); expect(jkf).toEqual(JSON.parse(player2.toJKF())); }); it("getMoveFormat", () => { expect(player.getMoveFormat(0)).toEqual({comments: ["hoge"]}); expect(player.getMoveFormat(1)).toEqual({ move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}, forks: [ [{move: {from: p(2, 7), to: p(2, 6), piece: "FU", color: 0}}], ], }); player.forkAndForward(0); expect(player.getMoveFormat(0)).toEqual({comments: ["hoge"]}); expect(player.getMoveFormat(1)).toEqual({ move: {from: p(2, 7), to: p(2, 6), piece: "FU", color: 0}, }); }); }); it("static sameMoveMinimal", () => { // @ts-ignore expect(JKFPlayer.sameMoveMinimal({from: p(2, 3), to: p(2, 2), promote: true}, { from: p(2, 3), to: p(2, 2), promote: true, piece: "FU", })).toBeTruthy(); // @ts-ignore expect(JKFPlayer.sameMoveMinimal({to: p(2, 3), piece: "KY"}, {to: p(2, 3), piece: "KY"})).toBeTruthy(); // @ts-ignore expect(JKFPlayer.sameMoveMinimal({from: p(2, 3), to: p(2, 2), promote: false}, { from: p(2, 3), to: p(2, 2), promote: true, piece: "FU", })).toBe(false); // @ts-ignore expect(JKFPlayer.sameMoveMinimal({to: p(2, 3), piece: "KE"}, {to: p(2, 3), piece: "KY"})).toBeFalsy(); // @ts-ignore expect(JKFPlayer.sameMoveMinimal({from: p(2, 7), to: p(2, 6), piece: "FU"}, { to: p(2, 6), piece: "KA", })).toBe(false); }); describe("getMoveFormat", () => { it("only one", () => { const player = new JKFPlayer({ header: {}, moves: [ {comments: ["hoge"]}, { move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}, }, ], }); // @ts-ignore expect(player.getMoveFormat(0)).toEqual({comments: ["hoge"]}); // @ts-ignore expect(player.getMoveFormat(1)).toEqual({ move: {from: p(7, 7), to: p(7, 6), piece: "FU", color: 0}, }); }); }); });
the_stack
import {JSONPath} from 'jsonpath-plus'; import {BigNumber} from 'bignumber.js'; import {KeyStore, Signer} from '../../../types/ExternalInterfaces'; import {TezosNodeReader} from '../TezosNodeReader'; import {TezosNodeWriter} from '../TezosNodeWriter'; import {ConseilOperator, ConseilSortDirection, ConseilServerInfo} from '../../../types/conseil/QueryTypes'; import {ConseilQueryBuilder} from '../../../reporting/ConseilQueryBuilder'; import {TezosConseilClient} from '../../../reporting/tezos/TezosConseilClient'; import {MultiAssetTokenHelper, MultiAssetSimpleStorage, TransferPair} from './tzip12/MultiAssetTokenHelper'; import {TezosParameterFormat} from '../../../types/tezos/TezosChainTypes'; import {TezosContractUtils} from './TezosContractUtils'; import {TezosMessageUtils} from '../TezosMessageUtil'; export namespace HicNFTHelper { export const objktsAddress = 'KT1RJ6PbjHpwc3M5rw5s2Nbmefwbuwbdxton'; export const hDaoAddress = 'KT1AFA2mwNUMNd4SsujE1YYp29vd8BZejyKW'; /* * Get an instance of a Objkts contract's storage by querying a given address * @param server The Tezos node to communicate with * @param address Contract address, i.e. HicNFTHelper.objktsAddress or HicNFTHelper.hDaoAddress */ export async function getStorage(server: string, address: string): Promise<MultiAssetSimpleStorage> { const storageResult = await TezosNodeReader.getContractStorage(server, address); return { administrator: JSONPath({path: '$.args[0].args[0].string', json: storageResult })[0], tokens: Number(JSONPath({ path: '$.args[0].args[1].int', json: storageResult })[0]), ledger: Number(JSONPath({ path: '$.args[0].args[2].int', json: storageResult })[0]), metadata: Number(JSONPath({ path: '$.args[1].args[0].int', json: storageResult })[0]), operators: Number(JSONPath({ path: '$.args[1].args[1].int', json: storageResult })[0]), paused: (JSONPath({ path: '$.args[2].prim', json: storageResult })[0]).toString().toLowerCase().startsWith('t'), tokenMetadata: Number(JSONPath({ path: '$.args[3].int', json: storageResult })[0]) }; } /* * Returns a query for the last price. * * @param operations Array of chunks of operations (see `chunkArray()`) */ function makeLastPriceQuery(operations) { let lastPriceQuery = ConseilQueryBuilder.blankQuery(); lastPriceQuery = ConseilQueryBuilder.addFields(lastPriceQuery, 'timestamp', 'amount', 'operation_group_hash', 'parameters_entrypoints', 'parameters'); lastPriceQuery = ConseilQueryBuilder.addPredicate(lastPriceQuery, 'kind', ConseilOperator.EQ, ['transaction']); lastPriceQuery = ConseilQueryBuilder.addPredicate(lastPriceQuery, 'status', ConseilOperator.EQ, ['applied']); lastPriceQuery = ConseilQueryBuilder.addPredicate(lastPriceQuery, 'internal', ConseilOperator.EQ, ['false']); lastPriceQuery = ConseilQueryBuilder.addPredicate( lastPriceQuery, 'operation_group_hash', operations.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ, operations ); lastPriceQuery = ConseilQueryBuilder.setLimit(lastPriceQuery, operations.length); return lastPriceQuery; } /* * Retreives the collection of tokens owned by managerAddress. * * @param tokenMapId * @param managerAddress * @param serverInfo */ export async function getCollection(tokenMapId: number, managerAddress: string, serverInfo: ConseilServerInfo): Promise<any[]> { let collectionQuery = ConseilQueryBuilder.blankQuery(); // TODO: add comment with the query collectionQuery = ConseilQueryBuilder.addFields(collectionQuery, 'key', 'value', 'operation_group_id'); collectionQuery = ConseilQueryBuilder.addPredicate(collectionQuery, 'big_map_id', ConseilOperator.EQ, [tokenMapId]); collectionQuery = ConseilQueryBuilder.addPredicate(collectionQuery, 'key', ConseilOperator.STARTSWITH, [ `Pair 0x${TezosMessageUtils.writeAddress(managerAddress)}`, ]); collectionQuery = ConseilQueryBuilder.addPredicate(collectionQuery, 'value', ConseilOperator.EQ, [0], true); collectionQuery = ConseilQueryBuilder.setLimit(collectionQuery, 10_000); const collectionResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', collectionQuery); const operationGroupIds = collectionResult.map((r) => r.operation_group_id); const queryChunks = chunkArray(operationGroupIds, 30); const priceQueries = queryChunks.map((c) => makeLastPriceQuery(c)); const priceMap: any = {}; await Promise.all( priceQueries.map( async (q) => await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'operations', q).then((result) => result.map((row) => { let amount = 0; const action = row.parameters_entrypoints; if (action === 'collect') { amount = Number(row.parameters.toString().replace(/^Pair ([0-9]+) [0-9]+/, '$1')); } else if (action === 'transfer') { amount = Number( row.parameters .toString() .replace( /[{] Pair \"[1-9A-HJ-NP-Za-km-z]{36}\" [{] Pair \"[1-9A-HJ-NP-Za-km-z]{36}\" [(]Pair [0-9]+ [0-9]+[)] [}] [}]/, '$1' ) ); } priceMap[row.operation_group_hash] = { price: new BigNumber(row.amount), amount, timestamp: row.timestamp, action, }; }) ) ) ); const collection = collectionResult.map((row) => { let price = 0; let receivedOn = new Date(); let action = ''; try { const priceRecord = priceMap[row.operation_group_id]; price = priceRecord.price.dividedToIntegerBy(priceRecord.amount).toNumber(); receivedOn = new Date(priceRecord.timestamp); action = priceRecord.action === 'collect' ? 'Purchased' : 'Received'; } catch { // } return { piece: row.key.toString().replace(/.* ([0-9]{1,}$)/, '$1'), amount: Number(row.value), price: isNaN(price) ? 0 : price, receivedOn, action, }; }); return collection.sort((a, b) => b.receivedOn.getTime() - a.receivedOn.getTime()); } /* * Fetch an account's collection and return its size. * * @param */ export async function getCollectionSize(tokenMapId: number, managerAddress: string, serverInfo: ConseilServerInfo): Promise<number> { const collection = await getCollection(tokenMapId, managerAddress, serverInfo); const tokenCount = collection.reduce((a, c) => a + c.amount, 0); return tokenCount; } /** * Returns raw hDAO token balance for the account. * KT1AFA2mwNUMNd4SsujE1YYp29vd8BZejyKW, ledger map id 515 * * @param server * @param mapId * @param address */ export async function getBalance(server: string, mapId: number, address: string): Promise<number> { const packedTokenKey = TezosMessageUtils.encodeBigMapKey( Buffer.from(TezosMessageUtils.writePackedData(`(Pair 0x${TezosMessageUtils.writeAddress(address)} 0)`, '', TezosParameterFormat.Michelson), 'hex') ); let balance = 0; try { const balanceResult = await TezosNodeReader.getValueForBigMapKey(server, mapId, packedTokenKey); balance = new BigNumber(JSONPath({ path: '$.int', json: balanceResult })[0]).toNumber(); } catch (err) { // } return balance; } /* * Return the number of holders and total balance held of hDao tokens. * * @param */ export async function getTokenInfo(serverInfo: ConseilServerInfo, mapId: number = 515): Promise<{ holders: number; totalBalance: number }> { let holdersQuery = ConseilQueryBuilder.blankQuery(); holdersQuery = ConseilQueryBuilder.addFields(holdersQuery, 'value'); holdersQuery = ConseilQueryBuilder.addPredicate(holdersQuery, 'big_map_id', ConseilOperator.EQ, [mapId]); holdersQuery = ConseilQueryBuilder.setLimit(holdersQuery, 20_000); const holdersResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', holdersQuery); let holders = 0; let totalBalance = new BigNumber(0); holdersResult.forEach((r) => { try { const balance = new BigNumber(r.value); if (balance.isGreaterThan(0)) { totalBalance = totalBalance.plus(balance); } holders++; } catch { // eh } }); return { holders, totalBalance: totalBalance.toNumber() }; } /* * Retrieves an NFT object's metadata. * * @param server The Teznos node to query * @param objectId The token_id of the NFT to query */ export async function getNFTObjectDetails(server: string, objectId: number) { const packedNftId = TezosMessageUtils.encodeBigMapKey(Buffer.from(TezosMessageUtils.writePackedData(objectId, 'int'), 'hex')); const nftInfo = await TezosNodeReader.getValueForBigMapKey(server, 514, packedNftId); const ipfsUrlBytes = JSONPath({ path: '$.args[1][0].args[1].bytes', json: nftInfo })[0]; const ipfsHash = Buffer.from(ipfsUrlBytes, 'hex').toString().slice(7); const nftDetails = await fetch(`https://cloudflare-ipfs.com/ipfs/${ipfsHash}`, { cache: 'no-store' }); const nftDetailJson = await nftDetails.json(); const nftName = nftDetailJson.name; const nftDescription = nftDetailJson.description; const nftCreators = nftDetailJson.creators .map((c) => c.trim()) .map((c) => `${c.slice(0, 6)}...${c.slice(c.length - 6, c.length)}`) .join(', '); // TODO: use names where possible const nftArtifact = `https://cloudflare-ipfs.com/ipfs/${nftDetailJson.formats[0].uri.toString().slice(7)}`; const nftArtifactType = nftDetailJson.formats[0].mimeType.toString(); return { name: nftName, description: nftDescription, creators: nftCreators, artifactUrl: nftArtifact, artifactType: nftArtifactType }; } /* * Turn an array of n=k*len elements into an array of k arrays of length len. * * @param arr * @param len */ function chunkArray(arr: any[], len: number) { const chunks: any[] = []; const n = arr.length; let i = 0; while (i < n) { chunks.push(arr.slice(i, (i += len))); } return chunks; } }
the_stack
import { act, fireEvent, waitFor } from "@testing-library/react"; import { Button } from "@components/button"; import { DateRangeInput } from "@components/date-input"; import { GroupField } from "@components/field"; import { Keys } from "@components/shared"; import { createRef } from "react"; import { renderWithTheme } from "@jest-utils"; import userEvent from "@testing-library/user-event"; // Using userEvent.type with a string having multiple characters doesn't work because of the mask. Only the last character ends up being typed. // Providing an option.delay fix the problem but we get the following warning: "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one." function type(element: HTMLElement, text: string) { [...text].forEach(x => { act(() => { userEvent.type(element, x); }); }); } function backspace(element: HTMLElement, times = 1) { for (let x = 0; x < times; x += 1) { act(() => { userEvent.type(element, "{backspace}"); }); } } function getStartDateInput(container: HTMLElement, name = "date-range") { return container.querySelector(`:scope [name=${name}-start-date]`) as HTMLElement; } function getEndDateInput(container: HTMLElement, name = "date-range") { return container.querySelector(`:scope [name=${name}-end-date]`) as HTMLElement; } // ***** Behaviors ***** test("when a valid date has been entered in the start date input, move focus to the end date input", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "01012020"); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); }); test("when the focus is in the end date input and the end date input value is empty, move focus to the start date input on backspace keypress", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "01012020"); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); backspace(getEndDateInput(container)); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when the focus is in the end date input and the end date input value is empty, keep focus in the end date input on non digit character keypress", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "01012020"); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); type(getEndDateInput(container), "ab"); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); }); test("when the focus is in the end date input and the end date input value is not empty, move focus to the start date input on the next backspace keypress following the clearing of the end date input value", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); type(getEndDateInput(container), "01012020"); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); backspace(getEndDateInput(container), 9); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when the focus is in the start date input, tab keypress move the focus to the end date input", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); act(() => { userEvent.tab(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveFocus()); }); test("when the focus is in the end date input, shift + tab keypress move the focus to the start date input", async () => { const { container } = renderWithTheme( <DateRangeInput name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); act(() => { userEvent.tab({ shift: true }); }); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when the start date is greater than the end date, reset the start date to the end date value", async () => { const { container } = renderWithTheme( <DateRangeInput defaultEndDate={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "02022021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getStartDateInput(container).focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("01/01/2020")); }); test("when the end date is lower than the start date, reset the end date to the start date value", async () => { const { container } = renderWithTheme( <DateRangeInput defaultStartDate={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); type(getEndDateInput(container), "02022019"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("01/01/2020")); }); test("when the start date is lower than the min date, reset the start date to the min date value", async () => { const { container } = renderWithTheme( <DateRangeInput min={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "02022019"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getStartDateInput(container).focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("01/01/2020")); }); test("when the start date is greater than the max date, reset the start date to the max date value", async () => { const { container } = renderWithTheme( <DateRangeInput max={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "02022021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getStartDateInput(container).focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("01/01/2020")); }); test("when the end date is lower than the min date, reset the end date to the min date value", async () => { const { container } = renderWithTheme( <DateRangeInput min={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); type(getEndDateInput(container), "02022019"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("01/01/2020")); }); test("when the end date is greater than the max date, reset the end date to the max date value", async () => { const { container } = renderWithTheme( <DateRangeInput max={new Date(2020, 0, 1)} name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); type(getEndDateInput(container), "02022021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("01/01/2020")); }); test("clear both dates on clear button click", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput defaultStartDate={new Date(2020, 0, 1)} defaultEndDate={new Date(2021, 0, 1)} name="date-range" /> ); act(() => { userEvent.click(getByRole("button")); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("")); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("")); }); test("clear both dates on esc keypress", async () => { const { container } = renderWithTheme( <DateRangeInput defaultStartDate={new Date(2020, 0, 1)} defaultEndDate={new Date(2021, 0, 1)} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); act(() => { fireEvent.keyDown(getStartDateInput(container), { key: Keys.esc }); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("")); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("")); }); test("tab keypress from outside will focus the start date input", async () => { const { container, getByTestId } = renderWithTheme( <> <Button data-testid="previous">Previous</Button> <DateRangeInput defaultStartDate={new Date(2020, 0, 1)} defaultEndDate={new Date(2021, 0, 1)} name="date-range" /> </> ); act(() => { getByTestId("previous").focus(); }); await waitFor(() => expect(getByTestId("previous")).toHaveFocus()); act(() => { userEvent.tab(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); // test("shift + tab keypress from outside will focus the start date input", async () => { // const { container, getByTestId } = renderWithTheme( // <> // <DateRangeInput // defaultStartDate={new Date(2020, 0, 1)} // defaultEndDate={new Date(2021, 0, 1)} // name="date-range" // /> // <Button data-testid="after">After</Button> // </> // ); // act(() => { // getByTestId("after").focus(); // }); // await waitFor(() => expect(getByTestId("after")).toHaveFocus()); // act(() => { // userEvent.tab({ shift: true }); // }); // await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); // }); test("when autofocus is true, the date range input is focused on render", async () => { const { container, getByTestId } = renderWithTheme( <DateRangeInput autoFocus name="date-range" data-testid="date-range-input" /> ); await waitFor(() => expect(getByTestId("date-range-input")).toHaveClass("o-ui-date-range-input-focus")); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when autofocus is true and the date range input is disabled, the date range input is not focused on render", async () => { const { container, getByTestId } = renderWithTheme( <DateRangeInput disabled autoFocus name="date-range" data-testid="date-range-input" /> ); await waitFor(() => expect(getByTestId("date-range-input")).not.toHaveClass("o-ui-date-range-input-focus")); await waitFor(() => expect(getStartDateInput(container)).not.toHaveFocus()); }); test("when autofocus is true and the date range input is readonly, the date range input is not focused on render", async () => { const { container, getByTestId } = renderWithTheme( <DateRangeInput readOnly autoFocus name="date-range" data-testid="date-range-input" /> ); await waitFor(() => expect(getByTestId("date-range-input")).not.toHaveClass("o-ui-date-range-input-focus")); await waitFor(() => expect(getStartDateInput(container)).not.toHaveFocus()); }); test("when autofocus is specified with a delay, the date range input is focused after the delay", async () => { const { container, getByTestId } = renderWithTheme( <DateRangeInput autoFocus={10} name="date-range" data-testid="date-range-input" /> ); await waitFor(() => expect(getByTestId("date-range-input")).not.toHaveClass("o-ui-date-range-input-focus")); expect(getStartDateInput(container)).not.toHaveFocus(); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); describe("compact presets", () => { test("when a preset is selected, both inputs are filled with the preset dates", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" name="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("Tue, Jan 7, 2020")); act(() => { getStartDateInput(container).focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("01/01/2020")); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("07/01/2020")); }); test("when a preset is selected, the preset menu trigger is focused", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" name="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(container.querySelector(":scope [aria-label=\"Date presets\"]")).toHaveFocus()); }); test("when a preset is selected from the menu, the selected item of the menu match the selected preset", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" name="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(getByRole("menuitemradio")).toHaveAttribute("aria-checked", "true")); }); test("when dates match a preset, the selected item of the menu match the preset", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput startDate={new Date(2020, 0, 1)} endDate={new Date(2020, 0, 7)} presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" name="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); await waitFor(() => expect(getByRole("menuitemradio")).toHaveAttribute("aria-checked", "true")); }); }); describe("extended presets", () => { test("when a preset is selected, both inputs are filled with the preset dates", async () => { const { container, getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="expanded" name="date-range" /> ); act(() => { userEvent.click(getByRole("radio")); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("Wed, Jan 1, 2020")); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("Tue, Jan 7, 2020")); act(() => { getStartDateInput(container).focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveValue("01/01/2020")); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(getEndDateInput(container)).toHaveValue("07/01/2020")); }); test("when a preset is selected, the toggled button match the selected preset", async () => { const { getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="expanded" name="date-range" /> ); act(() => { userEvent.click(getByRole("radio")); }); await waitFor(() => expect(getByRole("radio")).toHaveAttribute("aria-checked", "true")); }); test("when dates match a preset, the toggled button match the preset", async () => { const { getByRole } = renderWithTheme( <DateRangeInput startDate={new Date(2020, 0, 1)} endDate={new Date(2020, 0, 7)} presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="expanded" name="date-range" /> ); await waitFor(() => expect(getByRole("radio")).toHaveAttribute("aria-checked", "true")); }); }); // ***** Aria ***** test("when is not in a group field, role is \"group\"", async () => { const { getByTestId } = renderWithTheme( <DateRangeInput data-testid="date-range-input" /> ); await waitFor(() => expect(getByTestId("date-range-input")).toHaveAttribute("role", "group")); }); test("when is in a group field, a role attribute is not rendered", async () => { const { getByTestId } = renderWithTheme( <GroupField> <DateRangeInput data-testid="date-range-input" /> </GroupField> ); await waitFor(() => expect(getByTestId("date-range-input")).not.toHaveAttribute("role")); }); // ***** Api ***** test("when a start date is applied, call onDatesChange with the new start date", async () => { const handler = jest.fn(); const { container } = renderWithTheme( <DateRangeInput onDatesChange={handler} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "01012020"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), new Date(2020, 0, 1), null)); }); test("when an end date is applied, call onDatesChange with the new end date", async () => { const handler = jest.fn(); const { container } = renderWithTheme( <DateRangeInput onDatesChange={handler} name="date-range" /> ); act(() => { getEndDateInput(container).focus(); }); type(getEndDateInput(container), "01012020"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), null, new Date(2020, 0, 1))); }); test("when the start date and the end date are applied, call onDatesChange with both dates", async () => { const handler = jest.fn(); const { container } = renderWithTheme( <DateRangeInput onDatesChange={handler} name="date-range" /> ); act(() => { getStartDateInput(container).focus(); }); type(getStartDateInput(container), "01012020"); act(() => { getEndDateInput(container).focus(); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), new Date(2020, 0, 1), null)); type(getEndDateInput(container), "01012021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), new Date(2020, 0, 1), new Date(2021, 0, 1))); await waitFor(() => expect(handler).toHaveBeenCalledTimes(2)); }); test("when the dates are cleared, call onDatesChange with null for both dates", async () => { const handler = jest.fn(); const { getByRole } = renderWithTheme( <DateRangeInput defaultStartDate={new Date(2020, 0, 1)} defaultEndDate={new Date(2021, 0, 1)} onDatesChange={handler} /> ); act(() => { userEvent.click(getByRole("button")); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), null, null)); }); test("when a preset is selected, call onDatesChange with both dates", async () => { const handler = jest.fn(); const { container, getByRole } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} onDatesChange={handler} name="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), new Date(2020, 0, 1), new Date(2020, 0, 7))); }); test("can focus the start date input with the focus api", async () => { const ref = createRef<HTMLElement>(); const { container } = renderWithTheme( <DateRangeInput name="date-range" ref={ref} /> ); act(() => { ref.current.focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when compact presets are provided, can focus the start date input with the focus api", async () => { const ref = createRef<HTMLElement>(); const { container } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" name="date-range" ref={ref} /> ); act(() => { ref.current.focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); test("when expanded presets are provided, can focus the start date input with the focus api", async () => { const ref = createRef<HTMLElement>(); const { container } = renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="expanded" name="date-range" ref={ref} /> ); act(() => { ref.current.focus(); }); await waitFor(() => expect(getStartDateInput(container)).toHaveFocus()); }); // ***** Refs ***** test("ref is a DOM element", async () => { const ref = createRef<HTMLElement>(); renderWithTheme( <DateRangeInput ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when compact presets are provided, ref is a DOM element", async () => { const ref = createRef<HTMLElement>(); renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="compact" ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when expanded presets are provided, ref is a DOM element", async () => { const ref = createRef<HTMLElement>(); renderWithTheme( <DateRangeInput presets={[{ text: "Preset 1", startDate: new Date(2020, 0, 1), endDate: new Date(2020, 0, 7) }]} presetsVariant="expanded" ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when using a callback ref, ref is a DOM element", async () => { let refNode: HTMLElement = null; renderWithTheme( <DateRangeInput ref={node => { refNode = node; }} /> ); await waitFor(() => expect(refNode).not.toBeNull()); expect(refNode instanceof HTMLElement).toBeTruthy(); expect(refNode.tagName).toBe("DIV"); }); test("set ref once", async () => { const handler = jest.fn(); renderWithTheme( <DateRangeInput ref={handler} /> ); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); });
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import * as BuiltinFunctions from './builtinFunctions'; import { ExpressionEvaluator } from './expressionEvaluator'; import { ExpressionType } from './expressionType'; /** * <summary> * Definition of default built-in functions for expressions. * </summary> * <remarks> * These functions are largely from WDL https://docs.microsoft.com/en-us/azure/logic-apps/workflow-definition-language-functions-reference * with a few extensions like infix operators for math, logic and comparisons. * This class also has some methods that are useful to use when defining custom functions. * You can always construct a <see cref="ExpressionEvaluator"/> directly which gives the maximum amount of control over validation and evaluation. * Validators are static checkers that should throw an exception if something is not valid statically. * Evaluators are called to evaluate an expression and should try not to throw. * There are some evaluators in this file that take in a verifier that is called at runtime to verify arguments are proper. * </remarks> */ export class ExpressionFunctions { /** * Read only Dictionary of built in functions. */ static readonly standardFunctions: ReadonlyMap< string, ExpressionEvaluator > = ExpressionFunctions.getStandardFunctions(); /** * @private */ private static getStandardFunctions(): ReadonlyMap<string, ExpressionEvaluator> { const functions: ExpressionEvaluator[] = [ new BuiltinFunctions.Abs(), new BuiltinFunctions.Accessor(), new BuiltinFunctions.Add(), new BuiltinFunctions.AddDays(), new BuiltinFunctions.AddHours(), new BuiltinFunctions.AddMinutes(), new BuiltinFunctions.AddOrdinal(), new BuiltinFunctions.AddProperty(), new BuiltinFunctions.AddSeconds(), new BuiltinFunctions.AddToTime(), new BuiltinFunctions.All(), new BuiltinFunctions.And(), new BuiltinFunctions.Any(), new BuiltinFunctions.Average(), new BuiltinFunctions.Base64(), new BuiltinFunctions.Base64ToBinary(), new BuiltinFunctions.Base64ToString(), new BuiltinFunctions.Binary(), new BuiltinFunctions.Bool(), new BuiltinFunctions.Ceiling(), new BuiltinFunctions.Coalesce(), new BuiltinFunctions.Concat(), new BuiltinFunctions.Contains(), new BuiltinFunctions.ConvertFromUTC(), new BuiltinFunctions.ConvertToUTC(), new BuiltinFunctions.Count(), new BuiltinFunctions.CountWord(), new BuiltinFunctions.CreateArray(), new BuiltinFunctions.DataUri(), new BuiltinFunctions.DataUriToBinary(), new BuiltinFunctions.DataUriToString(), new BuiltinFunctions.DateFunc(), new BuiltinFunctions.DateReadBack(), new BuiltinFunctions.DateTimeDiff(), new BuiltinFunctions.DayOfMonth(), new BuiltinFunctions.DayOfWeek(), new BuiltinFunctions.DayOfYear(), new BuiltinFunctions.Divide(), new BuiltinFunctions.Element(), new BuiltinFunctions.Empty(), new BuiltinFunctions.EndsWith(), new BuiltinFunctions.EOL(), new BuiltinFunctions.Equal(), new BuiltinFunctions.Exists(), new BuiltinFunctions.Flatten(), new BuiltinFunctions.First(), new BuiltinFunctions.Float(), new BuiltinFunctions.Floor(), new BuiltinFunctions.Foreach(), new BuiltinFunctions.FormatDateTime(), new BuiltinFunctions.FormatEpoch(), new BuiltinFunctions.FormatNumber(), new BuiltinFunctions.FormatTicks(), new BuiltinFunctions.GetFutureTime(), new BuiltinFunctions.GetNextViableDate(), new BuiltinFunctions.GetNextViableTime(), new BuiltinFunctions.GetPastTime(), new BuiltinFunctions.GetPreviousViableDate(), new BuiltinFunctions.GetPreviousViableTime(), new BuiltinFunctions.GetPastTime(), new BuiltinFunctions.GetProperty(), new BuiltinFunctions.GetTimeOfDay(), new BuiltinFunctions.GreaterThan(), new BuiltinFunctions.GreaterThanOrEqual(), new BuiltinFunctions.If(), new BuiltinFunctions.Ignore(), new BuiltinFunctions.IndexOf(), new BuiltinFunctions.IndicesAndValues(), new BuiltinFunctions.Int(), new BuiltinFunctions.Intersection(), new BuiltinFunctions.IsArray(), new BuiltinFunctions.IsBoolean(), new BuiltinFunctions.IsDate(), new BuiltinFunctions.IsDateRange(), new BuiltinFunctions.IsDateTime(), new BuiltinFunctions.IsDefinite(), new BuiltinFunctions.IsDuration(), new BuiltinFunctions.IsFloat(), new BuiltinFunctions.IsInteger(), new BuiltinFunctions.IsMatch(), new BuiltinFunctions.IsObject(), new BuiltinFunctions.IsPresent(), new BuiltinFunctions.IsString(), new BuiltinFunctions.IsTime(), new BuiltinFunctions.IsTimeRange(), new BuiltinFunctions.Join(), new BuiltinFunctions.JPath(), new BuiltinFunctions.Json(), new BuiltinFunctions.JsonStringify(), new BuiltinFunctions.Last(), new BuiltinFunctions.LastIndexOf(), new BuiltinFunctions.Length(), new BuiltinFunctions.LessThan(), new BuiltinFunctions.LessThanOrEqual(), new BuiltinFunctions.Max(), new BuiltinFunctions.Merge(), new BuiltinFunctions.Min(), new BuiltinFunctions.Mod(), new BuiltinFunctions.Month(), new BuiltinFunctions.Multiply(), new BuiltinFunctions.NewGuid(), new BuiltinFunctions.Not(), new BuiltinFunctions.NotEqual(), new BuiltinFunctions.Optional(), new BuiltinFunctions.Or(), new BuiltinFunctions.Power(), new BuiltinFunctions.Rand(), new BuiltinFunctions.Range(), new BuiltinFunctions.RemoveProperty(), new BuiltinFunctions.Replace(), new BuiltinFunctions.ReplaceIgnoreCase(), new BuiltinFunctions.Reverse(), new BuiltinFunctions.Round(), new BuiltinFunctions.Select(), new BuiltinFunctions.SentenceCase(), new BuiltinFunctions.SetPathToValue(), new BuiltinFunctions.SetProperty(), new BuiltinFunctions.Skip(), new BuiltinFunctions.SortBy(), new BuiltinFunctions.SortByDescending(), new BuiltinFunctions.Split(), new BuiltinFunctions.Sqrt(), new BuiltinFunctions.StartOfDay(), new BuiltinFunctions.StartOfHour(), new BuiltinFunctions.StartOfMonth(), new BuiltinFunctions.StartsWith(), new BuiltinFunctions.String(), new BuiltinFunctions.StringOrValue(), new BuiltinFunctions.SubArray(), new BuiltinFunctions.Substring(), new BuiltinFunctions.Subtract(), new BuiltinFunctions.SubtractFromTime(), new BuiltinFunctions.Sum(), new BuiltinFunctions.Take(), new BuiltinFunctions.Ticks(), new BuiltinFunctions.TicksToDays(), new BuiltinFunctions.TicksToHours(), new BuiltinFunctions.TicksToMinutes(), new BuiltinFunctions.TimexResolve(), new BuiltinFunctions.TitleCase(), new BuiltinFunctions.ToLower(), new BuiltinFunctions.ToUpper(), new BuiltinFunctions.Trim(), new BuiltinFunctions.Union(), new BuiltinFunctions.Unique(), new BuiltinFunctions.UriComponent(), new BuiltinFunctions.UriComponentToString(), new BuiltinFunctions.UriHost(), new BuiltinFunctions.UriPath(), new BuiltinFunctions.UriPathAndQuery(), new BuiltinFunctions.UriPort(), new BuiltinFunctions.UriQuery(), new BuiltinFunctions.UriScheme(), new BuiltinFunctions.UtcNow(), new BuiltinFunctions.Where(), new BuiltinFunctions.XML(), new BuiltinFunctions.XPath(), new BuiltinFunctions.Year(), ]; const lookup: Map<string, ExpressionEvaluator> = new Map<string, ExpressionEvaluator>(); functions.forEach((func: ExpressionEvaluator): void => { lookup.set(func.type, func); }); // Attach negations lookup.get(ExpressionType.LessThan).negation = lookup.get(ExpressionType.GreaterThanOrEqual); lookup.get(ExpressionType.LessThanOrEqual).negation = lookup.get(ExpressionType.GreaterThan); lookup.get(ExpressionType.Equal).negation = lookup.get(ExpressionType.NotEqual); // Math aliases lookup.set('add', lookup.get(ExpressionType.Add)); // more than 1 param lookup.set('mul', lookup.get(ExpressionType.Multiply)); // more than 1 param lookup.set('div', lookup.get(ExpressionType.Divide)); // more than 1 param lookup.set('sub', lookup.get(ExpressionType.Subtract)); // more than 1 param lookup.set('exp', lookup.get(ExpressionType.Power)); // more than 1 param lookup.set('mod', lookup.get(ExpressionType.Mod)); // Comparison aliases lookup.set('and', lookup.get(ExpressionType.And)); lookup.set('equals', lookup.get(ExpressionType.Equal)); lookup.set('greater', lookup.get(ExpressionType.GreaterThan)); lookup.set('greaterOrEquals', lookup.get(ExpressionType.GreaterThanOrEqual)); lookup.set('less', lookup.get(ExpressionType.LessThan)); lookup.set('lessOrEquals', lookup.get(ExpressionType.LessThanOrEqual)); lookup.set('not', lookup.get(ExpressionType.Not)); lookup.set('or', lookup.get(ExpressionType.Or)); lookup.set('&', lookup.get(ExpressionType.Concat)); lookup.set('??', lookup.get(ExpressionType.Coalesce)); return lookup as ReadonlyMap<string, ExpressionEvaluator>; } }
the_stack
import * as React from 'react'; import { IDataGrid } from '../common/@types'; import { DataGridEnums } from '../common/@enums'; import getAvailScrollLeft from '../utils/getAvailScrollLeft'; import { delay } from '../utils/delay'; interface IProps { colGroup: IDataGrid.ICol[]; col: IDataGrid.ICol; li: number; item?: IDataGrid.IDataItem; columnHeight: number; lineHeight: number; columnBorderWidth: number; colAlign: string; setStoreState: IDataGrid.setStoreState; dispatch: IDataGrid.dispatch; inlineEditingCell: IDataGrid.IEditingCell; focusedRow: number; focusedCol: number; printStartColIndex?: number; printEndColIndex?: number; scrollLeft?: number; scrollTop?: number; options?: IDataGrid.IOptions; styles?: IDataGrid.IStyles; } class CellEditor extends React.PureComponent<IProps> { customEditorRef: React.RefObject<HTMLDivElement>; activeComposition: boolean = false; lastEventName: string = ''; busy = false; constructor(props: IProps) { super(props); this.customEditorRef = React.createRef(); } onInputTextBlur = (e: React.FocusEvent<HTMLInputElement>) => { const { dispatch, inlineEditingCell = {}, colGroup = [], col, li, } = this.props; // console.log('fire onInputTextBlur', this.lastEventName); if (this.lastEventName === 'update') { dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, { isInlineEditing: false, inlineEditingCell: {}, }); } else { dispatch(DataGridEnums.DispatchTypes.UPDATE, { row: li, colIndex: col.colIndex, value: e.currentTarget.value, // eventWhichKey: e.which, isInlineEditing: false, inlineEditingCell: {}, }); } }; onInputTextKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { const { dispatch, inlineEditingCell = {}, colGroup = [], col, li, } = this.props; switch (e.which) { case DataGridEnums.KeyCodes.ESC: this.lastEventName = 'esc'; e.preventDefault(); dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, { isInlineEditing: false, inlineEditingCell: {}, }); break; case DataGridEnums.KeyCodes.UP_ARROW: case DataGridEnums.KeyCodes.DOWN_ARROW: case DataGridEnums.KeyCodes.ENTER: // console.log('fire onInputTextKeyDown ENTER'); this.lastEventName = 'update'; e.preventDefault(); dispatch(DataGridEnums.DispatchTypes.UPDATE, { row: inlineEditingCell.rowIndex, col, colIndex: inlineEditingCell.colIndex, value: e.currentTarget.value, eventWhichKey: e.which, keepEditing: true, }); break; case DataGridEnums.KeyCodes.TAB: e.preventDefault(); this.lastEventName = 'update'; const { colIndex = 0 } = col; const nextCol = colGroup[ e.shiftKey ? colIndex - 1 > -1 ? colIndex - 1 : colGroup.length - 1 : colIndex + 1 < colGroup.length ? colIndex + 1 : 0 ]; dispatch(DataGridEnums.DispatchTypes.UPDATE, { row: inlineEditingCell.rowIndex, col, colIndex: inlineEditingCell.colIndex, value: e.currentTarget.value, eventWhichKey: e.which, keepEditing: true, isInlineEditing: true, inlineEditingCell: { rowIndex: li, colIndex: nextCol.colIndex, editor: nextCol.editor, }, newFocusedRow: li, newFocusedCol: nextCol.colIndex, }); break; default: break; } }; handleUpdateValue: IDataGrid.CellEditorDataUpdate = (value: any, options) => { const { dispatch, li, col } = this.props; const { keepEditing = false, updateItem = false, focus = false } = options || {}; if (this.lastEventName === 'update' || this.lastEventName === 'cancel') { return; } this.lastEventName = 'update'; dispatch( updateItem ? DataGridEnums.DispatchTypes.UPDATE_ITEM : DataGridEnums.DispatchTypes.UPDATE, { row: li, col, colIndex: col.colIndex, value, eventWhichKey: 'custom-editor-action', keepEditing, }, ); if (focus) { dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, {}); } }; handleCancelEdit: IDataGrid.CellEditorDataCancel = options => { const { setStoreState, dispatch } = this.props; const { keepEditing = false } = options || {}; if (!this.busy) { this.lastEventName = 'cancel'; setStoreState({ isInlineEditing: false, inlineEditingCell: {}, }); if (keepEditing) { dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, {}); } } }; handelKeyAction: IDataGrid.CellEditorKeyAction = (action, value, options) => { const { dispatch, li, colGroup, col, printStartColIndex = 0, printEndColIndex = 0, scrollLeft = 0, scrollTop = 0, options: { frozenColumnIndex = 0 } = {}, styles: { scrollContentWidth = 0, scrollContentHeight = 0, scrollContentContainerWidth = 0, scrollContentContainerHeight = 0, frozenPanelWidth = 0, rightPanelWidth = 0, verticalScrollerWidth = 0, } = {}, } = this.props; const { updateItem = false, e } = options || { e: null }; this.busy = true; switch (action) { case 'EDIT_NEXT': const { colIndex = 0 } = col; this.lastEventName = 'update'; const nextCol = colGroup[ e && e.shiftKey ? colIndex - 1 > -1 ? colIndex - 1 : colGroup.length - 1 : colIndex + 1 < colGroup.length ? colIndex + 1 : 0 ]; if (nextCol.colIndex !== undefined) { // const nextColEditor = nextCol.editor; // const nextEditor: IDataGrid.IColEditor = // nextColEditor === 'text' // ? { type: 'text' } // : (nextColEditor as IDataGrid.IColEditor); // const hasNextColEditor = // nextEditor && // (nextEditor.activeType === 'click' || // nextEditor.activeType === 'dblclick'); // console.log('hasNextColEditor', hasNextColEditor, nextEditor); dispatch( updateItem ? DataGridEnums.DispatchTypes.UPDATE_ITEM : DataGridEnums.DispatchTypes.UPDATE, { row: li, col, colIndex, value, eventWhichKey: 'custom-editor-action', scrollLeft: getAvailScrollLeft(nextCol.colIndex, { colGroup, sColIndex: printStartColIndex, eColIndex: printEndColIndex === 0 ? colGroup.length - 1 : printEndColIndex, frozenColumnIndex, frozenPanelWidth, verticalScrollerWidth, rightPanelWidth, scrollContentWidth, scrollContentHeight, scrollContentContainerWidth, scrollContentContainerHeight, scrollTop, scrollLeft, }), keepEditing: true, isInlineEditing: true, inlineEditingCell: { rowIndex: li, colIndex: nextCol.colIndex, editor: nextCol.editor, }, newFocusedRow: li, newFocusedCol: nextCol.colIndex, }, ); } break; default: } this.busy = false; }; handleCustomEditorFocus = () => { const { setStoreState, li, col } = this.props; // console.log('handleCustomEditorFocus : setStoreState'); setStoreState({ isInlineEditing: true, inlineEditingCell: { rowIndex: li, colIndex: col.colIndex, editor: col.editor, }, }); }; handleCustomEditorBlur = () => { const { dispatch } = this.props; dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, { isInlineEditing: false, inlineEditingCell: {}, }); }; inputTextRender = (value: any, disable: boolean = false) => { return ( <input type="text" onCompositionUpdate={() => { this.activeComposition = true; }} onCompositionEnd={() => { setTimeout(() => { this.activeComposition = false; }); }} onFocus={e => {}} onBlur={this.onInputTextBlur} onKeyDown={this.onInputTextKeyDown} data-inline-edit defaultValue={value} /> ); }; handleCheckboxValue = (value: boolean) => { const { dispatch, li, col } = this.props; dispatch(DataGridEnums.DispatchTypes.UPDATE, { row: li, col, colIndex: col.colIndex, value: value, eventWhichKey: 'click-checkbox', keepEditing: false, }); }; handleCheckboxKeyUp = (e: React.KeyboardEvent, currentValue: any) => { switch (e.which) { case DataGridEnums.KeyCodes.SPACE: case DataGridEnums.KeyCodes.ENTER: this.handleCheckboxValue(!currentValue); break; default: break; } }; checkboxRender = ( value: any, label: React.ReactNode | string = '', disabled: boolean = false, ) => { const { columnHeight, lineHeight, columnBorderWidth, colAlign, } = this.props; let justifyContent: string = ''; switch (colAlign) { case 'center': justifyContent = 'center'; break; case 'right': justifyContent = 'flex-end'; break; default: } return ( <span data-span={'checkbox-editor'} className={`${disabled ? 'disabled' : ''}`} style={{ height: columnHeight - columnBorderWidth + 'px', lineHeight: lineHeight + 'px', justifyContent, }} onClick={() => { if (!disabled) { this.handleCheckboxValue(!value); } }} > <div className="axui-datagrid-check-box" data-checked={value} style={{ width: lineHeight + 'px', height: lineHeight + 'px', }} /> <label style={{ height: lineHeight + 'px', lineHeight: lineHeight + 'px', }} > {label} </label> </span> ); }; componentDidMount() { const { col: { editor: colEditor }, } = this.props; const editor: IDataGrid.IColEditor = colEditor === 'text' ? { type: 'text' } : (colEditor as IDataGrid.IColEditor); if (this.customEditorRef.current) { const inputEl = this.customEditorRef.current.querySelector('input'); if (editor.activeType !== 'always' && inputEl) { inputEl.focus(); return; } } // dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, {}); } componentDidUpdate(prevProps: IProps) { this.lastEventName = ''; } handleInputTextSelect = (inputCurrent: any) => { const { col: { editor: colEditor }, } = this.props; const editor: IDataGrid.IColEditor = colEditor === 'text' ? { type: 'text' } : (colEditor as IDataGrid.IColEditor); if (editor.activeType !== 'always') { inputCurrent.select(); } }; render() { const { item, col, li } = this.props; if (!item) { return null; } const value = item && item.changed && item.changed![col.key || ''] ? item.changed![col.key || ''] : item.value[col.key || '']; const editor: IDataGrid.IColEditor = col.editor === 'text' ? { type: 'text' } : (col.editor as IDataGrid.IColEditor); const disabled = editor.disable ? editor.disable({ col: col, rowIndex: li, colIndex: col.colIndex || 0, item, value, }) : false; switch (editor.type) { case 'text': return ( <div ref={this.customEditorRef}>{this.inputTextRender(value)}</div> ); case 'checkbox': return this.checkboxRender(value, editor.label, disabled); default: if (!editor.render) { return ( <div ref={this.customEditorRef}>{this.inputTextRender(value)}</div> ); } return ( <div ref={this.customEditorRef}> {editor.render({ col: col, li, colIndex: col.colIndex || 0, item, value, update: this.handleUpdateValue, cancel: this.handleCancelEdit, focus: this.handleCustomEditorFocus, blur: this.handleCustomEditorBlur, keyAction: this.handelKeyAction, })} </div> ); } } } export default CellEditor;
the_stack
import * as vscode from 'vscode'; import { blockBuildCommands, languageClient } from '../extension'; import * as fs from 'fs'; import Utils from '../utils'; import { showCompileResult } from './buildResult'; var windows1252 = require('windows-1252'); var windows1251 = require('windows-1251'); import * as nls from 'vscode-nls'; import { ResponseError } from 'vscode-languageclient'; import { CompileResult } from './CompileResult'; import { sendCompilation } from '../protocolMessages'; let localize = nls.loadMessageBundle(); interface CompileOptions { recompile: boolean; debugAphInfo: boolean; gradualSending: boolean; generatePpoFile: boolean; showPreCompiler: boolean; priorVelocity: boolean; returnPpo: boolean; commitWithErrorOrWarning: boolean; } //TODO: pegar as opções de compilação da configuração (talvez por server? ou workspace?) function _getCompileOptionsDefault(): CompileOptions { let config = vscode.workspace.getConfiguration('totvsLanguageServer'); let generatePpoFile = config.get('compilation.generatePpoFile'); let showPreCompiler = config.get('compilation.showPreCompiler'); let commitWithErrorOrWarning = config.get( 'compilation.commitWithErrorOrWarning' ); return { recompile: false, debugAphInfo: true, gradualSending: true, generatePpoFile: generatePpoFile as boolean, showPreCompiler: showPreCompiler as boolean, priorVelocity: true, returnPpo: false, commitWithErrorOrWarning: commitWithErrorOrWarning as boolean, }; } export function generatePpo(filePath: string, options?: any): Promise<string> { return new Promise<string>((resolve, reject) => { if (!filePath || filePath.length == 0) { reject(new Error('Undefined filePath.')); return; } if (!fs.existsSync(filePath)) { reject(new Error("File '" + filePath + "' not found.")); return; } const server = Utils.getCurrentServer(); if (!server) { reject( new Error( "No server connected. Check if there is a server connected in 'totvs.tds-vscode' extension." ) ); return; } const serverItem = Utils.getServerById(server.id); let isAdvplsource: boolean = Utils.isAdvPlSource(filePath); if (!isAdvplsource) { reject( new Error('This file has an invalid AdvPL source file extension.') ); return; } const includes = Utils.getIncludes(true, serverItem) || []; let includesUris: Array<string> = includes.map((include) => { return vscode.Uri.file(include).toString(); }); if (includesUris.length == 0) { reject(new Error('Includes undefined.')); return; } let filesUris: Array<string> = []; filesUris.push(vscode.Uri.file(filePath).toString()); //const configADVPL = vscode.workspace.getConfiguration("totvsLanguageServer"); let extensionsAllowed: string[]; // if (configADVPL.get("folder.enableExtensionsFilter", true)) { // extensionsAllowed = configADVPL.get("folder.extensionsAllowed", []); // Le a chave especifica // } const compileOptions = _getCompileOptionsDefault(); compileOptions.recompile = true; compileOptions.generatePpoFile = false; compileOptions.showPreCompiler = false; compileOptions.returnPpo = true; if (blockBuildCommands(true)) { sendCompilation( server, includesUris, filesUris, compileOptions, extensionsAllowed, isAdvplsource ).then( (response: CompileResult) => { blockBuildCommands(false); if (response.compileInfos.length > 0) { for (let index = 0; index < response.compileInfos.length; index++) { const compileInfo = response.compileInfos[index]; if (compileInfo.status === 'APPRE') { // o compileInfo.detail chega do LS com encoding utf8 // a extensão tds-vscode realiza a conversão para o enconding conforme informado em options.encoding // caso nenhum encoding seja informado, converte para o padrão AdvPL cp1252 if (options && options.encoding) { let encoding: string = (<string>( options.encoding )).toLowerCase(); //console.log("encoding: "+encoding); if (options.encoding === 'utf8') { resolve(compileInfo.detail); } else if ( encoding === 'windows-1252' || encoding === 'cp1252' ) { //let apple = "Maçã"; //console.log(apple); resolve(windows1252.encode(compileInfo.detail)); } else if ( encoding === 'windows-1251' || encoding === 'cp1251' ) { //let helloWorld = "Привет мир"; //console.log(helloWorld); //resolve(windows1251.encode(helloWorld)); resolve(windows1251.encode(compileInfo.detail)); } else { // unknown encoding - fallback to utf8 resolve(compileInfo.detail); } } else { // if there is no encoding option - use windows-1252 resolve(windows1252.encode(compileInfo.detail)); } } } } }, (err: ResponseError<object>) => { blockBuildCommands(false); languageClient.error(err.message, err); reject(new Error(err.message)); } ); } }); } /** * Builds a file. */ export function buildFile( filename: string[], recompile: boolean, context: vscode.ExtensionContext ) { const compileOptions = _getCompileOptionsDefault(); compileOptions.recompile = recompile; buildCode(filename, compileOptions, context); } /** * Build a file list. */ async function buildCode( filesPaths: string[], compileOptions: CompileOptions, context: vscode.ExtensionContext ) { const server = Utils.getCurrentServer(); const configADVPL = vscode.workspace.getConfiguration('totvsLanguageServer'); const shouldClearConsole = configADVPL.get('clearConsoleBeforeCompile'); if (shouldClearConsole !== false) { languageClient.outputChannel.clear(); } const showConsoleOnCompile = configADVPL.get('showConsoleOnCompile'); if (showConsoleOnCompile !== false) { languageClient.outputChannel.show(); } const resourcesToConfirm: vscode.TextDocument[] = vscode.workspace.textDocuments.filter((d) => !d.isUntitled && d.isDirty); const count = resourcesToConfirm.length; if (count !== 0) { if (!vscode.workspace.saveAll(false)) { vscode.window.showWarningMessage( localize( 'tds.webview.tdsBuild.canceled', 'Operation canceled because it is not possible to save edited files.' ) ); return; } vscode.window.showWarningMessage( localize('tds.webview.tdsBuild.saved', 'Files saved successfully.') ); } if (server) { //Só faz sentido processar os includes se existir um servidor selecionado onde sera compilado. let serverItem = Utils.getServerById(server.id); let hasAdvplsource: boolean = filesPaths.filter((file) => { return Utils.isAdvPlSource(file); }).length > 0; let includes: Array<string> = []; if (hasAdvplsource) { includes = Utils.getIncludes(true, serverItem) || []; if (!includes.toString()) { return; } } let includesUris: Array<string> = []; for (let idx = 0; idx < includes.length; idx++) { includesUris.push(vscode.Uri.file(includes[idx]).toString()); } if (includesUris.length === 0) { const wp: string[] = vscode.workspace.workspaceFolders.map((uri) => { return uri.uri.toString(); }); includesUris.push(...wp); } let filesUris: Array<string> = []; filesPaths.forEach((file) => { if (!Utils.ignoreResource(file)) { filesUris.push(vscode.Uri.file(file).toString()); } else { languageClient.warn( localize( 'tds.webview.tdsBuild.resourceInList', 'Resource appears in the list of files to ignore. Resource: {0}', file ) ); } }); let extensionsAllowed: string[]; if (configADVPL.get('folder.enableExtensionsFilter', true)) { extensionsAllowed = configADVPL.get('folder.extensionsAllowed', []); // Le a chave especifica } if (blockBuildCommands(true)) { sendCompilation( server, includesUris, filesUris, compileOptions, extensionsAllowed, hasAdvplsource ).then( (response: CompileResult) => { blockBuildCommands(false); if (response.returnCode === 40840) { Utils.removeExpiredAuthorization(); } if (response.compileInfos.length > 0) { // Exibe aba problems casa haja pelo menos um erro ou warning let showProblems = false; for (let index = 0; index < response.compileInfos.length; index++) { const compileInfo = response.compileInfos[index]; if ( compileInfo.status === 'FATAL' || compileInfo.status === 'ERROR' || compileInfo.status === 'WARN' ) { showProblems = true; break; } } if (showProblems) { // focus vscode.commands.executeCommand('workbench.action.problems.focus'); } if (context !== undefined) { verifyCompileResult(response, context); } } }, (err: ResponseError<object>) => { blockBuildCommands(false); languageClient.error(err.message, err); vscode.window.showErrorMessage(err.message); } ); } } else { vscode.window.showErrorMessage( localize('tds.webview.tdsBuild.noServer', 'No server connected') ); } } function verifyCompileResult(response, context) { const textNoAsk = localize('tds.vscode.noAskAgain', "Don't ask again"); const textNo = localize('tds.vscode.no', 'No'); const textYes = localize('tds.vscode.yes', 'Yes'); const textQuestion = localize( 'tds.vscode.question.showCompileResult', 'Show table with compile results?' ); let questionAgain = true; const configADVPL = vscode.workspace.getConfiguration('totvsLanguageServer'); const askCompileResult = configADVPL.get('askCompileResult'); if (askCompileResult !== false) { vscode.window .showInformationMessage(textQuestion, textYes, textNo, textNoAsk) .then((clicked) => { if (clicked === textYes) { showCompileResult(response, context); } else if (clicked === textNoAsk) { questionAgain = false; } configADVPL.update('askCompileResult', questionAgain); }); } } export function commandBuildFile(context, recompile: boolean, files) { let editor: vscode.TextEditor | undefined; let filename: string | undefined = undefined; if (context === undefined) { //A ação veio pelo ctrl+f9 editor = vscode.window.activeTextEditor; if (!editor) { vscode.window.showInformationMessage( localize( 'tds.vscode.editornotactive', 'No editor is active, cannot find current file to build.' ) ); return; } filename = editor.document.uri.fsPath; recompile = true; } if (files) { const arrayFiles: string[] = changeToArrayString(files); let allFiles = Utils.getAllFilesRecursive(arrayFiles); buildFile(allFiles, recompile, context); } else { if (filename !== undefined) { buildFile([filename], recompile, context); } } } function changeToArrayString(allFiles) { let arrayFiles: string[] = []; allFiles.forEach((element) => { if (element.fsPath) { arrayFiles.push(element.fsPath); } else { if (fs.existsSync(element)) { arrayFiles.push(element); } } }); return arrayFiles; } export function commandBuildWorkspace( recompile: boolean, context: vscode.ExtensionContext ) { if (vscode.workspace.workspaceFolders) { let folders: string[] = []; vscode.workspace.workspaceFolders.forEach((value) => { folders.push(value.uri.fsPath); }); let allFiles = Utils.getAllFilesRecursive(folders); buildFile(allFiles, recompile, context); } } export async function commandBuildOpenEditors( recompile: boolean, context: vscode.ExtensionContext ) { let delayNext = 250; let files: string[] = []; let filename: string | undefined = undefined; let editor = vscode.window.activeTextEditor; let nextEditor = editor; if (!editor) { vscode.window.showInformationMessage( localize( 'tds.vscode.editornotactive', 'No editor is active, cannot find current file to build.' ) ); return; } if (editor.viewColumn) { filename = editor.document.uri.fsPath; if (files.indexOf(filename) === -1) { files.push(filename); } } else { vscode.commands.executeCommand('workbench.action.nextEditor'); await delay(delayNext); editor = vscode.window.activeTextEditor; if (editor) { if (editor.viewColumn) { filename = editor.document.uri.fsPath; if (files.indexOf(filename) === -1) { files.push(filename); } } else { vscode.window.showWarningMessage( '[SKIPPING] Editor file is not fully open' ); } } } do { vscode.commands.executeCommand('workbench.action.nextEditor'); await delay(delayNext); nextEditor = vscode.window.activeTextEditor; if (!nextEditor) { // arquivo que não pode ser aberto pelo editor (binarios ou requerem confirmacao do usuario) continue; } if ( nextEditor && !sameEditor(editor as vscode.TextEditor, nextEditor as vscode.TextEditor) ) { if (nextEditor.viewColumn) { filename = nextEditor.document.uri.fsPath; if (files.indexOf(filename) === -1) { files.push(filename); } } else { vscode.window.showWarningMessage( '[SKIPPING] Editor file is not fully open' ); } } else { // retornou ao primeiro editor break; } } while (true); // check if there are files to compile if (files.length > 0) { const compileOptions = _getCompileOptionsDefault(); compileOptions.recompile = recompile; buildCode(files, compileOptions, context); } else { vscode.window.showWarningMessage('There is nothing to compile'); } } function delay(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } function sameEditor(editor: vscode.TextEditor, nextEditor: vscode.TextEditor) { if (editor === undefined && nextEditor === undefined) { return true; } if (editor === undefined || nextEditor === undefined) { return false; } return editor.document === nextEditor.document; }
the_stack
import { BadRequestException, HttpException, Injectable, Logger, NotFoundException } from '@nestjs/common'; import { auth, driver, Driver, Transaction } from 'neo4j-driver'; import { ConfigKey, ConfigService } from '../config/config.service'; import { DocumentDefinition, Model } from 'mongoose'; import { User } from '../users/user.schema'; import { InjectModel } from '@nestjs/mongoose'; import { Movie } from '../movies/movie.schema'; import { Category } from '../categories/category.schema'; import { Comment } from "../comments/comment.schema"; import { ShowTime } from '../show-times/show-time.schema'; import { Theatre } from '../theatres/theatre.schema'; import { Reservation } from '../reservations/reservation.schema'; import { LocationDto } from '../common/location.dto'; import { catchError, exhaustMap, first, map, shareReplay, tap, toArray } from 'rxjs/operators'; import { concat, defer, identity, merge, Observable, of, partition, throwError } from 'rxjs'; import { UserPayload } from '../auth/get-user.decorator'; import { checkCompletedLogin, constants, getCoordinates } from '../common/utils'; import { Parameters } from 'neo4j-driver/types/query-runner'; import { SearchMoviesDto } from './search-movies.dto'; import { Person } from '../people/person.schema'; const FAVORITE_SCORE = 1; const COMMENT_SCORE = (comment: DocumentDefinition<Comment>) => comment.rate_star; const RESERVED_SCORE = 2; function splitIdAndRests(idAndRests: IdAndRest[]): IdAndMap { const ids: string[] = idAndRests.map(r => r._id); const restById: Map<string, Record<string, any>> = idAndRests.reduce( (acc, e) => { const { _id, ...rest } = e; acc.set(_id, rest); return acc; }, new Map<string, Record<string, any>>() ); return { ids, restById }; } type IdAndRest = { _id: string, [k: string]: any, }; type IdAndMap = { ids: string[]; restById: Map<string, Record<string, any>> }; export type MovieAndExtraInfo = DocumentDefinition<Movie> & Record<string, any>; @Injectable() export class Neo4jService { private readonly logger = new Logger(Neo4jService.name); private readonly driver: Driver; constructor( configService: ConfigService, @InjectModel(User.name) private readonly userModel: Model<User>, @InjectModel(Movie.name) private readonly movieModel: Model<Movie>, @InjectModel(Category.name) private readonly categoryModel: Model<Category>, @InjectModel(Comment.name) private readonly commentModel: Model<Comment>, @InjectModel(ShowTime.name) private readonly showTimeModel: Model<ShowTime>, @InjectModel(Theatre.name) private readonly theatreModel: Model<Theatre>, @InjectModel(Reservation.name) private readonly reservationModel: Model<Reservation>, @InjectModel(Person.name) private readonly personModel: Model<Person>, ) { try { this.driver = driver( configService.get(ConfigKey.NEO4J_URL), auth.basic( configService.get(ConfigKey.NEO4J_USER), configService.get(ConfigKey.NEO4J_PASSWORD), ), { disableLosslessIntegers: true }, ); this.logger.debug(`Done ${this.driver}`); } catch (e) { this.logger.debug(`Error ${e}`); } } /// /// START TRANSFER DATA /// async transferData(): Promise<void> { await this.runTransaction(txc => txc.run(` MATCH (n) DETACH DELETE n` ), '[DELETE]', ); await this.addCategories(); await this.addPeople(); await this.addMovies(); await this.addUsers(); await this.addComments(); await this.addTheatres(); await this.addShowTimes(); await this.addReservations(); } private async addUsers() { const users: DocumentDefinition<User>[] = await this.userModel.find({}).lean(); await this.runTransaction( async txc => { for (const user of users) { await txc.run( ` MERGE(user: USER { _id: $_id }) ON CREATE SET user.uid = $uid, user.email = $email, user.full_name = $full_name, user.gender = $gender, user.address = $address, user.location = point({ latitude: toFloat($latitude), longitude: toFloat($longitude) }) ON MATCH SET user.uid = $uid, user.email = $email, user.full_name = $full_name, user.gender = $gender, user.address = $address, user.location = point({ latitude: toFloat($latitude), longitude: toFloat($longitude) }) WITH user MATCH (o: USER) WHERE o._id <> user._id AND o.gender = user.gender WITH user, o MERGE (user)-[r:SIMILAR_GENDER]-(o) ON CREATE SET r.score = 1 ON MATCH SET r.score = r.score + 1 WITH user, o, coalesce(distance(user.location, o.location), -1.0) AS d WHERE 0 <= d AND d <= $max_distance WITH user, o MERGE (user)-[r:SIMILAR_LOCATION]-(o) ON CREATE SET r.score = 3 ON MATCH SET r.score = r.score + 3 `, { _id: user._id.toString(), uid: user.uid, email: user.email ?? '', full_name: user.full_name ?? '', gender: user.gender ?? 'MALE', address: user.address ?? '', longitude: user.location?.coordinates?.[0] ?? null, latitude: user.location?.coordinates?.[1] ?? null, max_distance: constants.maxDistanceInMeters, } ); } }, `[USERS] ${users.length}`, ); await this.runTransaction( async txc => { await txc.run( ` MATCH(u1:USER)-[r]-(u2:USER) WITH u1, u2, r, sum(r.score) as score DELETE r MERGE (u1)-[rs:SIMILAR]-(u2) ON CREATE SET rs.score = score ON MATCH SET rs.score = score `, {}, ); }, `[USERS] ${users.length}`, ); await this.runTransaction( async txc => { for (const user of users) { const ids = Object.keys(user.favorite_movie_ids ?? {}); for (const mov_id of ids) { await txc.run( ` MATCH (user: USER { _id: $id }) MATCH (mov: MOVIE { _id: $mov_id }) MERGE (user)-[r:INTERACTIVE]->(mov) ON CREATE SET r.score = $score ON MATCH SET r.score = r.score + $score RETURN mov.title, user.title `, { id: user._id.toString(), mov_id, score: FAVORITE_SCORE, }, ); } } }, `[USERS] ${users.length}`, ); } private async runTransaction(operation: (txc: Transaction) => Promise<any>, tag?: string): Promise<void> { const session = this.driver.session(); const transaction = session.beginTransaction(); try { const result = await operation(transaction); await transaction.commit(); this.logger.debug(`${tag} success ${JSON.stringify(result)}`); } catch (e) { await transaction.rollback(); this.logger.debug(`${tag} error ${e}`); throw e; } finally { await session.close(); } } private async addMovies() { const movies = await this.movieModel.find({}) .lean() .populate({ path: 'categories', populate: { path: 'category_id' }, }); await this.runTransaction(async txc => { let i = 0; for (const mov of movies) { this.logger.debug(`movies1 ${i++}/${movies.length}`); await txc.run( ` MERGE(mov: MOVIE { _id: $_id }) ON CREATE SET mov.title = $title, mov.trailer_video_url = $trailer_video_url, mov.poster_url = $poster_url, mov.overview = $overview, mov.released_date = apoc.date.fromISO8601($released_date), mov.duration = $duration, mov.original_language = $original_language, mov.age_type = $age_type, mov.total_rate = $total_rate, mov.rate_star = $rate_star, mov.total_favorite = $total_favorite, mov.is_active = $is_active ON MATCH SET mov.title = $title, mov.trailer_video_url = $trailer_video_url, mov.poster_url = $poster_url, mov.overview = $overview, mov.released_date = apoc.date.fromISO8601($released_date), mov.duration = $duration, mov.original_language = $original_language, mov.age_type = $age_type, mov.total_rate = $total_rate, mov.rate_star = $rate_star, mov.total_favorite = $total_favorite, mov.is_active = $is_active `, { _id: mov._id.toString(), title: mov.title ?? '', trailer_video_url: mov.trailer_video_url ?? '', poster_url: mov.poster_url ?? '', overview: mov.overview ?? '', released_date: (mov.released_date ?? new Date()).toISOString(), duration: mov.duration ?? 0, original_language: mov.original_language ?? 'en', age_type: mov.age_type ?? 'P', total_rate: mov.total_rate ?? 0, rate_star: mov.rate_star ?? 0.0, total_favorite: mov.total_favorite ?? 0, is_active: mov.is_active ?? true, }, ); } }, `[MOVIES] [1] ${movies.length}`); await this.runTransaction(async txc => { let i = 0; for (const mov of movies) { this.logger.debug(`movies2 ${i++}/${movies.length}`); const ids: string[] = (mov as any).categories.map(c => c.category_id._id.toString()); for (const cat_id of ids) { await txc.run( ` MATCH (cat: CATEGORY { _id: $cat_id }) MATCH (mov: MOVIE { _id: $mov_id }) MERGE (mov)-[r:IN_CATEGORY]->(cat) RETURN mov.title `, { cat_id, mov_id: mov._id.toString(), }, ); } } }, `[MOVIES] [2] ${movies.length}`); await this.runTransaction(async txc => { let i = 0; for (const mov of movies) { this.logger.debug(`movies3 ${i++}/${movies.length}`); const actors: string[] = mov.actors.map(i => i.toString()); for (const p_id of actors) { await txc.run( ` MATCH (p: PERSON { _id: $p_id }) MATCH (mov: MOVIE { _id: $mov_id }) MERGE (p)-[r:ACTED_IN]->(mov) RETURN mov.title, p.full_name `, { p_id, mov_id: mov._id.toString(), }, ); } const directors: string[] = mov.directors.map(i => i.toString()); for (const p_id of directors) { await txc.run( ` MATCH (p: PERSON { _id: $p_id }) MATCH (mov: MOVIE { _id: $mov_id }) MERGE (p)-[r:DIRECTED]->(mov) RETURN mov.title, p.full_name `, { p_id, mov_id: mov._id.toString(), }, ); } } }, `[MOVIES] [3] ${movies.length}`); } private async addCategories(): Promise<void> { const categories = await this.categoryModel.find({}).lean(); await this.runTransaction(async txc => { for (const cat of categories) { await txc.run( ` MERGE(cat: CATEGORY { _id: $_id }) ON CREATE SET cat.name = $name ON MATCH SET cat.name = $name `, { _id: cat._id.toString(), name: cat.name, }, ); } }, `[CATEGORIES] ${categories.length}`); } private async addComments() { const comments: DocumentDefinition<Comment>[] = await this.commentModel.find({}, { movie: 1, user: 1, rate_star: 1 }) .sort({ createdAt: -1 }) .limit(1_000) .lean(); await this.runTransaction( async txc => { let i = 0; for (const comment of comments) { this.logger.debug(`comments ${i++}/${comments.length}`); await txc.run( ` MATCH (mov: MOVIE { _id: $movie_id }) MATCH (user: USER { _id: $user_id }) MERGE (user)-[r:INTERACTIVE]->(mov) ON CREATE SET r.score = $score ON MATCH SET r.score = r.score + $score RETURN mov.title, user.title, r `, { movie_id: comment.movie.toString(), user_id: comment.user.toString(), score: COMMENT_SCORE(comment), }, ); } }, `[COMMENTS] ${comments.length}`, ) } private async addShowTimes() { const showTimes = await this.showTimeModel.find({}).lean(); await this.runTransaction( async txc => { let i = 0; for (const st of showTimes) { this.logger.debug(`show-times1 ${i++}/${showTimes.length}`); await txc.run( ` MERGE(st: SHOW_TIME { _id: $id }) ON CREATE SET st.room = $room, st.start_time = apoc.date.fromISO8601($start_time), st.end_time = apoc.date.fromISO8601($end_time) ON MATCH SET st.room = $room, st.start_time = apoc.date.fromISO8601($start_time), st.end_time = apoc.date.fromISO8601($end_time) `, { id: st._id.toString(), room: st.room ?? '', start_time: st.start_time.toISOString(), end_time: st.end_time.toISOString(), }, ); } }, `[SHOW_TIMES] ${showTimes.length}`, ); await this.runTransaction( async txc => { let i = 0; for (const st of showTimes) { this.logger.debug(`show-times2 ${i++}/${showTimes.length}`); await txc.run( ` MATCH (st: SHOW_TIME { _id: $id }) MATCH (mov: MOVIE { _id: $mov_id }) MATCH (t: THEATRE { _id: $theatre_id }) MERGE (mov)-[r1:HAS_SHOW_TIME]-(st) MERGE (t)-[r2:HAS_SHOW_TIME]-(st) RETURN r1, r2 `, { id: st._id.toString(), mov_id: st.movie.toString(), theatre_id: st.theatre.toString(), }, ); } }, `[SHOW_TIMES] ${showTimes.length}`, ); } private async addTheatres() { const theatres: DocumentDefinition<Theatre>[] = await this.theatreModel.find({}).lean(); await this.runTransaction( async txc => { for (const t of theatres) { await txc.run( ` MERGE (t: THEATRE { _id: $id }) ON CREATE SET t.name = $name, t.address = $address, t.location = point({ latitude: toFloat($latitude), longitude: toFloat($longitude) }) ON MATCH SET t.name = $name, t.address = $address, t.location = point({ latitude: toFloat($latitude), longitude: toFloat($longitude) }) RETURN t.name `, { id: t._id.toString(), name: t.name ?? '', address: t.address ?? '', latitude: t.location?.coordinates?.[1] ?? null, longitude: t.location?.coordinates?.[0] ?? null, } ); } }, `[THEATRES] ${theatres.length}`, ); } private async addReservations() { const reservations: DocumentDefinition<Reservation>[] = await this.reservationModel.find({}) .populate('show_time') .lean(); await this.runTransaction( async txc => { for (const r of reservations) { const showTime = r.show_time as ShowTime; const r1 = await txc.run( ` MATCH (u: USER { _id: $uid }) MATCH (s: SHOW_TIME { _id: $sid }) MERGE (u)-[r:RESERVED]->(s) RETURN r `, { uid: r.user.toString(), sid: showTime._id.toString(), } ); const r2 = await txc.run( ` MATCH (mov: MOVIE { _id: $movie_id }) MATCH (user: USER { _id: $user_id }) MERGE (user)-[r:INTERACTIVE]->(mov) ON CREATE SET r.score = $score ON MATCH SET r.score = r.score + $score RETURN mov.title, user.title, r `, { movie_id: showTime.movie.toString(), user_id: r.user.toString(), score: RESERVED_SCORE, }, ); } }, `[RESERVATIONS] ${reservations.length}`, ); } private async addPeople() { const people = await this.personModel.find({}).lean(); await this.runTransaction(async txc => { let i = 0; for (const person of people) { this.logger.debug(`people ${i++}/${people.length}`); await txc.run( ` MERGE(cat: PERSON { _id: $_id }) ON CREATE SET cat.full_name = $name ON MATCH SET cat.full_name = $name `, { _id: person._id.toString(), name: person.full_name, }, ); } }, `[PEOPLE] ${people.length}`); } /// /// END TRANSFER DATA /// /// /// START RECOMMENDED /// getRecommendedMovies( dto: LocationDto, userPayload: UserPayload ): Observable<MovieAndExtraInfo[]> { const center: [number, number] | null = getCoordinates(dto); const user = checkCompletedLogin(userPayload); const isInteracted$ = this.userInteractedMovie(user).pipe(shareReplay(1)); const [interacted$, notInteracted$] = partition(isInteracted$, identity); const queryInteracted: () => [string, Parameters] = () => { if (center) { return [ ` MATCH (u1:USER { _id: $id })-[r1:INTERACTIVE]->(m:MOVIE) WITH u1, avg(r1.score) AS u1_mean MATCH (u1)-[r1:INTERACTIVE]->(m:MOVIE)<-[r2:INTERACTIVE]-(u2:USER) WITH u1, u1_mean, u2, collect({ r1: r1, r2: r2 }) AS iteractions WHERE size(iteractions) > 1 MATCH (u2)-[r2:INTERACTIVE]->(m:MOVIE) WITH u1, u1_mean, u2, avg(r2.score) AS u2_mean, iteractions UNWIND iteractions AS r WITH sum( (r.r1.score - u1_mean) * (r.r2.score - u2_mean) ) AS nom, sqrt( sum((r.r1.score - u1_mean) ^ 2) * sum((r.r2.score - u2_mean) ^ 2) ) AS denom, u1, u2 WHERE denom <> 0 WITH u1, u2, nom / denom AS pearson ORDER BY pearson DESC LIMIT 15 MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE), (m)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) WITH m, pearson, r, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) AS startOfDay, coalesce(distance(point({ latitude: $lat, longitude: $lng }), t.location), -1.0) AS distance WHERE 0 <= distance AND distance <= $max_distance AND startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) WITH m, pearson, r, distance RETURN m._id AS _id, sum(pearson * r.score) AS recommendation, pearson, r.score AS score, null AS cats, distance ORDER BY recommendation DESC LIMIT 24 UNION ALL MATCH (u:USER { _id: $id })-[r:INTERACTIVE]->(m:MOVIE) WITH u, avg(r.score) AS mean MATCH (u)-[r:INTERACTIVE]->(m:MOVIE)-[:IN_CATEGORY]->(cat:CATEGORY) WHERE r.score > mean WITH u, cat, COUNT(*) AS score MATCH (cat)<-[:IN_CATEGORY]-(rec:MOVIE), (rec)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WHERE NOT exists((u)-[:INTERACTIVE]->(rec)) WITH rec, score, cat, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) AS startOfDay, coalesce(distance(point({ latitude: $lat, longitude: $lng }), t.location), -1.0) AS distance WHERE 0 <= distance AND distance <= $max_distance AND startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) WITH sum(score) AS score, rec, cat, distance RETURN rec._id AS _id, score AS recommendation, null AS pearson, score, collect(DISTINCT cat.name) AS cats, distance ORDER BY recommendation DESC LIMIT 24 UNION ALL MATCH (u1:USER { _id: $id })-[r1:INTERACTIVE]->(m:MOVIE) WITH u1, avg(r1.score) AS u1_mean MATCH (u1)-[r1:INTERACTIVE]->(m:MOVIE)<-[r2:INTERACTIVE]-(u2:USER) WITH u1, u1_mean, u2, collect({ r1: r1, r2: r2 }) AS iteractions WHERE size(iteractions) > 1 MATCH (u2)-[r2:INTERACTIVE]->(m:MOVIE) WITH u1, u1_mean, u2, avg(r2.score) AS u2_mean, iteractions UNWIND iteractions AS r WITH sum( (r.r1.score - u1_mean) * (r.r2.score - u2_mean) ) AS nom, sqrt( sum((r.r1.score - u1_mean) ^ 2) * sum((r.r2.score - u2_mean) ^ 2) ) AS denom, u1, u2 WHERE denom <> 0 WITH u1, u2, nom / denom AS pearson ORDER BY pearson DESC LIMIT 15 MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) WITH m, pearson, r RETURN m._id AS _id, sum(pearson * r.score) AS recommendation, pearson, r.score AS score, null AS cats, null as distance ORDER BY recommendation DESC LIMIT 24 `, { id: user._id.toString(), lng: center[0], lat: center[1], max_distance: constants.maxDistanceInMeters, }, ]; } else { return [ ` MATCH (u1:USER { _id: $id })-[r1:INTERACTIVE]->(m:MOVIE) WITH u1, avg(r1.score) AS u1_mean MATCH (u1)-[r1:INTERACTIVE]->(m:MOVIE)<-[r2:INTERACTIVE]-(u2:USER) WITH u1, u1_mean, u2, collect({ r1: r1, r2: r2 }) AS iteractions WHERE size(iteractions) > 1 MATCH (u2)-[r2:INTERACTIVE]->(m:MOVIE) WITH u1, u1_mean, u2, avg(r2.score) AS u2_mean, iteractions UNWIND iteractions AS r WITH sum( (r.r1.score - u1_mean) * (r.r2.score - u2_mean) ) AS nom, sqrt( sum((r.r1.score - u1_mean) ^ 2) * sum((r.r2.score - u2_mean) ^ 2) ) AS denom, u1, u2 WHERE denom <> 0 WITH u1, u2, nom / denom AS pearson ORDER BY pearson DESC LIMIT 15 MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE), (m)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) WITH m, pearson, r, datetime({ epochMillis: st.start_time }) as startTime, datetime({ epochMillis: st.end_time }) as endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) as startOfDay WHERE startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) RETURN m._id AS _id, sum(pearson * r.score) AS recommendation, pearson, r.score AS score, null AS cats ORDER BY recommendation DESC LIMIT 24 UNION ALL MATCH (u:USER { _id: $id })-[r:INTERACTIVE]->(m:MOVIE) WITH u, avg(r.score) AS mean MATCH (u)-[r:INTERACTIVE]->(m:MOVIE)-[:IN_CATEGORY]->(cat:CATEGORY) WHERE r.score > mean WITH u, cat, COUNT(*) AS score MATCH (cat)<-[:IN_CATEGORY]-(rec:MOVIE), (rec)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WHERE NOT exists((u)-[:INTERACTIVE]->(rec)) WITH rec, score, cat, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) AS startOfDay WHERE startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) WITH sum(score) AS score, rec, cat RETURN rec._id AS _id, score AS recommendation, null AS pearson, score, collect(DISTINCT cat.name) AS cats ORDER BY recommendation DESC LIMIT 24 UNION ALL MATCH (u1:USER { _id: $id })-[r1:INTERACTIVE]->(m:MOVIE) WITH u1, avg(r1.score) AS u1_mean MATCH (u1)-[r1:INTERACTIVE]->(m:MOVIE)<-[r2:INTERACTIVE]-(u2:USER) WITH u1, u1_mean, u2, collect({ r1: r1, r2: r2 }) AS iteractions WHERE size(iteractions) > 1 MATCH (u2)-[r2:INTERACTIVE]->(m:MOVIE) WITH u1, u1_mean, u2, avg(r2.score) AS u2_mean, iteractions UNWIND iteractions AS r WITH sum( (r.r1.score - u1_mean) * (r.r2.score - u2_mean) ) AS nom, sqrt( sum((r.r1.score - u1_mean) ^ 2) * sum((r.r2.score - u2_mean) ^ 2) ) AS denom, u1, u2 WHERE denom <> 0 WITH u1, u2, nom / denom AS pearson ORDER BY pearson DESC LIMIT 15 MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) WITH m, pearson, r RETURN m._id AS _id, sum(pearson * r.score) AS recommendation, pearson, r.score AS score, null AS cats ORDER BY recommendation DESC LIMIT 24 `, { id: user._id.toString(), }, ]; } }; const queryNotInteracted: () => [string, Parameters] = () => { if (center) { return [ ` MATCH (u:USER { _id: $id })-[r:SIMILAR]-(other:USER) WITH other, sum(r.score) AS score MATCH (other)-[r:INTERACTIVE]->(m: MOVIE), (m)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WITH r.score + score AS recommendation, m, score, st, t, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) AS startOfDay, coalesce(distance(point({ latitude: $lat, longitude: $lng }), t.location), -1.0) AS distance WHERE 0 <= distance AND distance <= $max_distance AND startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) RETURN m._id AS _id, recommendation, score, distance ORDER BY recommendation DESC LIMIT 24 `, { id: user._id.toString(), lng: center[0], lat: center[1], max_distance: constants.maxDistanceInMeters, }, ]; } else { return [ ` MATCH (u:USER { _id: $id })-[r:SIMILAR]-(other:USER) WITH other, sum(r.score) AS score MATCH (other)-[r:INTERACTIVE]->(m: MOVIE), (m)-[:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[:HAS_SHOW_TIME]-(t:THEATRE) WITH r.score + score AS recommendation, m, score, st, t, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime.truncate('hour', datetime(), { minute: 0, second: 0, millisecond: 0, microsecond: 0 }) AS startOfDay WHERE startTime >= startOfDay AND endTime <= startOfDay + duration({ days: 4 }) RETURN m._id AS _id, recommendation, score ORDER BY recommendation DESC LIMIT 24 `, { id: user._id.toString(), }, ]; } }; return merge( interacted$.pipe(map(queryInteracted)), notInteracted$.pipe(map(queryNotInteracted)), ).pipe( exhaustMap(([query, parameters]) => { const session = this.driver.rxSession(); return concat( session .run(query, parameters) .records() .pipe( map(record => ({ ...record.toObject(), _id: record.get('_id') as string, }) ), toArray(), map(splitIdAndRests), exhaustMap((idAndMap) => { return this .findMoviesInIds(idAndMap) .pipe( map(movies => { const a1 = movies .filter(m => m.pearson !== null && m.pearson !== undefined) .sort((l, r) => r.recommendation - l.recommendation); const a2 = movies .filter(m => m.pearson === null || m.pearson === undefined) .sort((l, r) => r.recommendation - l.recommendation); const result = a1.concat(a2).distinct(v => v._id.toString()); this.logger.debug(movies.length, '[]'); this.logger.debug(a1.length, '[1]'); this.logger.debug(a2.length, '[2]'); this.logger.debug(result.length, '[*]'); return result; } ), ); }, ), ), session.close() as Observable<never>, ); }), ); } private userInteractedMovie(user: User): Observable<boolean> { const session = this.driver.rxSession(); const result$ = session .run( ` RETURN exists( (:USER { _id: $id })-[:INTERACTIVE]->(:MOVIE) ) AS interacted `, { id: user._id.toString(), }, ) .records() .pipe( map(r => r.get('interacted') === true), first( identity, false, ), ); return concat( result$, session.close() as Observable<never>, ) } private findMoviesInIds({ ids, restById }: IdAndMap): Observable<MovieAndExtraInfo[]> { return defer(() => this.movieModel.find({ _id: { $in: ids } })) .pipe( map(movies => movies.map(m => ({ ...m.toObject(), ...(restById.get(m._id.toString()) ?? {}), }), ), ), ); } /// /// END RECOMMENDED /// searchMovies(userPayload: UserPayload, dto: SearchMoviesDto): Observable<MovieAndExtraInfo[]> { this.logger.debug(dto.category_ids); return defer(() => dto.category_ids ? this.categoryModel.find({ _id: { $in: dto.category_ids } }) : this.categoryModel.find({}) ).pipe( exhaustMap(cats => dto.category_ids ? ( cats.length != dto.category_ids.length ? throwError(new BadRequestException(`Invalid category ids`)) : of(cats) ) : of(cats), ), catchError(e => e instanceof HttpException ? throwError(e) : throwError(new BadRequestException(e.message ?? 'Error')) ), tap(cats => this.logger.debug(`Cats.length: ${cats.length}`)), exhaustMap(cats => { dto.category_ids = cats.map(c => c._id.toString()); const [query, parameters] = Neo4jService.buildQueryAndParams(checkCompletedLogin(userPayload), dto); this.logger.debug(dto); return this .getMovies(query, parameters) .pipe(map(movies => [...movies].sort((l, r) => r.recommendation - l.recommendation))); }), ); } private static buildQueryAndParams(user: User, dto: SearchMoviesDto): [string, Record<string, any>] { // return [ // ` // MATCH (m: MOVIE)-[r1:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[r2:HAS_SHOW_TIME]-(t:THEATRE) // WITH m, // st, // ('(?i).*' + $query + '.*') AS query // WHERE ( // m.title =~ query // OR m.overview =~ query // OR st.room =~ query // OR t.name =~ query // OR t.address =~ query // ) // RETURN m._id as _id, query // `, // { // query: dto.query, // } // ]; const center = getCoordinates(dto); if (center) { return [ ` MATCH (m: MOVIE)-[r1:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[r2:HAS_SHOW_TIME]-(t:THEATRE), (m)-[r3:IN_CATEGORY]->(c:CATEGORY) WHERE c._id IN $cat_ids WITH m, st, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime({epochMillis: m.released_date}) AS released_date, datetime($search_start_time) AS search_start_time, datetime($search_end_time) AS search_end_time, coalesce(distance(point({ latitude: $lat, longitude: $lng }), t.location), -1.0) AS distance, ('(?i).*' + $query + '.*') AS query, datetime($min_released_date) AS min_released_date, datetime($max_released_date) AS max_released_date WHERE ( m.title =~ query OR m.overview =~ query OR st.room =~ query OR t.name =~ query OR t.address =~ query ) AND $min_duration <= m.duration AND m.duration <= $max_duration AND m.age_type = $age_type AND 0 <= distance AND distance <= $max_distance AND min_released_date <= released_date AND released_date <= max_released_date AND search_start_time <= startTime AND endTime <= search_end_time AND m.is_active = true OPTIONAL MATCH (u: USER { _id: $uid })-[r:INTERACTIVE]->(m: MOVIE) WITH DISTINCT m, sum(r.score) AS recommendation, st RETURN m._id AS _id, recommendation ORDER BY recommendation DESC, st.start_time ASC LIMIT 100 `, { search_start_time: dto.search_start_time.toISOString(), search_end_time: dto.search_end_time.toISOString(), lng: center[0], lat: center[1], query: dto.query, min_released_date: dto.min_released_date.toISOString(), max_released_date: dto.max_released_date.toISOString(), min_duration: dto.min_duration, max_duration: dto.max_duration, age_type: dto.age_type, max_distance: constants.maxDistanceInMeters, uid: user._id, cat_ids: dto.category_ids, }, ]; } return [ ` MATCH (m: MOVIE)-[r1:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[r2:HAS_SHOW_TIME]-(t:THEATRE), (m)-[r3:IN_CATEGORY]->(c:CATEGORY) WHERE c._id IN $cat_ids WITH m, st, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime({epochMillis: m.released_date}) AS released_date, datetime($search_start_time) AS search_start_time, datetime($search_end_time) AS search_end_time, ('(?i).*' + $query + '.*') AS query, datetime($min_released_date) AS min_released_date, datetime($max_released_date) AS max_released_date WHERE ( m.title =~ query OR m.overview =~ query OR st.room =~ query OR t.name =~ query OR t.address =~ query ) AND $min_duration <= m.duration AND m.duration <= $max_duration AND m.age_type = $age_type AND min_released_date <= released_date AND released_date <= max_released_date AND search_start_time <= startTime AND endTime <= search_end_time AND m.is_active = TRUE OPTIONAL MATCH (u: USER { _id: $uid })-[r:INTERACTIVE]->(m: MOVIE) WITH DISTINCT m, sum(r.score) AS recommendation, st RETURN m._id AS _id, recommendation ORDER BY recommendation DESC, st.start_time ASC LIMIT 100 `, { search_start_time: dto.search_start_time.toISOString(), search_end_time: dto.search_end_time.toISOString(), query: dto.query, min_released_date: dto.min_released_date.toISOString(), max_released_date: dto.max_released_date.toISOString(), min_duration: dto.min_duration, max_duration: dto.max_duration, age_type: dto.age_type, uid: user._id, cat_ids: dto.category_ids, }, ]; } getRelatedMovies(movieId: string) { return defer(() => this.movieModel.findById(movieId)).pipe( exhaustMap(movie => { if (!movie) { return throwError(new NotFoundException(`Not found movie with id ${movieId}`)); } this.logger.debug(`getRelatedMovies ${movie.title}`); const query = ` MATCH (m:MOVIE {_id: $id })-[:IN_CATEGORY|:DIRECTED|ACTED_IN]->(c)<-[:IN_CATEGORY|:DIRECTED|ACTED_IN]-(other:MOVIE) WITH m, other, count(c) AS intersection, collect(c._id) AS i MATCH (m)-[:IN_CATEGORY|:DIRECTED|ACTED_IN]->(mg) WITH m, other, intersection, i, collect(mg._id) AS s1 MATCH (other)-[:IN_CATEGORY|:DIRECTED|ACTED_IN]->(og) WITH m, other, intersection, i, s1, collect(og._id) AS s2 WITH m, other, intersection, s1, s2 WITH m, other, intersection, s1+[x IN s2 WHERE NOT x IN s1] AS union, s1, s2 RETURN other._id AS _id, ((1.0 * intersection) / size(union)) AS jaccard, s1, s2 ORDER BY jaccard DESC LIMIT 16 `; const parameters = { id: movieId, }; return this .getMovies(query, parameters) .pipe(map(movies => [...movies].sort((l, r) => r.jaccard - l.jaccard))); }), catchError(e => e instanceof HttpException ? throwError(e) : throwError(new BadRequestException(e.message ?? 'Error')) ) ); } private getMovies(query: string, parameters: Record<string, any>): Observable<MovieAndExtraInfo[]> { const session = this.driver.rxSession(); return concat( session .run(query, parameters) .records() .pipe( map(record => ({ ...record.toObject(), _id: record.get('_id') as string, }) ), toArray(), map(splitIdAndRests), exhaustMap(idAndMap => this.findMoviesInIds(idAndMap)), ), session.close() as Observable<never>, ); } test(id: string) { const session = this.driver.rxSession(); return concat( session .run( ` MATCH (u1:USER { _id: $id })-[r1:INTERACTIVE]->(m:MOVIE) WITH u1, avg(r1.score) AS u1_mean MATCH (u1)-[r1:INTERACTIVE]->(m:MOVIE)<-[r2:INTERACTIVE]-(u2:USER) WITH u1, u1_mean, u2, collect({ r1: r1, r2: r2 }) AS interactions MATCH (u2)-[r2:INTERACTIVE]->(m:MOVIE) WITH u1, u1_mean, u2, avg(r2.score) AS u2_mean, interactions UNWIND interactions AS r WITH sum( (r.r1.score - u1_mean) * (r.r2.score - u2_mean) ) AS nom, sqrt( sum((r.r1.score - u1_mean) ^ 2) * sum((r.r2.score - u2_mean) ^ 2) ) AS denom, u1, u2 WHERE denom <> 0 WITH u1, u2, nom / denom AS pearson ORDER BY pearson DESC LIMIT 30 MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) RETURN m, sum(pearson * r.score) AS recommendation, pearson, r.score AS score ORDER BY recommendation DESC LIMIT 64 `, { id } ) .records() .pipe( map(record => record.toObject()), toArray(), ), session.close() as Observable<never>, ); } } ` OPTIONAL MATCH (u2)-[r:INTERACTIVE]->(m:MOVIE) WHERE NOT exists( (u1)-[:INTERACTIVE]->(m) ) WITH m, pearson, r RETURN m._id AS _id, sum(pearson * r.score) AS recommendation, pearson, r.score AS score ORDER BY recommendation DESC LIMIT 24`; ` MATCH (m: MOVIE)-[r1:HAS_SHOW_TIME]->(st:SHOW_TIME)<-[r2:HAS_SHOW_TIME]-(t:THEATRE) WITH m, st, datetime({ epochMillis: st.start_time }) AS startTime, datetime({ epochMillis: st.end_time }) AS endTime, datetime($search_start_time) AS search_start_time, datetime($search_end_time) AS search_end_time, coalesce(distance(point({ latitude: $lat, longitude: $lng }), t.location), -1.0) AS distance, ('(?i).*' + $query + '.*') AS query, datetime($min_released_date) AS min_released_date, datetime($max_released_date) AS max_released_date WHERE $min_duration <= m.duration AND m.duration <= $max_duration AND m.age_type = $age_type AND min_released_date <= m.released_date AND m.released_date <= max_released_date AND 0 <= distance AND distance <= $max_distance AND search_start_time <= startTime AND endTime <= search_end_time AND ( m.title =~ query OR m.overview =~ query OR st.room =~ query OR t.name =~ query OR t.address =~ query ) OPTIONAL MATCH (u: USER { _id: $uid })-[r:INTERACTIVE]->(m: MOVIE) WITH DISTINCT m, sum(r.score) AS recommendation, st RETURN m._id AS _id, recommendation ORDER BY recommendation DESC, st.start_time ASC LIMIT 100 `;
the_stack
import { Component } from "@angular/core"; import { TORUS_BUILD_ENV_TYPE, VerifierArgs } from "@toruslabs/torus-embed"; import { encrypt, recoverTypedMessage } from "eth-sig-util"; import { ethers } from "ethers"; import { keccak256 } from "ethers/lib/utils"; import { AbstractProvider } from "web3-core"; import { AbiType, StateMutabilityType } from "web3-utils"; import { getV3TypedData, getV4TypedData, whiteLabelData } from "./data"; import web3Obj from "./helper"; const tokenAbi = [ { constant: false, inputs: [ { name: "_to", type: "address", }, { name: "_value", type: "uint256", }, ], name: "transfer", outputs: [ { name: "", type: "bool", }, ], payable: false, stateMutability: "nonpayable" as StateMutabilityType, type: "function" as AbiType, }, ]; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"], }) export class AppComponent { publicAddress = ""; chainId = 4; verifierId = ""; selectedVerifier = "google"; placeholder = "Enter google email"; chainIdNetworkMap = { 1: "mainnet", 3: "ropsten", 4: "rinkeby", 5: "goerli", 42: "kovan", 97: "bsc_testnet", 56: "bsc_mainnet", } as Record<string, string>; messageToEncrypt = ""; encryptionKey = ""; messageEncrypted = ""; buildEnv = "testing" as TORUS_BUILD_ENV_TYPE; buildEnvironments = ["production", "binance", "testing", "development", "lrc", "beta"]; selectedVerifiers = [ { label: "Google", value: "google" }, { label: "Reddit", value: "reddit" }, { label: "Discord", value: "discord" }, ]; ngAfterContentInit(): void { const torusEnv = sessionStorage.getItem("pageUsingTorus"); if (torusEnv) { this.login().catch(console.error); } } login = async (): Promise<void> => { try { const { torus, web3 } = web3Obj; const { buildEnv, chainIdNetworkMap, chainId } = this; await torus.init({ buildEnv, enabledVerifiers: { reddit: false, }, enableLogging: true, network: { host: chainIdNetworkMap[chainId.toString()], // mandatory chainId, // chainId: 336, // networkName: 'DES Network', // host: 'https://quorum.block360.io/https', // ticker: 'DES', // tickerName: 'DES Coin', }, showTorusButton: true, integrity: { version: "1.11.0", check: false, // hash: 'sha384-jwXOV6VJu+PM89ksbCSZyQRjf5FdX8n39nWfE/iQBMh4r5m027ua2tkQ+83FPdp9' }, loginConfig: buildEnv === "lrc" ? { "torus-auth0-email-passwordless": { name: "torus-auth0-email-passwordless", typeOfLogin: "passwordless", showOnModal: false, }, } : undefined, whiteLabel: whiteLabelData, skipTKey: true, }); await torus.login(); // await torus.ethereum.enable() sessionStorage.setItem("pageUsingTorus", buildEnv); web3Obj.setweb3(torus.provider); torus.provider.on("chainChanged", (resp) => { console.log(resp, "chainchanged"); this.chainId = parseInt(resp as string, 10); }); torus.provider.on("accountsChanged", (accounts) => { console.log(accounts, "accountsChanged"); this.publicAddress = (Array.isArray(accounts) && accounts[0]) || ""; }); const accounts = await web3.eth.getAccounts(); console.log("accounts[0]", accounts[0]); this.publicAddress = (Array.isArray(accounts) && accounts[0]) || ""; web3.eth.getBalance(accounts[0]).then(console.log).catch(console.error); } catch (error) { console.error(error, "caught in vue-app"); } }; toggleTorusWidget = (_: Event): void => { const { torus } = web3Obj; if (torus.torusWidgetVisibility) { torus.hideTorusButton(); } else { torus.showTorusButton(); } }; onSelectedVerifierChanged = (e: Event): void => { const verifier = (<HTMLSelectElement>e.target).value; let placeholder = "Enter google email"; switch (verifier) { case "google": placeholder = "Enter google email"; break; case "reddit": placeholder = "Enter reddit username"; break; case "discord": placeholder = "Enter discord ID"; break; default: placeholder = "Enter google email"; break; } this.selectedVerifier = verifier; this.placeholder = placeholder; }; changeProvider = async (_: Event): Promise<void> => { await web3Obj.torus.setProvider({ host: "ropsten" }); this.console("finished changing provider"); }; createPaymentTx = async (_: Event): Promise<void> => { try { const { torus } = web3Obj; const res = await torus.initiateTopup("mercuryo", { selectedCurrency: "USD", }); console.log(res); } catch (error) { console.error(error); } }; sendEth = (_: Event): void => { const { web3 } = web3Obj; const { publicAddress } = this; web3.eth .sendTransaction({ from: publicAddress, to: publicAddress, value: web3.utils.toWei("0.01") }) .then((resp) => this.console(resp)) .catch(console.error); }; signMessageWithoutPopup = (_: Event): void => { const { web3 } = web3Obj; const { publicAddress } = this; // hex message const message = "Hello world"; const customPrefix = `\u0019${window.location.hostname} Signed Message:\n`; const prefixWithLength = Buffer.from(`${customPrefix}${message.length.toString()}`, "utf-8"); const hashedMsg = keccak256(Buffer.concat([prefixWithLength, Buffer.from(message)])); (web3.currentProvider as AbstractProvider).send( { method: "eth_sign", params: [publicAddress, hashedMsg, { customPrefix, customMessage: message }], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } const signerAddress = ethers.utils.recoverAddress(hashedMsg, result.result); return this.console( "sign message => true", `message: ${prefixWithLength + message}`, `msgHash: ${hashedMsg}`, `sig: ${result.result}`, `signer: ${signerAddress}` ); } ); }; signMessage = (_: Event): void => { const { web3 } = web3Obj; const { publicAddress } = this; // hex message const message = "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"; (web3.currentProvider as AbstractProvider).send( { method: "eth_sign", params: [publicAddress, message], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } return this.console("sign message => true", result); } ); }; signTypedDataV1 = (_: Event): void => { const { publicAddress } = this; const typedData = [ { type: "string", name: "message", value: "Hi, Alice!", }, { type: "uint8", name: "value", value: 10, }, ]; const currentProvider = web3Obj.web3.currentProvider as AbstractProvider; currentProvider.send( { method: "eth_signTypedData", params: [typedData, publicAddress], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } const recovered = recoverTypedMessage( { data: typedData, sig: result.result, }, "V1" ); if (publicAddress && recovered.toLowerCase() === publicAddress?.toLowerCase()) { return this.console(`sign typed message v1 => true${result}Recovered signer: ${publicAddress}`); } return this.console(`Failed to verify signer, got: ${recovered}`); } ); }; signTypedDataV3 = (_: Event): void => { const { chainId, publicAddress } = this; const typedData = getV3TypedData(chainId); const currentProvider = web3Obj.web3.currentProvider as AbstractProvider; currentProvider.send( { method: "eth_signTypedData_v3", params: [publicAddress, JSON.stringify(typedData)], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } const recovered = recoverTypedMessage( { data: typedData as any, sig: result.result, }, "V3" ); if (recovered.toLowerCase() === publicAddress?.toLowerCase()) { return this.console(`sign typed message v3 => true${result}Recovered signer: ${publicAddress}`); } return this.console(`Failed to verify signer, got: ${recovered}`); } ); }; signTypedDataV4 = (_: Event): void => { const { chainId, publicAddress } = this; const { web3 } = web3Obj; const typedData = getV4TypedData(chainId); (web3.currentProvider as AbstractProvider).send( { method: "eth_signTypedData_v4", params: [publicAddress, JSON.stringify(typedData)], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } const recovered = recoverTypedMessage( { data: typedData as any, sig: result.result, }, "V4" ); if (recovered.toLowerCase() === publicAddress.toLowerCase()) { return this.console("sign typed message v4 => true", result, `Recovered signer: ${publicAddress}`); } return this.console(`Failed to verify signer, got: ${recovered}`); } ); }; console = (...args: any[]): void => { const el = document.querySelector("#console>p"); if (el) { el.innerHTML = JSON.stringify(args || {}, null, 2); } }; sendDai = async (_: Event): Promise<void> => { try { const { chainId, publicAddress } = this; const { torus, web3 } = web3Obj; if (chainId !== 1) { await torus.setProvider({ host: "mainnet" }); } const instance = new web3.eth.Contract(tokenAbi, "0x6b175474e89094c44da98b954eedeac495271d0f"); const balance = await instance.methods.balanceOf(publicAddress).call(); console.log(balance, "dai balance"); const value = Math.floor(parseFloat("0.01") * 10 ** parseFloat("18")).toString(); if (Number(balance) < Number(value)) { // eslint-disable-next-line no-alert window.alert("You do not have enough dai tokens for transfer"); return; } instance.methods.transfer(publicAddress, value).send( { from: publicAddress, }, (err: Error, hash: string) => { if (err) this.console(err); else this.console(hash); } ); } catch (error) { console.error(error); } }; approveKnc = async (_: Event): Promise<void> => { try { const { chainId, publicAddress } = this; const { torus, web3 } = web3Obj; console.log(chainId, "current chain id"); if (chainId !== 1) { await torus.setProvider({ host: "mainnet" }); } const instance = new web3.eth.Contract(tokenAbi, "0xdd974D5C2e2928deA5F71b9825b8b646686BD200"); let value = Math.floor(parseFloat("0.01") * 10 ** parseFloat("18")).toString(); const allowance = await instance.methods.allowance(publicAddress, "0x3E2a1F4f6b6b5d281Ee9a9B36Bb33F7FBf0614C3").call(); console.log(allowance, "current allowance"); if (Number(allowance) > 0) value = "0"; instance.methods.approve("0x3E2a1F4f6b6b5d281Ee9a9B36Bb33F7FBf0614C3", value).send( { from: publicAddress, }, (err: Error, hash: string) => { if (err) this.console(err); else this.console(hash); } ); } catch (error) { console.error(error); } }; signPersonalMsg = async (_: Event): Promise<void> => { try { const { web3 } = web3Obj; const { publicAddress } = this; const message = "Some string"; const hash = web3.utils.sha3(message) as string; const sig = await web3.eth.personal.sign(hash, publicAddress, ""); const hostnamealAddress = await web3.eth.personal.ecRecover(hash, sig); if (publicAddress.toLowerCase() === hostnamealAddress.toLowerCase()) this.console("Success"); else this.console("Failed"); } catch (error) { console.error(error); this.console("failed"); } }; getUserInfo = (_: Event): void => { const { torus } = web3Obj; torus.getUserInfo("").then(this.console).catch(this.console); }; getPublicAddress = (_: Event): void => { const { torus } = web3Obj; const { selectedVerifier, verifierId } = this; console.log(selectedVerifier, verifierId); torus .getPublicAddress({ verifier: selectedVerifier, verifierId } as VerifierArgs) .then(this.console) .catch(console.error); }; getEncryptionKey = (_: Event): void => { const { web3 } = web3Obj; const { publicAddress } = this; (web3.currentProvider as AbstractProvider).send( { method: "eth_getEncryptionPublicKey", params: [publicAddress], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } this.encryptionKey = result.result; return this.console(`encryption public key => ${result.result}`); } ); }; encryptMessage = (_: Event): void => { try { const { encryptionKey, messageToEncrypt } = this; const messageEncrypted = encrypt(encryptionKey, { data: messageToEncrypt }, "x25519-xsalsa20-poly1305"); const encryptedMessage = this.stringifiableToHex(messageEncrypted); this.messageEncrypted = encryptedMessage; this.console(`encrypted message => ${encryptedMessage}`); } catch (error) { console.error(error); } }; decryptMessage = (_: Event): void => { const { web3 } = web3Obj; const { messageEncrypted, publicAddress } = this; (web3.currentProvider as AbstractProvider).send( { method: "eth_decrypt", params: [messageEncrypted, publicAddress], jsonrpc: "2.0", }, (err: Error, result: any) => { if (err) { return console.error(err); } const decMsg = result.result; return this.console(`decrypted message => ${decMsg}`); } ); }; stringifiableToHex = (value: any): string => ethers.utils.hexlify(Buffer.from(JSON.stringify(value))); logout = (_: Event): void => { web3Obj.torus .cleanUp() .then(() => { this.publicAddress = ""; return undefined; }) .catch(console.error); }; }
the_stack
import { isString, extend, map } from 'zrender/src/core/util'; import * as graphic from '../../util/graphic'; import {createTextStyle} from '../../label/labelStyle'; import { formatTplSimple } from '../../util/format'; import { parsePercent } from '../../util/number'; import type CalendarModel from '../../coord/calendar/CalendarModel'; import {CalendarParsedDateRangeInfo, CalendarParsedDateInfo} from '../../coord/calendar/Calendar'; import type GlobalModel from '../../model/Global'; import type ExtensionAPI from '../../core/ExtensionAPI'; import { LayoutOrient, OptionDataValueDate, ZRTextAlign, ZRTextVerticalAlign } from '../../util/types'; import ComponentView from '../../view/Component'; import { PathStyleProps } from 'zrender/src/graphic/Path'; import { TextStyleProps, TextProps } from 'zrender/src/graphic/Text'; import { LocaleOption, getLocaleModel } from '../../core/locale'; import type Model from '../../model/Model'; class CalendarView extends ComponentView { static type = 'calendar'; type = CalendarView.type; /** * top/left line points */ private _tlpoints: number[][]; /** * bottom/right line points */ private _blpoints: number[][]; /** * first day of month */ private _firstDayOfMonth: CalendarParsedDateInfo[]; /** * first day point of month */ private _firstDayPoints: number[][]; render(calendarModel: CalendarModel, ecModel: GlobalModel, api: ExtensionAPI) { const group = this.group; group.removeAll(); const coordSys = calendarModel.coordinateSystem; // range info const rangeData = coordSys.getRangeInfo(); const orient = coordSys.getOrient(); // locale const localeModel = ecModel.getLocaleModel(); this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function this._renderLines(calendarModel, rangeData, orient, group); this._renderYearText(calendarModel, rangeData, orient, group); this._renderMonthText(calendarModel, localeModel, orient, group); this._renderWeekText(calendarModel, localeModel, rangeData, orient, group); } // render day rect _renderDayRect(calendarModel: CalendarModel, rangeData: CalendarParsedDateRangeInfo, group: graphic.Group) { const coordSys = calendarModel.coordinateSystem; const itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle(); const sw = coordSys.getCellWidth(); const sh = coordSys.getCellHeight(); for (let i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time ) { const point = coordSys.dataToRect([i], false).tl; // every rect const rect = new graphic.Rect({ shape: { x: point[0], y: point[1], width: sw, height: sh }, cursor: 'default', style: itemRectStyleModel }); group.add(rect); } } // render separate line _renderLines( calendarModel: CalendarModel, rangeData: CalendarParsedDateRangeInfo, orient: LayoutOrient, group: graphic.Group ) { const self = this; const coordSys = calendarModel.coordinateSystem; const lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle(); const show = calendarModel.get(['splitLine', 'show']); const lineWidth = lineStyleModel.lineWidth; this._tlpoints = []; this._blpoints = []; this._firstDayOfMonth = []; this._firstDayPoints = []; let firstDay = rangeData.start; for (let i = 0; firstDay.time <= rangeData.end.time; i++) { addPoints(firstDay.formatedDate); if (i === 0) { firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m); } const date = firstDay.date; date.setMonth(date.getMonth() + 1); firstDay = coordSys.getDateInfo(date); } addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate); function addPoints(date: OptionDataValueDate) { self._firstDayOfMonth.push(coordSys.getDateInfo(date)); self._firstDayPoints.push(coordSys.dataToRect([date], false).tl); const points = self._getLinePointsOfOneWeek(calendarModel, date, orient); self._tlpoints.push(points[0]); self._blpoints.push(points[points.length - 1]); show && self._drawSplitline(points, lineStyleModel, group); } // render top/left line show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group); } // get points at both ends _getEdgesPoints(points: number[][], lineWidth: number, orient: LayoutOrient) { const rs = [points[0].slice(), points[points.length - 1].slice()]; const idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth rs[0][idx] = rs[0][idx] - lineWidth / 2; rs[1][idx] = rs[1][idx] + lineWidth / 2; return rs; } // render split line _drawSplitline(points: number[][], lineStyle: PathStyleProps, group: graphic.Group) { const poyline = new graphic.Polyline({ z2: 20, shape: { points: points }, style: lineStyle }); group.add(poyline); } // render month line of one week points _getLinePointsOfOneWeek(calendarModel: CalendarModel, date: OptionDataValueDate, orient: LayoutOrient) { const coordSys = calendarModel.coordinateSystem; const parsedDate = coordSys.getDateInfo(date); const points = []; for (let i = 0; i < 7; i++) { const tmpD = coordSys.getNextNDay(parsedDate.time, i); const point = coordSys.dataToRect([tmpD.time], false); points[2 * tmpD.day] = point.tl; points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr']; } return points; } _formatterLabel<T extends { nameMap: string }>( formatter: string | ((params: T) => string), params: T ) { if (typeof formatter === 'string' && formatter) { return formatTplSimple(formatter, params); } if (typeof formatter === 'function') { return formatter(params); } return params.nameMap; } _yearTextPositionControl( textEl: graphic.Text, point: number[], orient: LayoutOrient, position: 'left' | 'right' | 'top' | 'bottom', margin: number ): TextProps { let x = point[0]; let y = point[1]; let aligns: [ZRTextAlign, ZRTextVerticalAlign] = ['center', 'bottom']; if (position === 'bottom') { y += margin; aligns = ['center', 'top']; } else if (position === 'left') { x -= margin; } else if (position === 'right') { x += margin; aligns = ['center', 'top']; } else { // top y -= margin; } let rotate = 0; if (position === 'left' || position === 'right') { rotate = Math.PI / 2; } return { rotation: rotate, x, y, style: { align: aligns[0], verticalAlign: aligns[1] } }; } // render year _renderYearText( calendarModel: CalendarModel, rangeData: CalendarParsedDateRangeInfo, orient: LayoutOrient, group: graphic.Group ) { const yearLabel = calendarModel.getModel('yearLabel'); if (!yearLabel.get('show')) { return; } const margin = yearLabel.get('margin'); let pos = yearLabel.get('position'); if (!pos) { pos = orient !== 'horizontal' ? 'top' : 'left'; } const points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]]; const xc = (points[0][0] + points[1][0]) / 2; const yc = (points[0][1] + points[1][1]) / 2; const idx = orient === 'horizontal' ? 0 : 1; const posPoints = { top: [xc, points[idx][1]], bottom: [xc, points[1 - idx][1]], left: [points[1 - idx][0], yc], right: [points[idx][0], yc] }; let name = rangeData.start.y; if (+rangeData.end.y > +rangeData.start.y) { name = name + '-' + rangeData.end.y; } const formatter = yearLabel.get('formatter'); const params = { start: rangeData.start.y, end: rangeData.end.y, nameMap: name }; const content = this._formatterLabel(formatter, params); const yearText = new graphic.Text({ z2: 30, style: createTextStyle(yearLabel, { text: content }) }); yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin)); group.add(yearText); } _monthTextPositionControl( point: number[], isCenter: boolean, orient: LayoutOrient, position: 'start' | 'end', margin: number ): TextStyleProps { let align: ZRTextAlign = 'left'; let vAlign: ZRTextVerticalAlign = 'top'; let x = point[0]; let y = point[1]; if (orient === 'horizontal') { y = y + margin; if (isCenter) { align = 'center'; } if (position === 'start') { vAlign = 'bottom'; } } else { x = x + margin; if (isCenter) { vAlign = 'middle'; } if (position === 'start') { align = 'right'; } } return { x: x, y: y, align: align, verticalAlign: vAlign }; } // render month and year text _renderMonthText( calendarModel: CalendarModel, localeModel: Model<LocaleOption>, orient: LayoutOrient, group: graphic.Group ) { const monthLabel = calendarModel.getModel('monthLabel'); if (!monthLabel.get('show')) { return; } let nameMap = monthLabel.get('nameMap'); let margin = monthLabel.get('margin'); const pos = monthLabel.get('position'); const align = monthLabel.get('align'); const termPoints = [this._tlpoints, this._blpoints]; if (!nameMap || isString(nameMap)) { if (nameMap) { // case-sensitive localeModel = getLocaleModel(nameMap as string) || localeModel; } // PENDING // for ZH locale, original form is `一月` but current form is `1月` nameMap = localeModel.get(['time', 'monthAbbr']) || []; } const idx = pos === 'start' ? 0 : 1; const axis = orient === 'horizontal' ? 0 : 1; margin = pos === 'start' ? -margin : margin; const isCenter = (align === 'center'); for (let i = 0; i < termPoints[idx].length - 1; i++) { const tmp = termPoints[idx][i].slice(); const firstDay = this._firstDayOfMonth[i]; if (isCenter) { const firstDayPoints = this._firstDayPoints[i]; tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2; } const formatter = monthLabel.get('formatter'); const name = nameMap[+firstDay.m - 1]; const params = { yyyy: firstDay.y, yy: (firstDay.y + '').slice(2), MM: firstDay.m, M: +firstDay.m, nameMap: name }; const content = this._formatterLabel(formatter, params); const monthText = new graphic.Text({ z2: 30, style: extend( createTextStyle(monthLabel, {text: content}), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin) ) }); group.add(monthText); } } _weekTextPositionControl( point: number[], orient: LayoutOrient, position: 'start' | 'end', margin: number, cellSize: number[] ): TextStyleProps { let align: ZRTextAlign = 'center'; let vAlign: ZRTextVerticalAlign = 'middle'; let x = point[0]; let y = point[1]; const isStart = position === 'start'; if (orient === 'horizontal') { x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2; align = isStart ? 'right' : 'left'; } else { y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2; vAlign = isStart ? 'bottom' : 'top'; } return { x: x, y: y, align: align, verticalAlign: vAlign }; } // render weeks _renderWeekText( calendarModel: CalendarModel, localeModel: Model<LocaleOption>, rangeData: CalendarParsedDateRangeInfo, orient: LayoutOrient, group: graphic.Group ) { const dayLabel = calendarModel.getModel('dayLabel'); if (!dayLabel.get('show')) { return; } const coordSys = calendarModel.coordinateSystem; const pos = dayLabel.get('position'); let nameMap = dayLabel.get('nameMap'); let margin = dayLabel.get('margin'); const firstDayOfWeek = coordSys.getFirstDayOfWeek(); if (!nameMap || isString(nameMap)) { if (nameMap) { // case-sensitive localeModel = getLocaleModel(nameMap as string) || localeModel; } // Use the first letter of `dayOfWeekAbbr` if `dayOfWeekShort` doesn't exist in the locale file const dayOfWeekShort = localeModel.get(['time', 'dayOfWeekShort' as any]); nameMap = dayOfWeekShort || map( localeModel.get(['time', 'dayOfWeekAbbr']), val => val[0] ); } let start = coordSys.getNextNDay( rangeData.end.time, (7 - rangeData.lweek) ).time; const cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()]; margin = parsePercent(margin, Math.min(cellSize[1], cellSize[0])); if (pos === 'start') { start = coordSys.getNextNDay( rangeData.start.time, -(7 + rangeData.fweek) ).time; margin = -margin; } for (let i = 0; i < 7; i++) { const tmpD = coordSys.getNextNDay(start, i); const point = coordSys.dataToRect([tmpD.time], false).center; let day = i; day = Math.abs((i + firstDayOfWeek) % 7); const weekText = new graphic.Text({ z2: 30, style: extend( createTextStyle(dayLabel, {text: nameMap[day]}), this._weekTextPositionControl(point, orient, pos, margin, cellSize) ) }); group.add(weekText); } } } export default CalendarView;
the_stack
import _ from 'lodash' import axios from 'axios' import MockAdapter from 'axios-mock-adapter' import { InstanceElement, isObjectType, isInstanceElement, ReferenceExpression } from '@salto-io/adapter-api' import { buildElementsSourceFromElements } from '@salto-io/adapter-utils' import mockReplies from './mock_replies.json' import { adapter } from '../src/adapter_creator' import { usernamePasswordCredentialsType } from '../src/auth' import { configType, FETCH_CONFIG, DEFAULT_TYPES, API_DEFINITIONS_CONFIG } from '../src/config' type MockReply = { url: string params: Record<string, string> response: unknown } describe('adapter', () => { let mockAxiosAdapter: MockAdapter beforeEach(async () => { mockAxiosAdapter = new MockAdapter(axios, { delayResponse: 1, onNoMatch: 'throwException' }) mockAxiosAdapter.onGet('/account/settings').replyOnce(200, { settings: {} }); (mockReplies as MockReply[]).forEach(({ url, params, response }) => { mockAxiosAdapter.onGet(url, !_.isEmpty(params) ? { params } : undefined).replyOnce( 200, response ) }) }) afterEach(() => { mockAxiosAdapter.restore() }) describe('fetch', () => { describe('full fetch', () => { it('should generate the right elements on fetch', async () => { const { elements } = await adapter.operations({ credentials: new InstanceElement( 'config', usernamePasswordCredentialsType, { username: 'user123', password: 'token456' }, ), config: new InstanceElement( 'config', configType, { [FETCH_CONFIG]: { includeTypes: [...Object.keys(DEFAULT_TYPES)].sort(), }, } ), elementsSource: buildElementsSourceFromElements([]), }).fetch({ progressReporter: { reportProgress: () => null } }) expect(elements).toHaveLength(270) expect(elements.filter(isObjectType)).toHaveLength(154) expect(elements.filter(isInstanceElement)).toHaveLength(116) expect(elements.map(e => e.elemID.getFullName()).sort()).toEqual([ 'zendesk_support.account_setting', 'zendesk_support.account_setting.instance.unnamed_0_0', 'zendesk_support.account_setting__active_features', 'zendesk_support.account_setting__agents', 'zendesk_support.account_setting__api', 'zendesk_support.account_setting__apps', 'zendesk_support.account_setting__billing', 'zendesk_support.account_setting__branding', 'zendesk_support.account_setting__brands', 'zendesk_support.account_setting__cdn', 'zendesk_support.account_setting__cdn__hosts', 'zendesk_support.account_setting__chat', 'zendesk_support.account_setting__cross_sell', 'zendesk_support.account_setting__gooddata_advanced_analytics', 'zendesk_support.account_setting__google_apps', 'zendesk_support.account_setting__groups', 'zendesk_support.account_setting__knowledge', 'zendesk_support.account_setting__limits', 'zendesk_support.account_setting__localization', 'zendesk_support.account_setting__lotus', 'zendesk_support.account_setting__metrics', 'zendesk_support.account_setting__onboarding', 'zendesk_support.account_setting__rule', 'zendesk_support.account_setting__screencast', 'zendesk_support.account_setting__statistics', 'zendesk_support.account_setting__ticket_form', 'zendesk_support.account_setting__ticket_sharing_partners', 'zendesk_support.account_setting__tickets', 'zendesk_support.account_setting__twitter', 'zendesk_support.account_setting__user', 'zendesk_support.account_setting__voice', 'zendesk_support.account_settings', 'zendesk_support.app_installation', 'zendesk_support.app_installation.instance.Salesforce_1900000132965', 'zendesk_support.app_installation.instance.Slack_1900000132805', 'zendesk_support.app_installation__plan_information', 'zendesk_support.app_installation__settings', 'zendesk_support.app_installation__settings_objects', 'zendesk_support.app_installations', 'zendesk_support.apps_owned', 'zendesk_support.automation', 'zendesk_support.automation.instance.Close_ticket_4_days_after_status_is_set_to_solved_1500016953642@sssssssssu', 'zendesk_support.automation.instance.Close_ticket_4_days_after_status_is_set_to_solved_1500027162481@sssssssssu', 'zendesk_support.automation.instance.Pending_notification_24_hours_1500016953662@sssu', 'zendesk_support.automation.instance.Pending_notification_5_days_1500016953682@sssu', 'zendesk_support.automation__actions', 'zendesk_support.automation__conditions', 'zendesk_support.automation__conditions__all', 'zendesk_support.automations', 'zendesk_support.brand', 'zendesk_support.brand.instance.myBrand_1500000550682', 'zendesk_support.brands', 'zendesk_support.business_hours_schedule', 'zendesk_support.business_hours_schedule.instance.New_schedule_1900000004365@su', 'zendesk_support.business_hours_schedule.instance.Schedule_2_1500001035461@su', 'zendesk_support.business_hours_schedule.instance.Schedule_2_1500001036042@su', 'zendesk_support.business_hours_schedule__intervals', 'zendesk_support.business_hours_schedules', 'zendesk_support.custom_role', 'zendesk_support.custom_role.instance.Advisor_1500001601021', 'zendesk_support.custom_role.instance.Billing_admin_1500004942002@su', 'zendesk_support.custom_role.instance.Contributor_1500004941982', 'zendesk_support.custom_role.instance.Light_agent_1500004941962@su', 'zendesk_support.custom_role.instance.Staff_1500001600981', 'zendesk_support.custom_role.instance.Team_lead_1500001601001@su', 'zendesk_support.custom_role__configuration', 'zendesk_support.custom_roles', 'zendesk_support.dynamic_content_item', 'zendesk_support.dynamic_content_item.instance.Dynamic_content_item_title_543_1900000045325@ssssu', 'zendesk_support.dynamic_content_item__variants', 'zendesk_support.group', 'zendesk_support.group.instance.Support_1500002894482', 'zendesk_support.groups', 'zendesk_support.locale', 'zendesk_support.locale.instance.en_US@b', 'zendesk_support.locale.instance.es', 'zendesk_support.locale.instance.he', 'zendesk_support.locales', 'zendesk_support.macro', 'zendesk_support.macro.instance.Close_and_redirect_to_topics_1500016953922@ssssu', 'zendesk_support.macro.instance.Close_and_redirect_to_topics_1900002626825@ssssu', 'zendesk_support.macro.instance.Customer_not_responding_1500016953962@ssu', 'zendesk_support.macro.instance.Customer_not_responding__copy__with_rich_text_1500027465822@sssjksssu', 'zendesk_support.macro.instance.Downgrade_and_inform_1500016953942@ssu', 'zendesk_support.macro.instance.Take_it__1500016953862@slu', 'zendesk_support.macro.instance.macro235_1500027161281', 'zendesk_support.macro__actions', 'zendesk_support.macro__restriction', 'zendesk_support.macro_action', 'zendesk_support.macro_action__operators', 'zendesk_support.macro_action__values', 'zendesk_support.macro_action__values__list', 'zendesk_support.macro_categories', 'zendesk_support.macro_definition', 'zendesk_support.macro_definition.instance.unnamed_0_0', 'zendesk_support.macro_definition__actions', 'zendesk_support.macro_definition__actions__values', 'zendesk_support.macros', 'zendesk_support.macros_actions', 'zendesk_support.macros_actions.instance.unnamed_0', 'zendesk_support.macros_definitions', 'zendesk_support.monitored_twitter_handles', 'zendesk_support.oauth_client', 'zendesk_support.oauth_client.instance.c123_1111', 'zendesk_support.oauth_client.instance.c124_1112', 'zendesk_support.oauth_clients', 'zendesk_support.oauth_global_clients', 'zendesk_support.organization', 'zendesk_support.organization.instance.myBrand_1500421645662', 'zendesk_support.organization.instance.test_org_123_1900025376085@ssu', 'zendesk_support.organization.instance.test_org_124_1500508294122@ssu', 'zendesk_support.organization__organization_fields', 'zendesk_support.organization_field', 'zendesk_support.organization_field.instance.org_field301', 'zendesk_support.organization_field.instance.org_field302', 'zendesk_support.organization_field.instance.org_field305', 'zendesk_support.organization_field.instance.org_field306', 'zendesk_support.organization_field.instance.org_field307', 'zendesk_support.organization_field.instance.org_field_n403', 'zendesk_support.organization_field.instance.org_field_n404', 'zendesk_support.organization_fields', 'zendesk_support.organizations', 'zendesk_support.recipient_address', 'zendesk_support.recipient_address.instance.myBrand_1500000743022', 'zendesk_support.recipient_addresses', 'zendesk_support.resource_collection', 'zendesk_support.resource_collection.instance.unnamed_0_0', 'zendesk_support.resource_collection__resources', 'zendesk_support.resource_collections', 'zendesk_support.routing_attribute', 'zendesk_support.routing_attribute.instance.Language_468ffec1_f80c_11eb_8231_51714e7ee9ec@ubbbb', 'zendesk_support.routing_attribute.instance.Location_76738421_f80c_11eb_b3db_1ded4e71c25a@ubbbb', 'zendesk_support.routing_attribute_definition', 'zendesk_support.routing_attribute_definition.instance.unnamed_0_0', 'zendesk_support.routing_attribute_definition__conditions_all', 'zendesk_support.routing_attribute_definition__conditions_all__operators', 'zendesk_support.routing_attribute_definition__conditions_all__values', 'zendesk_support.routing_attribute_definition__conditions_any', 'zendesk_support.routing_attribute_definition__conditions_any__operators', 'zendesk_support.routing_attribute_definition__conditions_any__values', 'zendesk_support.routing_attribute_definitions', 'zendesk_support.routing_attributes', 'zendesk_support.sharing_agreements', 'zendesk_support.sla_policies', 'zendesk_support.sla_policies_definitions', 'zendesk_support.sla_policy', 'zendesk_support.sla_policy.instance.SLA_501_1900000007885@su', 'zendesk_support.sla_policy.instance.SLA_502_1500001074121@su', 'zendesk_support.sla_policy__filter', 'zendesk_support.sla_policy__filter__all', 'zendesk_support.sla_policy__policy_metrics', 'zendesk_support.sla_policy_definition', 'zendesk_support.sla_policy_definition.instance.unnamed_0_0', 'zendesk_support.sla_policy_definition__all', 'zendesk_support.sla_policy_definition__all__operators', 'zendesk_support.sla_policy_definition__all__values', 'zendesk_support.sla_policy_definition__all__values__label', 'zendesk_support.sla_policy_definition__all__values__labels', 'zendesk_support.sla_policy_definition__all__values__list', 'zendesk_support.sla_policy_definition__any', 'zendesk_support.sla_policy_definition__any__operators', 'zendesk_support.sla_policy_definition__any__values', 'zendesk_support.sla_policy_definition__any__values__label', 'zendesk_support.sla_policy_definition__any__values__labels', 'zendesk_support.sla_policy_definition__any__values__list', 'zendesk_support.target', 'zendesk_support.target.instance.Slack_integration_Endpoint_url_target_v2@ssuuu', 'zendesk_support.targets', 'zendesk_support.ticket_field', 'zendesk_support.ticket_field.instance.assignee_Assignee_1500004937842', 'zendesk_support.ticket_field.instance.description_Description_1500004937742', 'zendesk_support.ticket_field.instance.group_Group_1500004937822', 'zendesk_support.ticket_field.instance.multiselect_agent_dropdown_643_for_agent_1500009152882@ussssu', 'zendesk_support.ticket_field.instance.partialcreditcard_credit_card_1_1500009152902@ussu', 'zendesk_support.ticket_field.instance.priority_Priority_1500004937802', 'zendesk_support.ticket_field.instance.regexp_zip_code_with_validation_1500009152922@usssu', 'zendesk_support.ticket_field.instance.status_Status_1500004937762', 'zendesk_support.ticket_field.instance.subject_Subject_1500004937722', 'zendesk_support.ticket_field.instance.text_agent_field_431_1900000813305@ussu', 'zendesk_support.ticket_field.instance.tickettype_Type_1500004937782', 'zendesk_support.ticket_field__custom_field_options', 'zendesk_support.ticket_field__custom_field_options', 'zendesk_support.ticket_field__custom_field_options.instance.multiselect_agent_dropdown_643_for_agent_1500009152882_ussssu__v1_1500015072702@uuuuuumuuu', 'zendesk_support.ticket_field__custom_field_options.instance.multiselect_agent_dropdown_643_for_agent_1500009152882_ussssu__v2_1500015072722@uuuuuumuuu', 'zendesk_support.ticket_field__system_field_options', 'zendesk_support.ticket_fields', 'zendesk_support.ticket_form', 'zendesk_support.ticket_form.instance.Default_Ticket_Form_1500000859362@ssu', 'zendesk_support.ticket_form.instance.Form_11_1500002488481@su', 'zendesk_support.ticket_form.instance.Form_11_1900000172165@su', 'zendesk_support.ticket_form.instance.Form_12_1500002488501@su', 'zendesk_support.ticket_form.instance.Form_6436_1500002488461@su', 'zendesk_support.ticket_forms', 'zendesk_support.trigger', 'zendesk_support.trigger.instance.Auto_assign_to_first_email_responding_agent_1500016953622@bsssssu', 'zendesk_support.trigger.instance.Notify_all_agents_of_received_request_1500016953602@sssssu', 'zendesk_support.trigger.instance.Notify_assignee_of_assignment_1500016953542@sssu', 'zendesk_support.trigger.instance.Notify_assignee_of_comment_update_1500016953522@ssssu', 'zendesk_support.trigger.instance.Notify_assignee_of_reopened_ticket_1500016953562@ssssu', 'zendesk_support.trigger.instance.Notify_group_of_assignment_1500016953582@sssu', 'zendesk_support.trigger.instance.Notify_requester_and_CCs_of_comment_update_1500016953502@ssssssu', 'zendesk_support.trigger.instance.Notify_requester_and_CCs_of_received_request_1500016953462@ssssssu', 'zendesk_support.trigger.instance.Notify_requester_of_new_proactive_ticket_1500016953482@sssssu', 'zendesk_support.trigger.instance.Slack_Ticket_Trigger_1900002626665@ssu', 'zendesk_support.trigger__actions', 'zendesk_support.trigger__conditions', 'zendesk_support.trigger__conditions__all', 'zendesk_support.trigger__conditions__any', 'zendesk_support.trigger_categories', 'zendesk_support.trigger_categories__links', 'zendesk_support.trigger_categories__meta', 'zendesk_support.trigger_category', 'zendesk_support.trigger_category.instance.Custom_Events_1500001608041@su', 'zendesk_support.trigger_category.instance.Custom_Events_1500001608061@su', 'zendesk_support.trigger_category.instance.Notifications_1500000362362', 'zendesk_support.triggers', 'zendesk_support.user_field', 'zendesk_support.user_field.instance.another_text_3425', 'zendesk_support.user_field.instance.date6436', 'zendesk_support.user_field.instance.decimal_765_field', 'zendesk_support.user_field.instance.description_123', 'zendesk_support.user_field.instance.dropdown_25', 'zendesk_support.user_field.instance.f201', 'zendesk_support.user_field.instance.f202', 'zendesk_support.user_field.instance.f203', 'zendesk_support.user_field.instance.f204', 'zendesk_support.user_field.instance.f205', 'zendesk_support.user_field.instance.f206', 'zendesk_support.user_field.instance.modified_multi75_key', 'zendesk_support.user_field.instance.numeric65', 'zendesk_support.user_field.instance.regex_6546', 'zendesk_support.user_field.instance.this_is_a_checkbox', 'zendesk_support.user_field__custom_field_options', 'zendesk_support.user_field__custom_field_options', 'zendesk_support.user_field__custom_field_options.instance.dropdown_25__Choice1_1500001753322', 'zendesk_support.user_field__custom_field_options.instance.dropdown_25__another_choice_1500001753342@uuusu', 'zendesk_support.user_field__custom_field_options.instance.dropdown_25__bla_1500001753362', 'zendesk_support.user_fields', 'zendesk_support.view', 'zendesk_support.view.instance.All_unsolved_tickets_1500016953782@ssu', 'zendesk_support.view.instance.Copy_of_All_unsolved_tickets_1500027465762@ssssu', 'zendesk_support.view.instance.Current_tasks_1500016953882@su', 'zendesk_support.view.instance.Custom_view_123_1500027465722@ssu', 'zendesk_support.view.instance.Custom_view_123_1500027465802@ssu', 'zendesk_support.view.instance.New_tickets_in_your_groups_1500016953742@ssssu', 'zendesk_support.view.instance.Overdue_tasks_1500016953902@su', 'zendesk_support.view.instance.Pending_tickets_1500016953842@su', 'zendesk_support.view.instance.Recently_solved_tickets_1500016953762@ssu', 'zendesk_support.view.instance.Recently_updated_tickets_1500016953822@ssu', 'zendesk_support.view.instance.Unassigned_tickets_1500016953802@su', 'zendesk_support.view.instance.Unassigned_tickets_1500027465742@su', 'zendesk_support.view.instance.Unsolved_tickets_in_your_groups_1500016953722@ssssu', 'zendesk_support.view.instance.Your_unsolved_tickets_1500016953702@ssu', 'zendesk_support.view__conditions', 'zendesk_support.view__conditions__all', 'zendesk_support.view__conditions__any', 'zendesk_support.view__execution', 'zendesk_support.view__execution__columns', 'zendesk_support.view__execution__fields', 'zendesk_support.view__execution__group', 'zendesk_support.view__execution__sort', 'zendesk_support.view__restriction', 'zendesk_support.views', 'zendesk_support.workspace', 'zendesk_support.workspace.instance.New_Workspace_123_1500001200962@ssu', 'zendesk_support.workspace__conditions', 'zendesk_support.workspace__conditions__all', 'zendesk_support.workspace__conditions__any', 'zendesk_support.workspace__selected_macros', 'zendesk_support.workspaces', ]) const recipientAddress = elements.filter(isInstanceElement).find(e => e.elemID.getFullName().startsWith('zendesk_support.recipient_address.instance.myBrand')) expect(recipientAddress).toBeDefined() expect(recipientAddress?.value).toEqual({ id: 1500000743022, default: true, name: 'myBrand', email: 'support@myBrand.zendesk.com', // eslint-disable-next-line camelcase brand_id: expect.any(ReferenceExpression), }) expect(recipientAddress?.value.brand_id.elemID.getFullName()).toEqual('zendesk_support.brand.instance.myBrand_1500000550682') }) }) describe('type overrides', () => { it('should fetch only the relevant types', async () => { const { elements } = await adapter.operations({ credentials: new InstanceElement( 'config', usernamePasswordCredentialsType, { username: 'user123', password: 'pwd456', subdomain: 'abc' }, ), config: new InstanceElement( 'config', configType, { [FETCH_CONFIG]: { includeTypes: ['groups'], }, [API_DEFINITIONS_CONFIG]: { types: { group: { transformation: { sourceTypeName: 'groups__groups', }, }, groups: { request: { url: '/groups', }, transformation: { dataField: 'groups', }, }, }, }, }, ), elementsSource: buildElementsSourceFromElements([]), }).fetch({ progressReporter: { reportProgress: () => null } }) expect(elements).toHaveLength(3) expect(elements.filter(isObjectType)).toHaveLength(2) expect(elements.filter(isInstanceElement)).toHaveLength(1) expect(elements.map(e => e.elemID.getFullName()).sort()).toEqual([ 'zendesk_support.group', 'zendesk_support.group.instance.Support_1500002894482', 'zendesk_support.groups', ]) }) }) }) describe('deploy', () => { it('should throw not implemented', async () => { const operations = adapter.operations({ credentials: new InstanceElement( 'config', usernamePasswordCredentialsType, { username: 'user123', password: 'pwd456', subdomain: 'abc' }, ), config: new InstanceElement( 'config', configType, { [FETCH_CONFIG]: { includeTypes: [...Object.keys(DEFAULT_TYPES)].sort(), }, } ), elementsSource: buildElementsSourceFromElements([]), }) await expect(operations.deploy({ changeGroup: { groupID: '', changes: [] } })).rejects.toThrow(new Error('Not implemented.')) }) }) })
the_stack
import { auxiliaries } from 'webgl-operate'; import { Camera, Canvas, Context, DefaultFramebuffer, FontFace, Invalidate, Label, LabelRenderPass, Position2DLabel, Renderer, Text, Wizard, } from 'webgl-operate'; import { Example } from './example'; /* spellchecker: enable */ // tslint:disable:max-classes-per-file class LabelElideRenderer extends Renderer { protected _extensions = false; protected _labelPass: LabelRenderPass; protected _labelSize: Position2DLabel; protected _labelLeft: Position2DLabel; protected _labelMiddle: Position2DLabel; protected _labelRight: Position2DLabel; protected _labelCustom: Position2DLabel; protected _camera: Camera; protected _defaultFBO: DefaultFramebuffer; protected _fontFace: FontFace | undefined; protected _interval: number | undefined; /** * Initializes and sets up rendering passes, navigation, loads a font face and links shaders with program. * @param context - valid context to create the object for. * @param identifier - meaningful name for identification of this instance. * @param mouseEventProvider - required for mouse interaction * @returns - whether initialization was successful */ protected onInitialize(context: Context, callback: Invalidate, /* eventProvider: EventProvider */): boolean { /* Create framebuffers, textures, and render buffers. */ this._defaultFBO = new DefaultFramebuffer(this._context, 'DefaultFBO'); this._defaultFBO.initialize(); this._defaultFBO.bind(); /* Create and configure test navigation. */ this._camera = new Camera(); /* Create and configure label pass. */ this._labelPass = new LabelRenderPass(context); this._labelPass.initialize(); this._labelPass.camera = this._camera; this._labelPass.target = this._defaultFBO; this._labelPass.depthMask = true; FontFace.fromFile('./data/opensans2048p160d16.fnt', context) .then((fontFace) => { for (const label of this._labelPass.labels) { label.fontFace = fontFace; } this._fontFace = fontFace; this.updateLabels(); this.finishLoading(); this.invalidate(); }) .catch((reason) => auxiliaries.log(auxiliaries.LogLevel.Error, reason)); this.setupScene(); return true; } /** * Uninitializes Buffers, Textures, and Program. */ protected onUninitialize(): void { super.uninitialize(); this._defaultFBO.uninitialize(); this._labelPass.uninitialize(); if (this._interval !== undefined) { clearTimeout(this._interval); this._interval = undefined; } } protected onDiscarded(): void { this._altered.alter('canvasSize'); this._altered.alter('clearColor'); if (this._interval !== undefined) { clearTimeout(this._interval); this._interval = undefined; } } /** * This is invoked in order to check if rendering of a frame is required by means of implementation specific * evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation, * frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have * changed or the renderer was invalidated @see{@link invalidate}. * @returns whether to redraw */ protected onUpdate(): boolean { for (const label of this._labelPass.labels) { if (label.altered || label.color.altered) { return true; } } return this._altered.any || this._camera.altered; } /** * This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and * camera-updates. */ protected onPrepare(): void { if (this._altered.canvasSize) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; this._camera.viewport = this._canvasSize; this.updateLabels(); } if (this._altered.clearColor) { this._defaultFBO.clearColor(this._clearColor); } this._labelPass.update(); this._altered.reset(); this._camera.altered = false; } /** * After (1) update and (2) preparation are invoked, a frame is invoked. Renders both 2D and 3D labels. * @param frameNumber - for intermediate frames in accumulation rendering */ protected onFrame(/*frameNumber: number*/): void { const gl = this._context.gl; gl.viewport(0, 0, this._camera.viewport[0], this._camera.viewport[1]); this._defaultFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, false, false); this._labelPass.frame(); } /** * Sets up an example scene with 2D and 3D labels and sets the corresponding data on LabelGeometries. The * FontFace is set on each label by the LabelRenderPass. */ protected setupScene(): void { /** Wrapped labels, showcasing Ellipsis and NewLine */ const werther = 'A wonderful serenity has taken possession of my entire soul, like these sweet mornings \ of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was \ created for the bliss of souls like mine. I am so happy, my dear friend, so absorbed in the exquisite sense of mere \ tranquil existence, that I neglect my talents. I should be incapable of drawing a single stroke at the present \ moment; and yet I feel that I never was a greater artist than now. When, while the lovely valley teems with vapour \ around me, and the meridian sun strikes the upper surface of the impenetrable foliage of my trees, and but a few \ stray gleams steal into the inner sanctuary, I throw myself down among the tall grass by the trickling stream; and, \ as I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world \ among the stalks, and grow familiar with the countless indescribable forms of the insects and flies, then I feel the \ presence of the Almighty, who formed us in his own image, and the breath of that universal love which bears and \ sustains us, as it floats around us in an eternity of bliss; and then, my friend, when darkness overspreads my eyes, \ and heaven and earth seem to dwell in my soul and absorb its power, like the form of a beloved mistress, then I often \ think with longing, Oh, would I could describe these conceptions, could impress upon paper all that is living so full \ and warm within me, that it might be the mirror of my soul, as my soul is the mirror of the infinite God!'; this._labelSize = new Position2DLabel(new Text(), Label.Type.Dynamic); this._labelSize.fontSize = 20; this._labelSize.fontSizeUnit = Label.Unit.Pixel; this._labelSize.alignment = Label.Alignment.Left; this._labelSize.lineAnchor = Label.LineAnchor.Baseline; this._labelSize.color.fromHex('#27aae1'); this._labelLeft = new Position2DLabel( new Text(`Label.Elide.Right | ${werther}`), Label.Type.Dynamic); this._labelLeft.fontSizeUnit = Label.Unit.Pixel; this._labelLeft.elide = Label.Elide.Right; this._labelLeft.alignment = Label.Alignment.Left; this._labelLeft.lineAnchor = Label.LineAnchor.Baseline; this._labelLeft.color.fromHex('#fff'); this._labelRight = new Position2DLabel( new Text(`${werther} | Label.Elide.Left`), Label.Type.Dynamic); this._labelRight.fontSizeUnit = Label.Unit.Pixel; this._labelRight.elide = Label.Elide.Left; this._labelRight.alignment = Label.Alignment.Right; this._labelRight.lineAnchor = Label.LineAnchor.Baseline; this._labelRight.color.fromHex('#fff'); this._labelMiddle = new Position2DLabel( new Text(`Label.Elide.Middle | ${werther} | Label.Elide.Middle`), Label.Type.Dynamic); this._labelMiddle.fontSizeUnit = Label.Unit.Pixel; this._labelMiddle.elide = Label.Elide.Middle; this._labelMiddle.alignment = Label.Alignment.Center; this._labelMiddle.lineAnchor = Label.LineAnchor.Baseline; this._labelMiddle.color.fromHex('#fff'); this._labelCustom = new Position2DLabel( new Text(`Custom Ellipsis | ${werther}`), Label.Type.Dynamic); this._labelCustom.fontSizeUnit = Label.Unit.Pixel; this._labelCustom.elide = Label.Elide.Right; this._labelCustom.alignment = Label.Alignment.Left; this._labelCustom.lineAnchor = Label.LineAnchor.Baseline; this._labelCustom.color.fromHex('#fff'); this._labelPass.aaStepScale = 1.0; this._labelPass.labels = [this._labelSize , this._labelLeft, this._labelRight, this._labelMiddle, this._labelCustom]; this._interval = window.setInterval(() => { if (!this.initialized) { return; } const size = 16 + Math.sin(performance.now() * 0.001) * 4.0; this._labelSize.text.text = `// label.fontSize = ${size.toFixed(2)} (${this._labelSize.fontSizeUnit})`; this._labelLeft.fontSize = size; this._labelRight.fontSize = size; this._labelMiddle.fontSize = size; this._labelCustom.ellipsis = '.'.repeat(Math.floor(Math.sin(performance.now() * 0.001) * 4.0) + 5); this.invalidate(); }, 1000.0 / 60.0); } protected updateLabels(): void { if (!this._labelLeft.valid) { return; } const top = +this._canvasSize[1] * 0.5; const step = 32.0 * Label.devicePixelRatio(); const width = this._canvasSize[0] - 32.0 /* margin */ * Label.devicePixelRatio(); this._labelSize.position = [-width * 0.5, top - 1.0 * step]; this._labelLeft.lineWidth = width; this._labelLeft.position = [-width * 0.5, top - 2.5 * step]; this._labelRight.lineWidth = width; this._labelRight.position = [+width * 0.5, top - 3.5 * step]; this._labelMiddle.lineWidth = width; this._labelMiddle.position = [0.0, top - 4.5 * step]; this._labelCustom.lineWidth = width * 0.5; this._labelCustom.position = [-width * 0.5, top - 6.0 * step]; } } export class LabelElideExample extends Example { private _canvas: Canvas; private _renderer: LabelElideRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { this._canvas = new Canvas(element, { antialias: false }); this._canvas.controller.multiFrameNumber = 1; this._canvas.framePrecision = Wizard.Precision.byte; this._canvas.frameScale = [1.0, 1.0]; this._renderer = new LabelElideRenderer(); this._canvas.renderer = this._renderer; return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): LabelElideRenderer { return this._renderer; } }
the_stack
import { EventLog } from "./event-log" class DisplayDetails { // Class for managing detail text we want to display when hovering. private createTime: string; private beginTime: string = "--"; private completeTime: string = "--"; private buildTime: string = "--"; private totalTime: string = "--"; private machineId: string = "--"; private _activated = false; constructor(private owner: any) { this.createTime = owner.startTime.toLocaleString(); } update(evt: any): void { this.machineId = evt['host-id']; if (!this._activated && this.owner.active) { // Record our start time this._activated = true; this.beginTime = evt['date'].toLocaleString(); } if (this.owner.closeTime) { // Record our finish time this.completeTime = this.owner.closeTime.toLocaleString(); this.buildTime = this.formatTimeDiff(this.owner.closeTime - this.owner.activeTime); this.totalTime = this.formatTimeDiff(this.owner.closeTime - this.owner.startTime); } } formatTimeDiff(value): string { let dt = new Date(value); let result = dt.getUTCHours() + "h " + dt.getUTCMinutes() + "m " + dt.getUTCSeconds() + "s"; return result; } } export class ProgressView { progressRoot = null; private _progressPathLookup = {}; private _progressHostIdLookup = {}; private _currentTime = null; private _progressStartTime = null; private _updateMarker = 0; private _maxDepth = 0; private _columnAdvance = 40; constructor(private _eventLog: EventLog) { } clearProgress(): void { this.progressRoot = null; this._progressPathLookup = {}; this._progressHostIdLookup = {}; this._currentTime = null; this._progressStartTime = null; this._updateMarker = 0; this._maxDepth = 0; } updateProgress(currentTime: Date): void { this._currentTime = currentTime; let updateNodes = []; this._updateMarker++; let events = this._eventLog.events; for (var eventIdx = this._eventLog.frameStartIndex; eventIdx < events.length; eventIdx++) { var evt = events[eventIdx]; var pathStr = evt['path']; var timestamp = evt['date']; var existingNode = undefined; if (pathStr === undefined || pathStr === null) { continue; } if (this._progressStartTime == null) { this._progressStartTime = new Date(timestamp.getTime() - 48000); // Start 48 seconds earlier to add a 48 pixel buffer to get everything onscreen correctly } var path = JSON.parse(pathStr); var searchPath = path.slice(0); // deep copy // Find the deepest node in the hierarchy with a path that prefixes the node we're looking for while (true) { existingNode = this._progressPathLookup[searchPath]; if (existingNode !== undefined) { break; } if (searchPath.length) { searchPath.pop(); } else { var progressParent = { 'children': [], 'path': [], 'childLeadPos': 0, 'childTailPos': 0, 'closeTimePos': 0, 'childrenClosed': false }; this.progressRoot = this.createNode(progressParent, [], evt, timestamp); this.progressRoot.parent = null; existingNode = this.progressRoot; break; } } // Now extend the node we found with new children up to the sought-after path while (searchPath.length < path.length) { searchPath.push(path[searchPath.length]); var newChild = this.createNode(existingNode, searchPath, evt, timestamp); if (existingNode.children.length) { newChild.prevSibling = existingNode.children[existingNode.children.length - 1]; newChild.prevSibling.nextSibling = newChild; } else { existingNode.startTime = timestamp; existingNode.startTimePos = this.timeToPosition(timestamp); } this._maxDepth = Math.max(this._maxDepth, newChild.path.length); existingNode.children.push(newChild); existingNode.childrenClosed = false; existingNode = newChild; } // Record information about the event in the node we found/created this._progressHostIdLookup[evt['host-id']] = existingNode; var description = evt['desc']; var status = evt['status'] existingNode['nextLabel'] = description ? (status ? (description + ": " + status) : description) : ""; if (!existingNode.active && evt['phase']) { // Record the moment this node became "active", i.e. done with division phase existingNode.active = true; existingNode.activeTime = timestamp; } if (!evt['activity']) { // An activity has ended, so record whatever closing information is applicable var desc = existingNode.lastEvent['desc']; var phase = existingNode.lastEvent['phase']; if (phase != null) { if (phase == 0) { // Once the division phase ends is where the node's start time begins existingNode['startTime'] = timestamp; existingNode['startTimePos'] = this.timeToPosition(timestamp); } else { // Any other phase ending is where the node's end time is recorded existingNode['closeTime'] = timestamp; existingNode['closeTimePos'] = this.timeToPosition(timestamp); if (!path.length) { this.progressRoot.fixedParent.childTailPos = existingNode.closeTimePos; } } } } existingNode.lastEvent = evt; existingNode.details.update(evt); // Make sure all parent nodes to this node get their geometries updated while (existingNode) { if (existingNode.updateMarker != this._updateMarker) { existingNode.updateMarker = this._updateMarker; updateNodes.push(existingNode); } existingNode = existingNode.parent; } } updateNodes.sort(function(a, b) { return b.path.length - a.path.length; }); let now = this._currentTime; let nowPos = this.timeToPosition(now); let self = this; setTimeout(function() { for (let idx = 0; idx < updateNodes.length; idx++) { self.updateProgressNode(updateNodes[idx], nowPos); } self.progressFrameUpdate(nowPos); }, 0); } private updateProgressNode(node: any, nowPos: number): void { // Update the geomoetry for this node let indent = node.path.length * this._columnAdvance; node.label = node.nextLabel; node.initialized = true; node.childrenClosed = node.children.reduce(function(incoming, current) { return incoming && current.closeTimePos; }, true); node.childLeadPos = node.children.reduce(function(best, current) { return Math.min(best, current.startTimePos); }, node.startTimePos) + indent; node.childTailPos = node.children.reduce(function(best, current) { return Math.max(best, current.closeTimePos); }, 0) + indent + this._columnAdvance * (this._maxDepth - node.path.length); if (!node.childTailPos) { node.childTailPos = nowPos + indent; } node.childSpace = node.children.length ? (node.childTailPos - node.childLeadPos) : 0; node.leadEndPos = node.startTimePos + indent; node.mainPos = node.startTimePos + node.childSpace + indent + (node.children.length ? this._columnAdvance * (this._maxDepth - node.path.length - 1) : 0); if (node.closeTimePos) { // This node is closed, so position its tail as well as the tail for its children node.mainEndPos = node.closeTimePos + indent + this._columnAdvance * 2 * (this._maxDepth - node.path.length); if (node.childrenClosed) { node.childTailPos = node.mainPos; } } else { // This node is open, so its tail is zero-length node.mainEndPos = node.mainPos; } node.childrenHeight = node.children.reduce(function(sum, current) { return sum + current.containerHeight; }, 0); node.shaftHeight = node.children.length ? (node.childrenHeight - node.children[node.children.length - 1].containerHeight + 24) : 0; node.containerHeight = node.childrenHeight + 24; } private progressFrameUpdate(nowPos: number): void { if (!this.progressRoot) { return; } for (var pathKey in this._progressPathLookup) { var node = this._progressPathLookup[pathKey]; if (node.fixedParent.childrenClosed) { continue; } var indent = node.path.length * this._columnAdvance; if (!node.closeTimePos) { if (node.childrenClosed) { node.mainEndPos = nowPos + indent; if (node.children.length) { node.mainEndPos += this._columnAdvance * 2 * (this._maxDepth - node.path.length); } node.childTailPos = node.mainPos; } else { node.childTailPos = nowPos + indent + this._columnAdvance * (this._maxDepth - node.path.length); } } } if (!this.progressRoot.closeTimePos) { this.progressRoot.fixedParent.childTailPos = nowPos + this._columnAdvance * this._maxDepth; } } private timeToPosition(dt: any): number { return (dt - this._progressStartTime) / 1000; } private createNode(parent: any, path: Array<any>, evt: any, timestamp: Date): any { var result = { 'index': parent.children.length, 'updateMarker': 0, 'path': path.slice(0), 'pathStr': path.toString(), 'parent': parent, 'fixedParent': parent, 'children': [], 'childrenClosed': true, 'label': "", 'nextLabel': "", 'containerHeight': 0, 'childrenHeight': 0, 'startTime': timestamp, 'startTimePos': this.timeToPosition(timestamp), 'activeTime': null, 'closeTimePos': 0, 'closeTime': null, 'nextSibling': null, 'prevSibling': null, 'lastEvent': evt, 'active': false, 'initialized': false, 'entered': false, 'details': null, 'mainPos': 0, 'childSpace': 0, 'childLeadPos': 0, 'childTailPos': 0, 'leadEndPos': 0 }; result.leadEndPos = result.startTimePos + path.length * this._columnAdvance; result.details = new DisplayDetails(result); this._progressPathLookup[path.toString()] = result; return result; } }
the_stack
import { accountBoxFill, accountBoxLine, accountCircleFill, accountCircleLine, accountPinBoxFill, accountPinBoxLine, accountPinCircleFill, accountPinCircleLine, addBoxFill, addBoxLine, addCircleFill, addCircleLine, adminFill, adminLine, advertisementFill, advertisementLine, airplayFill, airplayLine, alarmFill, alarmLine, alarmWarningFill, alarmWarningLine, albumFill, albumLine, alertFill, aliensFill, aliensLine, alipayFill, alipayLine, amazonFill, amazonLine, anchorFill, anchorLine, ancientGateFill, ancientGateLine, ancientPavilionFill, ancientPavilionLine, androidFill, androidLine, angularjsFill, angularjsLine, anticlockwise2Fill, anticlockwise2Line, anticlockwiseFill, anticlockwiseLine, appleFill, appleLine, apps2Fill, apps2Line, appsFill, appStoreFill, appStoreLine, archiveDrawerFill, archiveDrawerLine, archiveFill, archiveLine, arrowDownCircleFill, arrowDownCircleLine, arrowDownFill, arrowDownLine, arrowDownSLine, arrowDropDownFill, arrowDropDownLine, arrowDropLeftFill, arrowDropLeftLine, arrowDropRightFill, arrowDropRightLine, arrowDropUpFill, arrowDropUpLine, arrowGoBackLine, arrowGoForwardLine, arrowLeftCircleFill, arrowLeftCircleLine, arrowLeftDownFill, arrowLeftDownLine, arrowLeftFill, arrowLeftLine, arrowLeftRightFill, arrowLeftRightLine, arrowLeftSLine, arrowLeftUpFill, arrowLeftUpLine, arrowRightCircleFill, arrowRightCircleLine, arrowRightDownFill, arrowRightDownLine, arrowRightFill, arrowRightLine, arrowRightSLine, arrowRightUpFill, arrowRightUpLine, arrowUpCircleFill, arrowUpCircleLine, arrowUpDownFill, arrowUpDownLine, arrowUpFill, arrowUpLine, arrowUpSLine, artboard2Fill, artboard2Line, artboardFill, artboardLine, articleFill, articleLine, aspectRatioFill, aspectRatioLine, atFill, atLine, attachmentFill, attachmentLine, auctionFill, auctionLine, awardFill, awardLine, baiduFill, baiduLine, ballPenFill, ballPenLine, bankCard2Fill, bankCard2Line, bankCardFill, bankCardLine, bankFill, bankLine, barChart2Fill, barChart2Line, barChartBoxFill, barChartBoxLine, barChartFill, barChartGroupedFill, barChartGroupedLine, barChartHorizontalFill, barChartHorizontalLine, barChartLine, barcodeBoxFill, barcodeBoxLine, barcodeFill, barcodeLine, barricadeFill, barricadeLine, baseStationFill, baseStationLine, basketballFill, basketballLine, battery2ChargeFill, battery2ChargeLine, battery2Fill, battery2Line, batteryChargeFill, batteryChargeLine, batteryFill, batteryLine, batteryLowFill, batteryLowLine, batterySaverFill, batterySaverLine, batteryShareFill, batteryShareLine, bearSmileFill, bearSmileLine, behanceFill, behanceLine, bellFill, bellLine, bikeFill, bikeLine, bilibiliFill, bilibiliLine, billFill, billiardsFill, billiardsLine, billLine, bitCoinFill, bitCoinLine, blazeFill, blazeLine, bluetoothConnectFill, bluetoothConnectLine, bluetoothFill, bluetoothLine, blurOffFill, blurOffLine, bodyScanFill, bodyScanLine, book2Fill, book2Line, book3Fill, book3Line, bookFill, bookletFill, bookletLine, bookLine, bookmark2Fill, bookmark2Line, bookmark3Fill, bookmark3Line, bookMarkFill, bookmarkFill, bookMarkLine, bookmarkLine, bookOpenFill, bookOpenLine, bookReadFill, bookReadLine, boxingFill, boxingLine, bracesFill, bracketsFill, bracketsLine, briefcase2Fill, briefcase2Line, briefcase3Fill, briefcase3Line, briefcase4Fill, briefcase4Line, briefcase5Fill, briefcase5Line, briefcaseFill, briefcaseLine, broadcastFill, broadcastLine, brush2Fill, brush2Line, brush3Fill, brush3Line, brush4Fill, brush4Line, brushFill, brushLine, bubbleChartFill, bubbleChartLine, bug2Fill, bug2Line, bugFill, bugLine, building2Fill, building2Line, building3Fill, building3Line, building4Fill, building4Line, buildingFill, buildingLine, bus2Fill, bus2Line, busFill, busLine, busWifiFill, busWifiLine, cactusFill, cactusLine, cake2Fill, cake2Line, cake3Fill, cake3Line, cakeFill, cakeLine, calculatorFill, calculatorLine, calendar2Fill, calendar2Line, calendarCheckFill, calendarCheckLine, calendarEventFill, calendarEventLine, calendarFill, calendarLine, calendarTodoFill, calendarTodoLine, camera2Fill, camera2Line, camera3Fill, camera3Line, cameraFill, cameraLensFill, cameraLensLine, cameraLine, cameraOffFill, cameraOffLine, cameraSwitchFill, cameraSwitchLine, capsuleFill, capsuleLine, caravanFill, caravanLine, carFill, carLine, carWashingFill, carWashingLine, castFill, castLine, cellphoneFill, cellphoneLine, celsiusFill, celsiusLine, centosFill, centosLine, characterRecognitionFill, characterRecognitionLine, chargingPile2Fill, chargingPile2Line, chargingPileFill, chargingPileLine, chat1Fill, chat1Line, chat2Fill, chat2Line, chat3Fill, chat3Line, chat4Fill, chat4Line, chatCheckFill, chatCheckLine, chatDeleteFill, chatDeleteLine, chatDownloadFill, chatDownloadLine, chatFollowUpFill, chatFollowUpLine, chatForwardFill, chatForwardLine, chatHeartFill, chatHeartLine, chatHistoryFill, chatHistoryLine, chatNewFill, chatOffFill, chatOffLine, chatPollFill, chatPollLine, chatPrivateFill, chatPrivateLine, chatQuoteFill, chatQuoteLine, chatSettingsFill, chatSettingsLine, chatSmile2Fill, chatSmile2Line, chatSmile3Fill, chatSmile3Line, chatSmileFill, chatSmileLine, chatUploadFill, chatUploadLine, chatVoiceFill, chatVoiceLine, checkboxBlankCircleFill, checkboxBlankCircleLine, checkboxBlankFill, checkboxBlankLine, checkboxCircleFill, checkboxFill, checkboxIndeterminateFill, checkboxIndeterminateLine, checkboxLine, checkboxMultipleBlankFill, checkboxMultipleBlankLine, checkboxMultipleFill, checkboxMultipleLine, checkDoubleFill, checkDoubleLine, checkFill, checkLine, chinaRailwayFill, chinaRailwayLine, chromeFill, chromeLine, clapperboardFill, clapperboardLine, clockwise2Fill, clockwise2Line, clockwiseFill, clockwiseLine, closeCircleFill, closedCaptioningFill, closedCaptioningLine, cloudFill, cloudLine, cloudOffFill, cloudOffLine, cloudWindyFill, cloudWindyLine, cloudy2Fill, cloudy2Line, cloudyFill, cloudyLine, codeBoxFill, codeBoxLine, codeFill, codepenFill, codepenLine, codeSFill, codeSLine, codeSSlashFill, codeSSlashLine, coinFill, coinLine, coinsFill, coinsLine, collageFill, collageLine, commandFill, commandLine, communityFill, communityLine, compass2Fill, compass2Line, compass3Fill, compass3Line, compass4Fill, compass4Line, compassDiscoverFill, compassDiscoverLine, compasses2Fill, compasses2Line, compassesFill, compassesLine, compassFill, compassLine, computerFill, computerLine, contactsBook2Fill, contactsBook2Line, contactsBookFill, contactsBookLine, contactsBookUploadFill, contactsBookUploadLine, contactsFill, contactsLine, contrast2Fill, contrast2Line, contrastDrop2Fill, contrastDrop2Line, contrastDropFill, contrastDropLine, contrastFill, contrastLine, copperCoinFill, copperCoinLine, copperDiamondFill, copperDiamondLine, copyleftFill, copyleftLine, copyrightFill, copyrightLine, coreosFill, coreosLine, coupon2Fill, coupon2Line, coupon3Fill, coupon3Line, coupon4Fill, coupon4Line, coupon5Fill, coupon5Line, couponFill, couponLine, cpuFill, cpuLine, creativeCommonsByFill, creativeCommonsByLine, creativeCommonsFill, creativeCommonsLine, creativeCommonsNcFill, creativeCommonsNcLine, creativeCommonsNdFill, creativeCommonsNdLine, creativeCommonsSaFill, creativeCommonsSaLine, creativeCommonsZeroFill, creativeCommonsZeroLine, criminalFill, criminalLine, crop2Fill, crop2Line, cropFill, cropLine, css3Fill, css3Line, cupFill, cupLine, currencyFill, currencyLine, cursorFill, cursorLine, customerService2Fill, customerService2Line, customerServiceFill, customerServiceLine, dashboard2Fill, dashboard2Line, dashboard3Fill, dashboard3Line, dashboardFill, dashboardLine, database2Fill, database2Line, databaseFill, databaseLine, deleteBack2Fill, deleteBack2Line, deleteBackFill, deleteBackLine, deleteBin2Fill, deleteBin2Line, deleteBin3Fill, deleteBin3Line, deleteBin4Fill, deleteBin4Line, deleteBin5Fill, deleteBin5Line, deleteBin6Fill, deleteBin6Line, deleteBin7Fill, deleteBin7Line, deviceFill, deviceLine, deviceRecoverFill, deviceRecoverLine, dingdingFill, dingdingLine, directionFill, directionLine, discFill, discLine, discordFill, discordLine, discussFill, discussLine, dislikeFill, dislikeLine, disqusFill, disqusLine, divideFill, divideLine, donutChartFill, donutChartLine, doorClosedFill, doorClosedLine, doorFill, doorLine, doorLockBoxFill, doorLockBoxLine, doorLockFill, doorLockLine, doorOpenFill, doorOpenLine, dossierFill, dossierLine, doubanFill, doubanLine, download2Line, downloadCloud2Fill, downloadCloud2Line, downloadCloudFill, downloadCloudLine, downloadFill, downloadLine, draftFill, draftLine, dragDropFill, dragMove2Fill, dragMove2Line, dragMoveFill, dragMoveLine, dribbbleFill, dribbbleLine, driveFill, driveLine, drizzleFill, drizzleLine, dropboxFill, dropboxLine, dropFill, dropLine, dualSim1Fill, dualSim1Line, dualSim2Fill, dualSim2Line, dvdFill, dvdLine, dvFill, dvLine, earthFill, earthLine, earthquakeFill, earthquakeLine, eBike2Fill, eBike2Line, eBikeFill, eBikeLine, edgeFill, edgeLine, edit2Fill, edit2Line, editBoxFill, editBoxLine, editCircleFill, editCircleLine, editFill, editLine, ejectFill, ejectLine, emotion2Fill, emotion2Line, emotionFill, emotionHappyFill, emotionHappyLine, emotionLaughFill, emotionLaughLine, emotionLine, emotionNormalFill, emotionNormalLine, emotionSadFill, emotionSadLine, emotionUnhappyFill, emotionUnhappyLine, empathizeFill, empathizeLine, equalizerFill, equalizerLine, eraserFill, eraserLine, errorWarningFill, evernoteFill, evernoteLine, exchangeBoxFill, exchangeBoxLine, exchangeCnyFill, exchangeCnyLine, exchangeDollarFill, exchangeDollarLine, exchangeFill, exchangeFundsFill, exchangeFundsLine, exchangeLine, externalLinkLine, eye2Fill, eye2Line, eyeCloseFill, eyeCloseLine, eyeFill, eyeLine, eyeOffFill, eyeOffLine, facebookBoxFill, facebookBoxLine, facebookCircleFill, facebookCircleLine, facebookFill, facebookLine, fahrenheitFill, fahrenheitLine, feedbackFill, feedbackLine, file2Fill, file2Line, file3Fill, file3Line, file4Fill, file4Line, fileAddFill, fileAddLine, fileChart2Fill, fileChart2Line, fileChartFill, fileChartLine, fileCloudFill, fileCloudLine, fileCodeFill, fileCodeLine, fileCopy2Fill, fileCopy2Line, fileCopyFill, fileDamageFill, fileDamageLine, fileDownloadFill, fileDownloadLine, fileEditFill, fileEditLine, fileExcel2Fill, fileExcel2Line, fileExcelFill, fileExcelLine, fileFill, fileForbidFill, fileForbidLine, fileGifFill, fileGifLine, fileHistoryFill, fileHistoryLine, fileHwpFill, fileHwpLine, fileInfoFill, fileInfoLine, fileLine, fileList2Fill, fileList2Line, fileList3Fill, fileList3Line, fileListFill, fileListLine, fileLockFill, fileLockLine, fileMarkFill, fileMarkLine, fileMusicFill, fileMusicLine, filePaper2Fill, filePaper2Line, filePaperFill, filePaperLine, filePdfFill, filePdfLine, filePpt2Fill, filePpt2Line, filePptFill, filePptLine, fileReduceFill, fileReduceLine, fileSearchFill, fileSearchLine, fileSettingsFill, fileSettingsLine, fileShield2Fill, fileShield2Line, fileShieldFill, fileShieldLine, fileShredFill, fileShredLine, fileTextFill, fileTextLine, fileTransferFill, fileTransferLine, fileUnknowFill, fileUnknowLine, fileUploadFill, fileUploadLine, fileUserFill, fileUserLine, fileWarningFill, fileWarningLine, fileWord2Fill, fileWord2Line, fileWordFill, fileWordLine, fileZipFill, fileZipLine, filmFill, filmLine, filter2Fill, filter2Line, filter3Fill, filter3Line, filterFill, filterLine, filterOffFill, filterOffLine, finderFill, finderLine, findReplaceFill, findReplaceLine, fingerprint2Fill, fingerprint2Line, fingerprintFill, fingerprintLine, fireFill, firefoxFill, firefoxLine, fireLine, firstAidKitFill, firstAidKitLine, flag2Fill, flag2Line, flagFill, flagLine, flashlightFill, flashlightLine, flaskFill, flaskLine, flightLandFill, flightLandLine, flightTakeoffFill, flightTakeoffLine, floodFill, floodLine, flutterFill, flutterLine, focus2Fill, focus2Line, focus3Fill, focus3Line, focusFill, focusLine, foggyFill, foggyLine, folder2Fill, folder2Line, folder3Fill, folder3Line, folder4Fill, folder4Line, folder5Fill, folder5Line, folderAddFill, folderAddLine, folderChart2Fill, folderChart2Line, folderChartFill, folderChartLine, folderDownloadFill, folderDownloadLine, folderFill, folderForbidFill, folderForbidLine, folderHistoryFill, folderHistoryLine, folderInfoFill, folderInfoLine, folderKeyholeFill, folderKeyholeLine, folderLine, folderLockFill, folderLockLine, folderMusicFill, folderMusicLine, folderOpenFill, folderOpenLine, folderReceivedFill, folderReceivedLine, folderReduceFill, folderReduceLine, folderSettingsFill, folderSettingsLine, foldersFill, folderSharedFill, folderSharedLine, folderShield2Fill, folderShield2Line, folderShieldFill, folderShieldLine, foldersLine, folderTransferFill, folderTransferLine, folderUnknowFill, folderUnknowLine, folderUploadFill, folderUploadLine, folderUserFill, folderUserLine, folderWarningFill, folderWarningLine, folderZipFill, folderZipLine, footballFill, footballLine, footprintFill, footprintLine, forbid2Fill, forbid2Line, forbidFill, forbidLine, fourKFill, fourKLine, fridgeFill, fridgeLine, fullscreenExitFill, fullscreenFill, functionFill, functionLine, fundsBoxFill, fundsBoxLine, fundsFill, fundsLine, galleryFill, galleryLine, galleryUploadFill, gameFill, gameLine, gamepadFill, gamepadLine, gasStationFill, gasStationLine, gatsbyFill, gatsbyLine, genderlessFill, genderlessLine, ghost2Fill, ghost2Line, ghostFill, ghostLine, ghostSmileFill, ghostSmileLine, gift2Fill, gift2Line, giftFill, giftLine, gitBranchFill, gitBranchLine, gitCommitFill, gitCommitLine, githubFill, githubLine, gitlabFill, gitlabLine, gitMergeFill, gitMergeLine, gitPullRequestFill, gitPullRequestLine, gitRepositoryCommitsFill, gitRepositoryCommitsLine, gitRepositoryFill, gitRepositoryLine, gitRepositoryPrivateFill, gitRepositoryPrivateLine, globalFill, globalLine, globeFill, globeLine, gobletFill, gobletLine, googleFill, googleLine, googlePlayFill, googlePlayLine, governmentFill, governmentLine, gpsFill, gpsLine, gradienterFill, gradienterLine, gridFill, gridLine, group2Fill, group2Line, groupFill, groupLine, guideFill, guideLine, hailFill, hailLine, hammerFill, hammerLine, handbagFill, handbagLine, handCoinFill, handCoinLine, handHeartFill, handHeartLine, handSanitizerFill, handSanitizerLine, hardDrive2Fill, hardDrive2Line, hardDriveFill, hardDriveLine, haze2Fill, haze2Line, hazeFill, hazeLine, hdFill, hdLine, headphoneFill, headphoneLine, healthBookFill, healthBookLine, heart2Fill, heart2Line, heart3Fill, heart3Line, heartAddFill, heartAddLine, heartFill, heartLine, heartPulseFill, heartPulseLine, heartsFill, heartsLine, heavyShowersFill, heavyShowersLine, historyFill, historyLine, home2Fill, home2Line, home3Fill, home3Line, home4Fill, home4Line, home5Fill, home5Line, home6Fill, home6Line, home7Fill, home7Line, home8Fill, home8Line, homeFill, homeGearFill, homeGearLine, homeHeartFill, homeHeartLine, homeLine, homeSmile2Fill, homeSmile2Line, homeSmileFill, homeSmileLine, homeWifiFill, homeWifiLine, honorOfKingsFill, honorOfKingsLine, honourFill, honourLine, hospitalFill, hospitalLine, hotelBedFill, hotelBedLine, hotelFill, hotelLine, hotspotFill, hotspotLine, hqFill, hqLine, html5Fill, html5Line, ieFill, ieLine, image2Fill, image2Line, imageAddFill, imageEditFill, imageFill, inboxArchiveFill, inboxArchiveLine, inboxFill, inboxLine, inboxUnarchiveFill, inboxUnarchiveLine, increaseDecreaseFill, increaseDecreaseLine, indeterminateCircleFill, indeterminateCircleLine, informationFill, infraredThermometerFill, infraredThermometerLine, inkBottleFill, inkBottleLine, inputMethodFill, inputMethodLine, instagramFill, instagramLine, installFill, installLine, invisionFill, invisionLine, kakaoTalkFill, kakaoTalkLine, key2Fill, key2Line, keyboardBoxFill, keyboardBoxLine, keyboardFill, keyboardLine, keyFill, keyLine, keynoteFill, keynoteLine, knifeBloodFill, knifeBloodLine, knifeFill, knifeLine, landscapeFill, landscapeLine, layout2Fill, layout2Line, layout3Fill, layout3Line, layout4Fill, layout4Line, layout5Fill, layout5Line, layout6Fill, layout6Line, layoutBottom2Fill, layoutBottom2Line, layoutBottomFill, layoutBottomLine, layoutColumnFill, layoutFill, layoutGridFill, layoutGridLine, layoutLeft2Fill, layoutLeft2Line, layoutLeftFill, layoutLeftLine, layoutLine, layoutMasonryFill, layoutMasonryLine, layoutRight2Fill, layoutRight2Line, layoutRightFill, layoutRightLine, layoutRowFill, layoutRowLine, layoutTop2Fill, layoutTop2Line, layoutTopFill, layoutTopLine, leafFill, leafLine, lifebuoyFill, lifebuoyLine, lightbulbFill, lightbulbFlashFill, lightbulbFlashLine, lightbulbLine, lineChartFill, lineChartLine, lineFill, lineLine, linkedinBoxFill, linkedinBoxLine, linkedinFill, linkedinLine, linksFill, linksLine, listSettingsFill, listSettingsLine, liveFill, liveLine, loader2Fill, loader2Line, loader3Fill, loader3Line, loader4Fill, loader4Line, loader5Fill, loader5Line, loaderFill, loaderLine, lock2Fill, lock2Line, lockFill, lockLine, lockPasswordFill, lockPasswordLine, lockUnlockFill, lockUnlockLine, loginBoxFill, loginBoxLine, loginCircleFill, loginCircleLine, logoutBoxFill, logoutBoxLine, logoutBoxRFill, logoutBoxRLine, logoutCircleFill, logoutCircleLine, logoutCircleRFill, logoutCircleRLine, luggageCartFill, luggageCartLine, luggageDepositFill, luggageDepositLine, lungsFill, lungsLine, macbookFill, macbookLine, macFill, macLine, magicFill, magicLine, mailAddFill, mailAddLine, mailCheckFill, mailCheckLine, mailCloseFill, mailCloseLine, mailDownloadFill, mailDownloadLine, mailFill, mailForbidFill, mailForbidLine, mailLine, mailLockFill, mailLockLine, mailOpenFill, mailOpenLine, mailSendFill, mailSendLine, mailSettingsFill, mailSettingsLine, mailStarFill, mailStarLine, mailUnreadFill, mailUnreadLine, mailVolumeFill, mailVolumeLine, map2Fill, map2Line, mapFill, mapLine, mapPin2Fill, mapPin2Line, mapPin3Fill, mapPin3Line, mapPin4Fill, mapPin4Line, mapPin5Fill, mapPin5Line, mapPinAddFill, mapPinAddLine, mapPinFill, mapPinLine, mapPinRangeFill, mapPinRangeLine, mapPinTimeFill, mapPinTimeLine, mapPinUserFill, mapPinUserLine, markPenFill, markupFill, markupLine, mastercardFill, mastercardLine, mastodonFill, mastodonLine, medal2Fill, medal2Line, medalFill, medalLine, medicineBottleFill, medicineBottleLine, mediumFill, mediumLine, menFill, menLine, mentalHealthFill, mentalHealthLine, menu2Fill, menu2Line, menu3Fill, menu3Line, menu4Fill, menu4Line, menu5Fill, menu5Line, menuAddFill, menuAddLine, menuFill, menuFoldFill, menuFoldLine, menuLine, menuUnfoldFill, menuUnfoldLine, message2Fill, message2Line, message3Fill, message3Line, messageFill, messageLine, messengerFill, messengerLine, meteorFill, meteorLine, mic2Fill, mic2Line, micFill, mickeyFill, mickeyLine, micLine, micOffFill, micOffLine, microscopeFill, microscopeLine, microsoftFill, microsoftLine, miniProgramFill, miniProgramLine, mistFill, mistLine, moneyCnyBoxFill, moneyCnyBoxLine, moneyCnyCircleFill, moneyCnyCircleLine, moneyDollarBoxFill, moneyDollarBoxLine, moneyDollarCircleFill, moneyDollarCircleLine, moneyEuroBoxFill, moneyEuroBoxLine, moneyEuroCircleFill, moneyEuroCircleLine, moneyPoundBoxFill, moneyPoundBoxLine, moneyPoundCircleFill, moneyPoundCircleLine, moonClearFill, moonClearLine, moonCloudyFill, moonCloudyLine, moonFill, moonFoggyFill, moonFoggyLine, moonLine, more2Fill, more2Line, moreLine, motorbikeFill, motorbikeLine, mouseFill, mouseLine, movie2Fill, movie2Line, movieFill, movieLine, music2Fill, music2Line, musicFill, musicLine, mvFill, mvLine, navigationFill, navigationLine, neteaseCloudMusicFill, neteaseCloudMusicLine, netflixFill, netflixLine, newspaperFill, newspaperLine, notification2Fill, notification2Line, notification3Fill, notification3Line, notification4Fill, notification4Line, notificationBadgeFill, notificationBadgeLine, notificationFill, notificationLine, notificationOffFill, notificationOffLine, npmjsFill, npmjsLine, numbersFill, numbersLine, nurseFill, nurseLine, oilFill, oilLine, openArmFill, openArmLine, openSourceFill, openSourceLine, operaFill, operaLine, orderPlayFill, orderPlayLine, outlet2Fill, outlet2Line, outletFill, outletLine, pagesFill, pagesLine, paintBrushFill, paintBrushLine, paintFill, paintLine, paletteFill, paletteLine, pantoneFill, pantoneLine, parentFill, parenthesesFill, parenthesesLine, parentLine, parkingBoxFill, parkingBoxLine, parkingFill, parkingLine, passportFill, passportLine, patreonFill, patreonLine, pauseCircleFill, pauseCircleLine, pauseFill, pauseLine, pauseMiniFill, pauseMiniLine, paypalFill, paypalLine, pencilRuler2Fill, pencilRuler2Line, pencilRulerFill, pencilRulerLine, penNibFill, penNibLine, percentFill, percentLine, phoneCameraFill, phoneCameraLine, phoneFill, phoneFindFill, phoneFindLine, phoneLine, phoneLockFill, phoneLockLine, pictureInPicture2Fill, pictureInPicture2Line, pictureInPictureExitFill, pictureInPictureExitLine, pictureInPictureFill, pictureInPictureLine, pieChart2Fill, pieChart2Line, pieChartBoxFill, pieChartBoxLine, pieChartFill, pieChartLine, pinDistanceFill, pinDistanceLine, pingPongFill, pingPongLine, pinterestFill, pinterestLine, pixelfedFill, pixelfedLine, planeFill, planeLine, plantFill, plantLine, playCircleFill, playCircleLine, playFill, playLine, playList2Fill, playList2Line, playListAddFill, playListAddLine, playListFill, playListLine, playMiniFill, playMiniLine, playstationFill, playstationLine, plug2Fill, plug2Line, plugFill, plugLine, polaroid2Fill, polaroid2Line, polaroidFill, polaroidLine, policeCarFill, policeCarLine, priceTag2Fill, priceTag2Line, priceTag3Fill, priceTag3Line, priceTagFill, priceTagLine, printerCloudFill, printerCloudLine, printerFill, printerLine, productHuntFill, productHuntLine, profileFill, profileLine, projector2Fill, projector2Line, projectorFill, projectorLine, psychotherapyFill, psychotherapyLine, pulseFill, pulseLine, pushpin2Fill, pushpin2Line, pushpinFill, pushpinLine, qqFill, qqLine, qrCodeFill, qrCodeLine, qrScan2Fill, qrScan2Line, qrScanFill, qrScanLine, questionAnswerFill, questionAnswerLine, questionFill, questionLine, questionnaireFill, questionnaireLine, quillPenFill, quillPenLine, radarFill, radarLine, radio2Fill, radio2Line, radioButtonFill, radioButtonLine, radioFill, radioLine, rainbowFill, rainbowLine, rainyFill, rainyLine, reactjsFill, reactjsLine, recordCircleFill, recordCircleLine, recordMailFill, recordMailLine, recycleFill, recycleLine, redditFill, redditLine, redPacketFill, redPacketLine, refreshFill, refreshLine, refund2Fill, refund2Line, refundFill, refundLine, registeredFill, registeredLine, remixiconFill, remixiconLine, remoteControl2Fill, remoteControl2Line, remoteControlFill, remoteControlLine, repeat2Fill, repeat2Line, repeatFill, repeatLine, repeatOneFill, repeatOneLine, replyAllFill, replyAllLine, replyFill, replyLine, reservedFill, reservedLine, restartFill, restartLine, restaurant2Fill, restaurant2Line, restaurantFill, restaurantLine, restTimeFill, restTimeLine, rewindFill, rewindLine, rewindMiniFill, rewindMiniLine, rhythmFill, rhythmLine, ridingFill, ridingLine, roadMapFill, roadMapLine, roadsterFill, roadsterLine, robotFill, robotLine, rocket2Fill, rocket2Line, rocketFill, rocketLine, rotateLockFill, rotateLockLine, routeFill, routeLine, routerFill, routerLine, rssFill, rssLine, ruler2Fill, ruler2Line, rulerFill, rulerLine, runFill, runLine, safariFill, safariLine, safe2Fill, safe2Line, safeFill, safeLine, sailboatFill, sailboatLine, save2Fill, save2Line, save3Fill, save3Line, saveFill, saveLine, scales2Fill, scales2Line, scales3Fill, scales3Line, scalesFill, scalesLine, scan2Fill, scan2Line, scanFill, scanLine, scissors2Fill, scissors2Line, scissorsCutFill, scissorsCutLine, scissorsLine, screenshot2Fill, screenshot2Line, screenshotFill, screenshotLine, sdCardFill, sdCardLine, sdCardMiniFill, sdCardMiniLine, search2Fill, search2Line, searchEyeFill, searchEyeLine, searchFill, searchLine, securePaymentFill, securePaymentLine, seedlingFill, seedlingLine, sendPlane2Fill, sendPlane2Line, sendPlaneFill, sendPlaneLine, sensorFill, sensorLine, serverFill, serverLine, serviceFill, serviceLine, settings2Fill, settings2Line, settings3Fill, settings3Line, settings4Fill, settings4Line, settings5Fill, settings5Line, settings6Fill, settings6Line, settingsFill, settingsLine, shape2Fill, shape2Line, shapeFill, shapeLine, shareBoxFill, shareBoxLine, shareCircleFill, shareCircleLine, shareFill, shareForward2Fill, shareForward2Line, shareForwardBoxFill, shareForwardBoxLine, shareForwardFill, shareForwardLine, shareLine, shieldCheckFill, shieldCheckLine, shieldCrossFill, shieldCrossLine, shieldFill, shieldFlashFill, shieldFlashLine, shieldKeyholeFill, shieldKeyholeLine, shieldLine, shieldStarFill, shieldStarLine, shieldUserFill, shieldUserLine, ship2Fill, ship2Line, shipFill, shipLine, shirtFill, shirtLine, shoppingBag2Fill, shoppingBag2Line, shoppingBag3Fill, shoppingBag3Line, shoppingBagFill, shoppingBagLine, shoppingBasket2Fill, shoppingBasket2Line, shoppingBasketFill, shoppingBasketLine, shoppingCart2Fill, shoppingCart2Line, shoppingCartFill, shoppingCartLine, showersFill, showersLine, shuffleFill, shuffleLine, shutDownFill, shutDownLine, sideBarFill, sideBarLine, signalTowerFill, signalTowerLine, signalWifi1Fill, signalWifi1Line, signalWifi2Fill, signalWifi2Line, signalWifi3Fill, signalWifi3Line, signalWifiErrorFill, signalWifiErrorLine, signalWifiFill, signalWifiLine, signalWifiOffFill, signalWifiOffLine, simCard2Fill, simCard2Line, simCardFill, simCardLine, sipFill, sipLine, skipBackFill, skipBackLine, skipBackMiniFill, skipBackMiniLine, skipForwardFill, skipForwardLine, skipForwardMiniFill, skipForwardMiniLine, skull2Fill, skull2Line, skullFill, skullLine, skypeFill, skypeLine, slackFill, slackLine, sliceFill, sliceLine, slideshow2Fill, slideshow2Line, slideshow3Fill, slideshow3Line, slideshow4Fill, slideshow4Line, slideshowFill, slideshowLine, smartphoneFill, smartphoneLine, snapchatFill, snapchatLine, snowyFill, snowyLine, soundcloudFill, soundcloudLine, soundModuleFill, soundModuleLine, spaceShipFill, spaceShipLine, spam2Fill, spam2Line, spam3Fill, spam3Line, spamFill, speaker2Fill, speaker2Line, speaker3Fill, speaker3Line, speakerFill, speakerLine, spectrumFill, spectrumLine, speedFill, speedLine, speedMiniFill, speedMiniLine, spotifyFill, spotifyLine, spyFill, spyLine, stackFill, stackLine, stackOverflowFill, stackOverflowLine, stackshareFill, stackshareLine, starFill, starHalfFill, starHalfLine, starHalfSFill, starHalfSLine, starLine, starSFill, starSLine, starSmileFill, starSmileLine, steamFill, steamLine, steering2Fill, steering2Line, steeringFill, steeringLine, stethoscopeFill, stethoscopeLine, stickyNote2Fill, stickyNote2Line, stickyNoteFill, stickyNoteLine, stockFill, stockLine, stopCircleFill, stopCircleLine, stopFill, stopLine, stopMiniFill, stopMiniLine, store2Fill, store2Line, store3Fill, store3Line, storeFill, storeLine, subtractFill, subwayFill, subwayLine, subwayWifiFill, subwayWifiLine, suitcase2Fill, suitcase2Line, suitcase3Fill, suitcase3Line, suitcaseFill, suitcaseLine, sunCloudyFill, sunCloudyLine, sunFill, sunFoggyFill, sunFoggyLine, sunLine, surgicalMaskFill, surgicalMaskLine, surroundSoundFill, surroundSoundLine, surveyFill, surveyLine, swapBoxFill, swapBoxLine, swapFill, swapLine, switchFill, switchLine, swordFill, swordLine, syringeFill, syringeLine, tableAltFill, tableAltLine, tableFill, tabletFill, tabletLine, takeawayFill, takeawayLine, taobaoFill, taobaoLine, tapeFill, tapeLine, taskFill, taskLine, taxiFill, taxiLine, taxiWifiFill, taxiWifiLine, tBoxFill, tBoxLine, teamFill, teamLine, telegramFill, telegramLine, tempColdFill, tempColdLine, tempHotFill, tempHotLine, terminalBoxFill, terminalBoxLine, terminalFill, terminalLine, terminalWindowFill, terminalWindowLine, testTubeFill, testTubeLine, thermometerFill, thermometerLine, thumbDownFill, thumbDownLine, thumbUpFill, thumbUpLine, thunderstormsFill, thunderstormsLine, ticket2Fill, ticket2Line, ticketFill, ticketLine, timeFill, timeLine, timer2Fill, timer2Line, timerFill, timerFlashFill, timerFlashLine, timerLine, todoFill, todoLine, toggleFill, toggleLine, toolsFill, toolsLine, tornadoFill, tornadoLine, trademarkFill, trademarkLine, trafficLightFill, trafficLightLine, trainFill, trainLine, trainWifiFill, trainWifiLine, travestiFill, travestiLine, treasureMapFill, treasureMapLine, trelloFill, trelloLine, trophyFill, trophyLine, truckFill, truckLine, tShirt2Fill, tShirt2Line, tShirtAirFill, tShirtAirLine, tShirtFill, tShirtLine, tumblrFill, tumblrLine, tv2Fill, tv2Line, tvFill, tvLine, twentyFourHoursFill, twentyFourHoursLine, twitchFill, twitchLine, twitterFill, twitterLine, typhoonFill, typhoonLine, ubuntuFill, ubuntuLine, uDiskFill, uDiskLine, umbrellaFill, umbrellaLine, uninstallFill, uninstallLine, unsplashFill, unsplashLine, upload2Line, uploadCloud2Fill, uploadCloud2Line, uploadCloudFill, uploadCloudLine, uploadFill, uploadLine, usbFill, usbLine, user2Fill, user2Line, user3Fill, user3Line, user4Fill, user4Line, user5Fill, user5Line, user6Fill, user6Line, userAddFill, userAddLine, userFill, userFollowFill, userFollowLine, userHeartFill, userHeartLine, userLine, userLocationFill, userLocationLine, userReceived2Fill, userReceived2Line, userReceivedFill, userReceivedLine, userSearchFill, userSearchLine, userSettingsFill, userSettingsLine, userShared2Fill, userShared2Line, userSharedFill, userSharedLine, userSmileFill, userSmileLine, userStarFill, userStarLine, userUnfollowFill, userUnfollowLine, userVoiceFill, userVoiceLine, videoAddFill, videoAddLine, videoChatFill, videoChatLine, videoDownloadFill, videoDownloadLine, videoFill, videoUploadFill, videoUploadLine, vidicon2Fill, vidicon2Line, vidiconFill, vidiconLine, vimeoFill, vimeoLine, vipCrown2Fill, vipCrown2Line, vipCrownFill, vipCrownLine, vipDiamondFill, vipDiamondLine, vipFill, vipLine, virusFill, virusLine, visaFill, visaLine, voiceprintFill, voiceprintLine, voiceRecognitionFill, voiceRecognitionLine, volumeDownFill, volumeDownLine, volumeMuteFill, volumeMuteLine, volumeOffVibrateFill, volumeOffVibrateLine, volumeUpFill, volumeUpLine, volumeVibrateFill, volumeVibrateLine, vuejsFill, vuejsLine, walkFill, walkLine, wallet2Fill, wallet2Line, wallet3Fill, wallet3Line, walletFill, walletLine, waterFlashFill, waterFlashLine, webcamFill, webcamLine, wechat2Fill, wechat2Line, wechatFill, wechatLine, wechatPayFill, wechatPayLine, weiboFill, weiboLine, whatsappFill, whatsappLine, wheelchairFill, wheelchairLine, wifiFill, wifiLine, wifiOffFill, wifiOffLine, window2Fill, window2Line, windowFill, windowLine, windowsFill, windowsLine, windyFill, windyLine, wirelessChargingFill, wirelessChargingLine, womenFill, womenLine, xboxFill, xboxLine, xingFill, xingLine, youtubeFill, youtubeLine, zcoolFill, zcoolLine, zhihuFill, zhihuLine, zoomInFill, zoomInLine, zoomOutFill, zoomOutLine, zzzFill, zzzLine, } from '@remirror/icons/all'; import { GenIcon, IconType } from './icons-base'; /** * The react component for the `twenty-four-hours-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twenty Four Hours Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/24-hours-fill.svg) */ export const TwentyFourHoursFillIcon: IconType = (props) => { return GenIcon(twentyFourHoursFill)(props); }; /** * The react component for the `twenty-four-hours-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twenty Four Hours Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/24-hours-line.svg) */ export const TwentyFourHoursLineIcon: IconType = (props) => { return GenIcon(twentyFourHoursLine)(props); }; /** * The react component for the `four-k-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Four K Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/4k-fill.svg) */ export const FourKFillIcon: IconType = (props) => { return GenIcon(fourKFill)(props); }; /** * The react component for the `four-k-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Four K Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/4k-line.svg) */ export const FourKLineIcon: IconType = (props) => { return GenIcon(fourKLine)(props); }; /** * The react component for the `account-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-box-fill.svg) */ export const AccountBoxFillIcon: IconType = (props) => { return GenIcon(accountBoxFill)(props); }; /** * The react component for the `account-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-box-line.svg) */ export const AccountBoxLineIcon: IconType = (props) => { return GenIcon(accountBoxLine)(props); }; /** * The react component for the `account-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-circle-fill.svg) */ export const AccountCircleFillIcon: IconType = (props) => { return GenIcon(accountCircleFill)(props); }; /** * The react component for the `account-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-circle-line.svg) */ export const AccountCircleLineIcon: IconType = (props) => { return GenIcon(accountCircleLine)(props); }; /** * The react component for the `account-pin-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Pin Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-pin-box-fill.svg) */ export const AccountPinBoxFillIcon: IconType = (props) => { return GenIcon(accountPinBoxFill)(props); }; /** * The react component for the `account-pin-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Pin Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-pin-box-line.svg) */ export const AccountPinBoxLineIcon: IconType = (props) => { return GenIcon(accountPinBoxLine)(props); }; /** * The react component for the `account-pin-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Pin Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-pin-circle-fill.svg) */ export const AccountPinCircleFillIcon: IconType = (props) => { return GenIcon(accountPinCircleFill)(props); }; /** * The react component for the `account-pin-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Account Pin Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/account-pin-circle-line.svg) */ export const AccountPinCircleLineIcon: IconType = (props) => { return GenIcon(accountPinCircleLine)(props); }; /** * The react component for the `add-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Add Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/add-box-fill.svg) */ export const AddBoxFillIcon: IconType = (props) => { return GenIcon(addBoxFill)(props); }; /** * The react component for the `add-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Add Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/add-box-line.svg) */ export const AddBoxLineIcon: IconType = (props) => { return GenIcon(addBoxLine)(props); }; /** * The react component for the `add-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Add Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/add-circle-fill.svg) */ export const AddCircleFillIcon: IconType = (props) => { return GenIcon(addCircleFill)(props); }; /** * The react component for the `add-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Add Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/add-circle-line.svg) */ export const AddCircleLineIcon: IconType = (props) => { return GenIcon(addCircleLine)(props); }; /** * The react component for the `admin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Admin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/admin-fill.svg) */ export const AdminFillIcon: IconType = (props) => { return GenIcon(adminFill)(props); }; /** * The react component for the `admin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Admin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/admin-line.svg) */ export const AdminLineIcon: IconType = (props) => { return GenIcon(adminLine)(props); }; /** * The react component for the `advertisement-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Advertisement Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/advertisement-fill.svg) */ export const AdvertisementFillIcon: IconType = (props) => { return GenIcon(advertisementFill)(props); }; /** * The react component for the `advertisement-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Advertisement Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/advertisement-line.svg) */ export const AdvertisementLineIcon: IconType = (props) => { return GenIcon(advertisementLine)(props); }; /** * The react component for the `airplay-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Airplay Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/airplay-fill.svg) */ export const AirplayFillIcon: IconType = (props) => { return GenIcon(airplayFill)(props); }; /** * The react component for the `airplay-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Airplay Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/airplay-line.svg) */ export const AirplayLineIcon: IconType = (props) => { return GenIcon(airplayLine)(props); }; /** * The react component for the `alarm-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alarm Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/alarm-fill.svg) */ export const AlarmFillIcon: IconType = (props) => { return GenIcon(alarmFill)(props); }; /** * The react component for the `alarm-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alarm Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/alarm-line.svg) */ export const AlarmLineIcon: IconType = (props) => { return GenIcon(alarmLine)(props); }; /** * The react component for the `alarm-warning-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alarm Warning Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/alarm-warning-fill.svg) */ export const AlarmWarningFillIcon: IconType = (props) => { return GenIcon(alarmWarningFill)(props); }; /** * The react component for the `alarm-warning-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alarm Warning Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/alarm-warning-line.svg) */ export const AlarmWarningLineIcon: IconType = (props) => { return GenIcon(alarmWarningLine)(props); }; /** * The react component for the `album-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Album Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/album-fill.svg) */ export const AlbumFillIcon: IconType = (props) => { return GenIcon(albumFill)(props); }; /** * The react component for the `album-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Album Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/album-line.svg) */ export const AlbumLineIcon: IconType = (props) => { return GenIcon(albumLine)(props); }; /** * The react component for the `alert-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alert Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/alert-fill.svg) */ export const AlertFillIcon: IconType = (props) => { return GenIcon(alertFill)(props); }; /** * The react component for the `aliens-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Aliens Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/aliens-fill.svg) */ export const AliensFillIcon: IconType = (props) => { return GenIcon(aliensFill)(props); }; /** * The react component for the `aliens-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Aliens Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/aliens-line.svg) */ export const AliensLineIcon: IconType = (props) => { return GenIcon(aliensLine)(props); }; /** * The react component for the `alipay-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alipay Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/alipay-fill.svg) */ export const AlipayFillIcon: IconType = (props) => { return GenIcon(alipayFill)(props); }; /** * The react component for the `alipay-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Alipay Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/alipay-line.svg) */ export const AlipayLineIcon: IconType = (props) => { return GenIcon(alipayLine)(props); }; /** * The react component for the `amazon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Amazon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/amazon-fill.svg) */ export const AmazonFillIcon: IconType = (props) => { return GenIcon(amazonFill)(props); }; /** * The react component for the `amazon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Amazon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/amazon-line.svg) */ export const AmazonLineIcon: IconType = (props) => { return GenIcon(amazonLine)(props); }; /** * The react component for the `anchor-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anchor Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/anchor-fill.svg) */ export const AnchorFillIcon: IconType = (props) => { return GenIcon(anchorFill)(props); }; /** * The react component for the `anchor-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anchor Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/anchor-line.svg) */ export const AnchorLineIcon: IconType = (props) => { return GenIcon(anchorLine)(props); }; /** * The react component for the `ancient-gate-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ancient Gate Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/ancient-gate-fill.svg) */ export const AncientGateFillIcon: IconType = (props) => { return GenIcon(ancientGateFill)(props); }; /** * The react component for the `ancient-gate-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ancient Gate Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/ancient-gate-line.svg) */ export const AncientGateLineIcon: IconType = (props) => { return GenIcon(ancientGateLine)(props); }; /** * The react component for the `ancient-pavilion-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ancient Pavilion Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/ancient-pavilion-fill.svg) */ export const AncientPavilionFillIcon: IconType = (props) => { return GenIcon(ancientPavilionFill)(props); }; /** * The react component for the `ancient-pavilion-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ancient Pavilion Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/ancient-pavilion-line.svg) */ export const AncientPavilionLineIcon: IconType = (props) => { return GenIcon(ancientPavilionLine)(props); }; /** * The react component for the `android-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Android Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/android-fill.svg) */ export const AndroidFillIcon: IconType = (props) => { return GenIcon(androidFill)(props); }; /** * The react component for the `android-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Android Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/android-line.svg) */ export const AndroidLineIcon: IconType = (props) => { return GenIcon(androidLine)(props); }; /** * The react component for the `angularjs-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Angularjs Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/angularjs-fill.svg) */ export const AngularjsFillIcon: IconType = (props) => { return GenIcon(angularjsFill)(props); }; /** * The react component for the `angularjs-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Angularjs Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/angularjs-line.svg) */ export const AngularjsLineIcon: IconType = (props) => { return GenIcon(angularjsLine)(props); }; /** * The react component for the `anticlockwise-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anticlockwise 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/anticlockwise-2-fill.svg) */ export const Anticlockwise2FillIcon: IconType = (props) => { return GenIcon(anticlockwise2Fill)(props); }; /** * The react component for the `anticlockwise-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anticlockwise 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/anticlockwise-2-line.svg) */ export const Anticlockwise2LineIcon: IconType = (props) => { return GenIcon(anticlockwise2Line)(props); }; /** * The react component for the `anticlockwise-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anticlockwise Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/anticlockwise-fill.svg) */ export const AnticlockwiseFillIcon: IconType = (props) => { return GenIcon(anticlockwiseFill)(props); }; /** * The react component for the `anticlockwise-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Anticlockwise Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/anticlockwise-line.svg) */ export const AnticlockwiseLineIcon: IconType = (props) => { return GenIcon(anticlockwiseLine)(props); }; /** * The react component for the `app-store-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![App Store Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/app-store-fill.svg) */ export const AppStoreFillIcon: IconType = (props) => { return GenIcon(appStoreFill)(props); }; /** * The react component for the `app-store-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![App Store Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/app-store-line.svg) */ export const AppStoreLineIcon: IconType = (props) => { return GenIcon(appStoreLine)(props); }; /** * The react component for the `apple-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Apple Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/apple-fill.svg) */ export const AppleFillIcon: IconType = (props) => { return GenIcon(appleFill)(props); }; /** * The react component for the `apple-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Apple Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/apple-line.svg) */ export const AppleLineIcon: IconType = (props) => { return GenIcon(appleLine)(props); }; /** * The react component for the `apps-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Apps 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/apps-2-fill.svg) */ export const Apps2FillIcon: IconType = (props) => { return GenIcon(apps2Fill)(props); }; /** * The react component for the `apps-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Apps 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/apps-2-line.svg) */ export const Apps2LineIcon: IconType = (props) => { return GenIcon(apps2Line)(props); }; /** * The react component for the `apps-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Apps Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/apps-fill.svg) */ export const AppsFillIcon: IconType = (props) => { return GenIcon(appsFill)(props); }; /** * The react component for the `archive-drawer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Archive Drawer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/archive-drawer-fill.svg) */ export const ArchiveDrawerFillIcon: IconType = (props) => { return GenIcon(archiveDrawerFill)(props); }; /** * The react component for the `archive-drawer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Archive Drawer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/archive-drawer-line.svg) */ export const ArchiveDrawerLineIcon: IconType = (props) => { return GenIcon(archiveDrawerLine)(props); }; /** * The react component for the `archive-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Archive Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/archive-fill.svg) */ export const ArchiveFillIcon: IconType = (props) => { return GenIcon(archiveFill)(props); }; /** * The react component for the `archive-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Archive Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/archive-line.svg) */ export const ArchiveLineIcon: IconType = (props) => { return GenIcon(archiveLine)(props); }; /** * The react component for the `arrow-down-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Down Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-down-circle-fill.svg) */ export const ArrowDownCircleFillIcon: IconType = (props) => { return GenIcon(arrowDownCircleFill)(props); }; /** * The react component for the `arrow-down-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Down Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-down-circle-line.svg) */ export const ArrowDownCircleLineIcon: IconType = (props) => { return GenIcon(arrowDownCircleLine)(props); }; /** * The react component for the `arrow-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-down-fill.svg) */ export const ArrowDownFillIcon: IconType = (props) => { return GenIcon(arrowDownFill)(props); }; /** * The react component for the `arrow-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-down-line.svg) */ export const ArrowDownLineIcon: IconType = (props) => { return GenIcon(arrowDownLine)(props); }; /** * The react component for the `arrow-down-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Down S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-down-s-line.svg) */ export const ArrowDownSLineIcon: IconType = (props) => { return GenIcon(arrowDownSLine)(props); }; /** * The react component for the `arrow-drop-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-down-fill.svg) */ export const ArrowDropDownFillIcon: IconType = (props) => { return GenIcon(arrowDropDownFill)(props); }; /** * The react component for the `arrow-drop-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-down-line.svg) */ export const ArrowDropDownLineIcon: IconType = (props) => { return GenIcon(arrowDropDownLine)(props); }; /** * The react component for the `arrow-drop-left-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Left Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-left-fill.svg) */ export const ArrowDropLeftFillIcon: IconType = (props) => { return GenIcon(arrowDropLeftFill)(props); }; /** * The react component for the `arrow-drop-left-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Left Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-left-line.svg) */ export const ArrowDropLeftLineIcon: IconType = (props) => { return GenIcon(arrowDropLeftLine)(props); }; /** * The react component for the `arrow-drop-right-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Right Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-right-fill.svg) */ export const ArrowDropRightFillIcon: IconType = (props) => { return GenIcon(arrowDropRightFill)(props); }; /** * The react component for the `arrow-drop-right-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Right Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-right-line.svg) */ export const ArrowDropRightLineIcon: IconType = (props) => { return GenIcon(arrowDropRightLine)(props); }; /** * The react component for the `arrow-drop-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-up-fill.svg) */ export const ArrowDropUpFillIcon: IconType = (props) => { return GenIcon(arrowDropUpFill)(props); }; /** * The react component for the `arrow-drop-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Drop Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-drop-up-line.svg) */ export const ArrowDropUpLineIcon: IconType = (props) => { return GenIcon(arrowDropUpLine)(props); }; /** * The react component for the `arrow-go-back-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Go Back Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-go-back-line.svg) */ export const ArrowGoBackLineIcon: IconType = (props) => { return GenIcon(arrowGoBackLine)(props); }; /** * The react component for the `arrow-go-forward-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Go Forward Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-go-forward-line.svg) */ export const ArrowGoForwardLineIcon: IconType = (props) => { return GenIcon(arrowGoForwardLine)(props); }; /** * The react component for the `arrow-left-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-circle-fill.svg) */ export const ArrowLeftCircleFillIcon: IconType = (props) => { return GenIcon(arrowLeftCircleFill)(props); }; /** * The react component for the `arrow-left-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-circle-line.svg) */ export const ArrowLeftCircleLineIcon: IconType = (props) => { return GenIcon(arrowLeftCircleLine)(props); }; /** * The react component for the `arrow-left-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-down-fill.svg) */ export const ArrowLeftDownFillIcon: IconType = (props) => { return GenIcon(arrowLeftDownFill)(props); }; /** * The react component for the `arrow-left-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-down-line.svg) */ export const ArrowLeftDownLineIcon: IconType = (props) => { return GenIcon(arrowLeftDownLine)(props); }; /** * The react component for the `arrow-left-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-fill.svg) */ export const ArrowLeftFillIcon: IconType = (props) => { return GenIcon(arrowLeftFill)(props); }; /** * The react component for the `arrow-left-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-line.svg) */ export const ArrowLeftLineIcon: IconType = (props) => { return GenIcon(arrowLeftLine)(props); }; /** * The react component for the `arrow-left-right-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Right Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-right-fill.svg) */ export const ArrowLeftRightFillIcon: IconType = (props) => { return GenIcon(arrowLeftRightFill)(props); }; /** * The react component for the `arrow-left-right-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Right Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-right-line.svg) */ export const ArrowLeftRightLineIcon: IconType = (props) => { return GenIcon(arrowLeftRightLine)(props); }; /** * The react component for the `arrow-left-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-s-line.svg) */ export const ArrowLeftSLineIcon: IconType = (props) => { return GenIcon(arrowLeftSLine)(props); }; /** * The react component for the `arrow-left-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-up-fill.svg) */ export const ArrowLeftUpFillIcon: IconType = (props) => { return GenIcon(arrowLeftUpFill)(props); }; /** * The react component for the `arrow-left-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Left Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-left-up-line.svg) */ export const ArrowLeftUpLineIcon: IconType = (props) => { return GenIcon(arrowLeftUpLine)(props); }; /** * The react component for the `arrow-right-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-circle-fill.svg) */ export const ArrowRightCircleFillIcon: IconType = (props) => { return GenIcon(arrowRightCircleFill)(props); }; /** * The react component for the `arrow-right-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-circle-line.svg) */ export const ArrowRightCircleLineIcon: IconType = (props) => { return GenIcon(arrowRightCircleLine)(props); }; /** * The react component for the `arrow-right-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-down-fill.svg) */ export const ArrowRightDownFillIcon: IconType = (props) => { return GenIcon(arrowRightDownFill)(props); }; /** * The react component for the `arrow-right-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-down-line.svg) */ export const ArrowRightDownLineIcon: IconType = (props) => { return GenIcon(arrowRightDownLine)(props); }; /** * The react component for the `arrow-right-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-fill.svg) */ export const ArrowRightFillIcon: IconType = (props) => { return GenIcon(arrowRightFill)(props); }; /** * The react component for the `arrow-right-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-line.svg) */ export const ArrowRightLineIcon: IconType = (props) => { return GenIcon(arrowRightLine)(props); }; /** * The react component for the `arrow-right-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-s-line.svg) */ export const ArrowRightSLineIcon: IconType = (props) => { return GenIcon(arrowRightSLine)(props); }; /** * The react component for the `arrow-right-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-up-fill.svg) */ export const ArrowRightUpFillIcon: IconType = (props) => { return GenIcon(arrowRightUpFill)(props); }; /** * The react component for the `arrow-right-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Right Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-right-up-line.svg) */ export const ArrowRightUpLineIcon: IconType = (props) => { return GenIcon(arrowRightUpLine)(props); }; /** * The react component for the `arrow-up-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-circle-fill.svg) */ export const ArrowUpCircleFillIcon: IconType = (props) => { return GenIcon(arrowUpCircleFill)(props); }; /** * The react component for the `arrow-up-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-circle-line.svg) */ export const ArrowUpCircleLineIcon: IconType = (props) => { return GenIcon(arrowUpCircleLine)(props); }; /** * The react component for the `arrow-up-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-down-fill.svg) */ export const ArrowUpDownFillIcon: IconType = (props) => { return GenIcon(arrowUpDownFill)(props); }; /** * The react component for the `arrow-up-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-down-line.svg) */ export const ArrowUpDownLineIcon: IconType = (props) => { return GenIcon(arrowUpDownLine)(props); }; /** * The react component for the `arrow-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-fill.svg) */ export const ArrowUpFillIcon: IconType = (props) => { return GenIcon(arrowUpFill)(props); }; /** * The react component for the `arrow-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-line.svg) */ export const ArrowUpLineIcon: IconType = (props) => { return GenIcon(arrowUpLine)(props); }; /** * The react component for the `arrow-up-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Arrow Up S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/arrow-up-s-line.svg) */ export const ArrowUpSLineIcon: IconType = (props) => { return GenIcon(arrowUpSLine)(props); }; /** * The react component for the `artboard-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Artboard 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/artboard-2-fill.svg) */ export const Artboard2FillIcon: IconType = (props) => { return GenIcon(artboard2Fill)(props); }; /** * The react component for the `artboard-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Artboard 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/artboard-2-line.svg) */ export const Artboard2LineIcon: IconType = (props) => { return GenIcon(artboard2Line)(props); }; /** * The react component for the `artboard-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Artboard Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/artboard-fill.svg) */ export const ArtboardFillIcon: IconType = (props) => { return GenIcon(artboardFill)(props); }; /** * The react component for the `artboard-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Artboard Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/artboard-line.svg) */ export const ArtboardLineIcon: IconType = (props) => { return GenIcon(artboardLine)(props); }; /** * The react component for the `article-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Article Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/article-fill.svg) */ export const ArticleFillIcon: IconType = (props) => { return GenIcon(articleFill)(props); }; /** * The react component for the `article-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Article Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/article-line.svg) */ export const ArticleLineIcon: IconType = (props) => { return GenIcon(articleLine)(props); }; /** * The react component for the `aspect-ratio-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Aspect Ratio Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/aspect-ratio-fill.svg) */ export const AspectRatioFillIcon: IconType = (props) => { return GenIcon(aspectRatioFill)(props); }; /** * The react component for the `aspect-ratio-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Aspect Ratio Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/aspect-ratio-line.svg) */ export const AspectRatioLineIcon: IconType = (props) => { return GenIcon(aspectRatioLine)(props); }; /** * The react component for the `at-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![At Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/at-fill.svg) */ export const AtFillIcon: IconType = (props) => { return GenIcon(atFill)(props); }; /** * The react component for the `at-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![At Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/at-line.svg) */ export const AtLineIcon: IconType = (props) => { return GenIcon(atLine)(props); }; /** * The react component for the `attachment-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Attachment Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/attachment-fill.svg) */ export const AttachmentFillIcon: IconType = (props) => { return GenIcon(attachmentFill)(props); }; /** * The react component for the `attachment-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Attachment Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/attachment-line.svg) */ export const AttachmentLineIcon: IconType = (props) => { return GenIcon(attachmentLine)(props); }; /** * The react component for the `auction-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Auction Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/auction-fill.svg) */ export const AuctionFillIcon: IconType = (props) => { return GenIcon(auctionFill)(props); }; /** * The react component for the `auction-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Auction Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/auction-line.svg) */ export const AuctionLineIcon: IconType = (props) => { return GenIcon(auctionLine)(props); }; /** * The react component for the `award-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Award Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/award-fill.svg) */ export const AwardFillIcon: IconType = (props) => { return GenIcon(awardFill)(props); }; /** * The react component for the `award-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Award Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/award-line.svg) */ export const AwardLineIcon: IconType = (props) => { return GenIcon(awardLine)(props); }; /** * The react component for the `baidu-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Baidu Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/baidu-fill.svg) */ export const BaiduFillIcon: IconType = (props) => { return GenIcon(baiduFill)(props); }; /** * The react component for the `baidu-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Baidu Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/baidu-line.svg) */ export const BaiduLineIcon: IconType = (props) => { return GenIcon(baiduLine)(props); }; /** * The react component for the `ball-pen-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ball Pen Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ball-pen-fill.svg) */ export const BallPenFillIcon: IconType = (props) => { return GenIcon(ballPenFill)(props); }; /** * The react component for the `ball-pen-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ball Pen Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ball-pen-line.svg) */ export const BallPenLineIcon: IconType = (props) => { return GenIcon(ballPenLine)(props); }; /** * The react component for the `bank-card-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Card 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bank-card-2-fill.svg) */ export const BankCard2FillIcon: IconType = (props) => { return GenIcon(bankCard2Fill)(props); }; /** * The react component for the `bank-card-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Card 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bank-card-2-line.svg) */ export const BankCard2LineIcon: IconType = (props) => { return GenIcon(bankCard2Line)(props); }; /** * The react component for the `bank-card-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Card Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bank-card-fill.svg) */ export const BankCardFillIcon: IconType = (props) => { return GenIcon(bankCardFill)(props); }; /** * The react component for the `bank-card-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Card Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bank-card-line.svg) */ export const BankCardLineIcon: IconType = (props) => { return GenIcon(bankCardLine)(props); }; /** * The react component for the `bank-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/bank-fill.svg) */ export const BankFillIcon: IconType = (props) => { return GenIcon(bankFill)(props); }; /** * The react component for the `bank-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bank Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/bank-line.svg) */ export const BankLineIcon: IconType = (props) => { return GenIcon(bankLine)(props); }; /** * The react component for the `bar-chart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-2-fill.svg) */ export const BarChart2FillIcon: IconType = (props) => { return GenIcon(barChart2Fill)(props); }; /** * The react component for the `bar-chart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-2-line.svg) */ export const BarChart2LineIcon: IconType = (props) => { return GenIcon(barChart2Line)(props); }; /** * The react component for the `bar-chart-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-box-fill.svg) */ export const BarChartBoxFillIcon: IconType = (props) => { return GenIcon(barChartBoxFill)(props); }; /** * The react component for the `bar-chart-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-box-line.svg) */ export const BarChartBoxLineIcon: IconType = (props) => { return GenIcon(barChartBoxLine)(props); }; /** * The react component for the `bar-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-fill.svg) */ export const BarChartFillIcon: IconType = (props) => { return GenIcon(barChartFill)(props); }; /** * The react component for the `bar-chart-grouped-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Grouped Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-grouped-fill.svg) */ export const BarChartGroupedFillIcon: IconType = (props) => { return GenIcon(barChartGroupedFill)(props); }; /** * The react component for the `bar-chart-grouped-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Grouped Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-grouped-line.svg) */ export const BarChartGroupedLineIcon: IconType = (props) => { return GenIcon(barChartGroupedLine)(props); }; /** * The react component for the `bar-chart-horizontal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Horizontal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-horizontal-fill.svg) */ export const BarChartHorizontalFillIcon: IconType = (props) => { return GenIcon(barChartHorizontalFill)(props); }; /** * The react component for the `bar-chart-horizontal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Horizontal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-horizontal-line.svg) */ export const BarChartHorizontalLineIcon: IconType = (props) => { return GenIcon(barChartHorizontalLine)(props); }; /** * The react component for the `bar-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bar Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bar-chart-line.svg) */ export const BarChartLineIcon: IconType = (props) => { return GenIcon(barChartLine)(props); }; /** * The react component for the `barcode-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barcode Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/barcode-box-fill.svg) */ export const BarcodeBoxFillIcon: IconType = (props) => { return GenIcon(barcodeBoxFill)(props); }; /** * The react component for the `barcode-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barcode Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/barcode-box-line.svg) */ export const BarcodeBoxLineIcon: IconType = (props) => { return GenIcon(barcodeBoxLine)(props); }; /** * The react component for the `barcode-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barcode Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/barcode-fill.svg) */ export const BarcodeFillIcon: IconType = (props) => { return GenIcon(barcodeFill)(props); }; /** * The react component for the `barcode-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barcode Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/barcode-line.svg) */ export const BarcodeLineIcon: IconType = (props) => { return GenIcon(barcodeLine)(props); }; /** * The react component for the `barricade-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barricade Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/barricade-fill.svg) */ export const BarricadeFillIcon: IconType = (props) => { return GenIcon(barricadeFill)(props); }; /** * The react component for the `barricade-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Barricade Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/barricade-line.svg) */ export const BarricadeLineIcon: IconType = (props) => { return GenIcon(barricadeLine)(props); }; /** * The react component for the `base-station-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Base Station Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/base-station-fill.svg) */ export const BaseStationFillIcon: IconType = (props) => { return GenIcon(baseStationFill)(props); }; /** * The react component for the `base-station-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Base Station Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/base-station-line.svg) */ export const BaseStationLineIcon: IconType = (props) => { return GenIcon(baseStationLine)(props); }; /** * The react component for the `basketball-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Basketball Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/basketball-fill.svg) */ export const BasketballFillIcon: IconType = (props) => { return GenIcon(basketballFill)(props); }; /** * The react component for the `basketball-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Basketball Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/basketball-line.svg) */ export const BasketballLineIcon: IconType = (props) => { return GenIcon(basketballLine)(props); }; /** * The react component for the `battery-2-charge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery 2 Charge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-2-charge-fill.svg) */ export const Battery2ChargeFillIcon: IconType = (props) => { return GenIcon(battery2ChargeFill)(props); }; /** * The react component for the `battery-2-charge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery 2 Charge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-2-charge-line.svg) */ export const Battery2ChargeLineIcon: IconType = (props) => { return GenIcon(battery2ChargeLine)(props); }; /** * The react component for the `battery-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-2-fill.svg) */ export const Battery2FillIcon: IconType = (props) => { return GenIcon(battery2Fill)(props); }; /** * The react component for the `battery-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-2-line.svg) */ export const Battery2LineIcon: IconType = (props) => { return GenIcon(battery2Line)(props); }; /** * The react component for the `battery-charge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Charge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-charge-fill.svg) */ export const BatteryChargeFillIcon: IconType = (props) => { return GenIcon(batteryChargeFill)(props); }; /** * The react component for the `battery-charge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Charge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-charge-line.svg) */ export const BatteryChargeLineIcon: IconType = (props) => { return GenIcon(batteryChargeLine)(props); }; /** * The react component for the `battery-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-fill.svg) */ export const BatteryFillIcon: IconType = (props) => { return GenIcon(batteryFill)(props); }; /** * The react component for the `battery-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-line.svg) */ export const BatteryLineIcon: IconType = (props) => { return GenIcon(batteryLine)(props); }; /** * The react component for the `battery-low-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Low Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-low-fill.svg) */ export const BatteryLowFillIcon: IconType = (props) => { return GenIcon(batteryLowFill)(props); }; /** * The react component for the `battery-low-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Low Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-low-line.svg) */ export const BatteryLowLineIcon: IconType = (props) => { return GenIcon(batteryLowLine)(props); }; /** * The react component for the `battery-saver-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Saver Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-saver-fill.svg) */ export const BatterySaverFillIcon: IconType = (props) => { return GenIcon(batterySaverFill)(props); }; /** * The react component for the `battery-saver-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Saver Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-saver-line.svg) */ export const BatterySaverLineIcon: IconType = (props) => { return GenIcon(batterySaverLine)(props); }; /** * The react component for the `battery-share-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Share Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-share-fill.svg) */ export const BatteryShareFillIcon: IconType = (props) => { return GenIcon(batteryShareFill)(props); }; /** * The react component for the `battery-share-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Battery Share Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/battery-share-line.svg) */ export const BatteryShareLineIcon: IconType = (props) => { return GenIcon(batteryShareLine)(props); }; /** * The react component for the `bear-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bear Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/bear-smile-fill.svg) */ export const BearSmileFillIcon: IconType = (props) => { return GenIcon(bearSmileFill)(props); }; /** * The react component for the `bear-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bear Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/bear-smile-line.svg) */ export const BearSmileLineIcon: IconType = (props) => { return GenIcon(bearSmileLine)(props); }; /** * The react component for the `behance-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Behance Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/behance-fill.svg) */ export const BehanceFillIcon: IconType = (props) => { return GenIcon(behanceFill)(props); }; /** * The react component for the `behance-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Behance Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/behance-line.svg) */ export const BehanceLineIcon: IconType = (props) => { return GenIcon(behanceLine)(props); }; /** * The react component for the `bell-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bell Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/bell-fill.svg) */ export const BellFillIcon: IconType = (props) => { return GenIcon(bellFill)(props); }; /** * The react component for the `bell-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bell Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/bell-line.svg) */ export const BellLineIcon: IconType = (props) => { return GenIcon(bellLine)(props); }; /** * The react component for the `bike-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bike Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bike-fill.svg) */ export const BikeFillIcon: IconType = (props) => { return GenIcon(bikeFill)(props); }; /** * The react component for the `bike-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bike Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bike-line.svg) */ export const BikeLineIcon: IconType = (props) => { return GenIcon(bikeLine)(props); }; /** * The react component for the `bilibili-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bilibili Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/bilibili-fill.svg) */ export const BilibiliFillIcon: IconType = (props) => { return GenIcon(bilibiliFill)(props); }; /** * The react component for the `bilibili-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bilibili Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/bilibili-line.svg) */ export const BilibiliLineIcon: IconType = (props) => { return GenIcon(bilibiliLine)(props); }; /** * The react component for the `bill-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bill Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/bill-fill.svg) */ export const BillFillIcon: IconType = (props) => { return GenIcon(billFill)(props); }; /** * The react component for the `bill-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bill Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/bill-line.svg) */ export const BillLineIcon: IconType = (props) => { return GenIcon(billLine)(props); }; /** * The react component for the `billiards-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Billiards Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/billiards-fill.svg) */ export const BilliardsFillIcon: IconType = (props) => { return GenIcon(billiardsFill)(props); }; /** * The react component for the `billiards-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Billiards Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/billiards-line.svg) */ export const BilliardsLineIcon: IconType = (props) => { return GenIcon(billiardsLine)(props); }; /** * The react component for the `bit-coin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bit Coin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bit-coin-fill.svg) */ export const BitCoinFillIcon: IconType = (props) => { return GenIcon(bitCoinFill)(props); }; /** * The react component for the `bit-coin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bit Coin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/bit-coin-line.svg) */ export const BitCoinLineIcon: IconType = (props) => { return GenIcon(bitCoinLine)(props); }; /** * The react component for the `blaze-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Blaze Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/blaze-fill.svg) */ export const BlazeFillIcon: IconType = (props) => { return GenIcon(blazeFill)(props); }; /** * The react component for the `blaze-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Blaze Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/blaze-line.svg) */ export const BlazeLineIcon: IconType = (props) => { return GenIcon(blazeLine)(props); }; /** * The react component for the `bluetooth-connect-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bluetooth Connect Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/bluetooth-connect-fill.svg) */ export const BluetoothConnectFillIcon: IconType = (props) => { return GenIcon(bluetoothConnectFill)(props); }; /** * The react component for the `bluetooth-connect-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bluetooth Connect Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/bluetooth-connect-line.svg) */ export const BluetoothConnectLineIcon: IconType = (props) => { return GenIcon(bluetoothConnectLine)(props); }; /** * The react component for the `bluetooth-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bluetooth Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/bluetooth-fill.svg) */ export const BluetoothFillIcon: IconType = (props) => { return GenIcon(bluetoothFill)(props); }; /** * The react component for the `bluetooth-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bluetooth Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/bluetooth-line.svg) */ export const BluetoothLineIcon: IconType = (props) => { return GenIcon(bluetoothLine)(props); }; /** * The react component for the `blur-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Blur Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/blur-off-fill.svg) */ export const BlurOffFillIcon: IconType = (props) => { return GenIcon(blurOffFill)(props); }; /** * The react component for the `blur-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Blur Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/blur-off-line.svg) */ export const BlurOffLineIcon: IconType = (props) => { return GenIcon(blurOffLine)(props); }; /** * The react component for the `body-scan-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Body Scan Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/body-scan-fill.svg) */ export const BodyScanFillIcon: IconType = (props) => { return GenIcon(bodyScanFill)(props); }; /** * The react component for the `body-scan-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Body Scan Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/body-scan-line.svg) */ export const BodyScanLineIcon: IconType = (props) => { return GenIcon(bodyScanLine)(props); }; /** * The react component for the `book-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-2-fill.svg) */ export const Book2FillIcon: IconType = (props) => { return GenIcon(book2Fill)(props); }; /** * The react component for the `book-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-2-line.svg) */ export const Book2LineIcon: IconType = (props) => { return GenIcon(book2Line)(props); }; /** * The react component for the `book-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-3-fill.svg) */ export const Book3FillIcon: IconType = (props) => { return GenIcon(book3Fill)(props); }; /** * The react component for the `book-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-3-line.svg) */ export const Book3LineIcon: IconType = (props) => { return GenIcon(book3Line)(props); }; /** * The react component for the `book-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-fill.svg) */ export const BookFillIcon: IconType = (props) => { return GenIcon(bookFill)(props); }; /** * The react component for the `book-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-line.svg) */ export const BookLineIcon: IconType = (props) => { return GenIcon(bookLine)(props); }; /** * The react component for the `book-mark-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Mark Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-mark-fill.svg) */ export const BookMarkFillIcon: IconType = (props) => { return GenIcon(bookMarkFill)(props); }; /** * The react component for the `book-mark-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Mark Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-mark-line.svg) */ export const BookMarkLineIcon: IconType = (props) => { return GenIcon(bookMarkLine)(props); }; /** * The react component for the `book-open-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Open Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-open-fill.svg) */ export const BookOpenFillIcon: IconType = (props) => { return GenIcon(bookOpenFill)(props); }; /** * The react component for the `book-open-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Open Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-open-line.svg) */ export const BookOpenLineIcon: IconType = (props) => { return GenIcon(bookOpenLine)(props); }; /** * The react component for the `book-read-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Read Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-read-fill.svg) */ export const BookReadFillIcon: IconType = (props) => { return GenIcon(bookReadFill)(props); }; /** * The react component for the `book-read-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Book Read Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/book-read-line.svg) */ export const BookReadLineIcon: IconType = (props) => { return GenIcon(bookReadLine)(props); }; /** * The react component for the `booklet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Booklet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/booklet-fill.svg) */ export const BookletFillIcon: IconType = (props) => { return GenIcon(bookletFill)(props); }; /** * The react component for the `booklet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Booklet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/booklet-line.svg) */ export const BookletLineIcon: IconType = (props) => { return GenIcon(bookletLine)(props); }; /** * The react component for the `bookmark-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-2-fill.svg) */ export const Bookmark2FillIcon: IconType = (props) => { return GenIcon(bookmark2Fill)(props); }; /** * The react component for the `bookmark-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-2-line.svg) */ export const Bookmark2LineIcon: IconType = (props) => { return GenIcon(bookmark2Line)(props); }; /** * The react component for the `bookmark-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-3-fill.svg) */ export const Bookmark3FillIcon: IconType = (props) => { return GenIcon(bookmark3Fill)(props); }; /** * The react component for the `bookmark-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-3-line.svg) */ export const Bookmark3LineIcon: IconType = (props) => { return GenIcon(bookmark3Line)(props); }; /** * The react component for the `bookmark-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-fill.svg) */ export const BookmarkFillIcon: IconType = (props) => { return GenIcon(bookmarkFill)(props); }; /** * The react component for the `bookmark-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bookmark Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bookmark-line.svg) */ export const BookmarkLineIcon: IconType = (props) => { return GenIcon(bookmarkLine)(props); }; /** * The react component for the `boxing-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Boxing Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/boxing-fill.svg) */ export const BoxingFillIcon: IconType = (props) => { return GenIcon(boxingFill)(props); }; /** * The react component for the `boxing-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Boxing Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/boxing-line.svg) */ export const BoxingLineIcon: IconType = (props) => { return GenIcon(boxingLine)(props); }; /** * The react component for the `braces-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Braces Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/braces-fill.svg) */ export const BracesFillIcon: IconType = (props) => { return GenIcon(bracesFill)(props); }; /** * The react component for the `brackets-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brackets Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/brackets-fill.svg) */ export const BracketsFillIcon: IconType = (props) => { return GenIcon(bracketsFill)(props); }; /** * The react component for the `brackets-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brackets Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/brackets-line.svg) */ export const BracketsLineIcon: IconType = (props) => { return GenIcon(bracketsLine)(props); }; /** * The react component for the `briefcase-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-2-fill.svg) */ export const Briefcase2FillIcon: IconType = (props) => { return GenIcon(briefcase2Fill)(props); }; /** * The react component for the `briefcase-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-2-line.svg) */ export const Briefcase2LineIcon: IconType = (props) => { return GenIcon(briefcase2Line)(props); }; /** * The react component for the `briefcase-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-3-fill.svg) */ export const Briefcase3FillIcon: IconType = (props) => { return GenIcon(briefcase3Fill)(props); }; /** * The react component for the `briefcase-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-3-line.svg) */ export const Briefcase3LineIcon: IconType = (props) => { return GenIcon(briefcase3Line)(props); }; /** * The react component for the `briefcase-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-4-fill.svg) */ export const Briefcase4FillIcon: IconType = (props) => { return GenIcon(briefcase4Fill)(props); }; /** * The react component for the `briefcase-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-4-line.svg) */ export const Briefcase4LineIcon: IconType = (props) => { return GenIcon(briefcase4Line)(props); }; /** * The react component for the `briefcase-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-5-fill.svg) */ export const Briefcase5FillIcon: IconType = (props) => { return GenIcon(briefcase5Fill)(props); }; /** * The react component for the `briefcase-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-5-line.svg) */ export const Briefcase5LineIcon: IconType = (props) => { return GenIcon(briefcase5Line)(props); }; /** * The react component for the `briefcase-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-fill.svg) */ export const BriefcaseFillIcon: IconType = (props) => { return GenIcon(briefcaseFill)(props); }; /** * The react component for the `briefcase-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Briefcase Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/briefcase-line.svg) */ export const BriefcaseLineIcon: IconType = (props) => { return GenIcon(briefcaseLine)(props); }; /** * The react component for the `broadcast-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Broadcast Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/broadcast-fill.svg) */ export const BroadcastFillIcon: IconType = (props) => { return GenIcon(broadcastFill)(props); }; /** * The react component for the `broadcast-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Broadcast Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/broadcast-line.svg) */ export const BroadcastLineIcon: IconType = (props) => { return GenIcon(broadcastLine)(props); }; /** * The react component for the `brush-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-2-fill.svg) */ export const Brush2FillIcon: IconType = (props) => { return GenIcon(brush2Fill)(props); }; /** * The react component for the `brush-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-2-line.svg) */ export const Brush2LineIcon: IconType = (props) => { return GenIcon(brush2Line)(props); }; /** * The react component for the `brush-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-3-fill.svg) */ export const Brush3FillIcon: IconType = (props) => { return GenIcon(brush3Fill)(props); }; /** * The react component for the `brush-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-3-line.svg) */ export const Brush3LineIcon: IconType = (props) => { return GenIcon(brush3Line)(props); }; /** * The react component for the `brush-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-4-fill.svg) */ export const Brush4FillIcon: IconType = (props) => { return GenIcon(brush4Fill)(props); }; /** * The react component for the `brush-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-4-line.svg) */ export const Brush4LineIcon: IconType = (props) => { return GenIcon(brush4Line)(props); }; /** * The react component for the `brush-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-fill.svg) */ export const BrushFillIcon: IconType = (props) => { return GenIcon(brushFill)(props); }; /** * The react component for the `brush-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Brush Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/brush-line.svg) */ export const BrushLineIcon: IconType = (props) => { return GenIcon(brushLine)(props); }; /** * The react component for the `bubble-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bubble Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bubble-chart-fill.svg) */ export const BubbleChartFillIcon: IconType = (props) => { return GenIcon(bubbleChartFill)(props); }; /** * The react component for the `bubble-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bubble Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/bubble-chart-line.svg) */ export const BubbleChartLineIcon: IconType = (props) => { return GenIcon(bubbleChartLine)(props); }; /** * The react component for the `bug-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bug 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/bug-2-fill.svg) */ export const Bug2FillIcon: IconType = (props) => { return GenIcon(bug2Fill)(props); }; /** * The react component for the `bug-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bug 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/bug-2-line.svg) */ export const Bug2LineIcon: IconType = (props) => { return GenIcon(bug2Line)(props); }; /** * The react component for the `bug-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bug Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/bug-fill.svg) */ export const BugFillIcon: IconType = (props) => { return GenIcon(bugFill)(props); }; /** * The react component for the `bug-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bug Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/bug-line.svg) */ export const BugLineIcon: IconType = (props) => { return GenIcon(bugLine)(props); }; /** * The react component for the `building-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-2-fill.svg) */ export const Building2FillIcon: IconType = (props) => { return GenIcon(building2Fill)(props); }; /** * The react component for the `building-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-2-line.svg) */ export const Building2LineIcon: IconType = (props) => { return GenIcon(building2Line)(props); }; /** * The react component for the `building-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-3-fill.svg) */ export const Building3FillIcon: IconType = (props) => { return GenIcon(building3Fill)(props); }; /** * The react component for the `building-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-3-line.svg) */ export const Building3LineIcon: IconType = (props) => { return GenIcon(building3Line)(props); }; /** * The react component for the `building-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-4-fill.svg) */ export const Building4FillIcon: IconType = (props) => { return GenIcon(building4Fill)(props); }; /** * The react component for the `building-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-4-line.svg) */ export const Building4LineIcon: IconType = (props) => { return GenIcon(building4Line)(props); }; /** * The react component for the `building-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-fill.svg) */ export const BuildingFillIcon: IconType = (props) => { return GenIcon(buildingFill)(props); }; /** * The react component for the `building-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Building Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/building-line.svg) */ export const BuildingLineIcon: IconType = (props) => { return GenIcon(buildingLine)(props); }; /** * The react component for the `bus-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-2-fill.svg) */ export const Bus2FillIcon: IconType = (props) => { return GenIcon(bus2Fill)(props); }; /** * The react component for the `bus-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-2-line.svg) */ export const Bus2LineIcon: IconType = (props) => { return GenIcon(bus2Line)(props); }; /** * The react component for the `bus-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-fill.svg) */ export const BusFillIcon: IconType = (props) => { return GenIcon(busFill)(props); }; /** * The react component for the `bus-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-line.svg) */ export const BusLineIcon: IconType = (props) => { return GenIcon(busLine)(props); }; /** * The react component for the `bus-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-wifi-fill.svg) */ export const BusWifiFillIcon: IconType = (props) => { return GenIcon(busWifiFill)(props); }; /** * The react component for the `bus-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Bus Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/bus-wifi-line.svg) */ export const BusWifiLineIcon: IconType = (props) => { return GenIcon(busWifiLine)(props); }; /** * The react component for the `cactus-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cactus Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cactus-fill.svg) */ export const CactusFillIcon: IconType = (props) => { return GenIcon(cactusFill)(props); }; /** * The react component for the `cactus-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cactus Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cactus-line.svg) */ export const CactusLineIcon: IconType = (props) => { return GenIcon(cactusLine)(props); }; /** * The react component for the `cake-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-2-fill.svg) */ export const Cake2FillIcon: IconType = (props) => { return GenIcon(cake2Fill)(props); }; /** * The react component for the `cake-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-2-line.svg) */ export const Cake2LineIcon: IconType = (props) => { return GenIcon(cake2Line)(props); }; /** * The react component for the `cake-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-3-fill.svg) */ export const Cake3FillIcon: IconType = (props) => { return GenIcon(cake3Fill)(props); }; /** * The react component for the `cake-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-3-line.svg) */ export const Cake3LineIcon: IconType = (props) => { return GenIcon(cake3Line)(props); }; /** * The react component for the `cake-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-fill.svg) */ export const CakeFillIcon: IconType = (props) => { return GenIcon(cakeFill)(props); }; /** * The react component for the `cake-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cake Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/cake-line.svg) */ export const CakeLineIcon: IconType = (props) => { return GenIcon(cakeLine)(props); }; /** * The react component for the `calculator-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calculator Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calculator-fill.svg) */ export const CalculatorFillIcon: IconType = (props) => { return GenIcon(calculatorFill)(props); }; /** * The react component for the `calculator-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calculator Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calculator-line.svg) */ export const CalculatorLineIcon: IconType = (props) => { return GenIcon(calculatorLine)(props); }; /** * The react component for the `calendar-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-2-fill.svg) */ export const Calendar2FillIcon: IconType = (props) => { return GenIcon(calendar2Fill)(props); }; /** * The react component for the `calendar-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-2-line.svg) */ export const Calendar2LineIcon: IconType = (props) => { return GenIcon(calendar2Line)(props); }; /** * The react component for the `calendar-check-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Check Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-check-fill.svg) */ export const CalendarCheckFillIcon: IconType = (props) => { return GenIcon(calendarCheckFill)(props); }; /** * The react component for the `calendar-check-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Check Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-check-line.svg) */ export const CalendarCheckLineIcon: IconType = (props) => { return GenIcon(calendarCheckLine)(props); }; /** * The react component for the `calendar-event-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Event Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-event-fill.svg) */ export const CalendarEventFillIcon: IconType = (props) => { return GenIcon(calendarEventFill)(props); }; /** * The react component for the `calendar-event-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Event Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-event-line.svg) */ export const CalendarEventLineIcon: IconType = (props) => { return GenIcon(calendarEventLine)(props); }; /** * The react component for the `calendar-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-fill.svg) */ export const CalendarFillIcon: IconType = (props) => { return GenIcon(calendarFill)(props); }; /** * The react component for the `calendar-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-line.svg) */ export const CalendarLineIcon: IconType = (props) => { return GenIcon(calendarLine)(props); }; /** * The react component for the `calendar-todo-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Todo Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-todo-fill.svg) */ export const CalendarTodoFillIcon: IconType = (props) => { return GenIcon(calendarTodoFill)(props); }; /** * The react component for the `calendar-todo-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Calendar Todo Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/calendar-todo-line.svg) */ export const CalendarTodoLineIcon: IconType = (props) => { return GenIcon(calendarTodoLine)(props); }; /** * The react component for the `camera-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-2-fill.svg) */ export const Camera2FillIcon: IconType = (props) => { return GenIcon(camera2Fill)(props); }; /** * The react component for the `camera-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-2-line.svg) */ export const Camera2LineIcon: IconType = (props) => { return GenIcon(camera2Line)(props); }; /** * The react component for the `camera-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-3-fill.svg) */ export const Camera3FillIcon: IconType = (props) => { return GenIcon(camera3Fill)(props); }; /** * The react component for the `camera-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-3-line.svg) */ export const Camera3LineIcon: IconType = (props) => { return GenIcon(camera3Line)(props); }; /** * The react component for the `camera-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-fill.svg) */ export const CameraFillIcon: IconType = (props) => { return GenIcon(cameraFill)(props); }; /** * The react component for the `camera-lens-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Lens Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-lens-fill.svg) */ export const CameraLensFillIcon: IconType = (props) => { return GenIcon(cameraLensFill)(props); }; /** * The react component for the `camera-lens-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Lens Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-lens-line.svg) */ export const CameraLensLineIcon: IconType = (props) => { return GenIcon(cameraLensLine)(props); }; /** * The react component for the `camera-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-line.svg) */ export const CameraLineIcon: IconType = (props) => { return GenIcon(cameraLine)(props); }; /** * The react component for the `camera-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-off-fill.svg) */ export const CameraOffFillIcon: IconType = (props) => { return GenIcon(cameraOffFill)(props); }; /** * The react component for the `camera-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-off-line.svg) */ export const CameraOffLineIcon: IconType = (props) => { return GenIcon(cameraOffLine)(props); }; /** * The react component for the `camera-switch-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Switch Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-switch-fill.svg) */ export const CameraSwitchFillIcon: IconType = (props) => { return GenIcon(cameraSwitchFill)(props); }; /** * The react component for the `camera-switch-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Camera Switch Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/camera-switch-line.svg) */ export const CameraSwitchLineIcon: IconType = (props) => { return GenIcon(cameraSwitchLine)(props); }; /** * The react component for the `capsule-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Capsule Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/capsule-fill.svg) */ export const CapsuleFillIcon: IconType = (props) => { return GenIcon(capsuleFill)(props); }; /** * The react component for the `capsule-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Capsule Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/capsule-line.svg) */ export const CapsuleLineIcon: IconType = (props) => { return GenIcon(capsuleLine)(props); }; /** * The react component for the `car-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Car Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/car-fill.svg) */ export const CarFillIcon: IconType = (props) => { return GenIcon(carFill)(props); }; /** * The react component for the `car-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Car Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/car-line.svg) */ export const CarLineIcon: IconType = (props) => { return GenIcon(carLine)(props); }; /** * The react component for the `car-washing-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Car Washing Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/car-washing-fill.svg) */ export const CarWashingFillIcon: IconType = (props) => { return GenIcon(carWashingFill)(props); }; /** * The react component for the `car-washing-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Car Washing Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/car-washing-line.svg) */ export const CarWashingLineIcon: IconType = (props) => { return GenIcon(carWashingLine)(props); }; /** * The react component for the `caravan-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Caravan Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/caravan-fill.svg) */ export const CaravanFillIcon: IconType = (props) => { return GenIcon(caravanFill)(props); }; /** * The react component for the `caravan-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Caravan Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/caravan-line.svg) */ export const CaravanLineIcon: IconType = (props) => { return GenIcon(caravanLine)(props); }; /** * The react component for the `cast-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cast Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cast-fill.svg) */ export const CastFillIcon: IconType = (props) => { return GenIcon(castFill)(props); }; /** * The react component for the `cast-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cast Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cast-line.svg) */ export const CastLineIcon: IconType = (props) => { return GenIcon(castLine)(props); }; /** * The react component for the `cellphone-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cellphone Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cellphone-fill.svg) */ export const CellphoneFillIcon: IconType = (props) => { return GenIcon(cellphoneFill)(props); }; /** * The react component for the `cellphone-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cellphone Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cellphone-line.svg) */ export const CellphoneLineIcon: IconType = (props) => { return GenIcon(cellphoneLine)(props); }; /** * The react component for the `celsius-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Celsius Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/celsius-fill.svg) */ export const CelsiusFillIcon: IconType = (props) => { return GenIcon(celsiusFill)(props); }; /** * The react component for the `celsius-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Celsius Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/celsius-line.svg) */ export const CelsiusLineIcon: IconType = (props) => { return GenIcon(celsiusLine)(props); }; /** * The react component for the `centos-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Centos Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/centos-fill.svg) */ export const CentosFillIcon: IconType = (props) => { return GenIcon(centosFill)(props); }; /** * The react component for the `centos-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Centos Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/centos-line.svg) */ export const CentosLineIcon: IconType = (props) => { return GenIcon(centosLine)(props); }; /** * The react component for the `character-recognition-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Character Recognition Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/character-recognition-fill.svg) */ export const CharacterRecognitionFillIcon: IconType = (props) => { return GenIcon(characterRecognitionFill)(props); }; /** * The react component for the `character-recognition-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Character Recognition Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/character-recognition-line.svg) */ export const CharacterRecognitionLineIcon: IconType = (props) => { return GenIcon(characterRecognitionLine)(props); }; /** * The react component for the `charging-pile-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Charging Pile 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/charging-pile-2-fill.svg) */ export const ChargingPile2FillIcon: IconType = (props) => { return GenIcon(chargingPile2Fill)(props); }; /** * The react component for the `charging-pile-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Charging Pile 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/charging-pile-2-line.svg) */ export const ChargingPile2LineIcon: IconType = (props) => { return GenIcon(chargingPile2Line)(props); }; /** * The react component for the `charging-pile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Charging Pile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/charging-pile-fill.svg) */ export const ChargingPileFillIcon: IconType = (props) => { return GenIcon(chargingPileFill)(props); }; /** * The react component for the `charging-pile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Charging Pile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/charging-pile-line.svg) */ export const ChargingPileLineIcon: IconType = (props) => { return GenIcon(chargingPileLine)(props); }; /** * The react component for the `chat-1-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 1 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-1-fill.svg) */ export const Chat1FillIcon: IconType = (props) => { return GenIcon(chat1Fill)(props); }; /** * The react component for the `chat-1-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 1 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-1-line.svg) */ export const Chat1LineIcon: IconType = (props) => { return GenIcon(chat1Line)(props); }; /** * The react component for the `chat-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-2-fill.svg) */ export const Chat2FillIcon: IconType = (props) => { return GenIcon(chat2Fill)(props); }; /** * The react component for the `chat-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-2-line.svg) */ export const Chat2LineIcon: IconType = (props) => { return GenIcon(chat2Line)(props); }; /** * The react component for the `chat-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-3-fill.svg) */ export const Chat3FillIcon: IconType = (props) => { return GenIcon(chat3Fill)(props); }; /** * The react component for the `chat-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-3-line.svg) */ export const Chat3LineIcon: IconType = (props) => { return GenIcon(chat3Line)(props); }; /** * The react component for the `chat-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-4-fill.svg) */ export const Chat4FillIcon: IconType = (props) => { return GenIcon(chat4Fill)(props); }; /** * The react component for the `chat-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-4-line.svg) */ export const Chat4LineIcon: IconType = (props) => { return GenIcon(chat4Line)(props); }; /** * The react component for the `chat-check-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Check Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-check-fill.svg) */ export const ChatCheckFillIcon: IconType = (props) => { return GenIcon(chatCheckFill)(props); }; /** * The react component for the `chat-check-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Check Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-check-line.svg) */ export const ChatCheckLineIcon: IconType = (props) => { return GenIcon(chatCheckLine)(props); }; /** * The react component for the `chat-delete-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Delete Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-delete-fill.svg) */ export const ChatDeleteFillIcon: IconType = (props) => { return GenIcon(chatDeleteFill)(props); }; /** * The react component for the `chat-delete-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Delete Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-delete-line.svg) */ export const ChatDeleteLineIcon: IconType = (props) => { return GenIcon(chatDeleteLine)(props); }; /** * The react component for the `chat-download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-download-fill.svg) */ export const ChatDownloadFillIcon: IconType = (props) => { return GenIcon(chatDownloadFill)(props); }; /** * The react component for the `chat-download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-download-line.svg) */ export const ChatDownloadLineIcon: IconType = (props) => { return GenIcon(chatDownloadLine)(props); }; /** * The react component for the `chat-follow-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Follow Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-follow-up-fill.svg) */ export const ChatFollowUpFillIcon: IconType = (props) => { return GenIcon(chatFollowUpFill)(props); }; /** * The react component for the `chat-follow-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Follow Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-follow-up-line.svg) */ export const ChatFollowUpLineIcon: IconType = (props) => { return GenIcon(chatFollowUpLine)(props); }; /** * The react component for the `chat-forward-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Forward Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-forward-fill.svg) */ export const ChatForwardFillIcon: IconType = (props) => { return GenIcon(chatForwardFill)(props); }; /** * The react component for the `chat-forward-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Forward Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-forward-line.svg) */ export const ChatForwardLineIcon: IconType = (props) => { return GenIcon(chatForwardLine)(props); }; /** * The react component for the `chat-heart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Heart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-heart-fill.svg) */ export const ChatHeartFillIcon: IconType = (props) => { return GenIcon(chatHeartFill)(props); }; /** * The react component for the `chat-heart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Heart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-heart-line.svg) */ export const ChatHeartLineIcon: IconType = (props) => { return GenIcon(chatHeartLine)(props); }; /** * The react component for the `chat-history-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat History Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-history-fill.svg) */ export const ChatHistoryFillIcon: IconType = (props) => { return GenIcon(chatHistoryFill)(props); }; /** * The react component for the `chat-history-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat History Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-history-line.svg) */ export const ChatHistoryLineIcon: IconType = (props) => { return GenIcon(chatHistoryLine)(props); }; /** * The react component for the `chat-new-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat New Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-new-fill.svg) */ export const ChatNewFillIcon: IconType = (props) => { return GenIcon(chatNewFill)(props); }; /** * The react component for the `chat-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-off-fill.svg) */ export const ChatOffFillIcon: IconType = (props) => { return GenIcon(chatOffFill)(props); }; /** * The react component for the `chat-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-off-line.svg) */ export const ChatOffLineIcon: IconType = (props) => { return GenIcon(chatOffLine)(props); }; /** * The react component for the `chat-poll-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Poll Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-poll-fill.svg) */ export const ChatPollFillIcon: IconType = (props) => { return GenIcon(chatPollFill)(props); }; /** * The react component for the `chat-poll-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Poll Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-poll-line.svg) */ export const ChatPollLineIcon: IconType = (props) => { return GenIcon(chatPollLine)(props); }; /** * The react component for the `chat-private-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Private Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-private-fill.svg) */ export const ChatPrivateFillIcon: IconType = (props) => { return GenIcon(chatPrivateFill)(props); }; /** * The react component for the `chat-private-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Private Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-private-line.svg) */ export const ChatPrivateLineIcon: IconType = (props) => { return GenIcon(chatPrivateLine)(props); }; /** * The react component for the `chat-quote-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Quote Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-quote-fill.svg) */ export const ChatQuoteFillIcon: IconType = (props) => { return GenIcon(chatQuoteFill)(props); }; /** * The react component for the `chat-quote-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Quote Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-quote-line.svg) */ export const ChatQuoteLineIcon: IconType = (props) => { return GenIcon(chatQuoteLine)(props); }; /** * The react component for the `chat-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-settings-fill.svg) */ export const ChatSettingsFillIcon: IconType = (props) => { return GenIcon(chatSettingsFill)(props); }; /** * The react component for the `chat-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-settings-line.svg) */ export const ChatSettingsLineIcon: IconType = (props) => { return GenIcon(chatSettingsLine)(props); }; /** * The react component for the `chat-smile-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-2-fill.svg) */ export const ChatSmile2FillIcon: IconType = (props) => { return GenIcon(chatSmile2Fill)(props); }; /** * The react component for the `chat-smile-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-2-line.svg) */ export const ChatSmile2LineIcon: IconType = (props) => { return GenIcon(chatSmile2Line)(props); }; /** * The react component for the `chat-smile-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-3-fill.svg) */ export const ChatSmile3FillIcon: IconType = (props) => { return GenIcon(chatSmile3Fill)(props); }; /** * The react component for the `chat-smile-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-3-line.svg) */ export const ChatSmile3LineIcon: IconType = (props) => { return GenIcon(chatSmile3Line)(props); }; /** * The react component for the `chat-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-fill.svg) */ export const ChatSmileFillIcon: IconType = (props) => { return GenIcon(chatSmileFill)(props); }; /** * The react component for the `chat-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-smile-line.svg) */ export const ChatSmileLineIcon: IconType = (props) => { return GenIcon(chatSmileLine)(props); }; /** * The react component for the `chat-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-upload-fill.svg) */ export const ChatUploadFillIcon: IconType = (props) => { return GenIcon(chatUploadFill)(props); }; /** * The react component for the `chat-upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-upload-line.svg) */ export const ChatUploadLineIcon: IconType = (props) => { return GenIcon(chatUploadLine)(props); }; /** * The react component for the `chat-voice-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Voice Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-voice-fill.svg) */ export const ChatVoiceFillIcon: IconType = (props) => { return GenIcon(chatVoiceFill)(props); }; /** * The react component for the `chat-voice-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chat Voice Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/chat-voice-line.svg) */ export const ChatVoiceLineIcon: IconType = (props) => { return GenIcon(chatVoiceLine)(props); }; /** * The react component for the `check-double-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Check Double Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/check-double-fill.svg) */ export const CheckDoubleFillIcon: IconType = (props) => { return GenIcon(checkDoubleFill)(props); }; /** * The react component for the `check-double-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Check Double Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/check-double-line.svg) */ export const CheckDoubleLineIcon: IconType = (props) => { return GenIcon(checkDoubleLine)(props); }; /** * The react component for the `check-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Check Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/check-fill.svg) */ export const CheckFillIcon: IconType = (props) => { return GenIcon(checkFill)(props); }; /** * The react component for the `check-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Check Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/check-line.svg) */ export const CheckLineIcon: IconType = (props) => { return GenIcon(checkLine)(props); }; /** * The react component for the `checkbox-blank-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Blank Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-blank-circle-fill.svg) */ export const CheckboxBlankCircleFillIcon: IconType = (props) => { return GenIcon(checkboxBlankCircleFill)(props); }; /** * The react component for the `checkbox-blank-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Blank Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-blank-circle-line.svg) */ export const CheckboxBlankCircleLineIcon: IconType = (props) => { return GenIcon(checkboxBlankCircleLine)(props); }; /** * The react component for the `checkbox-blank-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Blank Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-blank-fill.svg) */ export const CheckboxBlankFillIcon: IconType = (props) => { return GenIcon(checkboxBlankFill)(props); }; /** * The react component for the `checkbox-blank-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Blank Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-blank-line.svg) */ export const CheckboxBlankLineIcon: IconType = (props) => { return GenIcon(checkboxBlankLine)(props); }; /** * The react component for the `checkbox-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-circle-fill.svg) */ export const CheckboxCircleFillIcon: IconType = (props) => { return GenIcon(checkboxCircleFill)(props); }; /** * The react component for the `checkbox-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-fill.svg) */ export const CheckboxFillIcon: IconType = (props) => { return GenIcon(checkboxFill)(props); }; /** * The react component for the `checkbox-indeterminate-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Indeterminate Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-indeterminate-fill.svg) */ export const CheckboxIndeterminateFillIcon: IconType = (props) => { return GenIcon(checkboxIndeterminateFill)(props); }; /** * The react component for the `checkbox-indeterminate-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Indeterminate Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-indeterminate-line.svg) */ export const CheckboxIndeterminateLineIcon: IconType = (props) => { return GenIcon(checkboxIndeterminateLine)(props); }; /** * The react component for the `checkbox-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-line.svg) */ export const CheckboxLineIcon: IconType = (props) => { return GenIcon(checkboxLine)(props); }; /** * The react component for the `checkbox-multiple-blank-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Multiple Blank Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-multiple-blank-fill.svg) */ export const CheckboxMultipleBlankFillIcon: IconType = (props) => { return GenIcon(checkboxMultipleBlankFill)(props); }; /** * The react component for the `checkbox-multiple-blank-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Multiple Blank Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-multiple-blank-line.svg) */ export const CheckboxMultipleBlankLineIcon: IconType = (props) => { return GenIcon(checkboxMultipleBlankLine)(props); }; /** * The react component for the `checkbox-multiple-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Multiple Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-multiple-fill.svg) */ export const CheckboxMultipleFillIcon: IconType = (props) => { return GenIcon(checkboxMultipleFill)(props); }; /** * The react component for the `checkbox-multiple-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Checkbox Multiple Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/checkbox-multiple-line.svg) */ export const CheckboxMultipleLineIcon: IconType = (props) => { return GenIcon(checkboxMultipleLine)(props); }; /** * The react component for the `china-railway-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![China Railway Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/china-railway-fill.svg) */ export const ChinaRailwayFillIcon: IconType = (props) => { return GenIcon(chinaRailwayFill)(props); }; /** * The react component for the `china-railway-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![China Railway Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/china-railway-line.svg) */ export const ChinaRailwayLineIcon: IconType = (props) => { return GenIcon(chinaRailwayLine)(props); }; /** * The react component for the `chrome-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chrome Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/chrome-fill.svg) */ export const ChromeFillIcon: IconType = (props) => { return GenIcon(chromeFill)(props); }; /** * The react component for the `chrome-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Chrome Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/chrome-line.svg) */ export const ChromeLineIcon: IconType = (props) => { return GenIcon(chromeLine)(props); }; /** * The react component for the `clapperboard-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clapperboard Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/clapperboard-fill.svg) */ export const ClapperboardFillIcon: IconType = (props) => { return GenIcon(clapperboardFill)(props); }; /** * The react component for the `clapperboard-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clapperboard Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/clapperboard-line.svg) */ export const ClapperboardLineIcon: IconType = (props) => { return GenIcon(clapperboardLine)(props); }; /** * The react component for the `clockwise-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clockwise 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/clockwise-2-fill.svg) */ export const Clockwise2FillIcon: IconType = (props) => { return GenIcon(clockwise2Fill)(props); }; /** * The react component for the `clockwise-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clockwise 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/clockwise-2-line.svg) */ export const Clockwise2LineIcon: IconType = (props) => { return GenIcon(clockwise2Line)(props); }; /** * The react component for the `clockwise-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clockwise Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/clockwise-fill.svg) */ export const ClockwiseFillIcon: IconType = (props) => { return GenIcon(clockwiseFill)(props); }; /** * The react component for the `clockwise-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Clockwise Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/clockwise-line.svg) */ export const ClockwiseLineIcon: IconType = (props) => { return GenIcon(clockwiseLine)(props); }; /** * The react component for the `close-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Close Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/close-circle-fill.svg) */ export const CloseCircleFillIcon: IconType = (props) => { return GenIcon(closeCircleFill)(props); }; /** * The react component for the `closed-captioning-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Closed Captioning Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/closed-captioning-fill.svg) */ export const ClosedCaptioningFillIcon: IconType = (props) => { return GenIcon(closedCaptioningFill)(props); }; /** * The react component for the `closed-captioning-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Closed Captioning Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/closed-captioning-line.svg) */ export const ClosedCaptioningLineIcon: IconType = (props) => { return GenIcon(closedCaptioningLine)(props); }; /** * The react component for the `cloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/cloud-fill.svg) */ export const CloudFillIcon: IconType = (props) => { return GenIcon(cloudFill)(props); }; /** * The react component for the `cloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/cloud-line.svg) */ export const CloudLineIcon: IconType = (props) => { return GenIcon(cloudLine)(props); }; /** * The react component for the `cloud-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/cloud-off-fill.svg) */ export const CloudOffFillIcon: IconType = (props) => { return GenIcon(cloudOffFill)(props); }; /** * The react component for the `cloud-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/cloud-off-line.svg) */ export const CloudOffLineIcon: IconType = (props) => { return GenIcon(cloudOffLine)(props); }; /** * The react component for the `cloud-windy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Windy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloud-windy-fill.svg) */ export const CloudWindyFillIcon: IconType = (props) => { return GenIcon(cloudWindyFill)(props); }; /** * The react component for the `cloud-windy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloud Windy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloud-windy-line.svg) */ export const CloudWindyLineIcon: IconType = (props) => { return GenIcon(cloudWindyLine)(props); }; /** * The react component for the `cloudy-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloudy 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloudy-2-fill.svg) */ export const Cloudy2FillIcon: IconType = (props) => { return GenIcon(cloudy2Fill)(props); }; /** * The react component for the `cloudy-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloudy 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloudy-2-line.svg) */ export const Cloudy2LineIcon: IconType = (props) => { return GenIcon(cloudy2Line)(props); }; /** * The react component for the `cloudy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloudy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloudy-fill.svg) */ export const CloudyFillIcon: IconType = (props) => { return GenIcon(cloudyFill)(props); }; /** * The react component for the `cloudy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cloudy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/cloudy-line.svg) */ export const CloudyLineIcon: IconType = (props) => { return GenIcon(cloudyLine)(props); }; /** * The react component for the `code-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-box-fill.svg) */ export const CodeBoxFillIcon: IconType = (props) => { return GenIcon(codeBoxFill)(props); }; /** * The react component for the `code-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-box-line.svg) */ export const CodeBoxLineIcon: IconType = (props) => { return GenIcon(codeBoxLine)(props); }; /** * The react component for the `code-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-fill.svg) */ export const CodeFillIcon: IconType = (props) => { return GenIcon(codeFill)(props); }; /** * The react component for the `code-s-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code S Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-s-fill.svg) */ export const CodeSFillIcon: IconType = (props) => { return GenIcon(codeSFill)(props); }; /** * The react component for the `code-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-s-line.svg) */ export const CodeSLineIcon: IconType = (props) => { return GenIcon(codeSLine)(props); }; /** * The react component for the `code-s-slash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code S Slash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-s-slash-fill.svg) */ export const CodeSSlashFillIcon: IconType = (props) => { return GenIcon(codeSSlashFill)(props); }; /** * The react component for the `code-s-slash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Code S Slash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/code-s-slash-line.svg) */ export const CodeSSlashLineIcon: IconType = (props) => { return GenIcon(codeSSlashLine)(props); }; /** * The react component for the `codepen-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Codepen Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/codepen-fill.svg) */ export const CodepenFillIcon: IconType = (props) => { return GenIcon(codepenFill)(props); }; /** * The react component for the `codepen-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Codepen Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/codepen-line.svg) */ export const CodepenLineIcon: IconType = (props) => { return GenIcon(codepenLine)(props); }; /** * The react component for the `coin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coin-fill.svg) */ export const CoinFillIcon: IconType = (props) => { return GenIcon(coinFill)(props); }; /** * The react component for the `coin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coin-line.svg) */ export const CoinLineIcon: IconType = (props) => { return GenIcon(coinLine)(props); }; /** * The react component for the `coins-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coins Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coins-fill.svg) */ export const CoinsFillIcon: IconType = (props) => { return GenIcon(coinsFill)(props); }; /** * The react component for the `coins-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coins Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coins-line.svg) */ export const CoinsLineIcon: IconType = (props) => { return GenIcon(coinsLine)(props); }; /** * The react component for the `collage-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Collage Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/collage-fill.svg) */ export const CollageFillIcon: IconType = (props) => { return GenIcon(collageFill)(props); }; /** * The react component for the `collage-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Collage Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/collage-line.svg) */ export const CollageLineIcon: IconType = (props) => { return GenIcon(collageLine)(props); }; /** * The react component for the `command-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Command Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/command-fill.svg) */ export const CommandFillIcon: IconType = (props) => { return GenIcon(commandFill)(props); }; /** * The react component for the `command-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Command Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/command-line.svg) */ export const CommandLineIcon: IconType = (props) => { return GenIcon(commandLine)(props); }; /** * The react component for the `community-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Community Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/community-fill.svg) */ export const CommunityFillIcon: IconType = (props) => { return GenIcon(communityFill)(props); }; /** * The react component for the `community-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Community Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/community-line.svg) */ export const CommunityLineIcon: IconType = (props) => { return GenIcon(communityLine)(props); }; /** * The react component for the `compass-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-2-fill.svg) */ export const Compass2FillIcon: IconType = (props) => { return GenIcon(compass2Fill)(props); }; /** * The react component for the `compass-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-2-line.svg) */ export const Compass2LineIcon: IconType = (props) => { return GenIcon(compass2Line)(props); }; /** * The react component for the `compass-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-3-fill.svg) */ export const Compass3FillIcon: IconType = (props) => { return GenIcon(compass3Fill)(props); }; /** * The react component for the `compass-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-3-line.svg) */ export const Compass3LineIcon: IconType = (props) => { return GenIcon(compass3Line)(props); }; /** * The react component for the `compass-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-4-fill.svg) */ export const Compass4FillIcon: IconType = (props) => { return GenIcon(compass4Fill)(props); }; /** * The react component for the `compass-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-4-line.svg) */ export const Compass4LineIcon: IconType = (props) => { return GenIcon(compass4Line)(props); }; /** * The react component for the `compass-discover-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass Discover Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-discover-fill.svg) */ export const CompassDiscoverFillIcon: IconType = (props) => { return GenIcon(compassDiscoverFill)(props); }; /** * The react component for the `compass-discover-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass Discover Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-discover-line.svg) */ export const CompassDiscoverLineIcon: IconType = (props) => { return GenIcon(compassDiscoverLine)(props); }; /** * The react component for the `compass-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-fill.svg) */ export const CompassFillIcon: IconType = (props) => { return GenIcon(compassFill)(props); }; /** * The react component for the `compass-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compass Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/compass-line.svg) */ export const CompassLineIcon: IconType = (props) => { return GenIcon(compassLine)(props); }; /** * The react component for the `compasses-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compasses 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/compasses-2-fill.svg) */ export const Compasses2FillIcon: IconType = (props) => { return GenIcon(compasses2Fill)(props); }; /** * The react component for the `compasses-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compasses 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/compasses-2-line.svg) */ export const Compasses2LineIcon: IconType = (props) => { return GenIcon(compasses2Line)(props); }; /** * The react component for the `compasses-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compasses Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/compasses-fill.svg) */ export const CompassesFillIcon: IconType = (props) => { return GenIcon(compassesFill)(props); }; /** * The react component for the `compasses-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Compasses Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/compasses-line.svg) */ export const CompassesLineIcon: IconType = (props) => { return GenIcon(compassesLine)(props); }; /** * The react component for the `computer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Computer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/computer-fill.svg) */ export const ComputerFillIcon: IconType = (props) => { return GenIcon(computerFill)(props); }; /** * The react component for the `computer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Computer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/computer-line.svg) */ export const ComputerLineIcon: IconType = (props) => { return GenIcon(computerLine)(props); }; /** * The react component for the `contacts-book-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-2-fill.svg) */ export const ContactsBook2FillIcon: IconType = (props) => { return GenIcon(contactsBook2Fill)(props); }; /** * The react component for the `contacts-book-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-2-line.svg) */ export const ContactsBook2LineIcon: IconType = (props) => { return GenIcon(contactsBook2Line)(props); }; /** * The react component for the `contacts-book-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-fill.svg) */ export const ContactsBookFillIcon: IconType = (props) => { return GenIcon(contactsBookFill)(props); }; /** * The react component for the `contacts-book-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-line.svg) */ export const ContactsBookLineIcon: IconType = (props) => { return GenIcon(contactsBookLine)(props); }; /** * The react component for the `contacts-book-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-upload-fill.svg) */ export const ContactsBookUploadFillIcon: IconType = (props) => { return GenIcon(contactsBookUploadFill)(props); }; /** * The react component for the `contacts-book-upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Book Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/contacts-book-upload-line.svg) */ export const ContactsBookUploadLineIcon: IconType = (props) => { return GenIcon(contactsBookUploadLine)(props); }; /** * The react component for the `contacts-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/contacts-fill.svg) */ export const ContactsFillIcon: IconType = (props) => { return GenIcon(contactsFill)(props); }; /** * The react component for the `contacts-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contacts Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/contacts-line.svg) */ export const ContactsLineIcon: IconType = (props) => { return GenIcon(contactsLine)(props); }; /** * The react component for the `contrast-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-2-fill.svg) */ export const Contrast2FillIcon: IconType = (props) => { return GenIcon(contrast2Fill)(props); }; /** * The react component for the `contrast-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-2-line.svg) */ export const Contrast2LineIcon: IconType = (props) => { return GenIcon(contrast2Line)(props); }; /** * The react component for the `contrast-drop-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Drop 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-drop-2-fill.svg) */ export const ContrastDrop2FillIcon: IconType = (props) => { return GenIcon(contrastDrop2Fill)(props); }; /** * The react component for the `contrast-drop-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Drop 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-drop-2-line.svg) */ export const ContrastDrop2LineIcon: IconType = (props) => { return GenIcon(contrastDrop2Line)(props); }; /** * The react component for the `contrast-drop-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Drop Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-drop-fill.svg) */ export const ContrastDropFillIcon: IconType = (props) => { return GenIcon(contrastDropFill)(props); }; /** * The react component for the `contrast-drop-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Drop Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-drop-line.svg) */ export const ContrastDropLineIcon: IconType = (props) => { return GenIcon(contrastDropLine)(props); }; /** * The react component for the `contrast-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-fill.svg) */ export const ContrastFillIcon: IconType = (props) => { return GenIcon(contrastFill)(props); }; /** * The react component for the `contrast-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Contrast Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/contrast-line.svg) */ export const ContrastLineIcon: IconType = (props) => { return GenIcon(contrastLine)(props); }; /** * The react component for the `copper-coin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copper Coin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/copper-coin-fill.svg) */ export const CopperCoinFillIcon: IconType = (props) => { return GenIcon(copperCoinFill)(props); }; /** * The react component for the `copper-coin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copper Coin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/copper-coin-line.svg) */ export const CopperCoinLineIcon: IconType = (props) => { return GenIcon(copperCoinLine)(props); }; /** * The react component for the `copper-diamond-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copper Diamond Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/copper-diamond-fill.svg) */ export const CopperDiamondFillIcon: IconType = (props) => { return GenIcon(copperDiamondFill)(props); }; /** * The react component for the `copper-diamond-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copper Diamond Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/copper-diamond-line.svg) */ export const CopperDiamondLineIcon: IconType = (props) => { return GenIcon(copperDiamondLine)(props); }; /** * The react component for the `copyleft-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copyleft Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/copyleft-fill.svg) */ export const CopyleftFillIcon: IconType = (props) => { return GenIcon(copyleftFill)(props); }; /** * The react component for the `copyleft-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copyleft Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/copyleft-line.svg) */ export const CopyleftLineIcon: IconType = (props) => { return GenIcon(copyleftLine)(props); }; /** * The react component for the `copyright-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copyright Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/copyright-fill.svg) */ export const CopyrightFillIcon: IconType = (props) => { return GenIcon(copyrightFill)(props); }; /** * The react component for the `copyright-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Copyright Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/copyright-line.svg) */ export const CopyrightLineIcon: IconType = (props) => { return GenIcon(copyrightLine)(props); }; /** * The react component for the `coreos-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coreos Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/coreos-fill.svg) */ export const CoreosFillIcon: IconType = (props) => { return GenIcon(coreosFill)(props); }; /** * The react component for the `coreos-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coreos Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/coreos-line.svg) */ export const CoreosLineIcon: IconType = (props) => { return GenIcon(coreosLine)(props); }; /** * The react component for the `coupon-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-2-fill.svg) */ export const Coupon2FillIcon: IconType = (props) => { return GenIcon(coupon2Fill)(props); }; /** * The react component for the `coupon-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-2-line.svg) */ export const Coupon2LineIcon: IconType = (props) => { return GenIcon(coupon2Line)(props); }; /** * The react component for the `coupon-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-3-fill.svg) */ export const Coupon3FillIcon: IconType = (props) => { return GenIcon(coupon3Fill)(props); }; /** * The react component for the `coupon-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-3-line.svg) */ export const Coupon3LineIcon: IconType = (props) => { return GenIcon(coupon3Line)(props); }; /** * The react component for the `coupon-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-4-fill.svg) */ export const Coupon4FillIcon: IconType = (props) => { return GenIcon(coupon4Fill)(props); }; /** * The react component for the `coupon-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-4-line.svg) */ export const Coupon4LineIcon: IconType = (props) => { return GenIcon(coupon4Line)(props); }; /** * The react component for the `coupon-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-5-fill.svg) */ export const Coupon5FillIcon: IconType = (props) => { return GenIcon(coupon5Fill)(props); }; /** * The react component for the `coupon-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-5-line.svg) */ export const Coupon5LineIcon: IconType = (props) => { return GenIcon(coupon5Line)(props); }; /** * The react component for the `coupon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-fill.svg) */ export const CouponFillIcon: IconType = (props) => { return GenIcon(couponFill)(props); }; /** * The react component for the `coupon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Coupon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/coupon-line.svg) */ export const CouponLineIcon: IconType = (props) => { return GenIcon(couponLine)(props); }; /** * The react component for the `cpu-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cpu Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cpu-fill.svg) */ export const CpuFillIcon: IconType = (props) => { return GenIcon(cpuFill)(props); }; /** * The react component for the `cpu-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cpu Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/cpu-line.svg) */ export const CpuLineIcon: IconType = (props) => { return GenIcon(cpuLine)(props); }; /** * The react component for the `creative-commons-by-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons By Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-by-fill.svg) */ export const CreativeCommonsByFillIcon: IconType = (props) => { return GenIcon(creativeCommonsByFill)(props); }; /** * The react component for the `creative-commons-by-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons By Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-by-line.svg) */ export const CreativeCommonsByLineIcon: IconType = (props) => { return GenIcon(creativeCommonsByLine)(props); }; /** * The react component for the `creative-commons-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-fill.svg) */ export const CreativeCommonsFillIcon: IconType = (props) => { return GenIcon(creativeCommonsFill)(props); }; /** * The react component for the `creative-commons-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-line.svg) */ export const CreativeCommonsLineIcon: IconType = (props) => { return GenIcon(creativeCommonsLine)(props); }; /** * The react component for the `creative-commons-nc-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Nc Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-nc-fill.svg) */ export const CreativeCommonsNcFillIcon: IconType = (props) => { return GenIcon(creativeCommonsNcFill)(props); }; /** * The react component for the `creative-commons-nc-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Nc Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-nc-line.svg) */ export const CreativeCommonsNcLineIcon: IconType = (props) => { return GenIcon(creativeCommonsNcLine)(props); }; /** * The react component for the `creative-commons-nd-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Nd Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-nd-fill.svg) */ export const CreativeCommonsNdFillIcon: IconType = (props) => { return GenIcon(creativeCommonsNdFill)(props); }; /** * The react component for the `creative-commons-nd-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Nd Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-nd-line.svg) */ export const CreativeCommonsNdLineIcon: IconType = (props) => { return GenIcon(creativeCommonsNdLine)(props); }; /** * The react component for the `creative-commons-sa-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Sa Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-sa-fill.svg) */ export const CreativeCommonsSaFillIcon: IconType = (props) => { return GenIcon(creativeCommonsSaFill)(props); }; /** * The react component for the `creative-commons-sa-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Sa Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-sa-line.svg) */ export const CreativeCommonsSaLineIcon: IconType = (props) => { return GenIcon(creativeCommonsSaLine)(props); }; /** * The react component for the `creative-commons-zero-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Zero Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-zero-fill.svg) */ export const CreativeCommonsZeroFillIcon: IconType = (props) => { return GenIcon(creativeCommonsZeroFill)(props); }; /** * The react component for the `creative-commons-zero-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Creative Commons Zero Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/creative-commons-zero-line.svg) */ export const CreativeCommonsZeroLineIcon: IconType = (props) => { return GenIcon(creativeCommonsZeroLine)(props); }; /** * The react component for the `criminal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Criminal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/criminal-fill.svg) */ export const CriminalFillIcon: IconType = (props) => { return GenIcon(criminalFill)(props); }; /** * The react component for the `criminal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Criminal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/criminal-line.svg) */ export const CriminalLineIcon: IconType = (props) => { return GenIcon(criminalLine)(props); }; /** * The react component for the `crop-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Crop 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/crop-2-fill.svg) */ export const Crop2FillIcon: IconType = (props) => { return GenIcon(crop2Fill)(props); }; /** * The react component for the `crop-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Crop 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/crop-2-line.svg) */ export const Crop2LineIcon: IconType = (props) => { return GenIcon(crop2Line)(props); }; /** * The react component for the `crop-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Crop Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/crop-fill.svg) */ export const CropFillIcon: IconType = (props) => { return GenIcon(cropFill)(props); }; /** * The react component for the `crop-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Crop Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/crop-line.svg) */ export const CropLineIcon: IconType = (props) => { return GenIcon(cropLine)(props); }; /** * The react component for the `css-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Css 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/css3-fill.svg) */ export const Css3FillIcon: IconType = (props) => { return GenIcon(css3Fill)(props); }; /** * The react component for the `css-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Css 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/css3-line.svg) */ export const Css3LineIcon: IconType = (props) => { return GenIcon(css3Line)(props); }; /** * The react component for the `cup-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cup Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/cup-fill.svg) */ export const CupFillIcon: IconType = (props) => { return GenIcon(cupFill)(props); }; /** * The react component for the `cup-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cup Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/cup-line.svg) */ export const CupLineIcon: IconType = (props) => { return GenIcon(cupLine)(props); }; /** * The react component for the `currency-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Currency Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/currency-fill.svg) */ export const CurrencyFillIcon: IconType = (props) => { return GenIcon(currencyFill)(props); }; /** * The react component for the `currency-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Currency Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/currency-line.svg) */ export const CurrencyLineIcon: IconType = (props) => { return GenIcon(currencyLine)(props); }; /** * The react component for the `cursor-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cursor Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/cursor-fill.svg) */ export const CursorFillIcon: IconType = (props) => { return GenIcon(cursorFill)(props); }; /** * The react component for the `cursor-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Cursor Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/cursor-line.svg) */ export const CursorLineIcon: IconType = (props) => { return GenIcon(cursorLine)(props); }; /** * The react component for the `customer-service-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Customer Service 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/customer-service-2-fill.svg) */ export const CustomerService2FillIcon: IconType = (props) => { return GenIcon(customerService2Fill)(props); }; /** * The react component for the `customer-service-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Customer Service 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/customer-service-2-line.svg) */ export const CustomerService2LineIcon: IconType = (props) => { return GenIcon(customerService2Line)(props); }; /** * The react component for the `customer-service-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Customer Service Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/customer-service-fill.svg) */ export const CustomerServiceFillIcon: IconType = (props) => { return GenIcon(customerServiceFill)(props); }; /** * The react component for the `customer-service-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Customer Service Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/customer-service-line.svg) */ export const CustomerServiceLineIcon: IconType = (props) => { return GenIcon(customerServiceLine)(props); }; /** * The react component for the `dashboard-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dashboard-2-fill.svg) */ export const Dashboard2FillIcon: IconType = (props) => { return GenIcon(dashboard2Fill)(props); }; /** * The react component for the `dashboard-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dashboard-2-line.svg) */ export const Dashboard2LineIcon: IconType = (props) => { return GenIcon(dashboard2Line)(props); }; /** * The react component for the `dashboard-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dashboard-3-fill.svg) */ export const Dashboard3FillIcon: IconType = (props) => { return GenIcon(dashboard3Fill)(props); }; /** * The react component for the `dashboard-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dashboard-3-line.svg) */ export const Dashboard3LineIcon: IconType = (props) => { return GenIcon(dashboard3Line)(props); }; /** * The react component for the `dashboard-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/dashboard-fill.svg) */ export const DashboardFillIcon: IconType = (props) => { return GenIcon(dashboardFill)(props); }; /** * The react component for the `dashboard-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dashboard Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/dashboard-line.svg) */ export const DashboardLineIcon: IconType = (props) => { return GenIcon(dashboardLine)(props); }; /** * The react component for the `database-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Database 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/database-2-fill.svg) */ export const Database2FillIcon: IconType = (props) => { return GenIcon(database2Fill)(props); }; /** * The react component for the `database-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Database 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/database-2-line.svg) */ export const Database2LineIcon: IconType = (props) => { return GenIcon(database2Line)(props); }; /** * The react component for the `database-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Database Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/database-fill.svg) */ export const DatabaseFillIcon: IconType = (props) => { return GenIcon(databaseFill)(props); }; /** * The react component for the `database-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Database Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/database-line.svg) */ export const DatabaseLineIcon: IconType = (props) => { return GenIcon(databaseLine)(props); }; /** * The react component for the `delete-back-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Back 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-back-2-fill.svg) */ export const DeleteBack2FillIcon: IconType = (props) => { return GenIcon(deleteBack2Fill)(props); }; /** * The react component for the `delete-back-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Back 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-back-2-line.svg) */ export const DeleteBack2LineIcon: IconType = (props) => { return GenIcon(deleteBack2Line)(props); }; /** * The react component for the `delete-back-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Back Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-back-fill.svg) */ export const DeleteBackFillIcon: IconType = (props) => { return GenIcon(deleteBackFill)(props); }; /** * The react component for the `delete-back-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Back Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-back-line.svg) */ export const DeleteBackLineIcon: IconType = (props) => { return GenIcon(deleteBackLine)(props); }; /** * The react component for the `delete-bin-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-2-fill.svg) */ export const DeleteBin2FillIcon: IconType = (props) => { return GenIcon(deleteBin2Fill)(props); }; /** * The react component for the `delete-bin-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-2-line.svg) */ export const DeleteBin2LineIcon: IconType = (props) => { return GenIcon(deleteBin2Line)(props); }; /** * The react component for the `delete-bin-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-3-fill.svg) */ export const DeleteBin3FillIcon: IconType = (props) => { return GenIcon(deleteBin3Fill)(props); }; /** * The react component for the `delete-bin-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-3-line.svg) */ export const DeleteBin3LineIcon: IconType = (props) => { return GenIcon(deleteBin3Line)(props); }; /** * The react component for the `delete-bin-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-4-fill.svg) */ export const DeleteBin4FillIcon: IconType = (props) => { return GenIcon(deleteBin4Fill)(props); }; /** * The react component for the `delete-bin-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-4-line.svg) */ export const DeleteBin4LineIcon: IconType = (props) => { return GenIcon(deleteBin4Line)(props); }; /** * The react component for the `delete-bin-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-5-fill.svg) */ export const DeleteBin5FillIcon: IconType = (props) => { return GenIcon(deleteBin5Fill)(props); }; /** * The react component for the `delete-bin-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-5-line.svg) */ export const DeleteBin5LineIcon: IconType = (props) => { return GenIcon(deleteBin5Line)(props); }; /** * The react component for the `delete-bin-6-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 6 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-6-fill.svg) */ export const DeleteBin6FillIcon: IconType = (props) => { return GenIcon(deleteBin6Fill)(props); }; /** * The react component for the `delete-bin-6-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 6 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-6-line.svg) */ export const DeleteBin6LineIcon: IconType = (props) => { return GenIcon(deleteBin6Line)(props); }; /** * The react component for the `delete-bin-7-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 7 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-7-fill.svg) */ export const DeleteBin7FillIcon: IconType = (props) => { return GenIcon(deleteBin7Fill)(props); }; /** * The react component for the `delete-bin-7-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Delete Bin 7 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/delete-bin-7-line.svg) */ export const DeleteBin7LineIcon: IconType = (props) => { return GenIcon(deleteBin7Line)(props); }; /** * The react component for the `device-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Device Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/device-fill.svg) */ export const DeviceFillIcon: IconType = (props) => { return GenIcon(deviceFill)(props); }; /** * The react component for the `device-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Device Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/device-line.svg) */ export const DeviceLineIcon: IconType = (props) => { return GenIcon(deviceLine)(props); }; /** * The react component for the `device-recover-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Device Recover Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/device-recover-fill.svg) */ export const DeviceRecoverFillIcon: IconType = (props) => { return GenIcon(deviceRecoverFill)(props); }; /** * The react component for the `device-recover-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Device Recover Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/device-recover-line.svg) */ export const DeviceRecoverLineIcon: IconType = (props) => { return GenIcon(deviceRecoverLine)(props); }; /** * The react component for the `dingding-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dingding Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dingding-fill.svg) */ export const DingdingFillIcon: IconType = (props) => { return GenIcon(dingdingFill)(props); }; /** * The react component for the `dingding-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dingding Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dingding-line.svg) */ export const DingdingLineIcon: IconType = (props) => { return GenIcon(dingdingLine)(props); }; /** * The react component for the `direction-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Direction Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/direction-fill.svg) */ export const DirectionFillIcon: IconType = (props) => { return GenIcon(directionFill)(props); }; /** * The react component for the `direction-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Direction Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/direction-line.svg) */ export const DirectionLineIcon: IconType = (props) => { return GenIcon(directionLine)(props); }; /** * The react component for the `disc-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Disc Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/disc-fill.svg) */ export const DiscFillIcon: IconType = (props) => { return GenIcon(discFill)(props); }; /** * The react component for the `disc-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Disc Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/disc-line.svg) */ export const DiscLineIcon: IconType = (props) => { return GenIcon(discLine)(props); }; /** * The react component for the `discord-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Discord Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/discord-fill.svg) */ export const DiscordFillIcon: IconType = (props) => { return GenIcon(discordFill)(props); }; /** * The react component for the `discord-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Discord Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/discord-line.svg) */ export const DiscordLineIcon: IconType = (props) => { return GenIcon(discordLine)(props); }; /** * The react component for the `discuss-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Discuss Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/discuss-fill.svg) */ export const DiscussFillIcon: IconType = (props) => { return GenIcon(discussFill)(props); }; /** * The react component for the `discuss-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Discuss Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/discuss-line.svg) */ export const DiscussLineIcon: IconType = (props) => { return GenIcon(discussLine)(props); }; /** * The react component for the `dislike-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dislike Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/dislike-fill.svg) */ export const DislikeFillIcon: IconType = (props) => { return GenIcon(dislikeFill)(props); }; /** * The react component for the `dislike-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dislike Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/dislike-line.svg) */ export const DislikeLineIcon: IconType = (props) => { return GenIcon(dislikeLine)(props); }; /** * The react component for the `disqus-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Disqus Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/disqus-fill.svg) */ export const DisqusFillIcon: IconType = (props) => { return GenIcon(disqusFill)(props); }; /** * The react component for the `disqus-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Disqus Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/disqus-line.svg) */ export const DisqusLineIcon: IconType = (props) => { return GenIcon(disqusLine)(props); }; /** * The react component for the `divide-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Divide Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/divide-fill.svg) */ export const DivideFillIcon: IconType = (props) => { return GenIcon(divideFill)(props); }; /** * The react component for the `divide-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Divide Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/divide-line.svg) */ export const DivideLineIcon: IconType = (props) => { return GenIcon(divideLine)(props); }; /** * The react component for the `donut-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Donut Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/donut-chart-fill.svg) */ export const DonutChartFillIcon: IconType = (props) => { return GenIcon(donutChartFill)(props); }; /** * The react component for the `donut-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Donut Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/donut-chart-line.svg) */ export const DonutChartLineIcon: IconType = (props) => { return GenIcon(donutChartLine)(props); }; /** * The react component for the `door-closed-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Closed Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-closed-fill.svg) */ export const DoorClosedFillIcon: IconType = (props) => { return GenIcon(doorClosedFill)(props); }; /** * The react component for the `door-closed-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Closed Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-closed-line.svg) */ export const DoorClosedLineIcon: IconType = (props) => { return GenIcon(doorClosedLine)(props); }; /** * The react component for the `door-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-fill.svg) */ export const DoorFillIcon: IconType = (props) => { return GenIcon(doorFill)(props); }; /** * The react component for the `door-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-line.svg) */ export const DoorLineIcon: IconType = (props) => { return GenIcon(doorLine)(props); }; /** * The react component for the `door-lock-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Lock Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-lock-box-fill.svg) */ export const DoorLockBoxFillIcon: IconType = (props) => { return GenIcon(doorLockBoxFill)(props); }; /** * The react component for the `door-lock-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Lock Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-lock-box-line.svg) */ export const DoorLockBoxLineIcon: IconType = (props) => { return GenIcon(doorLockBoxLine)(props); }; /** * The react component for the `door-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-lock-fill.svg) */ export const DoorLockFillIcon: IconType = (props) => { return GenIcon(doorLockFill)(props); }; /** * The react component for the `door-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-lock-line.svg) */ export const DoorLockLineIcon: IconType = (props) => { return GenIcon(doorLockLine)(props); }; /** * The react component for the `door-open-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Open Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-open-fill.svg) */ export const DoorOpenFillIcon: IconType = (props) => { return GenIcon(doorOpenFill)(props); }; /** * The react component for the `door-open-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Door Open Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/door-open-line.svg) */ export const DoorOpenLineIcon: IconType = (props) => { return GenIcon(doorOpenLine)(props); }; /** * The react component for the `dossier-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dossier Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/dossier-fill.svg) */ export const DossierFillIcon: IconType = (props) => { return GenIcon(dossierFill)(props); }; /** * The react component for the `dossier-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dossier Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/dossier-line.svg) */ export const DossierLineIcon: IconType = (props) => { return GenIcon(dossierLine)(props); }; /** * The react component for the `douban-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Douban Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/douban-fill.svg) */ export const DoubanFillIcon: IconType = (props) => { return GenIcon(doubanFill)(props); }; /** * The react component for the `douban-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Douban Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/douban-line.svg) */ export const DoubanLineIcon: IconType = (props) => { return GenIcon(doubanLine)(props); }; /** * The react component for the `download-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-2-line.svg) */ export const Download2LineIcon: IconType = (props) => { return GenIcon(download2Line)(props); }; /** * The react component for the `download-cloud-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Cloud 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-cloud-2-fill.svg) */ export const DownloadCloud2FillIcon: IconType = (props) => { return GenIcon(downloadCloud2Fill)(props); }; /** * The react component for the `download-cloud-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Cloud 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-cloud-2-line.svg) */ export const DownloadCloud2LineIcon: IconType = (props) => { return GenIcon(downloadCloud2Line)(props); }; /** * The react component for the `download-cloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Cloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-cloud-fill.svg) */ export const DownloadCloudFillIcon: IconType = (props) => { return GenIcon(downloadCloudFill)(props); }; /** * The react component for the `download-cloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Cloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-cloud-line.svg) */ export const DownloadCloudLineIcon: IconType = (props) => { return GenIcon(downloadCloudLine)(props); }; /** * The react component for the `download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-fill.svg) */ export const DownloadFillIcon: IconType = (props) => { return GenIcon(downloadFill)(props); }; /** * The react component for the `download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/download-line.svg) */ export const DownloadLineIcon: IconType = (props) => { return GenIcon(downloadLine)(props); }; /** * The react component for the `draft-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Draft Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/draft-fill.svg) */ export const DraftFillIcon: IconType = (props) => { return GenIcon(draftFill)(props); }; /** * The react component for the `draft-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Draft Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/draft-line.svg) */ export const DraftLineIcon: IconType = (props) => { return GenIcon(draftLine)(props); }; /** * The react component for the `drag-drop-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drag Drop Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drag-drop-fill.svg) */ export const DragDropFillIcon: IconType = (props) => { return GenIcon(dragDropFill)(props); }; /** * The react component for the `drag-move-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drag Move 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drag-move-2-fill.svg) */ export const DragMove2FillIcon: IconType = (props) => { return GenIcon(dragMove2Fill)(props); }; /** * The react component for the `drag-move-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drag Move 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drag-move-2-line.svg) */ export const DragMove2LineIcon: IconType = (props) => { return GenIcon(dragMove2Line)(props); }; /** * The react component for the `drag-move-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drag Move Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drag-move-fill.svg) */ export const DragMoveFillIcon: IconType = (props) => { return GenIcon(dragMoveFill)(props); }; /** * The react component for the `drag-move-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drag Move Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drag-move-line.svg) */ export const DragMoveLineIcon: IconType = (props) => { return GenIcon(dragMoveLine)(props); }; /** * The react component for the `dribbble-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dribbble Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dribbble-fill.svg) */ export const DribbbleFillIcon: IconType = (props) => { return GenIcon(dribbbleFill)(props); }; /** * The react component for the `dribbble-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dribbble Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dribbble-line.svg) */ export const DribbbleLineIcon: IconType = (props) => { return GenIcon(dribbbleLine)(props); }; /** * The react component for the `drive-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drive Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/drive-fill.svg) */ export const DriveFillIcon: IconType = (props) => { return GenIcon(driveFill)(props); }; /** * The react component for the `drive-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drive Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/drive-line.svg) */ export const DriveLineIcon: IconType = (props) => { return GenIcon(driveLine)(props); }; /** * The react component for the `drizzle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drizzle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/drizzle-fill.svg) */ export const DrizzleFillIcon: IconType = (props) => { return GenIcon(drizzleFill)(props); }; /** * The react component for the `drizzle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drizzle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/drizzle-line.svg) */ export const DrizzleLineIcon: IconType = (props) => { return GenIcon(drizzleLine)(props); }; /** * The react component for the `drop-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drop Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drop-fill.svg) */ export const DropFillIcon: IconType = (props) => { return GenIcon(dropFill)(props); }; /** * The react component for the `drop-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Drop Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/drop-line.svg) */ export const DropLineIcon: IconType = (props) => { return GenIcon(dropLine)(props); }; /** * The react component for the `dropbox-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dropbox Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dropbox-fill.svg) */ export const DropboxFillIcon: IconType = (props) => { return GenIcon(dropboxFill)(props); }; /** * The react component for the `dropbox-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dropbox Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/dropbox-line.svg) */ export const DropboxLineIcon: IconType = (props) => { return GenIcon(dropboxLine)(props); }; /** * The react component for the `dual-sim-1-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dual Sim 1 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dual-sim-1-fill.svg) */ export const DualSim1FillIcon: IconType = (props) => { return GenIcon(dualSim1Fill)(props); }; /** * The react component for the `dual-sim-1-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dual Sim 1 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dual-sim-1-line.svg) */ export const DualSim1LineIcon: IconType = (props) => { return GenIcon(dualSim1Line)(props); }; /** * The react component for the `dual-sim-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dual Sim 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dual-sim-2-fill.svg) */ export const DualSim2FillIcon: IconType = (props) => { return GenIcon(dualSim2Fill)(props); }; /** * The react component for the `dual-sim-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dual Sim 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/dual-sim-2-line.svg) */ export const DualSim2LineIcon: IconType = (props) => { return GenIcon(dualSim2Line)(props); }; /** * The react component for the `dv-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dv Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/dv-fill.svg) */ export const DvFillIcon: IconType = (props) => { return GenIcon(dvFill)(props); }; /** * The react component for the `dv-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dv Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/dv-line.svg) */ export const DvLineIcon: IconType = (props) => { return GenIcon(dvLine)(props); }; /** * The react component for the `dvd-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dvd Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/dvd-fill.svg) */ export const DvdFillIcon: IconType = (props) => { return GenIcon(dvdFill)(props); }; /** * The react component for the `dvd-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Dvd Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/dvd-line.svg) */ export const DvdLineIcon: IconType = (props) => { return GenIcon(dvdLine)(props); }; /** * The react component for the `e-bike-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![E Bike 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/e-bike-2-fill.svg) */ export const EBike2FillIcon: IconType = (props) => { return GenIcon(eBike2Fill)(props); }; /** * The react component for the `e-bike-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![E Bike 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/e-bike-2-line.svg) */ export const EBike2LineIcon: IconType = (props) => { return GenIcon(eBike2Line)(props); }; /** * The react component for the `e-bike-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![E Bike Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/e-bike-fill.svg) */ export const EBikeFillIcon: IconType = (props) => { return GenIcon(eBikeFill)(props); }; /** * The react component for the `e-bike-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![E Bike Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/e-bike-line.svg) */ export const EBikeLineIcon: IconType = (props) => { return GenIcon(eBikeLine)(props); }; /** * The react component for the `earth-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Earth Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/earth-fill.svg) */ export const EarthFillIcon: IconType = (props) => { return GenIcon(earthFill)(props); }; /** * The react component for the `earth-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Earth Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/earth-line.svg) */ export const EarthLineIcon: IconType = (props) => { return GenIcon(earthLine)(props); }; /** * The react component for the `earthquake-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Earthquake Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/earthquake-fill.svg) */ export const EarthquakeFillIcon: IconType = (props) => { return GenIcon(earthquakeFill)(props); }; /** * The react component for the `earthquake-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Earthquake Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/earthquake-line.svg) */ export const EarthquakeLineIcon: IconType = (props) => { return GenIcon(earthquakeLine)(props); }; /** * The react component for the `edge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/edge-fill.svg) */ export const EdgeFillIcon: IconType = (props) => { return GenIcon(edgeFill)(props); }; /** * The react component for the `edge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/edge-line.svg) */ export const EdgeLineIcon: IconType = (props) => { return GenIcon(edgeLine)(props); }; /** * The react component for the `edit-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-2-fill.svg) */ export const Edit2FillIcon: IconType = (props) => { return GenIcon(edit2Fill)(props); }; /** * The react component for the `edit-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-2-line.svg) */ export const Edit2LineIcon: IconType = (props) => { return GenIcon(edit2Line)(props); }; /** * The react component for the `edit-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-box-fill.svg) */ export const EditBoxFillIcon: IconType = (props) => { return GenIcon(editBoxFill)(props); }; /** * The react component for the `edit-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-box-line.svg) */ export const EditBoxLineIcon: IconType = (props) => { return GenIcon(editBoxLine)(props); }; /** * The react component for the `edit-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-circle-fill.svg) */ export const EditCircleFillIcon: IconType = (props) => { return GenIcon(editCircleFill)(props); }; /** * The react component for the `edit-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-circle-line.svg) */ export const EditCircleLineIcon: IconType = (props) => { return GenIcon(editCircleLine)(props); }; /** * The react component for the `edit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-fill.svg) */ export const EditFillIcon: IconType = (props) => { return GenIcon(editFill)(props); }; /** * The react component for the `edit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Edit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/edit-line.svg) */ export const EditLineIcon: IconType = (props) => { return GenIcon(editLine)(props); }; /** * The react component for the `eject-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eject Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/eject-fill.svg) */ export const EjectFillIcon: IconType = (props) => { return GenIcon(ejectFill)(props); }; /** * The react component for the `eject-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eject Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/eject-line.svg) */ export const EjectLineIcon: IconType = (props) => { return GenIcon(ejectLine)(props); }; /** * The react component for the `emotion-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-2-fill.svg) */ export const Emotion2FillIcon: IconType = (props) => { return GenIcon(emotion2Fill)(props); }; /** * The react component for the `emotion-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-2-line.svg) */ export const Emotion2LineIcon: IconType = (props) => { return GenIcon(emotion2Line)(props); }; /** * The react component for the `emotion-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-fill.svg) */ export const EmotionFillIcon: IconType = (props) => { return GenIcon(emotionFill)(props); }; /** * The react component for the `emotion-happy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Happy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-happy-fill.svg) */ export const EmotionHappyFillIcon: IconType = (props) => { return GenIcon(emotionHappyFill)(props); }; /** * The react component for the `emotion-happy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Happy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-happy-line.svg) */ export const EmotionHappyLineIcon: IconType = (props) => { return GenIcon(emotionHappyLine)(props); }; /** * The react component for the `emotion-laugh-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Laugh Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-laugh-fill.svg) */ export const EmotionLaughFillIcon: IconType = (props) => { return GenIcon(emotionLaughFill)(props); }; /** * The react component for the `emotion-laugh-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Laugh Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-laugh-line.svg) */ export const EmotionLaughLineIcon: IconType = (props) => { return GenIcon(emotionLaughLine)(props); }; /** * The react component for the `emotion-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-line.svg) */ export const EmotionLineIcon: IconType = (props) => { return GenIcon(emotionLine)(props); }; /** * The react component for the `emotion-normal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Normal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-normal-fill.svg) */ export const EmotionNormalFillIcon: IconType = (props) => { return GenIcon(emotionNormalFill)(props); }; /** * The react component for the `emotion-normal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Normal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-normal-line.svg) */ export const EmotionNormalLineIcon: IconType = (props) => { return GenIcon(emotionNormalLine)(props); }; /** * The react component for the `emotion-sad-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Sad Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-sad-fill.svg) */ export const EmotionSadFillIcon: IconType = (props) => { return GenIcon(emotionSadFill)(props); }; /** * The react component for the `emotion-sad-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Sad Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-sad-line.svg) */ export const EmotionSadLineIcon: IconType = (props) => { return GenIcon(emotionSadLine)(props); }; /** * The react component for the `emotion-unhappy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Unhappy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-unhappy-fill.svg) */ export const EmotionUnhappyFillIcon: IconType = (props) => { return GenIcon(emotionUnhappyFill)(props); }; /** * The react component for the `emotion-unhappy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Emotion Unhappy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/emotion-unhappy-line.svg) */ export const EmotionUnhappyLineIcon: IconType = (props) => { return GenIcon(emotionUnhappyLine)(props); }; /** * The react component for the `empathize-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Empathize Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/empathize-fill.svg) */ export const EmpathizeFillIcon: IconType = (props) => { return GenIcon(empathizeFill)(props); }; /** * The react component for the `empathize-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Empathize Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/empathize-line.svg) */ export const EmpathizeLineIcon: IconType = (props) => { return GenIcon(empathizeLine)(props); }; /** * The react component for the `equalizer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Equalizer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/equalizer-fill.svg) */ export const EqualizerFillIcon: IconType = (props) => { return GenIcon(equalizerFill)(props); }; /** * The react component for the `equalizer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Equalizer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/equalizer-line.svg) */ export const EqualizerLineIcon: IconType = (props) => { return GenIcon(equalizerLine)(props); }; /** * The react component for the `eraser-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eraser Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/eraser-fill.svg) */ export const EraserFillIcon: IconType = (props) => { return GenIcon(eraserFill)(props); }; /** * The react component for the `eraser-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eraser Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/eraser-line.svg) */ export const EraserLineIcon: IconType = (props) => { return GenIcon(eraserLine)(props); }; /** * The react component for the `error-warning-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Error Warning Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/error-warning-fill.svg) */ export const ErrorWarningFillIcon: IconType = (props) => { return GenIcon(errorWarningFill)(props); }; /** * The react component for the `evernote-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Evernote Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/evernote-fill.svg) */ export const EvernoteFillIcon: IconType = (props) => { return GenIcon(evernoteFill)(props); }; /** * The react component for the `evernote-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Evernote Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/evernote-line.svg) */ export const EvernoteLineIcon: IconType = (props) => { return GenIcon(evernoteLine)(props); }; /** * The react component for the `exchange-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-box-fill.svg) */ export const ExchangeBoxFillIcon: IconType = (props) => { return GenIcon(exchangeBoxFill)(props); }; /** * The react component for the `exchange-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-box-line.svg) */ export const ExchangeBoxLineIcon: IconType = (props) => { return GenIcon(exchangeBoxLine)(props); }; /** * The react component for the `exchange-cny-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Cny Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-cny-fill.svg) */ export const ExchangeCnyFillIcon: IconType = (props) => { return GenIcon(exchangeCnyFill)(props); }; /** * The react component for the `exchange-cny-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Cny Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-cny-line.svg) */ export const ExchangeCnyLineIcon: IconType = (props) => { return GenIcon(exchangeCnyLine)(props); }; /** * The react component for the `exchange-dollar-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Dollar Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-dollar-fill.svg) */ export const ExchangeDollarFillIcon: IconType = (props) => { return GenIcon(exchangeDollarFill)(props); }; /** * The react component for the `exchange-dollar-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Dollar Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-dollar-line.svg) */ export const ExchangeDollarLineIcon: IconType = (props) => { return GenIcon(exchangeDollarLine)(props); }; /** * The react component for the `exchange-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-fill.svg) */ export const ExchangeFillIcon: IconType = (props) => { return GenIcon(exchangeFill)(props); }; /** * The react component for the `exchange-funds-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Funds Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-funds-fill.svg) */ export const ExchangeFundsFillIcon: IconType = (props) => { return GenIcon(exchangeFundsFill)(props); }; /** * The react component for the `exchange-funds-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Funds Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-funds-line.svg) */ export const ExchangeFundsLineIcon: IconType = (props) => { return GenIcon(exchangeFundsLine)(props); }; /** * The react component for the `exchange-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Exchange Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/exchange-line.svg) */ export const ExchangeLineIcon: IconType = (props) => { return GenIcon(exchangeLine)(props); }; /** * The react component for the `external-link-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![External Link Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/external-link-line.svg) */ export const ExternalLinkLineIcon: IconType = (props) => { return GenIcon(externalLinkLine)(props); }; /** * The react component for the `eye-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-2-fill.svg) */ export const Eye2FillIcon: IconType = (props) => { return GenIcon(eye2Fill)(props); }; /** * The react component for the `eye-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-2-line.svg) */ export const Eye2LineIcon: IconType = (props) => { return GenIcon(eye2Line)(props); }; /** * The react component for the `eye-close-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Close Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-close-fill.svg) */ export const EyeCloseFillIcon: IconType = (props) => { return GenIcon(eyeCloseFill)(props); }; /** * The react component for the `eye-close-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Close Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-close-line.svg) */ export const EyeCloseLineIcon: IconType = (props) => { return GenIcon(eyeCloseLine)(props); }; /** * The react component for the `eye-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-fill.svg) */ export const EyeFillIcon: IconType = (props) => { return GenIcon(eyeFill)(props); }; /** * The react component for the `eye-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-line.svg) */ export const EyeLineIcon: IconType = (props) => { return GenIcon(eyeLine)(props); }; /** * The react component for the `eye-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-off-fill.svg) */ export const EyeOffFillIcon: IconType = (props) => { return GenIcon(eyeOffFill)(props); }; /** * The react component for the `eye-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Eye Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/eye-off-line.svg) */ export const EyeOffLineIcon: IconType = (props) => { return GenIcon(eyeOffLine)(props); }; /** * The react component for the `facebook-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-box-fill.svg) */ export const FacebookBoxFillIcon: IconType = (props) => { return GenIcon(facebookBoxFill)(props); }; /** * The react component for the `facebook-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-box-line.svg) */ export const FacebookBoxLineIcon: IconType = (props) => { return GenIcon(facebookBoxLine)(props); }; /** * The react component for the `facebook-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-circle-fill.svg) */ export const FacebookCircleFillIcon: IconType = (props) => { return GenIcon(facebookCircleFill)(props); }; /** * The react component for the `facebook-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-circle-line.svg) */ export const FacebookCircleLineIcon: IconType = (props) => { return GenIcon(facebookCircleLine)(props); }; /** * The react component for the `facebook-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-fill.svg) */ export const FacebookFillIcon: IconType = (props) => { return GenIcon(facebookFill)(props); }; /** * The react component for the `facebook-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Facebook Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/facebook-line.svg) */ export const FacebookLineIcon: IconType = (props) => { return GenIcon(facebookLine)(props); }; /** * The react component for the `fahrenheit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fahrenheit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/fahrenheit-fill.svg) */ export const FahrenheitFillIcon: IconType = (props) => { return GenIcon(fahrenheitFill)(props); }; /** * The react component for the `fahrenheit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fahrenheit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/fahrenheit-line.svg) */ export const FahrenheitLineIcon: IconType = (props) => { return GenIcon(fahrenheitLine)(props); }; /** * The react component for the `feedback-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Feedback Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/feedback-fill.svg) */ export const FeedbackFillIcon: IconType = (props) => { return GenIcon(feedbackFill)(props); }; /** * The react component for the `feedback-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Feedback Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/feedback-line.svg) */ export const FeedbackLineIcon: IconType = (props) => { return GenIcon(feedbackLine)(props); }; /** * The react component for the `file-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-2-fill.svg) */ export const File2FillIcon: IconType = (props) => { return GenIcon(file2Fill)(props); }; /** * The react component for the `file-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-2-line.svg) */ export const File2LineIcon: IconType = (props) => { return GenIcon(file2Line)(props); }; /** * The react component for the `file-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-3-fill.svg) */ export const File3FillIcon: IconType = (props) => { return GenIcon(file3Fill)(props); }; /** * The react component for the `file-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-3-line.svg) */ export const File3LineIcon: IconType = (props) => { return GenIcon(file3Line)(props); }; /** * The react component for the `file-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-4-fill.svg) */ export const File4FillIcon: IconType = (props) => { return GenIcon(file4Fill)(props); }; /** * The react component for the `file-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-4-line.svg) */ export const File4LineIcon: IconType = (props) => { return GenIcon(file4Line)(props); }; /** * The react component for the `file-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-add-fill.svg) */ export const FileAddFillIcon: IconType = (props) => { return GenIcon(fileAddFill)(props); }; /** * The react component for the `file-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-add-line.svg) */ export const FileAddLineIcon: IconType = (props) => { return GenIcon(fileAddLine)(props); }; /** * The react component for the `file-chart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Chart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-chart-2-fill.svg) */ export const FileChart2FillIcon: IconType = (props) => { return GenIcon(fileChart2Fill)(props); }; /** * The react component for the `file-chart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Chart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-chart-2-line.svg) */ export const FileChart2LineIcon: IconType = (props) => { return GenIcon(fileChart2Line)(props); }; /** * The react component for the `file-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-chart-fill.svg) */ export const FileChartFillIcon: IconType = (props) => { return GenIcon(fileChartFill)(props); }; /** * The react component for the `file-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-chart-line.svg) */ export const FileChartLineIcon: IconType = (props) => { return GenIcon(fileChartLine)(props); }; /** * The react component for the `file-cloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Cloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-cloud-fill.svg) */ export const FileCloudFillIcon: IconType = (props) => { return GenIcon(fileCloudFill)(props); }; /** * The react component for the `file-cloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Cloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-cloud-line.svg) */ export const FileCloudLineIcon: IconType = (props) => { return GenIcon(fileCloudLine)(props); }; /** * The react component for the `file-code-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Code Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-code-fill.svg) */ export const FileCodeFillIcon: IconType = (props) => { return GenIcon(fileCodeFill)(props); }; /** * The react component for the `file-code-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Code Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-code-line.svg) */ export const FileCodeLineIcon: IconType = (props) => { return GenIcon(fileCodeLine)(props); }; /** * The react component for the `file-copy-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Copy 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-copy-2-fill.svg) */ export const FileCopy2FillIcon: IconType = (props) => { return GenIcon(fileCopy2Fill)(props); }; /** * The react component for the `file-copy-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Copy 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-copy-2-line.svg) */ export const FileCopy2LineIcon: IconType = (props) => { return GenIcon(fileCopy2Line)(props); }; /** * The react component for the `file-copy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Copy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-copy-fill.svg) */ export const FileCopyFillIcon: IconType = (props) => { return GenIcon(fileCopyFill)(props); }; /** * The react component for the `file-damage-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Damage Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-damage-fill.svg) */ export const FileDamageFillIcon: IconType = (props) => { return GenIcon(fileDamageFill)(props); }; /** * The react component for the `file-damage-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Damage Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-damage-line.svg) */ export const FileDamageLineIcon: IconType = (props) => { return GenIcon(fileDamageLine)(props); }; /** * The react component for the `file-download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-download-fill.svg) */ export const FileDownloadFillIcon: IconType = (props) => { return GenIcon(fileDownloadFill)(props); }; /** * The react component for the `file-download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-download-line.svg) */ export const FileDownloadLineIcon: IconType = (props) => { return GenIcon(fileDownloadLine)(props); }; /** * The react component for the `file-edit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Edit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-edit-fill.svg) */ export const FileEditFillIcon: IconType = (props) => { return GenIcon(fileEditFill)(props); }; /** * The react component for the `file-edit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Edit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-edit-line.svg) */ export const FileEditLineIcon: IconType = (props) => { return GenIcon(fileEditLine)(props); }; /** * The react component for the `file-excel-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Excel 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-excel-2-fill.svg) */ export const FileExcel2FillIcon: IconType = (props) => { return GenIcon(fileExcel2Fill)(props); }; /** * The react component for the `file-excel-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Excel 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-excel-2-line.svg) */ export const FileExcel2LineIcon: IconType = (props) => { return GenIcon(fileExcel2Line)(props); }; /** * The react component for the `file-excel-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Excel Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-excel-fill.svg) */ export const FileExcelFillIcon: IconType = (props) => { return GenIcon(fileExcelFill)(props); }; /** * The react component for the `file-excel-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Excel Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-excel-line.svg) */ export const FileExcelLineIcon: IconType = (props) => { return GenIcon(fileExcelLine)(props); }; /** * The react component for the `file-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-fill.svg) */ export const FileFillIcon: IconType = (props) => { return GenIcon(fileFill)(props); }; /** * The react component for the `file-forbid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Forbid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-forbid-fill.svg) */ export const FileForbidFillIcon: IconType = (props) => { return GenIcon(fileForbidFill)(props); }; /** * The react component for the `file-forbid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Forbid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-forbid-line.svg) */ export const FileForbidLineIcon: IconType = (props) => { return GenIcon(fileForbidLine)(props); }; /** * The react component for the `file-gif-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Gif Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-gif-fill.svg) */ export const FileGifFillIcon: IconType = (props) => { return GenIcon(fileGifFill)(props); }; /** * The react component for the `file-gif-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Gif Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-gif-line.svg) */ export const FileGifLineIcon: IconType = (props) => { return GenIcon(fileGifLine)(props); }; /** * The react component for the `file-history-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File History Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-history-fill.svg) */ export const FileHistoryFillIcon: IconType = (props) => { return GenIcon(fileHistoryFill)(props); }; /** * The react component for the `file-history-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File History Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-history-line.svg) */ export const FileHistoryLineIcon: IconType = (props) => { return GenIcon(fileHistoryLine)(props); }; /** * The react component for the `file-hwp-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Hwp Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-hwp-fill.svg) */ export const FileHwpFillIcon: IconType = (props) => { return GenIcon(fileHwpFill)(props); }; /** * The react component for the `file-hwp-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Hwp Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-hwp-line.svg) */ export const FileHwpLineIcon: IconType = (props) => { return GenIcon(fileHwpLine)(props); }; /** * The react component for the `file-info-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Info Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-info-fill.svg) */ export const FileInfoFillIcon: IconType = (props) => { return GenIcon(fileInfoFill)(props); }; /** * The react component for the `file-info-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Info Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-info-line.svg) */ export const FileInfoLineIcon: IconType = (props) => { return GenIcon(fileInfoLine)(props); }; /** * The react component for the `file-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-line.svg) */ export const FileLineIcon: IconType = (props) => { return GenIcon(fileLine)(props); }; /** * The react component for the `file-list-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-2-fill.svg) */ export const FileList2FillIcon: IconType = (props) => { return GenIcon(fileList2Fill)(props); }; /** * The react component for the `file-list-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-2-line.svg) */ export const FileList2LineIcon: IconType = (props) => { return GenIcon(fileList2Line)(props); }; /** * The react component for the `file-list-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-3-fill.svg) */ export const FileList3FillIcon: IconType = (props) => { return GenIcon(fileList3Fill)(props); }; /** * The react component for the `file-list-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-3-line.svg) */ export const FileList3LineIcon: IconType = (props) => { return GenIcon(fileList3Line)(props); }; /** * The react component for the `file-list-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-fill.svg) */ export const FileListFillIcon: IconType = (props) => { return GenIcon(fileListFill)(props); }; /** * The react component for the `file-list-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File List Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-list-line.svg) */ export const FileListLineIcon: IconType = (props) => { return GenIcon(fileListLine)(props); }; /** * The react component for the `file-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-lock-fill.svg) */ export const FileLockFillIcon: IconType = (props) => { return GenIcon(fileLockFill)(props); }; /** * The react component for the `file-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-lock-line.svg) */ export const FileLockLineIcon: IconType = (props) => { return GenIcon(fileLockLine)(props); }; /** * The react component for the `file-mark-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Mark Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-mark-fill.svg) */ export const FileMarkFillIcon: IconType = (props) => { return GenIcon(fileMarkFill)(props); }; /** * The react component for the `file-mark-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Mark Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-mark-line.svg) */ export const FileMarkLineIcon: IconType = (props) => { return GenIcon(fileMarkLine)(props); }; /** * The react component for the `file-music-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Music Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-music-fill.svg) */ export const FileMusicFillIcon: IconType = (props) => { return GenIcon(fileMusicFill)(props); }; /** * The react component for the `file-music-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Music Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-music-line.svg) */ export const FileMusicLineIcon: IconType = (props) => { return GenIcon(fileMusicLine)(props); }; /** * The react component for the `file-paper-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Paper 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-paper-2-fill.svg) */ export const FilePaper2FillIcon: IconType = (props) => { return GenIcon(filePaper2Fill)(props); }; /** * The react component for the `file-paper-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Paper 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-paper-2-line.svg) */ export const FilePaper2LineIcon: IconType = (props) => { return GenIcon(filePaper2Line)(props); }; /** * The react component for the `file-paper-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Paper Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-paper-fill.svg) */ export const FilePaperFillIcon: IconType = (props) => { return GenIcon(filePaperFill)(props); }; /** * The react component for the `file-paper-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Paper Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-paper-line.svg) */ export const FilePaperLineIcon: IconType = (props) => { return GenIcon(filePaperLine)(props); }; /** * The react component for the `file-pdf-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Pdf Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-pdf-fill.svg) */ export const FilePdfFillIcon: IconType = (props) => { return GenIcon(filePdfFill)(props); }; /** * The react component for the `file-pdf-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Pdf Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-pdf-line.svg) */ export const FilePdfLineIcon: IconType = (props) => { return GenIcon(filePdfLine)(props); }; /** * The react component for the `file-ppt-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Ppt 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-ppt-2-fill.svg) */ export const FilePpt2FillIcon: IconType = (props) => { return GenIcon(filePpt2Fill)(props); }; /** * The react component for the `file-ppt-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Ppt 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-ppt-2-line.svg) */ export const FilePpt2LineIcon: IconType = (props) => { return GenIcon(filePpt2Line)(props); }; /** * The react component for the `file-ppt-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Ppt Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-ppt-fill.svg) */ export const FilePptFillIcon: IconType = (props) => { return GenIcon(filePptFill)(props); }; /** * The react component for the `file-ppt-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Ppt Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-ppt-line.svg) */ export const FilePptLineIcon: IconType = (props) => { return GenIcon(filePptLine)(props); }; /** * The react component for the `file-reduce-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Reduce Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-reduce-fill.svg) */ export const FileReduceFillIcon: IconType = (props) => { return GenIcon(fileReduceFill)(props); }; /** * The react component for the `file-reduce-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Reduce Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-reduce-line.svg) */ export const FileReduceLineIcon: IconType = (props) => { return GenIcon(fileReduceLine)(props); }; /** * The react component for the `file-search-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Search Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-search-fill.svg) */ export const FileSearchFillIcon: IconType = (props) => { return GenIcon(fileSearchFill)(props); }; /** * The react component for the `file-search-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Search Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-search-line.svg) */ export const FileSearchLineIcon: IconType = (props) => { return GenIcon(fileSearchLine)(props); }; /** * The react component for the `file-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-settings-fill.svg) */ export const FileSettingsFillIcon: IconType = (props) => { return GenIcon(fileSettingsFill)(props); }; /** * The react component for the `file-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-settings-line.svg) */ export const FileSettingsLineIcon: IconType = (props) => { return GenIcon(fileSettingsLine)(props); }; /** * The react component for the `file-shield-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shield 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shield-2-fill.svg) */ export const FileShield2FillIcon: IconType = (props) => { return GenIcon(fileShield2Fill)(props); }; /** * The react component for the `file-shield-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shield 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shield-2-line.svg) */ export const FileShield2LineIcon: IconType = (props) => { return GenIcon(fileShield2Line)(props); }; /** * The react component for the `file-shield-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shield Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shield-fill.svg) */ export const FileShieldFillIcon: IconType = (props) => { return GenIcon(fileShieldFill)(props); }; /** * The react component for the `file-shield-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shield Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shield-line.svg) */ export const FileShieldLineIcon: IconType = (props) => { return GenIcon(fileShieldLine)(props); }; /** * The react component for the `file-shred-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shred Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shred-fill.svg) */ export const FileShredFillIcon: IconType = (props) => { return GenIcon(fileShredFill)(props); }; /** * The react component for the `file-shred-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Shred Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-shred-line.svg) */ export const FileShredLineIcon: IconType = (props) => { return GenIcon(fileShredLine)(props); }; /** * The react component for the `file-text-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Text Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-text-fill.svg) */ export const FileTextFillIcon: IconType = (props) => { return GenIcon(fileTextFill)(props); }; /** * The react component for the `file-text-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Text Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-text-line.svg) */ export const FileTextLineIcon: IconType = (props) => { return GenIcon(fileTextLine)(props); }; /** * The react component for the `file-transfer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Transfer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-transfer-fill.svg) */ export const FileTransferFillIcon: IconType = (props) => { return GenIcon(fileTransferFill)(props); }; /** * The react component for the `file-transfer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Transfer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-transfer-line.svg) */ export const FileTransferLineIcon: IconType = (props) => { return GenIcon(fileTransferLine)(props); }; /** * The react component for the `file-unknow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Unknow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-unknow-fill.svg) */ export const FileUnknowFillIcon: IconType = (props) => { return GenIcon(fileUnknowFill)(props); }; /** * The react component for the `file-unknow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Unknow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-unknow-line.svg) */ export const FileUnknowLineIcon: IconType = (props) => { return GenIcon(fileUnknowLine)(props); }; /** * The react component for the `file-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-upload-fill.svg) */ export const FileUploadFillIcon: IconType = (props) => { return GenIcon(fileUploadFill)(props); }; /** * The react component for the `file-upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-upload-line.svg) */ export const FileUploadLineIcon: IconType = (props) => { return GenIcon(fileUploadLine)(props); }; /** * The react component for the `file-user-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File User Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-user-fill.svg) */ export const FileUserFillIcon: IconType = (props) => { return GenIcon(fileUserFill)(props); }; /** * The react component for the `file-user-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File User Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-user-line.svg) */ export const FileUserLineIcon: IconType = (props) => { return GenIcon(fileUserLine)(props); }; /** * The react component for the `file-warning-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Warning Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-warning-fill.svg) */ export const FileWarningFillIcon: IconType = (props) => { return GenIcon(fileWarningFill)(props); }; /** * The react component for the `file-warning-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Warning Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-warning-line.svg) */ export const FileWarningLineIcon: IconType = (props) => { return GenIcon(fileWarningLine)(props); }; /** * The react component for the `file-word-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Word 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-word-2-fill.svg) */ export const FileWord2FillIcon: IconType = (props) => { return GenIcon(fileWord2Fill)(props); }; /** * The react component for the `file-word-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Word 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-word-2-line.svg) */ export const FileWord2LineIcon: IconType = (props) => { return GenIcon(fileWord2Line)(props); }; /** * The react component for the `file-word-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Word Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-word-fill.svg) */ export const FileWordFillIcon: IconType = (props) => { return GenIcon(fileWordFill)(props); }; /** * The react component for the `file-word-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Word Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-word-line.svg) */ export const FileWordLineIcon: IconType = (props) => { return GenIcon(fileWordLine)(props); }; /** * The react component for the `file-zip-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Zip Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-zip-fill.svg) */ export const FileZipFillIcon: IconType = (props) => { return GenIcon(fileZipFill)(props); }; /** * The react component for the `file-zip-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![File Zip Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/file-zip-line.svg) */ export const FileZipLineIcon: IconType = (props) => { return GenIcon(fileZipLine)(props); }; /** * The react component for the `film-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Film Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/film-fill.svg) */ export const FilmFillIcon: IconType = (props) => { return GenIcon(filmFill)(props); }; /** * The react component for the `film-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Film Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/film-line.svg) */ export const FilmLineIcon: IconType = (props) => { return GenIcon(filmLine)(props); }; /** * The react component for the `filter-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-2-fill.svg) */ export const Filter2FillIcon: IconType = (props) => { return GenIcon(filter2Fill)(props); }; /** * The react component for the `filter-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-2-line.svg) */ export const Filter2LineIcon: IconType = (props) => { return GenIcon(filter2Line)(props); }; /** * The react component for the `filter-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-3-fill.svg) */ export const Filter3FillIcon: IconType = (props) => { return GenIcon(filter3Fill)(props); }; /** * The react component for the `filter-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-3-line.svg) */ export const Filter3LineIcon: IconType = (props) => { return GenIcon(filter3Line)(props); }; /** * The react component for the `filter-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-fill.svg) */ export const FilterFillIcon: IconType = (props) => { return GenIcon(filterFill)(props); }; /** * The react component for the `filter-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-line.svg) */ export const FilterLineIcon: IconType = (props) => { return GenIcon(filterLine)(props); }; /** * The react component for the `filter-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-off-fill.svg) */ export const FilterOffFillIcon: IconType = (props) => { return GenIcon(filterOffFill)(props); }; /** * The react component for the `filter-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Filter Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/filter-off-line.svg) */ export const FilterOffLineIcon: IconType = (props) => { return GenIcon(filterOffLine)(props); }; /** * The react component for the `find-replace-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Find Replace Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/find-replace-fill.svg) */ export const FindReplaceFillIcon: IconType = (props) => { return GenIcon(findReplaceFill)(props); }; /** * The react component for the `find-replace-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Find Replace Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/find-replace-line.svg) */ export const FindReplaceLineIcon: IconType = (props) => { return GenIcon(findReplaceLine)(props); }; /** * The react component for the `finder-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Finder Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/finder-fill.svg) */ export const FinderFillIcon: IconType = (props) => { return GenIcon(finderFill)(props); }; /** * The react component for the `finder-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Finder Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/finder-line.svg) */ export const FinderLineIcon: IconType = (props) => { return GenIcon(finderLine)(props); }; /** * The react component for the `fingerprint-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fingerprint 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/fingerprint-2-fill.svg) */ export const Fingerprint2FillIcon: IconType = (props) => { return GenIcon(fingerprint2Fill)(props); }; /** * The react component for the `fingerprint-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fingerprint 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/fingerprint-2-line.svg) */ export const Fingerprint2LineIcon: IconType = (props) => { return GenIcon(fingerprint2Line)(props); }; /** * The react component for the `fingerprint-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fingerprint Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/fingerprint-fill.svg) */ export const FingerprintFillIcon: IconType = (props) => { return GenIcon(fingerprintFill)(props); }; /** * The react component for the `fingerprint-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fingerprint Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/fingerprint-line.svg) */ export const FingerprintLineIcon: IconType = (props) => { return GenIcon(fingerprintLine)(props); }; /** * The react component for the `fire-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fire Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/fire-fill.svg) */ export const FireFillIcon: IconType = (props) => { return GenIcon(fireFill)(props); }; /** * The react component for the `fire-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fire Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/fire-line.svg) */ export const FireLineIcon: IconType = (props) => { return GenIcon(fireLine)(props); }; /** * The react component for the `firefox-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Firefox Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/firefox-fill.svg) */ export const FirefoxFillIcon: IconType = (props) => { return GenIcon(firefoxFill)(props); }; /** * The react component for the `firefox-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Firefox Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/firefox-line.svg) */ export const FirefoxLineIcon: IconType = (props) => { return GenIcon(firefoxLine)(props); }; /** * The react component for the `first-aid-kit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![First Aid Kit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/first-aid-kit-fill.svg) */ export const FirstAidKitFillIcon: IconType = (props) => { return GenIcon(firstAidKitFill)(props); }; /** * The react component for the `first-aid-kit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![First Aid Kit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/first-aid-kit-line.svg) */ export const FirstAidKitLineIcon: IconType = (props) => { return GenIcon(firstAidKitLine)(props); }; /** * The react component for the `flag-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flag 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/flag-2-fill.svg) */ export const Flag2FillIcon: IconType = (props) => { return GenIcon(flag2Fill)(props); }; /** * The react component for the `flag-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flag 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/flag-2-line.svg) */ export const Flag2LineIcon: IconType = (props) => { return GenIcon(flag2Line)(props); }; /** * The react component for the `flag-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flag Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/flag-fill.svg) */ export const FlagFillIcon: IconType = (props) => { return GenIcon(flagFill)(props); }; /** * The react component for the `flag-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flag Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/flag-line.svg) */ export const FlagLineIcon: IconType = (props) => { return GenIcon(flagLine)(props); }; /** * The react component for the `flashlight-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flashlight Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/flashlight-fill.svg) */ export const FlashlightFillIcon: IconType = (props) => { return GenIcon(flashlightFill)(props); }; /** * The react component for the `flashlight-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flashlight Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/flashlight-line.svg) */ export const FlashlightLineIcon: IconType = (props) => { return GenIcon(flashlightLine)(props); }; /** * The react component for the `flask-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flask Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/flask-fill.svg) */ export const FlaskFillIcon: IconType = (props) => { return GenIcon(flaskFill)(props); }; /** * The react component for the `flask-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flask Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/flask-line.svg) */ export const FlaskLineIcon: IconType = (props) => { return GenIcon(flaskLine)(props); }; /** * The react component for the `flight-land-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flight Land Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/flight-land-fill.svg) */ export const FlightLandFillIcon: IconType = (props) => { return GenIcon(flightLandFill)(props); }; /** * The react component for the `flight-land-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flight Land Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/flight-land-line.svg) */ export const FlightLandLineIcon: IconType = (props) => { return GenIcon(flightLandLine)(props); }; /** * The react component for the `flight-takeoff-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flight Takeoff Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/flight-takeoff-fill.svg) */ export const FlightTakeoffFillIcon: IconType = (props) => { return GenIcon(flightTakeoffFill)(props); }; /** * The react component for the `flight-takeoff-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flight Takeoff Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/flight-takeoff-line.svg) */ export const FlightTakeoffLineIcon: IconType = (props) => { return GenIcon(flightTakeoffLine)(props); }; /** * The react component for the `flood-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flood Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/flood-fill.svg) */ export const FloodFillIcon: IconType = (props) => { return GenIcon(floodFill)(props); }; /** * The react component for the `flood-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flood Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/flood-line.svg) */ export const FloodLineIcon: IconType = (props) => { return GenIcon(floodLine)(props); }; /** * The react component for the `flutter-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flutter Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/flutter-fill.svg) */ export const FlutterFillIcon: IconType = (props) => { return GenIcon(flutterFill)(props); }; /** * The react component for the `flutter-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Flutter Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/flutter-line.svg) */ export const FlutterLineIcon: IconType = (props) => { return GenIcon(flutterLine)(props); }; /** * The react component for the `focus-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-2-fill.svg) */ export const Focus2FillIcon: IconType = (props) => { return GenIcon(focus2Fill)(props); }; /** * The react component for the `focus-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-2-line.svg) */ export const Focus2LineIcon: IconType = (props) => { return GenIcon(focus2Line)(props); }; /** * The react component for the `focus-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-3-fill.svg) */ export const Focus3FillIcon: IconType = (props) => { return GenIcon(focus3Fill)(props); }; /** * The react component for the `focus-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-3-line.svg) */ export const Focus3LineIcon: IconType = (props) => { return GenIcon(focus3Line)(props); }; /** * The react component for the `focus-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-fill.svg) */ export const FocusFillIcon: IconType = (props) => { return GenIcon(focusFill)(props); }; /** * The react component for the `focus-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Focus Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/focus-line.svg) */ export const FocusLineIcon: IconType = (props) => { return GenIcon(focusLine)(props); }; /** * The react component for the `foggy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Foggy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/foggy-fill.svg) */ export const FoggyFillIcon: IconType = (props) => { return GenIcon(foggyFill)(props); }; /** * The react component for the `foggy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Foggy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/foggy-line.svg) */ export const FoggyLineIcon: IconType = (props) => { return GenIcon(foggyLine)(props); }; /** * The react component for the `folder-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-2-fill.svg) */ export const Folder2FillIcon: IconType = (props) => { return GenIcon(folder2Fill)(props); }; /** * The react component for the `folder-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-2-line.svg) */ export const Folder2LineIcon: IconType = (props) => { return GenIcon(folder2Line)(props); }; /** * The react component for the `folder-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-3-fill.svg) */ export const Folder3FillIcon: IconType = (props) => { return GenIcon(folder3Fill)(props); }; /** * The react component for the `folder-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-3-line.svg) */ export const Folder3LineIcon: IconType = (props) => { return GenIcon(folder3Line)(props); }; /** * The react component for the `folder-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-4-fill.svg) */ export const Folder4FillIcon: IconType = (props) => { return GenIcon(folder4Fill)(props); }; /** * The react component for the `folder-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-4-line.svg) */ export const Folder4LineIcon: IconType = (props) => { return GenIcon(folder4Line)(props); }; /** * The react component for the `folder-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-5-fill.svg) */ export const Folder5FillIcon: IconType = (props) => { return GenIcon(folder5Fill)(props); }; /** * The react component for the `folder-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-5-line.svg) */ export const Folder5LineIcon: IconType = (props) => { return GenIcon(folder5Line)(props); }; /** * The react component for the `folder-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-add-fill.svg) */ export const FolderAddFillIcon: IconType = (props) => { return GenIcon(folderAddFill)(props); }; /** * The react component for the `folder-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-add-line.svg) */ export const FolderAddLineIcon: IconType = (props) => { return GenIcon(folderAddLine)(props); }; /** * The react component for the `folder-chart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Chart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-chart-2-fill.svg) */ export const FolderChart2FillIcon: IconType = (props) => { return GenIcon(folderChart2Fill)(props); }; /** * The react component for the `folder-chart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Chart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-chart-2-line.svg) */ export const FolderChart2LineIcon: IconType = (props) => { return GenIcon(folderChart2Line)(props); }; /** * The react component for the `folder-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-chart-fill.svg) */ export const FolderChartFillIcon: IconType = (props) => { return GenIcon(folderChartFill)(props); }; /** * The react component for the `folder-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-chart-line.svg) */ export const FolderChartLineIcon: IconType = (props) => { return GenIcon(folderChartLine)(props); }; /** * The react component for the `folder-download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-download-fill.svg) */ export const FolderDownloadFillIcon: IconType = (props) => { return GenIcon(folderDownloadFill)(props); }; /** * The react component for the `folder-download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-download-line.svg) */ export const FolderDownloadLineIcon: IconType = (props) => { return GenIcon(folderDownloadLine)(props); }; /** * The react component for the `folder-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-fill.svg) */ export const FolderFillIcon: IconType = (props) => { return GenIcon(folderFill)(props); }; /** * The react component for the `folder-forbid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Forbid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-forbid-fill.svg) */ export const FolderForbidFillIcon: IconType = (props) => { return GenIcon(folderForbidFill)(props); }; /** * The react component for the `folder-forbid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Forbid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-forbid-line.svg) */ export const FolderForbidLineIcon: IconType = (props) => { return GenIcon(folderForbidLine)(props); }; /** * The react component for the `folder-history-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder History Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-history-fill.svg) */ export const FolderHistoryFillIcon: IconType = (props) => { return GenIcon(folderHistoryFill)(props); }; /** * The react component for the `folder-history-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder History Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-history-line.svg) */ export const FolderHistoryLineIcon: IconType = (props) => { return GenIcon(folderHistoryLine)(props); }; /** * The react component for the `folder-info-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Info Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-info-fill.svg) */ export const FolderInfoFillIcon: IconType = (props) => { return GenIcon(folderInfoFill)(props); }; /** * The react component for the `folder-info-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Info Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-info-line.svg) */ export const FolderInfoLineIcon: IconType = (props) => { return GenIcon(folderInfoLine)(props); }; /** * The react component for the `folder-keyhole-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Keyhole Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-keyhole-fill.svg) */ export const FolderKeyholeFillIcon: IconType = (props) => { return GenIcon(folderKeyholeFill)(props); }; /** * The react component for the `folder-keyhole-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Keyhole Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-keyhole-line.svg) */ export const FolderKeyholeLineIcon: IconType = (props) => { return GenIcon(folderKeyholeLine)(props); }; /** * The react component for the `folder-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-line.svg) */ export const FolderLineIcon: IconType = (props) => { return GenIcon(folderLine)(props); }; /** * The react component for the `folder-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-lock-fill.svg) */ export const FolderLockFillIcon: IconType = (props) => { return GenIcon(folderLockFill)(props); }; /** * The react component for the `folder-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-lock-line.svg) */ export const FolderLockLineIcon: IconType = (props) => { return GenIcon(folderLockLine)(props); }; /** * The react component for the `folder-music-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Music Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-music-fill.svg) */ export const FolderMusicFillIcon: IconType = (props) => { return GenIcon(folderMusicFill)(props); }; /** * The react component for the `folder-music-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Music Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-music-line.svg) */ export const FolderMusicLineIcon: IconType = (props) => { return GenIcon(folderMusicLine)(props); }; /** * The react component for the `folder-open-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Open Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-open-fill.svg) */ export const FolderOpenFillIcon: IconType = (props) => { return GenIcon(folderOpenFill)(props); }; /** * The react component for the `folder-open-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Open Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-open-line.svg) */ export const FolderOpenLineIcon: IconType = (props) => { return GenIcon(folderOpenLine)(props); }; /** * The react component for the `folder-received-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Received Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-received-fill.svg) */ export const FolderReceivedFillIcon: IconType = (props) => { return GenIcon(folderReceivedFill)(props); }; /** * The react component for the `folder-received-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Received Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-received-line.svg) */ export const FolderReceivedLineIcon: IconType = (props) => { return GenIcon(folderReceivedLine)(props); }; /** * The react component for the `folder-reduce-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Reduce Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-reduce-fill.svg) */ export const FolderReduceFillIcon: IconType = (props) => { return GenIcon(folderReduceFill)(props); }; /** * The react component for the `folder-reduce-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Reduce Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-reduce-line.svg) */ export const FolderReduceLineIcon: IconType = (props) => { return GenIcon(folderReduceLine)(props); }; /** * The react component for the `folder-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-settings-fill.svg) */ export const FolderSettingsFillIcon: IconType = (props) => { return GenIcon(folderSettingsFill)(props); }; /** * The react component for the `folder-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-settings-line.svg) */ export const FolderSettingsLineIcon: IconType = (props) => { return GenIcon(folderSettingsLine)(props); }; /** * The react component for the `folder-shared-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shared Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shared-fill.svg) */ export const FolderSharedFillIcon: IconType = (props) => { return GenIcon(folderSharedFill)(props); }; /** * The react component for the `folder-shared-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shared Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shared-line.svg) */ export const FolderSharedLineIcon: IconType = (props) => { return GenIcon(folderSharedLine)(props); }; /** * The react component for the `folder-shield-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shield 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shield-2-fill.svg) */ export const FolderShield2FillIcon: IconType = (props) => { return GenIcon(folderShield2Fill)(props); }; /** * The react component for the `folder-shield-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shield 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shield-2-line.svg) */ export const FolderShield2LineIcon: IconType = (props) => { return GenIcon(folderShield2Line)(props); }; /** * The react component for the `folder-shield-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shield Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shield-fill.svg) */ export const FolderShieldFillIcon: IconType = (props) => { return GenIcon(folderShieldFill)(props); }; /** * The react component for the `folder-shield-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Shield Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-shield-line.svg) */ export const FolderShieldLineIcon: IconType = (props) => { return GenIcon(folderShieldLine)(props); }; /** * The react component for the `folder-transfer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Transfer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-transfer-fill.svg) */ export const FolderTransferFillIcon: IconType = (props) => { return GenIcon(folderTransferFill)(props); }; /** * The react component for the `folder-transfer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Transfer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-transfer-line.svg) */ export const FolderTransferLineIcon: IconType = (props) => { return GenIcon(folderTransferLine)(props); }; /** * The react component for the `folder-unknow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Unknow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-unknow-fill.svg) */ export const FolderUnknowFillIcon: IconType = (props) => { return GenIcon(folderUnknowFill)(props); }; /** * The react component for the `folder-unknow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Unknow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-unknow-line.svg) */ export const FolderUnknowLineIcon: IconType = (props) => { return GenIcon(folderUnknowLine)(props); }; /** * The react component for the `folder-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-upload-fill.svg) */ export const FolderUploadFillIcon: IconType = (props) => { return GenIcon(folderUploadFill)(props); }; /** * The react component for the `folder-upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-upload-line.svg) */ export const FolderUploadLineIcon: IconType = (props) => { return GenIcon(folderUploadLine)(props); }; /** * The react component for the `folder-user-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder User Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-user-fill.svg) */ export const FolderUserFillIcon: IconType = (props) => { return GenIcon(folderUserFill)(props); }; /** * The react component for the `folder-user-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder User Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-user-line.svg) */ export const FolderUserLineIcon: IconType = (props) => { return GenIcon(folderUserLine)(props); }; /** * The react component for the `folder-warning-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Warning Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-warning-fill.svg) */ export const FolderWarningFillIcon: IconType = (props) => { return GenIcon(folderWarningFill)(props); }; /** * The react component for the `folder-warning-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Warning Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-warning-line.svg) */ export const FolderWarningLineIcon: IconType = (props) => { return GenIcon(folderWarningLine)(props); }; /** * The react component for the `folder-zip-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Zip Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-zip-fill.svg) */ export const FolderZipFillIcon: IconType = (props) => { return GenIcon(folderZipFill)(props); }; /** * The react component for the `folder-zip-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folder Zip Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folder-zip-line.svg) */ export const FolderZipLineIcon: IconType = (props) => { return GenIcon(folderZipLine)(props); }; /** * The react component for the `folders-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folders Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folders-fill.svg) */ export const FoldersFillIcon: IconType = (props) => { return GenIcon(foldersFill)(props); }; /** * The react component for the `folders-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Folders Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/folders-line.svg) */ export const FoldersLineIcon: IconType = (props) => { return GenIcon(foldersLine)(props); }; /** * The react component for the `football-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Football Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/football-fill.svg) */ export const FootballFillIcon: IconType = (props) => { return GenIcon(footballFill)(props); }; /** * The react component for the `football-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Football Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/football-line.svg) */ export const FootballLineIcon: IconType = (props) => { return GenIcon(footballLine)(props); }; /** * The react component for the `footprint-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Footprint Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/footprint-fill.svg) */ export const FootprintFillIcon: IconType = (props) => { return GenIcon(footprintFill)(props); }; /** * The react component for the `footprint-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Footprint Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/footprint-line.svg) */ export const FootprintLineIcon: IconType = (props) => { return GenIcon(footprintLine)(props); }; /** * The react component for the `forbid-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Forbid 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/forbid-2-fill.svg) */ export const Forbid2FillIcon: IconType = (props) => { return GenIcon(forbid2Fill)(props); }; /** * The react component for the `forbid-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Forbid 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/forbid-2-line.svg) */ export const Forbid2LineIcon: IconType = (props) => { return GenIcon(forbid2Line)(props); }; /** * The react component for the `forbid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Forbid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/forbid-fill.svg) */ export const ForbidFillIcon: IconType = (props) => { return GenIcon(forbidFill)(props); }; /** * The react component for the `forbid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Forbid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/forbid-line.svg) */ export const ForbidLineIcon: IconType = (props) => { return GenIcon(forbidLine)(props); }; /** * The react component for the `fridge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fridge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/fridge-fill.svg) */ export const FridgeFillIcon: IconType = (props) => { return GenIcon(fridgeFill)(props); }; /** * The react component for the `fridge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fridge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/fridge-line.svg) */ export const FridgeLineIcon: IconType = (props) => { return GenIcon(fridgeLine)(props); }; /** * The react component for the `fullscreen-exit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fullscreen Exit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/fullscreen-exit-fill.svg) */ export const FullscreenExitFillIcon: IconType = (props) => { return GenIcon(fullscreenExitFill)(props); }; /** * The react component for the `fullscreen-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Fullscreen Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/fullscreen-fill.svg) */ export const FullscreenFillIcon: IconType = (props) => { return GenIcon(fullscreenFill)(props); }; /** * The react component for the `function-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Function Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/function-fill.svg) */ export const FunctionFillIcon: IconType = (props) => { return GenIcon(functionFill)(props); }; /** * The react component for the `function-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Function Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/function-line.svg) */ export const FunctionLineIcon: IconType = (props) => { return GenIcon(functionLine)(props); }; /** * The react component for the `funds-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Funds Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/funds-box-fill.svg) */ export const FundsBoxFillIcon: IconType = (props) => { return GenIcon(fundsBoxFill)(props); }; /** * The react component for the `funds-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Funds Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/funds-box-line.svg) */ export const FundsBoxLineIcon: IconType = (props) => { return GenIcon(fundsBoxLine)(props); }; /** * The react component for the `funds-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Funds Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/funds-fill.svg) */ export const FundsFillIcon: IconType = (props) => { return GenIcon(fundsFill)(props); }; /** * The react component for the `funds-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Funds Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/funds-line.svg) */ export const FundsLineIcon: IconType = (props) => { return GenIcon(fundsLine)(props); }; /** * The react component for the `gallery-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gallery Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/gallery-fill.svg) */ export const GalleryFillIcon: IconType = (props) => { return GenIcon(galleryFill)(props); }; /** * The react component for the `gallery-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gallery Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/gallery-line.svg) */ export const GalleryLineIcon: IconType = (props) => { return GenIcon(galleryLine)(props); }; /** * The react component for the `gallery-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gallery Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/gallery-upload-fill.svg) */ export const GalleryUploadFillIcon: IconType = (props) => { return GenIcon(galleryUploadFill)(props); }; /** * The react component for the `game-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Game Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/game-fill.svg) */ export const GameFillIcon: IconType = (props) => { return GenIcon(gameFill)(props); }; /** * The react component for the `game-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Game Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/game-line.svg) */ export const GameLineIcon: IconType = (props) => { return GenIcon(gameLine)(props); }; /** * The react component for the `gamepad-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gamepad Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gamepad-fill.svg) */ export const GamepadFillIcon: IconType = (props) => { return GenIcon(gamepadFill)(props); }; /** * The react component for the `gamepad-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gamepad Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gamepad-line.svg) */ export const GamepadLineIcon: IconType = (props) => { return GenIcon(gamepadLine)(props); }; /** * The react component for the `gas-station-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gas Station Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/gas-station-fill.svg) */ export const GasStationFillIcon: IconType = (props) => { return GenIcon(gasStationFill)(props); }; /** * The react component for the `gas-station-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gas Station Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/gas-station-line.svg) */ export const GasStationLineIcon: IconType = (props) => { return GenIcon(gasStationLine)(props); }; /** * The react component for the `gatsby-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gatsby Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/gatsby-fill.svg) */ export const GatsbyFillIcon: IconType = (props) => { return GenIcon(gatsbyFill)(props); }; /** * The react component for the `gatsby-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gatsby Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/gatsby-line.svg) */ export const GatsbyLineIcon: IconType = (props) => { return GenIcon(gatsbyLine)(props); }; /** * The react component for the `genderless-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Genderless Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/genderless-fill.svg) */ export const GenderlessFillIcon: IconType = (props) => { return GenIcon(genderlessFill)(props); }; /** * The react component for the `genderless-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Genderless Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/genderless-line.svg) */ export const GenderlessLineIcon: IconType = (props) => { return GenIcon(genderlessLine)(props); }; /** * The react component for the `ghost-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-2-fill.svg) */ export const Ghost2FillIcon: IconType = (props) => { return GenIcon(ghost2Fill)(props); }; /** * The react component for the `ghost-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-2-line.svg) */ export const Ghost2LineIcon: IconType = (props) => { return GenIcon(ghost2Line)(props); }; /** * The react component for the `ghost-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-fill.svg) */ export const GhostFillIcon: IconType = (props) => { return GenIcon(ghostFill)(props); }; /** * The react component for the `ghost-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-line.svg) */ export const GhostLineIcon: IconType = (props) => { return GenIcon(ghostLine)(props); }; /** * The react component for the `ghost-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-smile-fill.svg) */ export const GhostSmileFillIcon: IconType = (props) => { return GenIcon(ghostSmileFill)(props); }; /** * The react component for the `ghost-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ghost Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/ghost-smile-line.svg) */ export const GhostSmileLineIcon: IconType = (props) => { return GenIcon(ghostSmileLine)(props); }; /** * The react component for the `gift-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gift 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/gift-2-fill.svg) */ export const Gift2FillIcon: IconType = (props) => { return GenIcon(gift2Fill)(props); }; /** * The react component for the `gift-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gift 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/gift-2-line.svg) */ export const Gift2LineIcon: IconType = (props) => { return GenIcon(gift2Line)(props); }; /** * The react component for the `gift-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gift Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/gift-fill.svg) */ export const GiftFillIcon: IconType = (props) => { return GenIcon(giftFill)(props); }; /** * The react component for the `gift-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gift Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/gift-line.svg) */ export const GiftLineIcon: IconType = (props) => { return GenIcon(giftLine)(props); }; /** * The react component for the `git-branch-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Branch Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-branch-fill.svg) */ export const GitBranchFillIcon: IconType = (props) => { return GenIcon(gitBranchFill)(props); }; /** * The react component for the `git-branch-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Branch Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-branch-line.svg) */ export const GitBranchLineIcon: IconType = (props) => { return GenIcon(gitBranchLine)(props); }; /** * The react component for the `git-commit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Commit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-commit-fill.svg) */ export const GitCommitFillIcon: IconType = (props) => { return GenIcon(gitCommitFill)(props); }; /** * The react component for the `git-commit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Commit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-commit-line.svg) */ export const GitCommitLineIcon: IconType = (props) => { return GenIcon(gitCommitLine)(props); }; /** * The react component for the `git-merge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Merge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-merge-fill.svg) */ export const GitMergeFillIcon: IconType = (props) => { return GenIcon(gitMergeFill)(props); }; /** * The react component for the `git-merge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Merge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-merge-line.svg) */ export const GitMergeLineIcon: IconType = (props) => { return GenIcon(gitMergeLine)(props); }; /** * The react component for the `git-pull-request-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Pull Request Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-pull-request-fill.svg) */ export const GitPullRequestFillIcon: IconType = (props) => { return GenIcon(gitPullRequestFill)(props); }; /** * The react component for the `git-pull-request-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Pull Request Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-pull-request-line.svg) */ export const GitPullRequestLineIcon: IconType = (props) => { return GenIcon(gitPullRequestLine)(props); }; /** * The react component for the `git-repository-commits-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Commits Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-commits-fill.svg) */ export const GitRepositoryCommitsFillIcon: IconType = (props) => { return GenIcon(gitRepositoryCommitsFill)(props); }; /** * The react component for the `git-repository-commits-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Commits Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-commits-line.svg) */ export const GitRepositoryCommitsLineIcon: IconType = (props) => { return GenIcon(gitRepositoryCommitsLine)(props); }; /** * The react component for the `git-repository-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-fill.svg) */ export const GitRepositoryFillIcon: IconType = (props) => { return GenIcon(gitRepositoryFill)(props); }; /** * The react component for the `git-repository-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-line.svg) */ export const GitRepositoryLineIcon: IconType = (props) => { return GenIcon(gitRepositoryLine)(props); }; /** * The react component for the `git-repository-private-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Private Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-private-fill.svg) */ export const GitRepositoryPrivateFillIcon: IconType = (props) => { return GenIcon(gitRepositoryPrivateFill)(props); }; /** * The react component for the `git-repository-private-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Git Repository Private Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/git-repository-private-line.svg) */ export const GitRepositoryPrivateLineIcon: IconType = (props) => { return GenIcon(gitRepositoryPrivateLine)(props); }; /** * The react component for the `github-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Github Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/github-fill.svg) */ export const GithubFillIcon: IconType = (props) => { return GenIcon(githubFill)(props); }; /** * The react component for the `github-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Github Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/github-line.svg) */ export const GithubLineIcon: IconType = (props) => { return GenIcon(githubLine)(props); }; /** * The react component for the `gitlab-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gitlab Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/gitlab-fill.svg) */ export const GitlabFillIcon: IconType = (props) => { return GenIcon(gitlabFill)(props); }; /** * The react component for the `gitlab-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gitlab Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/gitlab-line.svg) */ export const GitlabLineIcon: IconType = (props) => { return GenIcon(gitlabLine)(props); }; /** * The react component for the `global-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Global Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/global-fill.svg) */ export const GlobalFillIcon: IconType = (props) => { return GenIcon(globalFill)(props); }; /** * The react component for the `global-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Global Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/global-line.svg) */ export const GlobalLineIcon: IconType = (props) => { return GenIcon(globalLine)(props); }; /** * The react component for the `globe-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Globe Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/globe-fill.svg) */ export const GlobeFillIcon: IconType = (props) => { return GenIcon(globeFill)(props); }; /** * The react component for the `globe-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Globe Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/globe-line.svg) */ export const GlobeLineIcon: IconType = (props) => { return GenIcon(globeLine)(props); }; /** * The react component for the `goblet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Goblet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/goblet-fill.svg) */ export const GobletFillIcon: IconType = (props) => { return GenIcon(gobletFill)(props); }; /** * The react component for the `goblet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Goblet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/goblet-line.svg) */ export const GobletLineIcon: IconType = (props) => { return GenIcon(gobletLine)(props); }; /** * The react component for the `google-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Google Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/google-fill.svg) */ export const GoogleFillIcon: IconType = (props) => { return GenIcon(googleFill)(props); }; /** * The react component for the `google-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Google Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/google-line.svg) */ export const GoogleLineIcon: IconType = (props) => { return GenIcon(googleLine)(props); }; /** * The react component for the `google-play-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Google Play Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/google-play-fill.svg) */ export const GooglePlayFillIcon: IconType = (props) => { return GenIcon(googlePlayFill)(props); }; /** * The react component for the `google-play-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Google Play Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/google-play-line.svg) */ export const GooglePlayLineIcon: IconType = (props) => { return GenIcon(googlePlayLine)(props); }; /** * The react component for the `government-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Government Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/government-fill.svg) */ export const GovernmentFillIcon: IconType = (props) => { return GenIcon(governmentFill)(props); }; /** * The react component for the `government-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Government Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/government-line.svg) */ export const GovernmentLineIcon: IconType = (props) => { return GenIcon(governmentLine)(props); }; /** * The react component for the `gps-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gps Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gps-fill.svg) */ export const GpsFillIcon: IconType = (props) => { return GenIcon(gpsFill)(props); }; /** * The react component for the `gps-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gps Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gps-line.svg) */ export const GpsLineIcon: IconType = (props) => { return GenIcon(gpsLine)(props); }; /** * The react component for the `gradienter-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gradienter Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gradienter-fill.svg) */ export const GradienterFillIcon: IconType = (props) => { return GenIcon(gradienterFill)(props); }; /** * The react component for the `gradienter-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Gradienter Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/gradienter-line.svg) */ export const GradienterLineIcon: IconType = (props) => { return GenIcon(gradienterLine)(props); }; /** * The react component for the `grid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Grid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/grid-fill.svg) */ export const GridFillIcon: IconType = (props) => { return GenIcon(gridFill)(props); }; /** * The react component for the `grid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Grid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/grid-line.svg) */ export const GridLineIcon: IconType = (props) => { return GenIcon(gridLine)(props); }; /** * The react component for the `group-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Group 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/group-2-fill.svg) */ export const Group2FillIcon: IconType = (props) => { return GenIcon(group2Fill)(props); }; /** * The react component for the `group-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Group 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/group-2-line.svg) */ export const Group2LineIcon: IconType = (props) => { return GenIcon(group2Line)(props); }; /** * The react component for the `group-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Group Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/group-fill.svg) */ export const GroupFillIcon: IconType = (props) => { return GenIcon(groupFill)(props); }; /** * The react component for the `group-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Group Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/group-line.svg) */ export const GroupLineIcon: IconType = (props) => { return GenIcon(groupLine)(props); }; /** * The react component for the `guide-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Guide Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/guide-fill.svg) */ export const GuideFillIcon: IconType = (props) => { return GenIcon(guideFill)(props); }; /** * The react component for the `guide-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Guide Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/guide-line.svg) */ export const GuideLineIcon: IconType = (props) => { return GenIcon(guideLine)(props); }; /** * The react component for the `hail-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hail Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/hail-fill.svg) */ export const HailFillIcon: IconType = (props) => { return GenIcon(hailFill)(props); }; /** * The react component for the `hail-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hail Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/hail-line.svg) */ export const HailLineIcon: IconType = (props) => { return GenIcon(hailLine)(props); }; /** * The react component for the `hammer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hammer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/hammer-fill.svg) */ export const HammerFillIcon: IconType = (props) => { return GenIcon(hammerFill)(props); }; /** * The react component for the `hammer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hammer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/hammer-line.svg) */ export const HammerLineIcon: IconType = (props) => { return GenIcon(hammerLine)(props); }; /** * The react component for the `hand-coin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Coin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/hand-coin-fill.svg) */ export const HandCoinFillIcon: IconType = (props) => { return GenIcon(handCoinFill)(props); }; /** * The react component for the `hand-coin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Coin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/hand-coin-line.svg) */ export const HandCoinLineIcon: IconType = (props) => { return GenIcon(handCoinLine)(props); }; /** * The react component for the `hand-heart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Heart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/hand-heart-fill.svg) */ export const HandHeartFillIcon: IconType = (props) => { return GenIcon(handHeartFill)(props); }; /** * The react component for the `hand-heart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Heart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/hand-heart-line.svg) */ export const HandHeartLineIcon: IconType = (props) => { return GenIcon(handHeartLine)(props); }; /** * The react component for the `hand-sanitizer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Sanitizer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/hand-sanitizer-fill.svg) */ export const HandSanitizerFillIcon: IconType = (props) => { return GenIcon(handSanitizerFill)(props); }; /** * The react component for the `hand-sanitizer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hand Sanitizer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/hand-sanitizer-line.svg) */ export const HandSanitizerLineIcon: IconType = (props) => { return GenIcon(handSanitizerLine)(props); }; /** * The react component for the `handbag-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Handbag Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/handbag-fill.svg) */ export const HandbagFillIcon: IconType = (props) => { return GenIcon(handbagFill)(props); }; /** * The react component for the `handbag-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Handbag Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/handbag-line.svg) */ export const HandbagLineIcon: IconType = (props) => { return GenIcon(handbagLine)(props); }; /** * The react component for the `hard-drive-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hard Drive 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hard-drive-2-fill.svg) */ export const HardDrive2FillIcon: IconType = (props) => { return GenIcon(hardDrive2Fill)(props); }; /** * The react component for the `hard-drive-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hard Drive 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hard-drive-2-line.svg) */ export const HardDrive2LineIcon: IconType = (props) => { return GenIcon(hardDrive2Line)(props); }; /** * The react component for the `hard-drive-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hard Drive Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hard-drive-fill.svg) */ export const HardDriveFillIcon: IconType = (props) => { return GenIcon(hardDriveFill)(props); }; /** * The react component for the `hard-drive-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hard Drive Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hard-drive-line.svg) */ export const HardDriveLineIcon: IconType = (props) => { return GenIcon(hardDriveLine)(props); }; /** * The react component for the `haze-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Haze 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/haze-2-fill.svg) */ export const Haze2FillIcon: IconType = (props) => { return GenIcon(haze2Fill)(props); }; /** * The react component for the `haze-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Haze 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/haze-2-line.svg) */ export const Haze2LineIcon: IconType = (props) => { return GenIcon(haze2Line)(props); }; /** * The react component for the `haze-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Haze Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/haze-fill.svg) */ export const HazeFillIcon: IconType = (props) => { return GenIcon(hazeFill)(props); }; /** * The react component for the `haze-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Haze Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/haze-line.svg) */ export const HazeLineIcon: IconType = (props) => { return GenIcon(hazeLine)(props); }; /** * The react component for the `hd-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hd Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/hd-fill.svg) */ export const HdFillIcon: IconType = (props) => { return GenIcon(hdFill)(props); }; /** * The react component for the `hd-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hd Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/hd-line.svg) */ export const HdLineIcon: IconType = (props) => { return GenIcon(hdLine)(props); }; /** * The react component for the `headphone-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Headphone Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/headphone-fill.svg) */ export const HeadphoneFillIcon: IconType = (props) => { return GenIcon(headphoneFill)(props); }; /** * The react component for the `headphone-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Headphone Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/headphone-line.svg) */ export const HeadphoneLineIcon: IconType = (props) => { return GenIcon(headphoneLine)(props); }; /** * The react component for the `health-book-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Health Book Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/health-book-fill.svg) */ export const HealthBookFillIcon: IconType = (props) => { return GenIcon(healthBookFill)(props); }; /** * The react component for the `health-book-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Health Book Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/health-book-line.svg) */ export const HealthBookLineIcon: IconType = (props) => { return GenIcon(healthBookLine)(props); }; /** * The react component for the `heart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-2-fill.svg) */ export const Heart2FillIcon: IconType = (props) => { return GenIcon(heart2Fill)(props); }; /** * The react component for the `heart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-2-line.svg) */ export const Heart2LineIcon: IconType = (props) => { return GenIcon(heart2Line)(props); }; /** * The react component for the `heart-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-3-fill.svg) */ export const Heart3FillIcon: IconType = (props) => { return GenIcon(heart3Fill)(props); }; /** * The react component for the `heart-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-3-line.svg) */ export const Heart3LineIcon: IconType = (props) => { return GenIcon(heart3Line)(props); }; /** * The react component for the `heart-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-add-fill.svg) */ export const HeartAddFillIcon: IconType = (props) => { return GenIcon(heartAddFill)(props); }; /** * The react component for the `heart-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-add-line.svg) */ export const HeartAddLineIcon: IconType = (props) => { return GenIcon(heartAddLine)(props); }; /** * The react component for the `heart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-fill.svg) */ export const HeartFillIcon: IconType = (props) => { return GenIcon(heartFill)(props); }; /** * The react component for the `heart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-line.svg) */ export const HeartLineIcon: IconType = (props) => { return GenIcon(heartLine)(props); }; /** * The react component for the `heart-pulse-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Pulse Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-pulse-fill.svg) */ export const HeartPulseFillIcon: IconType = (props) => { return GenIcon(heartPulseFill)(props); }; /** * The react component for the `heart-pulse-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heart Pulse Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/heart-pulse-line.svg) */ export const HeartPulseLineIcon: IconType = (props) => { return GenIcon(heartPulseLine)(props); }; /** * The react component for the `hearts-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hearts Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/hearts-fill.svg) */ export const HeartsFillIcon: IconType = (props) => { return GenIcon(heartsFill)(props); }; /** * The react component for the `hearts-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hearts Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/hearts-line.svg) */ export const HeartsLineIcon: IconType = (props) => { return GenIcon(heartsLine)(props); }; /** * The react component for the `heavy-showers-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heavy Showers Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/heavy-showers-fill.svg) */ export const HeavyShowersFillIcon: IconType = (props) => { return GenIcon(heavyShowersFill)(props); }; /** * The react component for the `heavy-showers-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Heavy Showers Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/heavy-showers-line.svg) */ export const HeavyShowersLineIcon: IconType = (props) => { return GenIcon(heavyShowersLine)(props); }; /** * The react component for the `history-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![History Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/history-fill.svg) */ export const HistoryFillIcon: IconType = (props) => { return GenIcon(historyFill)(props); }; /** * The react component for the `history-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![History Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/history-line.svg) */ export const HistoryLineIcon: IconType = (props) => { return GenIcon(historyLine)(props); }; /** * The react component for the `home-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-2-fill.svg) */ export const Home2FillIcon: IconType = (props) => { return GenIcon(home2Fill)(props); }; /** * The react component for the `home-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-2-line.svg) */ export const Home2LineIcon: IconType = (props) => { return GenIcon(home2Line)(props); }; /** * The react component for the `home-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-3-fill.svg) */ export const Home3FillIcon: IconType = (props) => { return GenIcon(home3Fill)(props); }; /** * The react component for the `home-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-3-line.svg) */ export const Home3LineIcon: IconType = (props) => { return GenIcon(home3Line)(props); }; /** * The react component for the `home-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-4-fill.svg) */ export const Home4FillIcon: IconType = (props) => { return GenIcon(home4Fill)(props); }; /** * The react component for the `home-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-4-line.svg) */ export const Home4LineIcon: IconType = (props) => { return GenIcon(home4Line)(props); }; /** * The react component for the `home-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-5-fill.svg) */ export const Home5FillIcon: IconType = (props) => { return GenIcon(home5Fill)(props); }; /** * The react component for the `home-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-5-line.svg) */ export const Home5LineIcon: IconType = (props) => { return GenIcon(home5Line)(props); }; /** * The react component for the `home-6-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 6 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-6-fill.svg) */ export const Home6FillIcon: IconType = (props) => { return GenIcon(home6Fill)(props); }; /** * The react component for the `home-6-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 6 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-6-line.svg) */ export const Home6LineIcon: IconType = (props) => { return GenIcon(home6Line)(props); }; /** * The react component for the `home-7-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 7 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-7-fill.svg) */ export const Home7FillIcon: IconType = (props) => { return GenIcon(home7Fill)(props); }; /** * The react component for the `home-7-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 7 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-7-line.svg) */ export const Home7LineIcon: IconType = (props) => { return GenIcon(home7Line)(props); }; /** * The react component for the `home-8-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 8 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-8-fill.svg) */ export const Home8FillIcon: IconType = (props) => { return GenIcon(home8Fill)(props); }; /** * The react component for the `home-8-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home 8 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-8-line.svg) */ export const Home8LineIcon: IconType = (props) => { return GenIcon(home8Line)(props); }; /** * The react component for the `home-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-fill.svg) */ export const HomeFillIcon: IconType = (props) => { return GenIcon(homeFill)(props); }; /** * The react component for the `home-gear-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Gear Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-gear-fill.svg) */ export const HomeGearFillIcon: IconType = (props) => { return GenIcon(homeGearFill)(props); }; /** * The react component for the `home-gear-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Gear Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-gear-line.svg) */ export const HomeGearLineIcon: IconType = (props) => { return GenIcon(homeGearLine)(props); }; /** * The react component for the `home-heart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Heart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-heart-fill.svg) */ export const HomeHeartFillIcon: IconType = (props) => { return GenIcon(homeHeartFill)(props); }; /** * The react component for the `home-heart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Heart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-heart-line.svg) */ export const HomeHeartLineIcon: IconType = (props) => { return GenIcon(homeHeartLine)(props); }; /** * The react component for the `home-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-line.svg) */ export const HomeLineIcon: IconType = (props) => { return GenIcon(homeLine)(props); }; /** * The react component for the `home-smile-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Smile 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-smile-2-fill.svg) */ export const HomeSmile2FillIcon: IconType = (props) => { return GenIcon(homeSmile2Fill)(props); }; /** * The react component for the `home-smile-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Smile 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-smile-2-line.svg) */ export const HomeSmile2LineIcon: IconType = (props) => { return GenIcon(homeSmile2Line)(props); }; /** * The react component for the `home-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-smile-fill.svg) */ export const HomeSmileFillIcon: IconType = (props) => { return GenIcon(homeSmileFill)(props); }; /** * The react component for the `home-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-smile-line.svg) */ export const HomeSmileLineIcon: IconType = (props) => { return GenIcon(homeSmileLine)(props); }; /** * The react component for the `home-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-wifi-fill.svg) */ export const HomeWifiFillIcon: IconType = (props) => { return GenIcon(homeWifiFill)(props); }; /** * The react component for the `home-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Home Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/home-wifi-line.svg) */ export const HomeWifiLineIcon: IconType = (props) => { return GenIcon(homeWifiLine)(props); }; /** * The react component for the `honor-of-kings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Honor Of Kings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/honor-of-kings-fill.svg) */ export const HonorOfKingsFillIcon: IconType = (props) => { return GenIcon(honorOfKingsFill)(props); }; /** * The react component for the `honor-of-kings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Honor Of Kings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/honor-of-kings-line.svg) */ export const HonorOfKingsLineIcon: IconType = (props) => { return GenIcon(honorOfKingsLine)(props); }; /** * The react component for the `honour-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Honour Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/honour-fill.svg) */ export const HonourFillIcon: IconType = (props) => { return GenIcon(honourFill)(props); }; /** * The react component for the `honour-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Honour Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/honour-line.svg) */ export const HonourLineIcon: IconType = (props) => { return GenIcon(honourLine)(props); }; /** * The react component for the `hospital-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hospital Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/hospital-fill.svg) */ export const HospitalFillIcon: IconType = (props) => { return GenIcon(hospitalFill)(props); }; /** * The react component for the `hospital-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hospital Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/hospital-line.svg) */ export const HospitalLineIcon: IconType = (props) => { return GenIcon(hospitalLine)(props); }; /** * The react component for the `hotel-bed-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotel Bed Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/hotel-bed-fill.svg) */ export const HotelBedFillIcon: IconType = (props) => { return GenIcon(hotelBedFill)(props); }; /** * The react component for the `hotel-bed-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotel Bed Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/hotel-bed-line.svg) */ export const HotelBedLineIcon: IconType = (props) => { return GenIcon(hotelBedLine)(props); }; /** * The react component for the `hotel-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotel Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/hotel-fill.svg) */ export const HotelFillIcon: IconType = (props) => { return GenIcon(hotelFill)(props); }; /** * The react component for the `hotel-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotel Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/hotel-line.svg) */ export const HotelLineIcon: IconType = (props) => { return GenIcon(hotelLine)(props); }; /** * The react component for the `hotspot-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotspot Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hotspot-fill.svg) */ export const HotspotFillIcon: IconType = (props) => { return GenIcon(hotspotFill)(props); }; /** * The react component for the `hotspot-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hotspot Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/hotspot-line.svg) */ export const HotspotLineIcon: IconType = (props) => { return GenIcon(hotspotLine)(props); }; /** * The react component for the `hq-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hq Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/hq-fill.svg) */ export const HqFillIcon: IconType = (props) => { return GenIcon(hqFill)(props); }; /** * The react component for the `hq-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Hq Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/hq-line.svg) */ export const HqLineIcon: IconType = (props) => { return GenIcon(hqLine)(props); }; /** * The react component for the `html-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Html 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/html5-fill.svg) */ export const Html5FillIcon: IconType = (props) => { return GenIcon(html5Fill)(props); }; /** * The react component for the `html-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Html 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/html5-line.svg) */ export const Html5LineIcon: IconType = (props) => { return GenIcon(html5Line)(props); }; /** * The react component for the `ie-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ie Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/ie-fill.svg) */ export const IeFillIcon: IconType = (props) => { return GenIcon(ieFill)(props); }; /** * The react component for the `ie-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ie Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/ie-line.svg) */ export const IeLineIcon: IconType = (props) => { return GenIcon(ieLine)(props); }; /** * The react component for the `image-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Image 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/image-2-fill.svg) */ export const Image2FillIcon: IconType = (props) => { return GenIcon(image2Fill)(props); }; /** * The react component for the `image-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Image 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/image-2-line.svg) */ export const Image2LineIcon: IconType = (props) => { return GenIcon(image2Line)(props); }; /** * The react component for the `image-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Image Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/image-add-fill.svg) */ export const ImageAddFillIcon: IconType = (props) => { return GenIcon(imageAddFill)(props); }; /** * The react component for the `image-edit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Image Edit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/image-edit-fill.svg) */ export const ImageEditFillIcon: IconType = (props) => { return GenIcon(imageEditFill)(props); }; /** * The react component for the `image-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Image Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/image-fill.svg) */ export const ImageFillIcon: IconType = (props) => { return GenIcon(imageFill)(props); }; /** * The react component for the `inbox-archive-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Archive Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-archive-fill.svg) */ export const InboxArchiveFillIcon: IconType = (props) => { return GenIcon(inboxArchiveFill)(props); }; /** * The react component for the `inbox-archive-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Archive Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-archive-line.svg) */ export const InboxArchiveLineIcon: IconType = (props) => { return GenIcon(inboxArchiveLine)(props); }; /** * The react component for the `inbox-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-fill.svg) */ export const InboxFillIcon: IconType = (props) => { return GenIcon(inboxFill)(props); }; /** * The react component for the `inbox-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-line.svg) */ export const InboxLineIcon: IconType = (props) => { return GenIcon(inboxLine)(props); }; /** * The react component for the `inbox-unarchive-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Unarchive Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-unarchive-fill.svg) */ export const InboxUnarchiveFillIcon: IconType = (props) => { return GenIcon(inboxUnarchiveFill)(props); }; /** * The react component for the `inbox-unarchive-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Inbox Unarchive Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/inbox-unarchive-line.svg) */ export const InboxUnarchiveLineIcon: IconType = (props) => { return GenIcon(inboxUnarchiveLine)(props); }; /** * The react component for the `increase-decrease-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Increase Decrease Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/increase-decrease-fill.svg) */ export const IncreaseDecreaseFillIcon: IconType = (props) => { return GenIcon(increaseDecreaseFill)(props); }; /** * The react component for the `increase-decrease-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Increase Decrease Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/increase-decrease-line.svg) */ export const IncreaseDecreaseLineIcon: IconType = (props) => { return GenIcon(increaseDecreaseLine)(props); }; /** * The react component for the `indeterminate-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Indeterminate Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/indeterminate-circle-fill.svg) */ export const IndeterminateCircleFillIcon: IconType = (props) => { return GenIcon(indeterminateCircleFill)(props); }; /** * The react component for the `indeterminate-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Indeterminate Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/indeterminate-circle-line.svg) */ export const IndeterminateCircleLineIcon: IconType = (props) => { return GenIcon(indeterminateCircleLine)(props); }; /** * The react component for the `information-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Information Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/information-fill.svg) */ export const InformationFillIcon: IconType = (props) => { return GenIcon(informationFill)(props); }; /** * The react component for the `infrared-thermometer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Infrared Thermometer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/infrared-thermometer-fill.svg) */ export const InfraredThermometerFillIcon: IconType = (props) => { return GenIcon(infraredThermometerFill)(props); }; /** * The react component for the `infrared-thermometer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Infrared Thermometer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/infrared-thermometer-line.svg) */ export const InfraredThermometerLineIcon: IconType = (props) => { return GenIcon(infraredThermometerLine)(props); }; /** * The react component for the `ink-bottle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ink Bottle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ink-bottle-fill.svg) */ export const InkBottleFillIcon: IconType = (props) => { return GenIcon(inkBottleFill)(props); }; /** * The react component for the `ink-bottle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ink Bottle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ink-bottle-line.svg) */ export const InkBottleLineIcon: IconType = (props) => { return GenIcon(inkBottleLine)(props); }; /** * The react component for the `input-method-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Input Method Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/input-method-fill.svg) */ export const InputMethodFillIcon: IconType = (props) => { return GenIcon(inputMethodFill)(props); }; /** * The react component for the `input-method-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Input Method Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/input-method-line.svg) */ export const InputMethodLineIcon: IconType = (props) => { return GenIcon(inputMethodLine)(props); }; /** * The react component for the `instagram-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Instagram Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/instagram-fill.svg) */ export const InstagramFillIcon: IconType = (props) => { return GenIcon(instagramFill)(props); }; /** * The react component for the `instagram-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Instagram Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/instagram-line.svg) */ export const InstagramLineIcon: IconType = (props) => { return GenIcon(instagramLine)(props); }; /** * The react component for the `install-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Install Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/install-fill.svg) */ export const InstallFillIcon: IconType = (props) => { return GenIcon(installFill)(props); }; /** * The react component for the `install-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Install Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/install-line.svg) */ export const InstallLineIcon: IconType = (props) => { return GenIcon(installLine)(props); }; /** * The react component for the `invision-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Invision Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/invision-fill.svg) */ export const InvisionFillIcon: IconType = (props) => { return GenIcon(invisionFill)(props); }; /** * The react component for the `invision-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Invision Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/invision-line.svg) */ export const InvisionLineIcon: IconType = (props) => { return GenIcon(invisionLine)(props); }; /** * The react component for the `kakao-talk-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Kakao Talk Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/kakao-talk-fill.svg) */ export const KakaoTalkFillIcon: IconType = (props) => { return GenIcon(kakaoTalkFill)(props); }; /** * The react component for the `kakao-talk-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Kakao Talk Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/kakao-talk-line.svg) */ export const KakaoTalkLineIcon: IconType = (props) => { return GenIcon(kakaoTalkLine)(props); }; /** * The react component for the `key-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Key 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/key-2-fill.svg) */ export const Key2FillIcon: IconType = (props) => { return GenIcon(key2Fill)(props); }; /** * The react component for the `key-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Key 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/key-2-line.svg) */ export const Key2LineIcon: IconType = (props) => { return GenIcon(key2Line)(props); }; /** * The react component for the `key-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Key Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/key-fill.svg) */ export const KeyFillIcon: IconType = (props) => { return GenIcon(keyFill)(props); }; /** * The react component for the `key-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Key Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/key-line.svg) */ export const KeyLineIcon: IconType = (props) => { return GenIcon(keyLine)(props); }; /** * The react component for the `keyboard-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keyboard Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/keyboard-box-fill.svg) */ export const KeyboardBoxFillIcon: IconType = (props) => { return GenIcon(keyboardBoxFill)(props); }; /** * The react component for the `keyboard-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keyboard Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/keyboard-box-line.svg) */ export const KeyboardBoxLineIcon: IconType = (props) => { return GenIcon(keyboardBoxLine)(props); }; /** * The react component for the `keyboard-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keyboard Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/keyboard-fill.svg) */ export const KeyboardFillIcon: IconType = (props) => { return GenIcon(keyboardFill)(props); }; /** * The react component for the `keyboard-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keyboard Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/keyboard-line.svg) */ export const KeyboardLineIcon: IconType = (props) => { return GenIcon(keyboardLine)(props); }; /** * The react component for the `keynote-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keynote Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/keynote-fill.svg) */ export const KeynoteFillIcon: IconType = (props) => { return GenIcon(keynoteFill)(props); }; /** * The react component for the `keynote-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Keynote Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/keynote-line.svg) */ export const KeynoteLineIcon: IconType = (props) => { return GenIcon(keynoteLine)(props); }; /** * The react component for the `knife-blood-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Knife Blood Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/knife-blood-fill.svg) */ export const KnifeBloodFillIcon: IconType = (props) => { return GenIcon(knifeBloodFill)(props); }; /** * The react component for the `knife-blood-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Knife Blood Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/knife-blood-line.svg) */ export const KnifeBloodLineIcon: IconType = (props) => { return GenIcon(knifeBloodLine)(props); }; /** * The react component for the `knife-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Knife Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/knife-fill.svg) */ export const KnifeFillIcon: IconType = (props) => { return GenIcon(knifeFill)(props); }; /** * The react component for the `knife-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Knife Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/knife-line.svg) */ export const KnifeLineIcon: IconType = (props) => { return GenIcon(knifeLine)(props); }; /** * The react component for the `landscape-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Landscape Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/landscape-fill.svg) */ export const LandscapeFillIcon: IconType = (props) => { return GenIcon(landscapeFill)(props); }; /** * The react component for the `landscape-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Landscape Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/landscape-line.svg) */ export const LandscapeLineIcon: IconType = (props) => { return GenIcon(landscapeLine)(props); }; /** * The react component for the `layout-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-2-fill.svg) */ export const Layout2FillIcon: IconType = (props) => { return GenIcon(layout2Fill)(props); }; /** * The react component for the `layout-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-2-line.svg) */ export const Layout2LineIcon: IconType = (props) => { return GenIcon(layout2Line)(props); }; /** * The react component for the `layout-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-3-fill.svg) */ export const Layout3FillIcon: IconType = (props) => { return GenIcon(layout3Fill)(props); }; /** * The react component for the `layout-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-3-line.svg) */ export const Layout3LineIcon: IconType = (props) => { return GenIcon(layout3Line)(props); }; /** * The react component for the `layout-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-4-fill.svg) */ export const Layout4FillIcon: IconType = (props) => { return GenIcon(layout4Fill)(props); }; /** * The react component for the `layout-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-4-line.svg) */ export const Layout4LineIcon: IconType = (props) => { return GenIcon(layout4Line)(props); }; /** * The react component for the `layout-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-5-fill.svg) */ export const Layout5FillIcon: IconType = (props) => { return GenIcon(layout5Fill)(props); }; /** * The react component for the `layout-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-5-line.svg) */ export const Layout5LineIcon: IconType = (props) => { return GenIcon(layout5Line)(props); }; /** * The react component for the `layout-6-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 6 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-6-fill.svg) */ export const Layout6FillIcon: IconType = (props) => { return GenIcon(layout6Fill)(props); }; /** * The react component for the `layout-6-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout 6 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-6-line.svg) */ export const Layout6LineIcon: IconType = (props) => { return GenIcon(layout6Line)(props); }; /** * The react component for the `layout-bottom-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Bottom 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-bottom-2-fill.svg) */ export const LayoutBottom2FillIcon: IconType = (props) => { return GenIcon(layoutBottom2Fill)(props); }; /** * The react component for the `layout-bottom-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Bottom 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-bottom-2-line.svg) */ export const LayoutBottom2LineIcon: IconType = (props) => { return GenIcon(layoutBottom2Line)(props); }; /** * The react component for the `layout-bottom-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Bottom Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-bottom-fill.svg) */ export const LayoutBottomFillIcon: IconType = (props) => { return GenIcon(layoutBottomFill)(props); }; /** * The react component for the `layout-bottom-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Bottom Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-bottom-line.svg) */ export const LayoutBottomLineIcon: IconType = (props) => { return GenIcon(layoutBottomLine)(props); }; /** * The react component for the `layout-column-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Column Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-column-fill.svg) */ export const LayoutColumnFillIcon: IconType = (props) => { return GenIcon(layoutColumnFill)(props); }; /** * The react component for the `layout-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-fill.svg) */ export const LayoutFillIcon: IconType = (props) => { return GenIcon(layoutFill)(props); }; /** * The react component for the `layout-grid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Grid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-grid-fill.svg) */ export const LayoutGridFillIcon: IconType = (props) => { return GenIcon(layoutGridFill)(props); }; /** * The react component for the `layout-grid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Grid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-grid-line.svg) */ export const LayoutGridLineIcon: IconType = (props) => { return GenIcon(layoutGridLine)(props); }; /** * The react component for the `layout-left-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Left 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-left-2-fill.svg) */ export const LayoutLeft2FillIcon: IconType = (props) => { return GenIcon(layoutLeft2Fill)(props); }; /** * The react component for the `layout-left-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Left 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-left-2-line.svg) */ export const LayoutLeft2LineIcon: IconType = (props) => { return GenIcon(layoutLeft2Line)(props); }; /** * The react component for the `layout-left-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Left Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-left-fill.svg) */ export const LayoutLeftFillIcon: IconType = (props) => { return GenIcon(layoutLeftFill)(props); }; /** * The react component for the `layout-left-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Left Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-left-line.svg) */ export const LayoutLeftLineIcon: IconType = (props) => { return GenIcon(layoutLeftLine)(props); }; /** * The react component for the `layout-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-line.svg) */ export const LayoutLineIcon: IconType = (props) => { return GenIcon(layoutLine)(props); }; /** * The react component for the `layout-masonry-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Masonry Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-masonry-fill.svg) */ export const LayoutMasonryFillIcon: IconType = (props) => { return GenIcon(layoutMasonryFill)(props); }; /** * The react component for the `layout-masonry-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Masonry Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-masonry-line.svg) */ export const LayoutMasonryLineIcon: IconType = (props) => { return GenIcon(layoutMasonryLine)(props); }; /** * The react component for the `layout-right-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Right 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-right-2-fill.svg) */ export const LayoutRight2FillIcon: IconType = (props) => { return GenIcon(layoutRight2Fill)(props); }; /** * The react component for the `layout-right-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Right 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-right-2-line.svg) */ export const LayoutRight2LineIcon: IconType = (props) => { return GenIcon(layoutRight2Line)(props); }; /** * The react component for the `layout-right-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Right Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-right-fill.svg) */ export const LayoutRightFillIcon: IconType = (props) => { return GenIcon(layoutRightFill)(props); }; /** * The react component for the `layout-right-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Right Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-right-line.svg) */ export const LayoutRightLineIcon: IconType = (props) => { return GenIcon(layoutRightLine)(props); }; /** * The react component for the `layout-row-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Row Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-row-fill.svg) */ export const LayoutRowFillIcon: IconType = (props) => { return GenIcon(layoutRowFill)(props); }; /** * The react component for the `layout-row-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Row Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-row-line.svg) */ export const LayoutRowLineIcon: IconType = (props) => { return GenIcon(layoutRowLine)(props); }; /** * The react component for the `layout-top-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Top 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-top-2-fill.svg) */ export const LayoutTop2FillIcon: IconType = (props) => { return GenIcon(layoutTop2Fill)(props); }; /** * The react component for the `layout-top-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Top 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-top-2-line.svg) */ export const LayoutTop2LineIcon: IconType = (props) => { return GenIcon(layoutTop2Line)(props); }; /** * The react component for the `layout-top-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Top Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-top-fill.svg) */ export const LayoutTopFillIcon: IconType = (props) => { return GenIcon(layoutTopFill)(props); }; /** * The react component for the `layout-top-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Layout Top Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/layout-top-line.svg) */ export const LayoutTopLineIcon: IconType = (props) => { return GenIcon(layoutTopLine)(props); }; /** * The react component for the `leaf-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Leaf Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/leaf-fill.svg) */ export const LeafFillIcon: IconType = (props) => { return GenIcon(leafFill)(props); }; /** * The react component for the `leaf-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Leaf Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/leaf-line.svg) */ export const LeafLineIcon: IconType = (props) => { return GenIcon(leafLine)(props); }; /** * The react component for the `lifebuoy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lifebuoy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/lifebuoy-fill.svg) */ export const LifebuoyFillIcon: IconType = (props) => { return GenIcon(lifebuoyFill)(props); }; /** * The react component for the `lifebuoy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lifebuoy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/lifebuoy-line.svg) */ export const LifebuoyLineIcon: IconType = (props) => { return GenIcon(lifebuoyLine)(props); }; /** * The react component for the `lightbulb-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lightbulb Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/lightbulb-fill.svg) */ export const LightbulbFillIcon: IconType = (props) => { return GenIcon(lightbulbFill)(props); }; /** * The react component for the `lightbulb-flash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lightbulb Flash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/lightbulb-flash-fill.svg) */ export const LightbulbFlashFillIcon: IconType = (props) => { return GenIcon(lightbulbFlashFill)(props); }; /** * The react component for the `lightbulb-flash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lightbulb Flash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/lightbulb-flash-line.svg) */ export const LightbulbFlashLineIcon: IconType = (props) => { return GenIcon(lightbulbFlashLine)(props); }; /** * The react component for the `lightbulb-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lightbulb Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/lightbulb-line.svg) */ export const LightbulbLineIcon: IconType = (props) => { return GenIcon(lightbulbLine)(props); }; /** * The react component for the `line-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Line Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/line-chart-fill.svg) */ export const LineChartFillIcon: IconType = (props) => { return GenIcon(lineChartFill)(props); }; /** * The react component for the `line-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Line Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/line-chart-line.svg) */ export const LineChartLineIcon: IconType = (props) => { return GenIcon(lineChartLine)(props); }; /** * The react component for the `line-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Line Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/line-fill.svg) */ export const LineFillIcon: IconType = (props) => { return GenIcon(lineFill)(props); }; /** * The react component for the `line-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Line Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/line-line.svg) */ export const LineLineIcon: IconType = (props) => { return GenIcon(lineLine)(props); }; /** * The react component for the `linkedin-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Linkedin Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/linkedin-box-fill.svg) */ export const LinkedinBoxFillIcon: IconType = (props) => { return GenIcon(linkedinBoxFill)(props); }; /** * The react component for the `linkedin-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Linkedin Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/linkedin-box-line.svg) */ export const LinkedinBoxLineIcon: IconType = (props) => { return GenIcon(linkedinBoxLine)(props); }; /** * The react component for the `linkedin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Linkedin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/linkedin-fill.svg) */ export const LinkedinFillIcon: IconType = (props) => { return GenIcon(linkedinFill)(props); }; /** * The react component for the `linkedin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Linkedin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/linkedin-line.svg) */ export const LinkedinLineIcon: IconType = (props) => { return GenIcon(linkedinLine)(props); }; /** * The react component for the `links-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Links Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/links-fill.svg) */ export const LinksFillIcon: IconType = (props) => { return GenIcon(linksFill)(props); }; /** * The react component for the `links-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Links Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/links-line.svg) */ export const LinksLineIcon: IconType = (props) => { return GenIcon(linksLine)(props); }; /** * The react component for the `list-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![List Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/list-settings-fill.svg) */ export const ListSettingsFillIcon: IconType = (props) => { return GenIcon(listSettingsFill)(props); }; /** * The react component for the `list-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![List Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/list-settings-line.svg) */ export const ListSettingsLineIcon: IconType = (props) => { return GenIcon(listSettingsLine)(props); }; /** * The react component for the `live-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Live Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/live-fill.svg) */ export const LiveFillIcon: IconType = (props) => { return GenIcon(liveFill)(props); }; /** * The react component for the `live-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Live Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/live-line.svg) */ export const LiveLineIcon: IconType = (props) => { return GenIcon(liveLine)(props); }; /** * The react component for the `loader-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-2-fill.svg) */ export const Loader2FillIcon: IconType = (props) => { return GenIcon(loader2Fill)(props); }; /** * The react component for the `loader-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-2-line.svg) */ export const Loader2LineIcon: IconType = (props) => { return GenIcon(loader2Line)(props); }; /** * The react component for the `loader-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-3-fill.svg) */ export const Loader3FillIcon: IconType = (props) => { return GenIcon(loader3Fill)(props); }; /** * The react component for the `loader-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-3-line.svg) */ export const Loader3LineIcon: IconType = (props) => { return GenIcon(loader3Line)(props); }; /** * The react component for the `loader-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-4-fill.svg) */ export const Loader4FillIcon: IconType = (props) => { return GenIcon(loader4Fill)(props); }; /** * The react component for the `loader-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-4-line.svg) */ export const Loader4LineIcon: IconType = (props) => { return GenIcon(loader4Line)(props); }; /** * The react component for the `loader-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-5-fill.svg) */ export const Loader5FillIcon: IconType = (props) => { return GenIcon(loader5Fill)(props); }; /** * The react component for the `loader-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-5-line.svg) */ export const Loader5LineIcon: IconType = (props) => { return GenIcon(loader5Line)(props); }; /** * The react component for the `loader-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-fill.svg) */ export const LoaderFillIcon: IconType = (props) => { return GenIcon(loaderFill)(props); }; /** * The react component for the `loader-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Loader Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/loader-line.svg) */ export const LoaderLineIcon: IconType = (props) => { return GenIcon(loaderLine)(props); }; /** * The react component for the `lock-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-2-fill.svg) */ export const Lock2FillIcon: IconType = (props) => { return GenIcon(lock2Fill)(props); }; /** * The react component for the `lock-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-2-line.svg) */ export const Lock2LineIcon: IconType = (props) => { return GenIcon(lock2Line)(props); }; /** * The react component for the `lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-fill.svg) */ export const LockFillIcon: IconType = (props) => { return GenIcon(lockFill)(props); }; /** * The react component for the `lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-line.svg) */ export const LockLineIcon: IconType = (props) => { return GenIcon(lockLine)(props); }; /** * The react component for the `lock-password-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Password Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-password-fill.svg) */ export const LockPasswordFillIcon: IconType = (props) => { return GenIcon(lockPasswordFill)(props); }; /** * The react component for the `lock-password-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Password Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-password-line.svg) */ export const LockPasswordLineIcon: IconType = (props) => { return GenIcon(lockPasswordLine)(props); }; /** * The react component for the `lock-unlock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Unlock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-unlock-fill.svg) */ export const LockUnlockFillIcon: IconType = (props) => { return GenIcon(lockUnlockFill)(props); }; /** * The react component for the `lock-unlock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lock Unlock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/lock-unlock-line.svg) */ export const LockUnlockLineIcon: IconType = (props) => { return GenIcon(lockUnlockLine)(props); }; /** * The react component for the `login-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Login Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/login-box-fill.svg) */ export const LoginBoxFillIcon: IconType = (props) => { return GenIcon(loginBoxFill)(props); }; /** * The react component for the `login-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Login Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/login-box-line.svg) */ export const LoginBoxLineIcon: IconType = (props) => { return GenIcon(loginBoxLine)(props); }; /** * The react component for the `login-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Login Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/login-circle-fill.svg) */ export const LoginCircleFillIcon: IconType = (props) => { return GenIcon(loginCircleFill)(props); }; /** * The react component for the `login-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Login Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/login-circle-line.svg) */ export const LoginCircleLineIcon: IconType = (props) => { return GenIcon(loginCircleLine)(props); }; /** * The react component for the `logout-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-box-fill.svg) */ export const LogoutBoxFillIcon: IconType = (props) => { return GenIcon(logoutBoxFill)(props); }; /** * The react component for the `logout-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-box-line.svg) */ export const LogoutBoxLineIcon: IconType = (props) => { return GenIcon(logoutBoxLine)(props); }; /** * The react component for the `logout-box-r-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Box R Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-box-r-fill.svg) */ export const LogoutBoxRFillIcon: IconType = (props) => { return GenIcon(logoutBoxRFill)(props); }; /** * The react component for the `logout-box-r-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Box R Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-box-r-line.svg) */ export const LogoutBoxRLineIcon: IconType = (props) => { return GenIcon(logoutBoxRLine)(props); }; /** * The react component for the `logout-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-circle-fill.svg) */ export const LogoutCircleFillIcon: IconType = (props) => { return GenIcon(logoutCircleFill)(props); }; /** * The react component for the `logout-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-circle-line.svg) */ export const LogoutCircleLineIcon: IconType = (props) => { return GenIcon(logoutCircleLine)(props); }; /** * The react component for the `logout-circle-r-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Circle R Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-circle-r-fill.svg) */ export const LogoutCircleRFillIcon: IconType = (props) => { return GenIcon(logoutCircleRFill)(props); }; /** * The react component for the `logout-circle-r-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Logout Circle R Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/logout-circle-r-line.svg) */ export const LogoutCircleRLineIcon: IconType = (props) => { return GenIcon(logoutCircleRLine)(props); }; /** * The react component for the `luggage-cart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Luggage Cart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/luggage-cart-fill.svg) */ export const LuggageCartFillIcon: IconType = (props) => { return GenIcon(luggageCartFill)(props); }; /** * The react component for the `luggage-cart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Luggage Cart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/luggage-cart-line.svg) */ export const LuggageCartLineIcon: IconType = (props) => { return GenIcon(luggageCartLine)(props); }; /** * The react component for the `luggage-deposit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Luggage Deposit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/luggage-deposit-fill.svg) */ export const LuggageDepositFillIcon: IconType = (props) => { return GenIcon(luggageDepositFill)(props); }; /** * The react component for the `luggage-deposit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Luggage Deposit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/luggage-deposit-line.svg) */ export const LuggageDepositLineIcon: IconType = (props) => { return GenIcon(luggageDepositLine)(props); }; /** * The react component for the `lungs-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lungs Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/lungs-fill.svg) */ export const LungsFillIcon: IconType = (props) => { return GenIcon(lungsFill)(props); }; /** * The react component for the `lungs-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Lungs Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/lungs-line.svg) */ export const LungsLineIcon: IconType = (props) => { return GenIcon(lungsLine)(props); }; /** * The react component for the `mac-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mac Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/mac-fill.svg) */ export const MacFillIcon: IconType = (props) => { return GenIcon(macFill)(props); }; /** * The react component for the `mac-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mac Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/mac-line.svg) */ export const MacLineIcon: IconType = (props) => { return GenIcon(macLine)(props); }; /** * The react component for the `macbook-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Macbook Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/macbook-fill.svg) */ export const MacbookFillIcon: IconType = (props) => { return GenIcon(macbookFill)(props); }; /** * The react component for the `macbook-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Macbook Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/macbook-line.svg) */ export const MacbookLineIcon: IconType = (props) => { return GenIcon(macbookLine)(props); }; /** * The react component for the `magic-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Magic Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/magic-fill.svg) */ export const MagicFillIcon: IconType = (props) => { return GenIcon(magicFill)(props); }; /** * The react component for the `magic-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Magic Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/magic-line.svg) */ export const MagicLineIcon: IconType = (props) => { return GenIcon(magicLine)(props); }; /** * The react component for the `mail-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-add-fill.svg) */ export const MailAddFillIcon: IconType = (props) => { return GenIcon(mailAddFill)(props); }; /** * The react component for the `mail-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-add-line.svg) */ export const MailAddLineIcon: IconType = (props) => { return GenIcon(mailAddLine)(props); }; /** * The react component for the `mail-check-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Check Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-check-fill.svg) */ export const MailCheckFillIcon: IconType = (props) => { return GenIcon(mailCheckFill)(props); }; /** * The react component for the `mail-check-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Check Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-check-line.svg) */ export const MailCheckLineIcon: IconType = (props) => { return GenIcon(mailCheckLine)(props); }; /** * The react component for the `mail-close-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Close Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-close-fill.svg) */ export const MailCloseFillIcon: IconType = (props) => { return GenIcon(mailCloseFill)(props); }; /** * The react component for the `mail-close-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Close Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-close-line.svg) */ export const MailCloseLineIcon: IconType = (props) => { return GenIcon(mailCloseLine)(props); }; /** * The react component for the `mail-download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-download-fill.svg) */ export const MailDownloadFillIcon: IconType = (props) => { return GenIcon(mailDownloadFill)(props); }; /** * The react component for the `mail-download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-download-line.svg) */ export const MailDownloadLineIcon: IconType = (props) => { return GenIcon(mailDownloadLine)(props); }; /** * The react component for the `mail-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-fill.svg) */ export const MailFillIcon: IconType = (props) => { return GenIcon(mailFill)(props); }; /** * The react component for the `mail-forbid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Forbid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-forbid-fill.svg) */ export const MailForbidFillIcon: IconType = (props) => { return GenIcon(mailForbidFill)(props); }; /** * The react component for the `mail-forbid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Forbid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-forbid-line.svg) */ export const MailForbidLineIcon: IconType = (props) => { return GenIcon(mailForbidLine)(props); }; /** * The react component for the `mail-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-line.svg) */ export const MailLineIcon: IconType = (props) => { return GenIcon(mailLine)(props); }; /** * The react component for the `mail-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-lock-fill.svg) */ export const MailLockFillIcon: IconType = (props) => { return GenIcon(mailLockFill)(props); }; /** * The react component for the `mail-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-lock-line.svg) */ export const MailLockLineIcon: IconType = (props) => { return GenIcon(mailLockLine)(props); }; /** * The react component for the `mail-open-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Open Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-open-fill.svg) */ export const MailOpenFillIcon: IconType = (props) => { return GenIcon(mailOpenFill)(props); }; /** * The react component for the `mail-open-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Open Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-open-line.svg) */ export const MailOpenLineIcon: IconType = (props) => { return GenIcon(mailOpenLine)(props); }; /** * The react component for the `mail-send-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Send Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-send-fill.svg) */ export const MailSendFillIcon: IconType = (props) => { return GenIcon(mailSendFill)(props); }; /** * The react component for the `mail-send-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Send Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-send-line.svg) */ export const MailSendLineIcon: IconType = (props) => { return GenIcon(mailSendLine)(props); }; /** * The react component for the `mail-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-settings-fill.svg) */ export const MailSettingsFillIcon: IconType = (props) => { return GenIcon(mailSettingsFill)(props); }; /** * The react component for the `mail-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-settings-line.svg) */ export const MailSettingsLineIcon: IconType = (props) => { return GenIcon(mailSettingsLine)(props); }; /** * The react component for the `mail-star-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Star Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-star-fill.svg) */ export const MailStarFillIcon: IconType = (props) => { return GenIcon(mailStarFill)(props); }; /** * The react component for the `mail-star-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Star Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-star-line.svg) */ export const MailStarLineIcon: IconType = (props) => { return GenIcon(mailStarLine)(props); }; /** * The react component for the `mail-unread-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Unread Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-unread-fill.svg) */ export const MailUnreadFillIcon: IconType = (props) => { return GenIcon(mailUnreadFill)(props); }; /** * The react component for the `mail-unread-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Unread Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-unread-line.svg) */ export const MailUnreadLineIcon: IconType = (props) => { return GenIcon(mailUnreadLine)(props); }; /** * The react component for the `mail-volume-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Volume Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-volume-fill.svg) */ export const MailVolumeFillIcon: IconType = (props) => { return GenIcon(mailVolumeFill)(props); }; /** * The react component for the `mail-volume-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mail Volume Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/mail-volume-line.svg) */ export const MailVolumeLineIcon: IconType = (props) => { return GenIcon(mailVolumeLine)(props); }; /** * The react component for the `map-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-2-fill.svg) */ export const Map2FillIcon: IconType = (props) => { return GenIcon(map2Fill)(props); }; /** * The react component for the `map-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-2-line.svg) */ export const Map2LineIcon: IconType = (props) => { return GenIcon(map2Line)(props); }; /** * The react component for the `map-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-fill.svg) */ export const MapFillIcon: IconType = (props) => { return GenIcon(mapFill)(props); }; /** * The react component for the `map-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-line.svg) */ export const MapLineIcon: IconType = (props) => { return GenIcon(mapLine)(props); }; /** * The react component for the `map-pin-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-2-fill.svg) */ export const MapPin2FillIcon: IconType = (props) => { return GenIcon(mapPin2Fill)(props); }; /** * The react component for the `map-pin-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-2-line.svg) */ export const MapPin2LineIcon: IconType = (props) => { return GenIcon(mapPin2Line)(props); }; /** * The react component for the `map-pin-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-3-fill.svg) */ export const MapPin3FillIcon: IconType = (props) => { return GenIcon(mapPin3Fill)(props); }; /** * The react component for the `map-pin-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-3-line.svg) */ export const MapPin3LineIcon: IconType = (props) => { return GenIcon(mapPin3Line)(props); }; /** * The react component for the `map-pin-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-4-fill.svg) */ export const MapPin4FillIcon: IconType = (props) => { return GenIcon(mapPin4Fill)(props); }; /** * The react component for the `map-pin-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-4-line.svg) */ export const MapPin4LineIcon: IconType = (props) => { return GenIcon(mapPin4Line)(props); }; /** * The react component for the `map-pin-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-5-fill.svg) */ export const MapPin5FillIcon: IconType = (props) => { return GenIcon(mapPin5Fill)(props); }; /** * The react component for the `map-pin-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-5-line.svg) */ export const MapPin5LineIcon: IconType = (props) => { return GenIcon(mapPin5Line)(props); }; /** * The react component for the `map-pin-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-add-fill.svg) */ export const MapPinAddFillIcon: IconType = (props) => { return GenIcon(mapPinAddFill)(props); }; /** * The react component for the `map-pin-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-add-line.svg) */ export const MapPinAddLineIcon: IconType = (props) => { return GenIcon(mapPinAddLine)(props); }; /** * The react component for the `map-pin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-fill.svg) */ export const MapPinFillIcon: IconType = (props) => { return GenIcon(mapPinFill)(props); }; /** * The react component for the `map-pin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-line.svg) */ export const MapPinLineIcon: IconType = (props) => { return GenIcon(mapPinLine)(props); }; /** * The react component for the `map-pin-range-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Range Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-range-fill.svg) */ export const MapPinRangeFillIcon: IconType = (props) => { return GenIcon(mapPinRangeFill)(props); }; /** * The react component for the `map-pin-range-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Range Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-range-line.svg) */ export const MapPinRangeLineIcon: IconType = (props) => { return GenIcon(mapPinRangeLine)(props); }; /** * The react component for the `map-pin-time-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Time Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-time-fill.svg) */ export const MapPinTimeFillIcon: IconType = (props) => { return GenIcon(mapPinTimeFill)(props); }; /** * The react component for the `map-pin-time-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin Time Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-time-line.svg) */ export const MapPinTimeLineIcon: IconType = (props) => { return GenIcon(mapPinTimeLine)(props); }; /** * The react component for the `map-pin-user-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin User Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-user-fill.svg) */ export const MapPinUserFillIcon: IconType = (props) => { return GenIcon(mapPinUserFill)(props); }; /** * The react component for the `map-pin-user-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Map Pin User Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/map-pin-user-line.svg) */ export const MapPinUserLineIcon: IconType = (props) => { return GenIcon(mapPinUserLine)(props); }; /** * The react component for the `mark-pen-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mark Pen Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/mark-pen-fill.svg) */ export const MarkPenFillIcon: IconType = (props) => { return GenIcon(markPenFill)(props); }; /** * The react component for the `markup-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Markup Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/markup-fill.svg) */ export const MarkupFillIcon: IconType = (props) => { return GenIcon(markupFill)(props); }; /** * The react component for the `markup-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Markup Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/markup-line.svg) */ export const MarkupLineIcon: IconType = (props) => { return GenIcon(markupLine)(props); }; /** * The react component for the `mastercard-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mastercard Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mastercard-fill.svg) */ export const MastercardFillIcon: IconType = (props) => { return GenIcon(mastercardFill)(props); }; /** * The react component for the `mastercard-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mastercard Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mastercard-line.svg) */ export const MastercardLineIcon: IconType = (props) => { return GenIcon(mastercardLine)(props); }; /** * The react component for the `mastodon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mastodon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mastodon-fill.svg) */ export const MastodonFillIcon: IconType = (props) => { return GenIcon(mastodonFill)(props); }; /** * The react component for the `mastodon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mastodon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mastodon-line.svg) */ export const MastodonLineIcon: IconType = (props) => { return GenIcon(mastodonLine)(props); }; /** * The react component for the `medal-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medal 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/medal-2-fill.svg) */ export const Medal2FillIcon: IconType = (props) => { return GenIcon(medal2Fill)(props); }; /** * The react component for the `medal-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medal 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/medal-2-line.svg) */ export const Medal2LineIcon: IconType = (props) => { return GenIcon(medal2Line)(props); }; /** * The react component for the `medal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/medal-fill.svg) */ export const MedalFillIcon: IconType = (props) => { return GenIcon(medalFill)(props); }; /** * The react component for the `medal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/medal-line.svg) */ export const MedalLineIcon: IconType = (props) => { return GenIcon(medalLine)(props); }; /** * The react component for the `medicine-bottle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medicine Bottle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/medicine-bottle-fill.svg) */ export const MedicineBottleFillIcon: IconType = (props) => { return GenIcon(medicineBottleFill)(props); }; /** * The react component for the `medicine-bottle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medicine Bottle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/medicine-bottle-line.svg) */ export const MedicineBottleLineIcon: IconType = (props) => { return GenIcon(medicineBottleLine)(props); }; /** * The react component for the `medium-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medium Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/medium-fill.svg) */ export const MediumFillIcon: IconType = (props) => { return GenIcon(mediumFill)(props); }; /** * The react component for the `medium-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Medium Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/medium-line.svg) */ export const MediumLineIcon: IconType = (props) => { return GenIcon(mediumLine)(props); }; /** * The react component for the `men-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Men Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/men-fill.svg) */ export const MenFillIcon: IconType = (props) => { return GenIcon(menFill)(props); }; /** * The react component for the `men-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Men Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/men-line.svg) */ export const MenLineIcon: IconType = (props) => { return GenIcon(menLine)(props); }; /** * The react component for the `mental-health-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mental Health Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/mental-health-fill.svg) */ export const MentalHealthFillIcon: IconType = (props) => { return GenIcon(mentalHealthFill)(props); }; /** * The react component for the `mental-health-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mental Health Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/mental-health-line.svg) */ export const MentalHealthLineIcon: IconType = (props) => { return GenIcon(mentalHealthLine)(props); }; /** * The react component for the `menu-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-2-fill.svg) */ export const Menu2FillIcon: IconType = (props) => { return GenIcon(menu2Fill)(props); }; /** * The react component for the `menu-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-2-line.svg) */ export const Menu2LineIcon: IconType = (props) => { return GenIcon(menu2Line)(props); }; /** * The react component for the `menu-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-3-fill.svg) */ export const Menu3FillIcon: IconType = (props) => { return GenIcon(menu3Fill)(props); }; /** * The react component for the `menu-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-3-line.svg) */ export const Menu3LineIcon: IconType = (props) => { return GenIcon(menu3Line)(props); }; /** * The react component for the `menu-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-4-fill.svg) */ export const Menu4FillIcon: IconType = (props) => { return GenIcon(menu4Fill)(props); }; /** * The react component for the `menu-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-4-line.svg) */ export const Menu4LineIcon: IconType = (props) => { return GenIcon(menu4Line)(props); }; /** * The react component for the `menu-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-5-fill.svg) */ export const Menu5FillIcon: IconType = (props) => { return GenIcon(menu5Fill)(props); }; /** * The react component for the `menu-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-5-line.svg) */ export const Menu5LineIcon: IconType = (props) => { return GenIcon(menu5Line)(props); }; /** * The react component for the `menu-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-add-fill.svg) */ export const MenuAddFillIcon: IconType = (props) => { return GenIcon(menuAddFill)(props); }; /** * The react component for the `menu-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-add-line.svg) */ export const MenuAddLineIcon: IconType = (props) => { return GenIcon(menuAddLine)(props); }; /** * The react component for the `menu-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-fill.svg) */ export const MenuFillIcon: IconType = (props) => { return GenIcon(menuFill)(props); }; /** * The react component for the `menu-fold-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Fold Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-fold-fill.svg) */ export const MenuFoldFillIcon: IconType = (props) => { return GenIcon(menuFoldFill)(props); }; /** * The react component for the `menu-fold-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Fold Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-fold-line.svg) */ export const MenuFoldLineIcon: IconType = (props) => { return GenIcon(menuFoldLine)(props); }; /** * The react component for the `menu-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-line.svg) */ export const MenuLineIcon: IconType = (props) => { return GenIcon(menuLine)(props); }; /** * The react component for the `menu-unfold-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Unfold Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-unfold-fill.svg) */ export const MenuUnfoldFillIcon: IconType = (props) => { return GenIcon(menuUnfoldFill)(props); }; /** * The react component for the `menu-unfold-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Menu Unfold Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/menu-unfold-line.svg) */ export const MenuUnfoldLineIcon: IconType = (props) => { return GenIcon(menuUnfoldLine)(props); }; /** * The react component for the `message-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-2-fill.svg) */ export const Message2FillIcon: IconType = (props) => { return GenIcon(message2Fill)(props); }; /** * The react component for the `message-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-2-line.svg) */ export const Message2LineIcon: IconType = (props) => { return GenIcon(message2Line)(props); }; /** * The react component for the `message-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-3-fill.svg) */ export const Message3FillIcon: IconType = (props) => { return GenIcon(message3Fill)(props); }; /** * The react component for the `message-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-3-line.svg) */ export const Message3LineIcon: IconType = (props) => { return GenIcon(message3Line)(props); }; /** * The react component for the `message-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-fill.svg) */ export const MessageFillIcon: IconType = (props) => { return GenIcon(messageFill)(props); }; /** * The react component for the `message-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Message Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/message-line.svg) */ export const MessageLineIcon: IconType = (props) => { return GenIcon(messageLine)(props); }; /** * The react component for the `messenger-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Messenger Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/messenger-fill.svg) */ export const MessengerFillIcon: IconType = (props) => { return GenIcon(messengerFill)(props); }; /** * The react component for the `messenger-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Messenger Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/messenger-line.svg) */ export const MessengerLineIcon: IconType = (props) => { return GenIcon(messengerLine)(props); }; /** * The react component for the `meteor-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Meteor Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/meteor-fill.svg) */ export const MeteorFillIcon: IconType = (props) => { return GenIcon(meteorFill)(props); }; /** * The react component for the `meteor-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Meteor Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/meteor-line.svg) */ export const MeteorLineIcon: IconType = (props) => { return GenIcon(meteorLine)(props); }; /** * The react component for the `mic-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-2-fill.svg) */ export const Mic2FillIcon: IconType = (props) => { return GenIcon(mic2Fill)(props); }; /** * The react component for the `mic-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-2-line.svg) */ export const Mic2LineIcon: IconType = (props) => { return GenIcon(mic2Line)(props); }; /** * The react component for the `mic-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-fill.svg) */ export const MicFillIcon: IconType = (props) => { return GenIcon(micFill)(props); }; /** * The react component for the `mic-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-line.svg) */ export const MicLineIcon: IconType = (props) => { return GenIcon(micLine)(props); }; /** * The react component for the `mic-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-off-fill.svg) */ export const MicOffFillIcon: IconType = (props) => { return GenIcon(micOffFill)(props); }; /** * The react component for the `mic-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mic Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mic-off-line.svg) */ export const MicOffLineIcon: IconType = (props) => { return GenIcon(micOffLine)(props); }; /** * The react component for the `mickey-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mickey Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/mickey-fill.svg) */ export const MickeyFillIcon: IconType = (props) => { return GenIcon(mickeyFill)(props); }; /** * The react component for the `mickey-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mickey Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/mickey-line.svg) */ export const MickeyLineIcon: IconType = (props) => { return GenIcon(mickeyLine)(props); }; /** * The react component for the `microscope-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Microscope Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/microscope-fill.svg) */ export const MicroscopeFillIcon: IconType = (props) => { return GenIcon(microscopeFill)(props); }; /** * The react component for the `microscope-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Microscope Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/microscope-line.svg) */ export const MicroscopeLineIcon: IconType = (props) => { return GenIcon(microscopeLine)(props); }; /** * The react component for the `microsoft-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Microsoft Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/microsoft-fill.svg) */ export const MicrosoftFillIcon: IconType = (props) => { return GenIcon(microsoftFill)(props); }; /** * The react component for the `microsoft-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Microsoft Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/microsoft-line.svg) */ export const MicrosoftLineIcon: IconType = (props) => { return GenIcon(microsoftLine)(props); }; /** * The react component for the `mini-program-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mini Program Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mini-program-fill.svg) */ export const MiniProgramFillIcon: IconType = (props) => { return GenIcon(miniProgramFill)(props); }; /** * The react component for the `mini-program-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mini Program Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/mini-program-line.svg) */ export const MiniProgramLineIcon: IconType = (props) => { return GenIcon(miniProgramLine)(props); }; /** * The react component for the `mist-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mist Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/mist-fill.svg) */ export const MistFillIcon: IconType = (props) => { return GenIcon(mistFill)(props); }; /** * The react component for the `mist-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mist Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/mist-line.svg) */ export const MistLineIcon: IconType = (props) => { return GenIcon(mistLine)(props); }; /** * The react component for the `money-cny-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Cny Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-cny-box-fill.svg) */ export const MoneyCnyBoxFillIcon: IconType = (props) => { return GenIcon(moneyCnyBoxFill)(props); }; /** * The react component for the `money-cny-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Cny Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-cny-box-line.svg) */ export const MoneyCnyBoxLineIcon: IconType = (props) => { return GenIcon(moneyCnyBoxLine)(props); }; /** * The react component for the `money-cny-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Cny Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-cny-circle-fill.svg) */ export const MoneyCnyCircleFillIcon: IconType = (props) => { return GenIcon(moneyCnyCircleFill)(props); }; /** * The react component for the `money-cny-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Cny Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-cny-circle-line.svg) */ export const MoneyCnyCircleLineIcon: IconType = (props) => { return GenIcon(moneyCnyCircleLine)(props); }; /** * The react component for the `money-dollar-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Dollar Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-dollar-box-fill.svg) */ export const MoneyDollarBoxFillIcon: IconType = (props) => { return GenIcon(moneyDollarBoxFill)(props); }; /** * The react component for the `money-dollar-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Dollar Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-dollar-box-line.svg) */ export const MoneyDollarBoxLineIcon: IconType = (props) => { return GenIcon(moneyDollarBoxLine)(props); }; /** * The react component for the `money-dollar-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Dollar Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-dollar-circle-fill.svg) */ export const MoneyDollarCircleFillIcon: IconType = (props) => { return GenIcon(moneyDollarCircleFill)(props); }; /** * The react component for the `money-dollar-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Dollar Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-dollar-circle-line.svg) */ export const MoneyDollarCircleLineIcon: IconType = (props) => { return GenIcon(moneyDollarCircleLine)(props); }; /** * The react component for the `money-euro-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Euro Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-euro-box-fill.svg) */ export const MoneyEuroBoxFillIcon: IconType = (props) => { return GenIcon(moneyEuroBoxFill)(props); }; /** * The react component for the `money-euro-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Euro Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-euro-box-line.svg) */ export const MoneyEuroBoxLineIcon: IconType = (props) => { return GenIcon(moneyEuroBoxLine)(props); }; /** * The react component for the `money-euro-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Euro Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-euro-circle-fill.svg) */ export const MoneyEuroCircleFillIcon: IconType = (props) => { return GenIcon(moneyEuroCircleFill)(props); }; /** * The react component for the `money-euro-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Euro Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-euro-circle-line.svg) */ export const MoneyEuroCircleLineIcon: IconType = (props) => { return GenIcon(moneyEuroCircleLine)(props); }; /** * The react component for the `money-pound-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Pound Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-pound-box-fill.svg) */ export const MoneyPoundBoxFillIcon: IconType = (props) => { return GenIcon(moneyPoundBoxFill)(props); }; /** * The react component for the `money-pound-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Pound Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-pound-box-line.svg) */ export const MoneyPoundBoxLineIcon: IconType = (props) => { return GenIcon(moneyPoundBoxLine)(props); }; /** * The react component for the `money-pound-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Pound Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-pound-circle-fill.svg) */ export const MoneyPoundCircleFillIcon: IconType = (props) => { return GenIcon(moneyPoundCircleFill)(props); }; /** * The react component for the `money-pound-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Money Pound Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/money-pound-circle-line.svg) */ export const MoneyPoundCircleLineIcon: IconType = (props) => { return GenIcon(moneyPoundCircleLine)(props); }; /** * The react component for the `moon-clear-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Clear Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-clear-fill.svg) */ export const MoonClearFillIcon: IconType = (props) => { return GenIcon(moonClearFill)(props); }; /** * The react component for the `moon-clear-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Clear Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-clear-line.svg) */ export const MoonClearLineIcon: IconType = (props) => { return GenIcon(moonClearLine)(props); }; /** * The react component for the `moon-cloudy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Cloudy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-cloudy-fill.svg) */ export const MoonCloudyFillIcon: IconType = (props) => { return GenIcon(moonCloudyFill)(props); }; /** * The react component for the `moon-cloudy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Cloudy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-cloudy-line.svg) */ export const MoonCloudyLineIcon: IconType = (props) => { return GenIcon(moonCloudyLine)(props); }; /** * The react component for the `moon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-fill.svg) */ export const MoonFillIcon: IconType = (props) => { return GenIcon(moonFill)(props); }; /** * The react component for the `moon-foggy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Foggy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-foggy-fill.svg) */ export const MoonFoggyFillIcon: IconType = (props) => { return GenIcon(moonFoggyFill)(props); }; /** * The react component for the `moon-foggy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Foggy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-foggy-line.svg) */ export const MoonFoggyLineIcon: IconType = (props) => { return GenIcon(moonFoggyLine)(props); }; /** * The react component for the `moon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Moon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/moon-line.svg) */ export const MoonLineIcon: IconType = (props) => { return GenIcon(moonLine)(props); }; /** * The react component for the `more-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![More 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/more-2-fill.svg) */ export const More2FillIcon: IconType = (props) => { return GenIcon(more2Fill)(props); }; /** * The react component for the `more-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![More 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/more-2-line.svg) */ export const More2LineIcon: IconType = (props) => { return GenIcon(more2Line)(props); }; /** * The react component for the `more-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![More Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/more-line.svg) */ export const MoreLineIcon: IconType = (props) => { return GenIcon(moreLine)(props); }; /** * The react component for the `motorbike-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Motorbike Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/motorbike-fill.svg) */ export const MotorbikeFillIcon: IconType = (props) => { return GenIcon(motorbikeFill)(props); }; /** * The react component for the `motorbike-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Motorbike Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/motorbike-line.svg) */ export const MotorbikeLineIcon: IconType = (props) => { return GenIcon(motorbikeLine)(props); }; /** * The react component for the `mouse-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mouse Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/mouse-fill.svg) */ export const MouseFillIcon: IconType = (props) => { return GenIcon(mouseFill)(props); }; /** * The react component for the `mouse-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mouse Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/mouse-line.svg) */ export const MouseLineIcon: IconType = (props) => { return GenIcon(mouseLine)(props); }; /** * The react component for the `movie-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Movie 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/movie-2-fill.svg) */ export const Movie2FillIcon: IconType = (props) => { return GenIcon(movie2Fill)(props); }; /** * The react component for the `movie-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Movie 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/movie-2-line.svg) */ export const Movie2LineIcon: IconType = (props) => { return GenIcon(movie2Line)(props); }; /** * The react component for the `movie-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Movie Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/movie-fill.svg) */ export const MovieFillIcon: IconType = (props) => { return GenIcon(movieFill)(props); }; /** * The react component for the `movie-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Movie Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/movie-line.svg) */ export const MovieLineIcon: IconType = (props) => { return GenIcon(movieLine)(props); }; /** * The react component for the `music-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Music 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/music-2-fill.svg) */ export const Music2FillIcon: IconType = (props) => { return GenIcon(music2Fill)(props); }; /** * The react component for the `music-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Music 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/music-2-line.svg) */ export const Music2LineIcon: IconType = (props) => { return GenIcon(music2Line)(props); }; /** * The react component for the `music-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Music Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/music-fill.svg) */ export const MusicFillIcon: IconType = (props) => { return GenIcon(musicFill)(props); }; /** * The react component for the `music-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Music Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/music-line.svg) */ export const MusicLineIcon: IconType = (props) => { return GenIcon(musicLine)(props); }; /** * The react component for the `mv-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mv Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mv-fill.svg) */ export const MvFillIcon: IconType = (props) => { return GenIcon(mvFill)(props); }; /** * The react component for the `mv-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Mv Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/mv-line.svg) */ export const MvLineIcon: IconType = (props) => { return GenIcon(mvLine)(props); }; /** * The react component for the `navigation-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Navigation Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/navigation-fill.svg) */ export const NavigationFillIcon: IconType = (props) => { return GenIcon(navigationFill)(props); }; /** * The react component for the `navigation-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Navigation Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/navigation-line.svg) */ export const NavigationLineIcon: IconType = (props) => { return GenIcon(navigationLine)(props); }; /** * The react component for the `netease-cloud-music-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Netease Cloud Music Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/netease-cloud-music-fill.svg) */ export const NeteaseCloudMusicFillIcon: IconType = (props) => { return GenIcon(neteaseCloudMusicFill)(props); }; /** * The react component for the `netease-cloud-music-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Netease Cloud Music Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/netease-cloud-music-line.svg) */ export const NeteaseCloudMusicLineIcon: IconType = (props) => { return GenIcon(neteaseCloudMusicLine)(props); }; /** * The react component for the `netflix-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Netflix Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/netflix-fill.svg) */ export const NetflixFillIcon: IconType = (props) => { return GenIcon(netflixFill)(props); }; /** * The react component for the `netflix-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Netflix Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/netflix-line.svg) */ export const NetflixLineIcon: IconType = (props) => { return GenIcon(netflixLine)(props); }; /** * The react component for the `newspaper-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Newspaper Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/newspaper-fill.svg) */ export const NewspaperFillIcon: IconType = (props) => { return GenIcon(newspaperFill)(props); }; /** * The react component for the `newspaper-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Newspaper Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/newspaper-line.svg) */ export const NewspaperLineIcon: IconType = (props) => { return GenIcon(newspaperLine)(props); }; /** * The react component for the `notification-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-2-fill.svg) */ export const Notification2FillIcon: IconType = (props) => { return GenIcon(notification2Fill)(props); }; /** * The react component for the `notification-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-2-line.svg) */ export const Notification2LineIcon: IconType = (props) => { return GenIcon(notification2Line)(props); }; /** * The react component for the `notification-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-3-fill.svg) */ export const Notification3FillIcon: IconType = (props) => { return GenIcon(notification3Fill)(props); }; /** * The react component for the `notification-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-3-line.svg) */ export const Notification3LineIcon: IconType = (props) => { return GenIcon(notification3Line)(props); }; /** * The react component for the `notification-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-4-fill.svg) */ export const Notification4FillIcon: IconType = (props) => { return GenIcon(notification4Fill)(props); }; /** * The react component for the `notification-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-4-line.svg) */ export const Notification4LineIcon: IconType = (props) => { return GenIcon(notification4Line)(props); }; /** * The react component for the `notification-badge-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Badge Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/notification-badge-fill.svg) */ export const NotificationBadgeFillIcon: IconType = (props) => { return GenIcon(notificationBadgeFill)(props); }; /** * The react component for the `notification-badge-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Badge Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/notification-badge-line.svg) */ export const NotificationBadgeLineIcon: IconType = (props) => { return GenIcon(notificationBadgeLine)(props); }; /** * The react component for the `notification-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-fill.svg) */ export const NotificationFillIcon: IconType = (props) => { return GenIcon(notificationFill)(props); }; /** * The react component for the `notification-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-line.svg) */ export const NotificationLineIcon: IconType = (props) => { return GenIcon(notificationLine)(props); }; /** * The react component for the `notification-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-off-fill.svg) */ export const NotificationOffFillIcon: IconType = (props) => { return GenIcon(notificationOffFill)(props); }; /** * The react component for the `notification-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Notification Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/notification-off-line.svg) */ export const NotificationOffLineIcon: IconType = (props) => { return GenIcon(notificationOffLine)(props); }; /** * The react component for the `npmjs-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Npmjs Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/npmjs-fill.svg) */ export const NpmjsFillIcon: IconType = (props) => { return GenIcon(npmjsFill)(props); }; /** * The react component for the `npmjs-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Npmjs Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/npmjs-line.svg) */ export const NpmjsLineIcon: IconType = (props) => { return GenIcon(npmjsLine)(props); }; /** * The react component for the `numbers-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Numbers Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/numbers-fill.svg) */ export const NumbersFillIcon: IconType = (props) => { return GenIcon(numbersFill)(props); }; /** * The react component for the `numbers-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Numbers Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/numbers-line.svg) */ export const NumbersLineIcon: IconType = (props) => { return GenIcon(numbersLine)(props); }; /** * The react component for the `nurse-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Nurse Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/nurse-fill.svg) */ export const NurseFillIcon: IconType = (props) => { return GenIcon(nurseFill)(props); }; /** * The react component for the `nurse-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Nurse Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/nurse-line.svg) */ export const NurseLineIcon: IconType = (props) => { return GenIcon(nurseLine)(props); }; /** * The react component for the `oil-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Oil Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/oil-fill.svg) */ export const OilFillIcon: IconType = (props) => { return GenIcon(oilFill)(props); }; /** * The react component for the `oil-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Oil Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/oil-line.svg) */ export const OilLineIcon: IconType = (props) => { return GenIcon(oilLine)(props); }; /** * The react component for the `open-arm-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Open Arm Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/open-arm-fill.svg) */ export const OpenArmFillIcon: IconType = (props) => { return GenIcon(openArmFill)(props); }; /** * The react component for the `open-arm-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Open Arm Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/open-arm-line.svg) */ export const OpenArmLineIcon: IconType = (props) => { return GenIcon(openArmLine)(props); }; /** * The react component for the `open-source-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Open Source Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/open-source-fill.svg) */ export const OpenSourceFillIcon: IconType = (props) => { return GenIcon(openSourceFill)(props); }; /** * The react component for the `open-source-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Open Source Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/open-source-line.svg) */ export const OpenSourceLineIcon: IconType = (props) => { return GenIcon(openSourceLine)(props); }; /** * The react component for the `opera-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Opera Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/opera-fill.svg) */ export const OperaFillIcon: IconType = (props) => { return GenIcon(operaFill)(props); }; /** * The react component for the `opera-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Opera Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/opera-line.svg) */ export const OperaLineIcon: IconType = (props) => { return GenIcon(operaLine)(props); }; /** * The react component for the `order-play-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Order Play Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/order-play-fill.svg) */ export const OrderPlayFillIcon: IconType = (props) => { return GenIcon(orderPlayFill)(props); }; /** * The react component for the `order-play-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Order Play Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/order-play-line.svg) */ export const OrderPlayLineIcon: IconType = (props) => { return GenIcon(orderPlayLine)(props); }; /** * The react component for the `outlet-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Outlet 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/outlet-2-fill.svg) */ export const Outlet2FillIcon: IconType = (props) => { return GenIcon(outlet2Fill)(props); }; /** * The react component for the `outlet-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Outlet 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/outlet-2-line.svg) */ export const Outlet2LineIcon: IconType = (props) => { return GenIcon(outlet2Line)(props); }; /** * The react component for the `outlet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Outlet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/outlet-fill.svg) */ export const OutletFillIcon: IconType = (props) => { return GenIcon(outletFill)(props); }; /** * The react component for the `outlet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Outlet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/outlet-line.svg) */ export const OutletLineIcon: IconType = (props) => { return GenIcon(outletLine)(props); }; /** * The react component for the `pages-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pages Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/pages-fill.svg) */ export const PagesFillIcon: IconType = (props) => { return GenIcon(pagesFill)(props); }; /** * The react component for the `pages-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pages Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/pages-line.svg) */ export const PagesLineIcon: IconType = (props) => { return GenIcon(pagesLine)(props); }; /** * The react component for the `paint-brush-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paint Brush Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/paint-brush-fill.svg) */ export const PaintBrushFillIcon: IconType = (props) => { return GenIcon(paintBrushFill)(props); }; /** * The react component for the `paint-brush-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paint Brush Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/paint-brush-line.svg) */ export const PaintBrushLineIcon: IconType = (props) => { return GenIcon(paintBrushLine)(props); }; /** * The react component for the `paint-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paint Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/paint-fill.svg) */ export const PaintFillIcon: IconType = (props) => { return GenIcon(paintFill)(props); }; /** * The react component for the `paint-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paint Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/paint-line.svg) */ export const PaintLineIcon: IconType = (props) => { return GenIcon(paintLine)(props); }; /** * The react component for the `palette-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Palette Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/palette-fill.svg) */ export const PaletteFillIcon: IconType = (props) => { return GenIcon(paletteFill)(props); }; /** * The react component for the `palette-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Palette Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/palette-line.svg) */ export const PaletteLineIcon: IconType = (props) => { return GenIcon(paletteLine)(props); }; /** * The react component for the `pantone-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pantone Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pantone-fill.svg) */ export const PantoneFillIcon: IconType = (props) => { return GenIcon(pantoneFill)(props); }; /** * The react component for the `pantone-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pantone Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pantone-line.svg) */ export const PantoneLineIcon: IconType = (props) => { return GenIcon(pantoneLine)(props); }; /** * The react component for the `parent-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parent Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/parent-fill.svg) */ export const ParentFillIcon: IconType = (props) => { return GenIcon(parentFill)(props); }; /** * The react component for the `parent-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parent Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/parent-line.svg) */ export const ParentLineIcon: IconType = (props) => { return GenIcon(parentLine)(props); }; /** * The react component for the `parentheses-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parentheses Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/parentheses-fill.svg) */ export const ParenthesesFillIcon: IconType = (props) => { return GenIcon(parenthesesFill)(props); }; /** * The react component for the `parentheses-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parentheses Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/parentheses-line.svg) */ export const ParenthesesLineIcon: IconType = (props) => { return GenIcon(parenthesesLine)(props); }; /** * The react component for the `parking-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parking Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/parking-box-fill.svg) */ export const ParkingBoxFillIcon: IconType = (props) => { return GenIcon(parkingBoxFill)(props); }; /** * The react component for the `parking-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parking Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/parking-box-line.svg) */ export const ParkingBoxLineIcon: IconType = (props) => { return GenIcon(parkingBoxLine)(props); }; /** * The react component for the `parking-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parking Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/parking-fill.svg) */ export const ParkingFillIcon: IconType = (props) => { return GenIcon(parkingFill)(props); }; /** * The react component for the `parking-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Parking Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/parking-line.svg) */ export const ParkingLineIcon: IconType = (props) => { return GenIcon(parkingLine)(props); }; /** * The react component for the `passport-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Passport Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/passport-fill.svg) */ export const PassportFillIcon: IconType = (props) => { return GenIcon(passportFill)(props); }; /** * The react component for the `passport-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Passport Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/passport-line.svg) */ export const PassportLineIcon: IconType = (props) => { return GenIcon(passportLine)(props); }; /** * The react component for the `patreon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Patreon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/patreon-fill.svg) */ export const PatreonFillIcon: IconType = (props) => { return GenIcon(patreonFill)(props); }; /** * The react component for the `patreon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Patreon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/patreon-line.svg) */ export const PatreonLineIcon: IconType = (props) => { return GenIcon(patreonLine)(props); }; /** * The react component for the `pause-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-circle-fill.svg) */ export const PauseCircleFillIcon: IconType = (props) => { return GenIcon(pauseCircleFill)(props); }; /** * The react component for the `pause-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-circle-line.svg) */ export const PauseCircleLineIcon: IconType = (props) => { return GenIcon(pauseCircleLine)(props); }; /** * The react component for the `pause-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-fill.svg) */ export const PauseFillIcon: IconType = (props) => { return GenIcon(pauseFill)(props); }; /** * The react component for the `pause-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-line.svg) */ export const PauseLineIcon: IconType = (props) => { return GenIcon(pauseLine)(props); }; /** * The react component for the `pause-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-mini-fill.svg) */ export const PauseMiniFillIcon: IconType = (props) => { return GenIcon(pauseMiniFill)(props); }; /** * The react component for the `pause-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pause Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/pause-mini-line.svg) */ export const PauseMiniLineIcon: IconType = (props) => { return GenIcon(pauseMiniLine)(props); }; /** * The react component for the `paypal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paypal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/paypal-fill.svg) */ export const PaypalFillIcon: IconType = (props) => { return GenIcon(paypalFill)(props); }; /** * The react component for the `paypal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Paypal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/paypal-line.svg) */ export const PaypalLineIcon: IconType = (props) => { return GenIcon(paypalLine)(props); }; /** * The react component for the `pen-nib-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pen Nib Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pen-nib-fill.svg) */ export const PenNibFillIcon: IconType = (props) => { return GenIcon(penNibFill)(props); }; /** * The react component for the `pen-nib-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pen Nib Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pen-nib-line.svg) */ export const PenNibLineIcon: IconType = (props) => { return GenIcon(penNibLine)(props); }; /** * The react component for the `pencil-ruler-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pencil Ruler 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pencil-ruler-2-fill.svg) */ export const PencilRuler2FillIcon: IconType = (props) => { return GenIcon(pencilRuler2Fill)(props); }; /** * The react component for the `pencil-ruler-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pencil Ruler 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pencil-ruler-2-line.svg) */ export const PencilRuler2LineIcon: IconType = (props) => { return GenIcon(pencilRuler2Line)(props); }; /** * The react component for the `pencil-ruler-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pencil Ruler Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pencil-ruler-fill.svg) */ export const PencilRulerFillIcon: IconType = (props) => { return GenIcon(pencilRulerFill)(props); }; /** * The react component for the `pencil-ruler-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pencil Ruler Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/pencil-ruler-line.svg) */ export const PencilRulerLineIcon: IconType = (props) => { return GenIcon(pencilRulerLine)(props); }; /** * The react component for the `percent-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Percent Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/percent-fill.svg) */ export const PercentFillIcon: IconType = (props) => { return GenIcon(percentFill)(props); }; /** * The react component for the `percent-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Percent Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/percent-line.svg) */ export const PercentLineIcon: IconType = (props) => { return GenIcon(percentLine)(props); }; /** * The react component for the `phone-camera-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Camera Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/phone-camera-fill.svg) */ export const PhoneCameraFillIcon: IconType = (props) => { return GenIcon(phoneCameraFill)(props); }; /** * The react component for the `phone-camera-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Camera Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/phone-camera-line.svg) */ export const PhoneCameraLineIcon: IconType = (props) => { return GenIcon(phoneCameraLine)(props); }; /** * The react component for the `phone-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-fill.svg) */ export const PhoneFillIcon: IconType = (props) => { return GenIcon(phoneFill)(props); }; /** * The react component for the `phone-find-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Find Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-find-fill.svg) */ export const PhoneFindFillIcon: IconType = (props) => { return GenIcon(phoneFindFill)(props); }; /** * The react component for the `phone-find-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Find Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-find-line.svg) */ export const PhoneFindLineIcon: IconType = (props) => { return GenIcon(phoneFindLine)(props); }; /** * The react component for the `phone-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-line.svg) */ export const PhoneLineIcon: IconType = (props) => { return GenIcon(phoneLine)(props); }; /** * The react component for the `phone-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-lock-fill.svg) */ export const PhoneLockFillIcon: IconType = (props) => { return GenIcon(phoneLockFill)(props); }; /** * The react component for the `phone-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Phone Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/phone-lock-line.svg) */ export const PhoneLockLineIcon: IconType = (props) => { return GenIcon(phoneLockLine)(props); }; /** * The react component for the `picture-in-picture-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-2-fill.svg) */ export const PictureInPicture2FillIcon: IconType = (props) => { return GenIcon(pictureInPicture2Fill)(props); }; /** * The react component for the `picture-in-picture-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-2-line.svg) */ export const PictureInPicture2LineIcon: IconType = (props) => { return GenIcon(pictureInPicture2Line)(props); }; /** * The react component for the `picture-in-picture-exit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture Exit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-exit-fill.svg) */ export const PictureInPictureExitFillIcon: IconType = (props) => { return GenIcon(pictureInPictureExitFill)(props); }; /** * The react component for the `picture-in-picture-exit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture Exit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-exit-line.svg) */ export const PictureInPictureExitLineIcon: IconType = (props) => { return GenIcon(pictureInPictureExitLine)(props); }; /** * The react component for the `picture-in-picture-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-fill.svg) */ export const PictureInPictureFillIcon: IconType = (props) => { return GenIcon(pictureInPictureFill)(props); }; /** * The react component for the `picture-in-picture-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Picture In Picture Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/picture-in-picture-line.svg) */ export const PictureInPictureLineIcon: IconType = (props) => { return GenIcon(pictureInPictureLine)(props); }; /** * The react component for the `pie-chart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-2-fill.svg) */ export const PieChart2FillIcon: IconType = (props) => { return GenIcon(pieChart2Fill)(props); }; /** * The react component for the `pie-chart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-2-line.svg) */ export const PieChart2LineIcon: IconType = (props) => { return GenIcon(pieChart2Line)(props); }; /** * The react component for the `pie-chart-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-box-fill.svg) */ export const PieChartBoxFillIcon: IconType = (props) => { return GenIcon(pieChartBoxFill)(props); }; /** * The react component for the `pie-chart-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-box-line.svg) */ export const PieChartBoxLineIcon: IconType = (props) => { return GenIcon(pieChartBoxLine)(props); }; /** * The react component for the `pie-chart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-fill.svg) */ export const PieChartFillIcon: IconType = (props) => { return GenIcon(pieChartFill)(props); }; /** * The react component for the `pie-chart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pie Chart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/pie-chart-line.svg) */ export const PieChartLineIcon: IconType = (props) => { return GenIcon(pieChartLine)(props); }; /** * The react component for the `pin-distance-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pin Distance Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pin-distance-fill.svg) */ export const PinDistanceFillIcon: IconType = (props) => { return GenIcon(pinDistanceFill)(props); }; /** * The react component for the `pin-distance-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pin Distance Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pin-distance-line.svg) */ export const PinDistanceLineIcon: IconType = (props) => { return GenIcon(pinDistanceLine)(props); }; /** * The react component for the `ping-pong-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ping Pong Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/ping-pong-fill.svg) */ export const PingPongFillIcon: IconType = (props) => { return GenIcon(pingPongFill)(props); }; /** * The react component for the `ping-pong-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ping Pong Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/ping-pong-line.svg) */ export const PingPongLineIcon: IconType = (props) => { return GenIcon(pingPongLine)(props); }; /** * The react component for the `pinterest-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pinterest Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/pinterest-fill.svg) */ export const PinterestFillIcon: IconType = (props) => { return GenIcon(pinterestFill)(props); }; /** * The react component for the `pinterest-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pinterest Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/pinterest-line.svg) */ export const PinterestLineIcon: IconType = (props) => { return GenIcon(pinterestLine)(props); }; /** * The react component for the `pixelfed-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pixelfed Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/pixelfed-fill.svg) */ export const PixelfedFillIcon: IconType = (props) => { return GenIcon(pixelfedFill)(props); }; /** * The react component for the `pixelfed-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pixelfed Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/pixelfed-line.svg) */ export const PixelfedLineIcon: IconType = (props) => { return GenIcon(pixelfedLine)(props); }; /** * The react component for the `plane-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plane Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/plane-fill.svg) */ export const PlaneFillIcon: IconType = (props) => { return GenIcon(planeFill)(props); }; /** * The react component for the `plane-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plane Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/plane-line.svg) */ export const PlaneLineIcon: IconType = (props) => { return GenIcon(planeLine)(props); }; /** * The react component for the `plant-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plant Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plant-fill.svg) */ export const PlantFillIcon: IconType = (props) => { return GenIcon(plantFill)(props); }; /** * The react component for the `plant-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plant Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plant-line.svg) */ export const PlantLineIcon: IconType = (props) => { return GenIcon(plantLine)(props); }; /** * The react component for the `play-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-circle-fill.svg) */ export const PlayCircleFillIcon: IconType = (props) => { return GenIcon(playCircleFill)(props); }; /** * The react component for the `play-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-circle-line.svg) */ export const PlayCircleLineIcon: IconType = (props) => { return GenIcon(playCircleLine)(props); }; /** * The react component for the `play-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-fill.svg) */ export const PlayFillIcon: IconType = (props) => { return GenIcon(playFill)(props); }; /** * The react component for the `play-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-line.svg) */ export const PlayLineIcon: IconType = (props) => { return GenIcon(playLine)(props); }; /** * The react component for the `play-list-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-2-fill.svg) */ export const PlayList2FillIcon: IconType = (props) => { return GenIcon(playList2Fill)(props); }; /** * The react component for the `play-list-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-2-line.svg) */ export const PlayList2LineIcon: IconType = (props) => { return GenIcon(playList2Line)(props); }; /** * The react component for the `play-list-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-add-fill.svg) */ export const PlayListAddFillIcon: IconType = (props) => { return GenIcon(playListAddFill)(props); }; /** * The react component for the `play-list-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-add-line.svg) */ export const PlayListAddLineIcon: IconType = (props) => { return GenIcon(playListAddLine)(props); }; /** * The react component for the `play-list-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-fill.svg) */ export const PlayListFillIcon: IconType = (props) => { return GenIcon(playListFill)(props); }; /** * The react component for the `play-list-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play List Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-list-line.svg) */ export const PlayListLineIcon: IconType = (props) => { return GenIcon(playListLine)(props); }; /** * The react component for the `play-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-mini-fill.svg) */ export const PlayMiniFillIcon: IconType = (props) => { return GenIcon(playMiniFill)(props); }; /** * The react component for the `play-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Play Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/play-mini-line.svg) */ export const PlayMiniLineIcon: IconType = (props) => { return GenIcon(playMiniLine)(props); }; /** * The react component for the `playstation-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Playstation Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/playstation-fill.svg) */ export const PlaystationFillIcon: IconType = (props) => { return GenIcon(playstationFill)(props); }; /** * The react component for the `playstation-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Playstation Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/playstation-line.svg) */ export const PlaystationLineIcon: IconType = (props) => { return GenIcon(playstationLine)(props); }; /** * The react component for the `plug-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plug 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plug-2-fill.svg) */ export const Plug2FillIcon: IconType = (props) => { return GenIcon(plug2Fill)(props); }; /** * The react component for the `plug-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plug 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plug-2-line.svg) */ export const Plug2LineIcon: IconType = (props) => { return GenIcon(plug2Line)(props); }; /** * The react component for the `plug-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plug Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plug-fill.svg) */ export const PlugFillIcon: IconType = (props) => { return GenIcon(plugFill)(props); }; /** * The react component for the `plug-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Plug Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/plug-line.svg) */ export const PlugLineIcon: IconType = (props) => { return GenIcon(plugLine)(props); }; /** * The react component for the `polaroid-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Polaroid 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/polaroid-2-fill.svg) */ export const Polaroid2FillIcon: IconType = (props) => { return GenIcon(polaroid2Fill)(props); }; /** * The react component for the `polaroid-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Polaroid 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/polaroid-2-line.svg) */ export const Polaroid2LineIcon: IconType = (props) => { return GenIcon(polaroid2Line)(props); }; /** * The react component for the `polaroid-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Polaroid Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/polaroid-fill.svg) */ export const PolaroidFillIcon: IconType = (props) => { return GenIcon(polaroidFill)(props); }; /** * The react component for the `polaroid-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Polaroid Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/polaroid-line.svg) */ export const PolaroidLineIcon: IconType = (props) => { return GenIcon(polaroidLine)(props); }; /** * The react component for the `police-car-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Police Car Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/police-car-fill.svg) */ export const PoliceCarFillIcon: IconType = (props) => { return GenIcon(policeCarFill)(props); }; /** * The react component for the `police-car-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Police Car Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/police-car-line.svg) */ export const PoliceCarLineIcon: IconType = (props) => { return GenIcon(policeCarLine)(props); }; /** * The react component for the `price-tag-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-2-fill.svg) */ export const PriceTag2FillIcon: IconType = (props) => { return GenIcon(priceTag2Fill)(props); }; /** * The react component for the `price-tag-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-2-line.svg) */ export const PriceTag2LineIcon: IconType = (props) => { return GenIcon(priceTag2Line)(props); }; /** * The react component for the `price-tag-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-3-fill.svg) */ export const PriceTag3FillIcon: IconType = (props) => { return GenIcon(priceTag3Fill)(props); }; /** * The react component for the `price-tag-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-3-line.svg) */ export const PriceTag3LineIcon: IconType = (props) => { return GenIcon(priceTag3Line)(props); }; /** * The react component for the `price-tag-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-fill.svg) */ export const PriceTagFillIcon: IconType = (props) => { return GenIcon(priceTagFill)(props); }; /** * The react component for the `price-tag-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Price Tag Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/price-tag-line.svg) */ export const PriceTagLineIcon: IconType = (props) => { return GenIcon(priceTagLine)(props); }; /** * The react component for the `printer-cloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Printer Cloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/printer-cloud-fill.svg) */ export const PrinterCloudFillIcon: IconType = (props) => { return GenIcon(printerCloudFill)(props); }; /** * The react component for the `printer-cloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Printer Cloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/printer-cloud-line.svg) */ export const PrinterCloudLineIcon: IconType = (props) => { return GenIcon(printerCloudLine)(props); }; /** * The react component for the `printer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Printer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/printer-fill.svg) */ export const PrinterFillIcon: IconType = (props) => { return GenIcon(printerFill)(props); }; /** * The react component for the `printer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Printer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/printer-line.svg) */ export const PrinterLineIcon: IconType = (props) => { return GenIcon(printerLine)(props); }; /** * The react component for the `product-hunt-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Product Hunt Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/product-hunt-fill.svg) */ export const ProductHuntFillIcon: IconType = (props) => { return GenIcon(productHuntFill)(props); }; /** * The react component for the `product-hunt-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Product Hunt Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/product-hunt-line.svg) */ export const ProductHuntLineIcon: IconType = (props) => { return GenIcon(productHuntLine)(props); }; /** * The react component for the `profile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Profile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/profile-fill.svg) */ export const ProfileFillIcon: IconType = (props) => { return GenIcon(profileFill)(props); }; /** * The react component for the `profile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Profile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/profile-line.svg) */ export const ProfileLineIcon: IconType = (props) => { return GenIcon(profileLine)(props); }; /** * The react component for the `projector-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Projector 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/projector-2-fill.svg) */ export const Projector2FillIcon: IconType = (props) => { return GenIcon(projector2Fill)(props); }; /** * The react component for the `projector-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Projector 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/projector-2-line.svg) */ export const Projector2LineIcon: IconType = (props) => { return GenIcon(projector2Line)(props); }; /** * The react component for the `projector-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Projector Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/projector-fill.svg) */ export const ProjectorFillIcon: IconType = (props) => { return GenIcon(projectorFill)(props); }; /** * The react component for the `projector-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Projector Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/projector-line.svg) */ export const ProjectorLineIcon: IconType = (props) => { return GenIcon(projectorLine)(props); }; /** * The react component for the `psychotherapy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Psychotherapy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/psychotherapy-fill.svg) */ export const PsychotherapyFillIcon: IconType = (props) => { return GenIcon(psychotherapyFill)(props); }; /** * The react component for the `psychotherapy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Psychotherapy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/psychotherapy-line.svg) */ export const PsychotherapyLineIcon: IconType = (props) => { return GenIcon(psychotherapyLine)(props); }; /** * The react component for the `pulse-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pulse Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/pulse-fill.svg) */ export const PulseFillIcon: IconType = (props) => { return GenIcon(pulseFill)(props); }; /** * The react component for the `pulse-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pulse Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/pulse-line.svg) */ export const PulseLineIcon: IconType = (props) => { return GenIcon(pulseLine)(props); }; /** * The react component for the `pushpin-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pushpin 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pushpin-2-fill.svg) */ export const Pushpin2FillIcon: IconType = (props) => { return GenIcon(pushpin2Fill)(props); }; /** * The react component for the `pushpin-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pushpin 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pushpin-2-line.svg) */ export const Pushpin2LineIcon: IconType = (props) => { return GenIcon(pushpin2Line)(props); }; /** * The react component for the `pushpin-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pushpin Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pushpin-fill.svg) */ export const PushpinFillIcon: IconType = (props) => { return GenIcon(pushpinFill)(props); }; /** * The react component for the `pushpin-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Pushpin Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/pushpin-line.svg) */ export const PushpinLineIcon: IconType = (props) => { return GenIcon(pushpinLine)(props); }; /** * The react component for the `qq-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qq Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/qq-fill.svg) */ export const QqFillIcon: IconType = (props) => { return GenIcon(qqFill)(props); }; /** * The react component for the `qq-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qq Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/qq-line.svg) */ export const QqLineIcon: IconType = (props) => { return GenIcon(qqLine)(props); }; /** * The react component for the `qr-code-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Code Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-code-fill.svg) */ export const QrCodeFillIcon: IconType = (props) => { return GenIcon(qrCodeFill)(props); }; /** * The react component for the `qr-code-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Code Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-code-line.svg) */ export const QrCodeLineIcon: IconType = (props) => { return GenIcon(qrCodeLine)(props); }; /** * The react component for the `qr-scan-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Scan 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-scan-2-fill.svg) */ export const QrScan2FillIcon: IconType = (props) => { return GenIcon(qrScan2Fill)(props); }; /** * The react component for the `qr-scan-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Scan 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-scan-2-line.svg) */ export const QrScan2LineIcon: IconType = (props) => { return GenIcon(qrScan2Line)(props); }; /** * The react component for the `qr-scan-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Scan Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-scan-fill.svg) */ export const QrScanFillIcon: IconType = (props) => { return GenIcon(qrScanFill)(props); }; /** * The react component for the `qr-scan-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Qr Scan Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/qr-scan-line.svg) */ export const QrScanLineIcon: IconType = (props) => { return GenIcon(qrScanLine)(props); }; /** * The react component for the `question-answer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Question Answer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/question-answer-fill.svg) */ export const QuestionAnswerFillIcon: IconType = (props) => { return GenIcon(questionAnswerFill)(props); }; /** * The react component for the `question-answer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Question Answer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/question-answer-line.svg) */ export const QuestionAnswerLineIcon: IconType = (props) => { return GenIcon(questionAnswerLine)(props); }; /** * The react component for the `question-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Question Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/question-fill.svg) */ export const QuestionFillIcon: IconType = (props) => { return GenIcon(questionFill)(props); }; /** * The react component for the `question-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Question Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/question-line.svg) */ export const QuestionLineIcon: IconType = (props) => { return GenIcon(questionLine)(props); }; /** * The react component for the `questionnaire-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Questionnaire Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/questionnaire-fill.svg) */ export const QuestionnaireFillIcon: IconType = (props) => { return GenIcon(questionnaireFill)(props); }; /** * The react component for the `questionnaire-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Questionnaire Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/questionnaire-line.svg) */ export const QuestionnaireLineIcon: IconType = (props) => { return GenIcon(questionnaireLine)(props); }; /** * The react component for the `quill-pen-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Quill Pen Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/quill-pen-fill.svg) */ export const QuillPenFillIcon: IconType = (props) => { return GenIcon(quillPenFill)(props); }; /** * The react component for the `quill-pen-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Quill Pen Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/quill-pen-line.svg) */ export const QuillPenLineIcon: IconType = (props) => { return GenIcon(quillPenLine)(props); }; /** * The react component for the `radar-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radar Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/radar-fill.svg) */ export const RadarFillIcon: IconType = (props) => { return GenIcon(radarFill)(props); }; /** * The react component for the `radar-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radar Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/radar-line.svg) */ export const RadarLineIcon: IconType = (props) => { return GenIcon(radarLine)(props); }; /** * The react component for the `radio-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/radio-2-fill.svg) */ export const Radio2FillIcon: IconType = (props) => { return GenIcon(radio2Fill)(props); }; /** * The react component for the `radio-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/radio-2-line.svg) */ export const Radio2LineIcon: IconType = (props) => { return GenIcon(radio2Line)(props); }; /** * The react component for the `radio-button-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio Button Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/radio-button-fill.svg) */ export const RadioButtonFillIcon: IconType = (props) => { return GenIcon(radioButtonFill)(props); }; /** * The react component for the `radio-button-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio Button Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/radio-button-line.svg) */ export const RadioButtonLineIcon: IconType = (props) => { return GenIcon(radioButtonLine)(props); }; /** * The react component for the `radio-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/radio-fill.svg) */ export const RadioFillIcon: IconType = (props) => { return GenIcon(radioFill)(props); }; /** * The react component for the `radio-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Radio Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/radio-line.svg) */ export const RadioLineIcon: IconType = (props) => { return GenIcon(radioLine)(props); }; /** * The react component for the `rainbow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rainbow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/rainbow-fill.svg) */ export const RainbowFillIcon: IconType = (props) => { return GenIcon(rainbowFill)(props); }; /** * The react component for the `rainbow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rainbow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/rainbow-line.svg) */ export const RainbowLineIcon: IconType = (props) => { return GenIcon(rainbowLine)(props); }; /** * The react component for the `rainy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rainy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/rainy-fill.svg) */ export const RainyFillIcon: IconType = (props) => { return GenIcon(rainyFill)(props); }; /** * The react component for the `rainy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rainy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/rainy-line.svg) */ export const RainyLineIcon: IconType = (props) => { return GenIcon(rainyLine)(props); }; /** * The react component for the `reactjs-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reactjs Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/reactjs-fill.svg) */ export const ReactjsFillIcon: IconType = (props) => { return GenIcon(reactjsFill)(props); }; /** * The react component for the `reactjs-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reactjs Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/reactjs-line.svg) */ export const ReactjsLineIcon: IconType = (props) => { return GenIcon(reactjsLine)(props); }; /** * The react component for the `record-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Record Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/record-circle-fill.svg) */ export const RecordCircleFillIcon: IconType = (props) => { return GenIcon(recordCircleFill)(props); }; /** * The react component for the `record-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Record Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/record-circle-line.svg) */ export const RecordCircleLineIcon: IconType = (props) => { return GenIcon(recordCircleLine)(props); }; /** * The react component for the `record-mail-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Record Mail Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/record-mail-fill.svg) */ export const RecordMailFillIcon: IconType = (props) => { return GenIcon(recordMailFill)(props); }; /** * The react component for the `record-mail-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Record Mail Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/record-mail-line.svg) */ export const RecordMailLineIcon: IconType = (props) => { return GenIcon(recordMailLine)(props); }; /** * The react component for the `recycle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Recycle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/recycle-fill.svg) */ export const RecycleFillIcon: IconType = (props) => { return GenIcon(recycleFill)(props); }; /** * The react component for the `recycle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Recycle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/recycle-line.svg) */ export const RecycleLineIcon: IconType = (props) => { return GenIcon(recycleLine)(props); }; /** * The react component for the `red-packet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Red Packet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/red-packet-fill.svg) */ export const RedPacketFillIcon: IconType = (props) => { return GenIcon(redPacketFill)(props); }; /** * The react component for the `red-packet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Red Packet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/red-packet-line.svg) */ export const RedPacketLineIcon: IconType = (props) => { return GenIcon(redPacketLine)(props); }; /** * The react component for the `reddit-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reddit Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/reddit-fill.svg) */ export const RedditFillIcon: IconType = (props) => { return GenIcon(redditFill)(props); }; /** * The react component for the `reddit-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reddit Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/reddit-line.svg) */ export const RedditLineIcon: IconType = (props) => { return GenIcon(redditLine)(props); }; /** * The react component for the `refresh-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refresh Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/refresh-fill.svg) */ export const RefreshFillIcon: IconType = (props) => { return GenIcon(refreshFill)(props); }; /** * The react component for the `refresh-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refresh Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/refresh-line.svg) */ export const RefreshLineIcon: IconType = (props) => { return GenIcon(refreshLine)(props); }; /** * The react component for the `refund-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refund 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/refund-2-fill.svg) */ export const Refund2FillIcon: IconType = (props) => { return GenIcon(refund2Fill)(props); }; /** * The react component for the `refund-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refund 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/refund-2-line.svg) */ export const Refund2LineIcon: IconType = (props) => { return GenIcon(refund2Line)(props); }; /** * The react component for the `refund-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refund Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/refund-fill.svg) */ export const RefundFillIcon: IconType = (props) => { return GenIcon(refundFill)(props); }; /** * The react component for the `refund-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Refund Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/refund-line.svg) */ export const RefundLineIcon: IconType = (props) => { return GenIcon(refundLine)(props); }; /** * The react component for the `registered-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Registered Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/registered-fill.svg) */ export const RegisteredFillIcon: IconType = (props) => { return GenIcon(registeredFill)(props); }; /** * The react component for the `registered-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Registered Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/registered-line.svg) */ export const RegisteredLineIcon: IconType = (props) => { return GenIcon(registeredLine)(props); }; /** * The react component for the `remixicon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remixicon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/remixicon-fill.svg) */ export const RemixiconFillIcon: IconType = (props) => { return GenIcon(remixiconFill)(props); }; /** * The react component for the `remixicon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remixicon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/remixicon-line.svg) */ export const RemixiconLineIcon: IconType = (props) => { return GenIcon(remixiconLine)(props); }; /** * The react component for the `remote-control-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remote Control 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/remote-control-2-fill.svg) */ export const RemoteControl2FillIcon: IconType = (props) => { return GenIcon(remoteControl2Fill)(props); }; /** * The react component for the `remote-control-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remote Control 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/remote-control-2-line.svg) */ export const RemoteControl2LineIcon: IconType = (props) => { return GenIcon(remoteControl2Line)(props); }; /** * The react component for the `remote-control-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remote Control Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/remote-control-fill.svg) */ export const RemoteControlFillIcon: IconType = (props) => { return GenIcon(remoteControlFill)(props); }; /** * The react component for the `remote-control-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Remote Control Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/remote-control-line.svg) */ export const RemoteControlLineIcon: IconType = (props) => { return GenIcon(remoteControlLine)(props); }; /** * The react component for the `repeat-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-2-fill.svg) */ export const Repeat2FillIcon: IconType = (props) => { return GenIcon(repeat2Fill)(props); }; /** * The react component for the `repeat-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-2-line.svg) */ export const Repeat2LineIcon: IconType = (props) => { return GenIcon(repeat2Line)(props); }; /** * The react component for the `repeat-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-fill.svg) */ export const RepeatFillIcon: IconType = (props) => { return GenIcon(repeatFill)(props); }; /** * The react component for the `repeat-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-line.svg) */ export const RepeatLineIcon: IconType = (props) => { return GenIcon(repeatLine)(props); }; /** * The react component for the `repeat-one-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat One Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-one-fill.svg) */ export const RepeatOneFillIcon: IconType = (props) => { return GenIcon(repeatOneFill)(props); }; /** * The react component for the `repeat-one-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Repeat One Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/repeat-one-line.svg) */ export const RepeatOneLineIcon: IconType = (props) => { return GenIcon(repeatOneLine)(props); }; /** * The react component for the `reply-all-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reply All Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/reply-all-fill.svg) */ export const ReplyAllFillIcon: IconType = (props) => { return GenIcon(replyAllFill)(props); }; /** * The react component for the `reply-all-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reply All Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/reply-all-line.svg) */ export const ReplyAllLineIcon: IconType = (props) => { return GenIcon(replyAllLine)(props); }; /** * The react component for the `reply-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reply Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/reply-fill.svg) */ export const ReplyFillIcon: IconType = (props) => { return GenIcon(replyFill)(props); }; /** * The react component for the `reply-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reply Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/reply-line.svg) */ export const ReplyLineIcon: IconType = (props) => { return GenIcon(replyLine)(props); }; /** * The react component for the `reserved-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reserved Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/reserved-fill.svg) */ export const ReservedFillIcon: IconType = (props) => { return GenIcon(reservedFill)(props); }; /** * The react component for the `reserved-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Reserved Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/reserved-line.svg) */ export const ReservedLineIcon: IconType = (props) => { return GenIcon(reservedLine)(props); }; /** * The react component for the `rest-time-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rest Time Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/rest-time-fill.svg) */ export const RestTimeFillIcon: IconType = (props) => { return GenIcon(restTimeFill)(props); }; /** * The react component for the `rest-time-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rest Time Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/rest-time-line.svg) */ export const RestTimeLineIcon: IconType = (props) => { return GenIcon(restTimeLine)(props); }; /** * The react component for the `restart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/restart-fill.svg) */ export const RestartFillIcon: IconType = (props) => { return GenIcon(restartFill)(props); }; /** * The react component for the `restart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/restart-line.svg) */ export const RestartLineIcon: IconType = (props) => { return GenIcon(restartLine)(props); }; /** * The react component for the `restaurant-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restaurant 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/restaurant-2-fill.svg) */ export const Restaurant2FillIcon: IconType = (props) => { return GenIcon(restaurant2Fill)(props); }; /** * The react component for the `restaurant-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restaurant 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/restaurant-2-line.svg) */ export const Restaurant2LineIcon: IconType = (props) => { return GenIcon(restaurant2Line)(props); }; /** * The react component for the `restaurant-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restaurant Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/restaurant-fill.svg) */ export const RestaurantFillIcon: IconType = (props) => { return GenIcon(restaurantFill)(props); }; /** * The react component for the `restaurant-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Restaurant Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/restaurant-line.svg) */ export const RestaurantLineIcon: IconType = (props) => { return GenIcon(restaurantLine)(props); }; /** * The react component for the `rewind-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rewind Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rewind-fill.svg) */ export const RewindFillIcon: IconType = (props) => { return GenIcon(rewindFill)(props); }; /** * The react component for the `rewind-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rewind Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rewind-line.svg) */ export const RewindLineIcon: IconType = (props) => { return GenIcon(rewindLine)(props); }; /** * The react component for the `rewind-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rewind Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rewind-mini-fill.svg) */ export const RewindMiniFillIcon: IconType = (props) => { return GenIcon(rewindMiniFill)(props); }; /** * The react component for the `rewind-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rewind Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rewind-mini-line.svg) */ export const RewindMiniLineIcon: IconType = (props) => { return GenIcon(rewindMiniLine)(props); }; /** * The react component for the `rhythm-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rhythm Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rhythm-fill.svg) */ export const RhythmFillIcon: IconType = (props) => { return GenIcon(rhythmFill)(props); }; /** * The react component for the `rhythm-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rhythm Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/rhythm-line.svg) */ export const RhythmLineIcon: IconType = (props) => { return GenIcon(rhythmLine)(props); }; /** * The react component for the `riding-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Riding Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/riding-fill.svg) */ export const RidingFillIcon: IconType = (props) => { return GenIcon(ridingFill)(props); }; /** * The react component for the `riding-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Riding Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/riding-line.svg) */ export const RidingLineIcon: IconType = (props) => { return GenIcon(ridingLine)(props); }; /** * The react component for the `road-map-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Road Map Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/road-map-fill.svg) */ export const RoadMapFillIcon: IconType = (props) => { return GenIcon(roadMapFill)(props); }; /** * The react component for the `road-map-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Road Map Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/road-map-line.svg) */ export const RoadMapLineIcon: IconType = (props) => { return GenIcon(roadMapLine)(props); }; /** * The react component for the `roadster-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Roadster Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/roadster-fill.svg) */ export const RoadsterFillIcon: IconType = (props) => { return GenIcon(roadsterFill)(props); }; /** * The react component for the `roadster-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Roadster Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/roadster-line.svg) */ export const RoadsterLineIcon: IconType = (props) => { return GenIcon(roadsterLine)(props); }; /** * The react component for the `robot-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Robot Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/robot-fill.svg) */ export const RobotFillIcon: IconType = (props) => { return GenIcon(robotFill)(props); }; /** * The react component for the `robot-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Robot Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/robot-line.svg) */ export const RobotLineIcon: IconType = (props) => { return GenIcon(robotLine)(props); }; /** * The react component for the `rocket-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rocket 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/rocket-2-fill.svg) */ export const Rocket2FillIcon: IconType = (props) => { return GenIcon(rocket2Fill)(props); }; /** * The react component for the `rocket-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rocket 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/rocket-2-line.svg) */ export const Rocket2LineIcon: IconType = (props) => { return GenIcon(rocket2Line)(props); }; /** * The react component for the `rocket-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rocket Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/rocket-fill.svg) */ export const RocketFillIcon: IconType = (props) => { return GenIcon(rocketFill)(props); }; /** * The react component for the `rocket-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rocket Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/rocket-line.svg) */ export const RocketLineIcon: IconType = (props) => { return GenIcon(rocketLine)(props); }; /** * The react component for the `rotate-lock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rotate Lock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/rotate-lock-fill.svg) */ export const RotateLockFillIcon: IconType = (props) => { return GenIcon(rotateLockFill)(props); }; /** * The react component for the `rotate-lock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rotate Lock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/rotate-lock-line.svg) */ export const RotateLockLineIcon: IconType = (props) => { return GenIcon(rotateLockLine)(props); }; /** * The react component for the `route-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Route Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/route-fill.svg) */ export const RouteFillIcon: IconType = (props) => { return GenIcon(routeFill)(props); }; /** * The react component for the `route-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Route Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/route-line.svg) */ export const RouteLineIcon: IconType = (props) => { return GenIcon(routeLine)(props); }; /** * The react component for the `router-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Router Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/router-fill.svg) */ export const RouterFillIcon: IconType = (props) => { return GenIcon(routerFill)(props); }; /** * The react component for the `router-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Router Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/router-line.svg) */ export const RouterLineIcon: IconType = (props) => { return GenIcon(routerLine)(props); }; /** * The react component for the `rss-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rss Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/rss-fill.svg) */ export const RssFillIcon: IconType = (props) => { return GenIcon(rssFill)(props); }; /** * The react component for the `rss-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Rss Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/rss-line.svg) */ export const RssLineIcon: IconType = (props) => { return GenIcon(rssLine)(props); }; /** * The react component for the `ruler-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ruler 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ruler-2-fill.svg) */ export const Ruler2FillIcon: IconType = (props) => { return GenIcon(ruler2Fill)(props); }; /** * The react component for the `ruler-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ruler 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ruler-2-line.svg) */ export const Ruler2LineIcon: IconType = (props) => { return GenIcon(ruler2Line)(props); }; /** * The react component for the `ruler-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ruler Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ruler-fill.svg) */ export const RulerFillIcon: IconType = (props) => { return GenIcon(rulerFill)(props); }; /** * The react component for the `ruler-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ruler Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/ruler-line.svg) */ export const RulerLineIcon: IconType = (props) => { return GenIcon(rulerLine)(props); }; /** * The react component for the `run-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Run Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/run-fill.svg) */ export const RunFillIcon: IconType = (props) => { return GenIcon(runFill)(props); }; /** * The react component for the `run-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Run Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/run-line.svg) */ export const RunLineIcon: IconType = (props) => { return GenIcon(runLine)(props); }; /** * The react component for the `safari-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safari Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/safari-fill.svg) */ export const SafariFillIcon: IconType = (props) => { return GenIcon(safariFill)(props); }; /** * The react component for the `safari-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safari Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/safari-line.svg) */ export const SafariLineIcon: IconType = (props) => { return GenIcon(safariLine)(props); }; /** * The react component for the `safe-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safe 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/safe-2-fill.svg) */ export const Safe2FillIcon: IconType = (props) => { return GenIcon(safe2Fill)(props); }; /** * The react component for the `safe-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safe 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/safe-2-line.svg) */ export const Safe2LineIcon: IconType = (props) => { return GenIcon(safe2Line)(props); }; /** * The react component for the `safe-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safe Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/safe-fill.svg) */ export const SafeFillIcon: IconType = (props) => { return GenIcon(safeFill)(props); }; /** * The react component for the `safe-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Safe Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/safe-line.svg) */ export const SafeLineIcon: IconType = (props) => { return GenIcon(safeLine)(props); }; /** * The react component for the `sailboat-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sailboat Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/sailboat-fill.svg) */ export const SailboatFillIcon: IconType = (props) => { return GenIcon(sailboatFill)(props); }; /** * The react component for the `sailboat-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sailboat Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/sailboat-line.svg) */ export const SailboatLineIcon: IconType = (props) => { return GenIcon(sailboatLine)(props); }; /** * The react component for the `save-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-2-fill.svg) */ export const Save2FillIcon: IconType = (props) => { return GenIcon(save2Fill)(props); }; /** * The react component for the `save-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-2-line.svg) */ export const Save2LineIcon: IconType = (props) => { return GenIcon(save2Line)(props); }; /** * The react component for the `save-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-3-fill.svg) */ export const Save3FillIcon: IconType = (props) => { return GenIcon(save3Fill)(props); }; /** * The react component for the `save-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-3-line.svg) */ export const Save3LineIcon: IconType = (props) => { return GenIcon(save3Line)(props); }; /** * The react component for the `save-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-fill.svg) */ export const SaveFillIcon: IconType = (props) => { return GenIcon(saveFill)(props); }; /** * The react component for the `save-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Save Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/save-line.svg) */ export const SaveLineIcon: IconType = (props) => { return GenIcon(saveLine)(props); }; /** * The react component for the `scales-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-2-fill.svg) */ export const Scales2FillIcon: IconType = (props) => { return GenIcon(scales2Fill)(props); }; /** * The react component for the `scales-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-2-line.svg) */ export const Scales2LineIcon: IconType = (props) => { return GenIcon(scales2Line)(props); }; /** * The react component for the `scales-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-3-fill.svg) */ export const Scales3FillIcon: IconType = (props) => { return GenIcon(scales3Fill)(props); }; /** * The react component for the `scales-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-3-line.svg) */ export const Scales3LineIcon: IconType = (props) => { return GenIcon(scales3Line)(props); }; /** * The react component for the `scales-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-fill.svg) */ export const ScalesFillIcon: IconType = (props) => { return GenIcon(scalesFill)(props); }; /** * The react component for the `scales-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scales Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/scales-line.svg) */ export const ScalesLineIcon: IconType = (props) => { return GenIcon(scalesLine)(props); }; /** * The react component for the `scan-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scan 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/scan-2-fill.svg) */ export const Scan2FillIcon: IconType = (props) => { return GenIcon(scan2Fill)(props); }; /** * The react component for the `scan-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scan 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/scan-2-line.svg) */ export const Scan2LineIcon: IconType = (props) => { return GenIcon(scan2Line)(props); }; /** * The react component for the `scan-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scan Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/scan-fill.svg) */ export const ScanFillIcon: IconType = (props) => { return GenIcon(scanFill)(props); }; /** * The react component for the `scan-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scan Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/scan-line.svg) */ export const ScanLineIcon: IconType = (props) => { return GenIcon(scanLine)(props); }; /** * The react component for the `scissors-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scissors 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/scissors-2-fill.svg) */ export const Scissors2FillIcon: IconType = (props) => { return GenIcon(scissors2Fill)(props); }; /** * The react component for the `scissors-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scissors 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/scissors-2-line.svg) */ export const Scissors2LineIcon: IconType = (props) => { return GenIcon(scissors2Line)(props); }; /** * The react component for the `scissors-cut-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scissors Cut Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/scissors-cut-fill.svg) */ export const ScissorsCutFillIcon: IconType = (props) => { return GenIcon(scissorsCutFill)(props); }; /** * The react component for the `scissors-cut-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scissors Cut Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/scissors-cut-line.svg) */ export const ScissorsCutLineIcon: IconType = (props) => { return GenIcon(scissorsCutLine)(props); }; /** * The react component for the `scissors-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Scissors Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/scissors-line.svg) */ export const ScissorsLineIcon: IconType = (props) => { return GenIcon(scissorsLine)(props); }; /** * The react component for the `screenshot-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Screenshot 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/screenshot-2-fill.svg) */ export const Screenshot2FillIcon: IconType = (props) => { return GenIcon(screenshot2Fill)(props); }; /** * The react component for the `screenshot-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Screenshot 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/screenshot-2-line.svg) */ export const Screenshot2LineIcon: IconType = (props) => { return GenIcon(screenshot2Line)(props); }; /** * The react component for the `screenshot-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Screenshot Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/screenshot-fill.svg) */ export const ScreenshotFillIcon: IconType = (props) => { return GenIcon(screenshotFill)(props); }; /** * The react component for the `screenshot-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Screenshot Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/screenshot-line.svg) */ export const ScreenshotLineIcon: IconType = (props) => { return GenIcon(screenshotLine)(props); }; /** * The react component for the `sd-card-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sd Card Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sd-card-fill.svg) */ export const SdCardFillIcon: IconType = (props) => { return GenIcon(sdCardFill)(props); }; /** * The react component for the `sd-card-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sd Card Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sd-card-line.svg) */ export const SdCardLineIcon: IconType = (props) => { return GenIcon(sdCardLine)(props); }; /** * The react component for the `sd-card-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sd Card Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sd-card-mini-fill.svg) */ export const SdCardMiniFillIcon: IconType = (props) => { return GenIcon(sdCardMiniFill)(props); }; /** * The react component for the `sd-card-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sd Card Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sd-card-mini-line.svg) */ export const SdCardMiniLineIcon: IconType = (props) => { return GenIcon(sdCardMiniLine)(props); }; /** * The react component for the `search-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-2-fill.svg) */ export const Search2FillIcon: IconType = (props) => { return GenIcon(search2Fill)(props); }; /** * The react component for the `search-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-2-line.svg) */ export const Search2LineIcon: IconType = (props) => { return GenIcon(search2Line)(props); }; /** * The react component for the `search-eye-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search Eye Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-eye-fill.svg) */ export const SearchEyeFillIcon: IconType = (props) => { return GenIcon(searchEyeFill)(props); }; /** * The react component for the `search-eye-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search Eye Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-eye-line.svg) */ export const SearchEyeLineIcon: IconType = (props) => { return GenIcon(searchEyeLine)(props); }; /** * The react component for the `search-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-fill.svg) */ export const SearchFillIcon: IconType = (props) => { return GenIcon(searchFill)(props); }; /** * The react component for the `search-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Search Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/search-line.svg) */ export const SearchLineIcon: IconType = (props) => { return GenIcon(searchLine)(props); }; /** * The react component for the `secure-payment-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Secure Payment Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/secure-payment-fill.svg) */ export const SecurePaymentFillIcon: IconType = (props) => { return GenIcon(securePaymentFill)(props); }; /** * The react component for the `secure-payment-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Secure Payment Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/secure-payment-line.svg) */ export const SecurePaymentLineIcon: IconType = (props) => { return GenIcon(securePaymentLine)(props); }; /** * The react component for the `seedling-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Seedling Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/seedling-fill.svg) */ export const SeedlingFillIcon: IconType = (props) => { return GenIcon(seedlingFill)(props); }; /** * The react component for the `seedling-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Seedling Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/seedling-line.svg) */ export const SeedlingLineIcon: IconType = (props) => { return GenIcon(seedlingLine)(props); }; /** * The react component for the `send-plane-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Send Plane 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/send-plane-2-fill.svg) */ export const SendPlane2FillIcon: IconType = (props) => { return GenIcon(sendPlane2Fill)(props); }; /** * The react component for the `send-plane-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Send Plane 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/send-plane-2-line.svg) */ export const SendPlane2LineIcon: IconType = (props) => { return GenIcon(sendPlane2Line)(props); }; /** * The react component for the `send-plane-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Send Plane Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/send-plane-fill.svg) */ export const SendPlaneFillIcon: IconType = (props) => { return GenIcon(sendPlaneFill)(props); }; /** * The react component for the `send-plane-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Send Plane Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/send-plane-line.svg) */ export const SendPlaneLineIcon: IconType = (props) => { return GenIcon(sendPlaneLine)(props); }; /** * The react component for the `sensor-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sensor Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sensor-fill.svg) */ export const SensorFillIcon: IconType = (props) => { return GenIcon(sensorFill)(props); }; /** * The react component for the `sensor-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sensor Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sensor-line.svg) */ export const SensorLineIcon: IconType = (props) => { return GenIcon(sensorLine)(props); }; /** * The react component for the `server-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Server Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/server-fill.svg) */ export const ServerFillIcon: IconType = (props) => { return GenIcon(serverFill)(props); }; /** * The react component for the `server-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Server Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/server-line.svg) */ export const ServerLineIcon: IconType = (props) => { return GenIcon(serverLine)(props); }; /** * The react component for the `service-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Service Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/service-fill.svg) */ export const ServiceFillIcon: IconType = (props) => { return GenIcon(serviceFill)(props); }; /** * The react component for the `service-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Service Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/service-line.svg) */ export const ServiceLineIcon: IconType = (props) => { return GenIcon(serviceLine)(props); }; /** * The react component for the `settings-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-2-fill.svg) */ export const Settings2FillIcon: IconType = (props) => { return GenIcon(settings2Fill)(props); }; /** * The react component for the `settings-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-2-line.svg) */ export const Settings2LineIcon: IconType = (props) => { return GenIcon(settings2Line)(props); }; /** * The react component for the `settings-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-3-fill.svg) */ export const Settings3FillIcon: IconType = (props) => { return GenIcon(settings3Fill)(props); }; /** * The react component for the `settings-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-3-line.svg) */ export const Settings3LineIcon: IconType = (props) => { return GenIcon(settings3Line)(props); }; /** * The react component for the `settings-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-4-fill.svg) */ export const Settings4FillIcon: IconType = (props) => { return GenIcon(settings4Fill)(props); }; /** * The react component for the `settings-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-4-line.svg) */ export const Settings4LineIcon: IconType = (props) => { return GenIcon(settings4Line)(props); }; /** * The react component for the `settings-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-5-fill.svg) */ export const Settings5FillIcon: IconType = (props) => { return GenIcon(settings5Fill)(props); }; /** * The react component for the `settings-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-5-line.svg) */ export const Settings5LineIcon: IconType = (props) => { return GenIcon(settings5Line)(props); }; /** * The react component for the `settings-6-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 6 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-6-fill.svg) */ export const Settings6FillIcon: IconType = (props) => { return GenIcon(settings6Fill)(props); }; /** * The react component for the `settings-6-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings 6 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-6-line.svg) */ export const Settings6LineIcon: IconType = (props) => { return GenIcon(settings6Line)(props); }; /** * The react component for the `settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-fill.svg) */ export const SettingsFillIcon: IconType = (props) => { return GenIcon(settingsFill)(props); }; /** * The react component for the `settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/settings-line.svg) */ export const SettingsLineIcon: IconType = (props) => { return GenIcon(settingsLine)(props); }; /** * The react component for the `shape-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shape 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/shape-2-fill.svg) */ export const Shape2FillIcon: IconType = (props) => { return GenIcon(shape2Fill)(props); }; /** * The react component for the `shape-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shape 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/shape-2-line.svg) */ export const Shape2LineIcon: IconType = (props) => { return GenIcon(shape2Line)(props); }; /** * The react component for the `shape-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shape Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/shape-fill.svg) */ export const ShapeFillIcon: IconType = (props) => { return GenIcon(shapeFill)(props); }; /** * The react component for the `shape-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shape Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/shape-line.svg) */ export const ShapeLineIcon: IconType = (props) => { return GenIcon(shapeLine)(props); }; /** * The react component for the `share-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-box-fill.svg) */ export const ShareBoxFillIcon: IconType = (props) => { return GenIcon(shareBoxFill)(props); }; /** * The react component for the `share-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-box-line.svg) */ export const ShareBoxLineIcon: IconType = (props) => { return GenIcon(shareBoxLine)(props); }; /** * The react component for the `share-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-circle-fill.svg) */ export const ShareCircleFillIcon: IconType = (props) => { return GenIcon(shareCircleFill)(props); }; /** * The react component for the `share-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-circle-line.svg) */ export const ShareCircleLineIcon: IconType = (props) => { return GenIcon(shareCircleLine)(props); }; /** * The react component for the `share-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-fill.svg) */ export const ShareFillIcon: IconType = (props) => { return GenIcon(shareFill)(props); }; /** * The react component for the `share-forward-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-2-fill.svg) */ export const ShareForward2FillIcon: IconType = (props) => { return GenIcon(shareForward2Fill)(props); }; /** * The react component for the `share-forward-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-2-line.svg) */ export const ShareForward2LineIcon: IconType = (props) => { return GenIcon(shareForward2Line)(props); }; /** * The react component for the `share-forward-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-box-fill.svg) */ export const ShareForwardBoxFillIcon: IconType = (props) => { return GenIcon(shareForwardBoxFill)(props); }; /** * The react component for the `share-forward-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-box-line.svg) */ export const ShareForwardBoxLineIcon: IconType = (props) => { return GenIcon(shareForwardBoxLine)(props); }; /** * The react component for the `share-forward-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-fill.svg) */ export const ShareForwardFillIcon: IconType = (props) => { return GenIcon(shareForwardFill)(props); }; /** * The react component for the `share-forward-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Forward Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-forward-line.svg) */ export const ShareForwardLineIcon: IconType = (props) => { return GenIcon(shareForwardLine)(props); }; /** * The react component for the `share-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Share Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/share-line.svg) */ export const ShareLineIcon: IconType = (props) => { return GenIcon(shareLine)(props); }; /** * The react component for the `shield-check-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Check Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-check-fill.svg) */ export const ShieldCheckFillIcon: IconType = (props) => { return GenIcon(shieldCheckFill)(props); }; /** * The react component for the `shield-check-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Check Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-check-line.svg) */ export const ShieldCheckLineIcon: IconType = (props) => { return GenIcon(shieldCheckLine)(props); }; /** * The react component for the `shield-cross-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Cross Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-cross-fill.svg) */ export const ShieldCrossFillIcon: IconType = (props) => { return GenIcon(shieldCrossFill)(props); }; /** * The react component for the `shield-cross-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Cross Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-cross-line.svg) */ export const ShieldCrossLineIcon: IconType = (props) => { return GenIcon(shieldCrossLine)(props); }; /** * The react component for the `shield-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-fill.svg) */ export const ShieldFillIcon: IconType = (props) => { return GenIcon(shieldFill)(props); }; /** * The react component for the `shield-flash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Flash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-flash-fill.svg) */ export const ShieldFlashFillIcon: IconType = (props) => { return GenIcon(shieldFlashFill)(props); }; /** * The react component for the `shield-flash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Flash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-flash-line.svg) */ export const ShieldFlashLineIcon: IconType = (props) => { return GenIcon(shieldFlashLine)(props); }; /** * The react component for the `shield-keyhole-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Keyhole Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-keyhole-fill.svg) */ export const ShieldKeyholeFillIcon: IconType = (props) => { return GenIcon(shieldKeyholeFill)(props); }; /** * The react component for the `shield-keyhole-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Keyhole Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-keyhole-line.svg) */ export const ShieldKeyholeLineIcon: IconType = (props) => { return GenIcon(shieldKeyholeLine)(props); }; /** * The react component for the `shield-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-line.svg) */ export const ShieldLineIcon: IconType = (props) => { return GenIcon(shieldLine)(props); }; /** * The react component for the `shield-star-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Star Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-star-fill.svg) */ export const ShieldStarFillIcon: IconType = (props) => { return GenIcon(shieldStarFill)(props); }; /** * The react component for the `shield-star-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield Star Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-star-line.svg) */ export const ShieldStarLineIcon: IconType = (props) => { return GenIcon(shieldStarLine)(props); }; /** * The react component for the `shield-user-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield User Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-user-fill.svg) */ export const ShieldUserFillIcon: IconType = (props) => { return GenIcon(shieldUserFill)(props); }; /** * The react component for the `shield-user-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shield User Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/shield-user-line.svg) */ export const ShieldUserLineIcon: IconType = (props) => { return GenIcon(shieldUserLine)(props); }; /** * The react component for the `ship-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ship 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/ship-2-fill.svg) */ export const Ship2FillIcon: IconType = (props) => { return GenIcon(ship2Fill)(props); }; /** * The react component for the `ship-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ship 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/ship-2-line.svg) */ export const Ship2LineIcon: IconType = (props) => { return GenIcon(ship2Line)(props); }; /** * The react component for the `ship-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ship Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/ship-fill.svg) */ export const ShipFillIcon: IconType = (props) => { return GenIcon(shipFill)(props); }; /** * The react component for the `ship-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ship Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/ship-line.svg) */ export const ShipLineIcon: IconType = (props) => { return GenIcon(shipLine)(props); }; /** * The react component for the `shirt-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shirt Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/shirt-fill.svg) */ export const ShirtFillIcon: IconType = (props) => { return GenIcon(shirtFill)(props); }; /** * The react component for the `shirt-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shirt Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/shirt-line.svg) */ export const ShirtLineIcon: IconType = (props) => { return GenIcon(shirtLine)(props); }; /** * The react component for the `shopping-bag-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-2-fill.svg) */ export const ShoppingBag2FillIcon: IconType = (props) => { return GenIcon(shoppingBag2Fill)(props); }; /** * The react component for the `shopping-bag-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-2-line.svg) */ export const ShoppingBag2LineIcon: IconType = (props) => { return GenIcon(shoppingBag2Line)(props); }; /** * The react component for the `shopping-bag-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-3-fill.svg) */ export const ShoppingBag3FillIcon: IconType = (props) => { return GenIcon(shoppingBag3Fill)(props); }; /** * The react component for the `shopping-bag-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-3-line.svg) */ export const ShoppingBag3LineIcon: IconType = (props) => { return GenIcon(shoppingBag3Line)(props); }; /** * The react component for the `shopping-bag-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-fill.svg) */ export const ShoppingBagFillIcon: IconType = (props) => { return GenIcon(shoppingBagFill)(props); }; /** * The react component for the `shopping-bag-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Bag Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-bag-line.svg) */ export const ShoppingBagLineIcon: IconType = (props) => { return GenIcon(shoppingBagLine)(props); }; /** * The react component for the `shopping-basket-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Basket 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-basket-2-fill.svg) */ export const ShoppingBasket2FillIcon: IconType = (props) => { return GenIcon(shoppingBasket2Fill)(props); }; /** * The react component for the `shopping-basket-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Basket 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-basket-2-line.svg) */ export const ShoppingBasket2LineIcon: IconType = (props) => { return GenIcon(shoppingBasket2Line)(props); }; /** * The react component for the `shopping-basket-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Basket Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-basket-fill.svg) */ export const ShoppingBasketFillIcon: IconType = (props) => { return GenIcon(shoppingBasketFill)(props); }; /** * The react component for the `shopping-basket-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Basket Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-basket-line.svg) */ export const ShoppingBasketLineIcon: IconType = (props) => { return GenIcon(shoppingBasketLine)(props); }; /** * The react component for the `shopping-cart-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Cart 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-cart-2-fill.svg) */ export const ShoppingCart2FillIcon: IconType = (props) => { return GenIcon(shoppingCart2Fill)(props); }; /** * The react component for the `shopping-cart-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Cart 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-cart-2-line.svg) */ export const ShoppingCart2LineIcon: IconType = (props) => { return GenIcon(shoppingCart2Line)(props); }; /** * The react component for the `shopping-cart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Cart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-cart-fill.svg) */ export const ShoppingCartFillIcon: IconType = (props) => { return GenIcon(shoppingCartFill)(props); }; /** * The react component for the `shopping-cart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shopping Cart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/shopping-cart-line.svg) */ export const ShoppingCartLineIcon: IconType = (props) => { return GenIcon(shoppingCartLine)(props); }; /** * The react component for the `showers-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Showers Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/showers-fill.svg) */ export const ShowersFillIcon: IconType = (props) => { return GenIcon(showersFill)(props); }; /** * The react component for the `showers-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Showers Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/showers-line.svg) */ export const ShowersLineIcon: IconType = (props) => { return GenIcon(showersLine)(props); }; /** * The react component for the `shuffle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shuffle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/shuffle-fill.svg) */ export const ShuffleFillIcon: IconType = (props) => { return GenIcon(shuffleFill)(props); }; /** * The react component for the `shuffle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shuffle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/shuffle-line.svg) */ export const ShuffleLineIcon: IconType = (props) => { return GenIcon(shuffleLine)(props); }; /** * The react component for the `shut-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shut Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/shut-down-fill.svg) */ export const ShutDownFillIcon: IconType = (props) => { return GenIcon(shutDownFill)(props); }; /** * The react component for the `shut-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Shut Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/shut-down-line.svg) */ export const ShutDownLineIcon: IconType = (props) => { return GenIcon(shutDownLine)(props); }; /** * The react component for the `side-bar-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Side Bar Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/side-bar-fill.svg) */ export const SideBarFillIcon: IconType = (props) => { return GenIcon(sideBarFill)(props); }; /** * The react component for the `side-bar-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Side Bar Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/side-bar-line.svg) */ export const SideBarLineIcon: IconType = (props) => { return GenIcon(sideBarLine)(props); }; /** * The react component for the `signal-tower-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Tower Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/signal-tower-fill.svg) */ export const SignalTowerFillIcon: IconType = (props) => { return GenIcon(signalTowerFill)(props); }; /** * The react component for the `signal-tower-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Tower Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/signal-tower-line.svg) */ export const SignalTowerLineIcon: IconType = (props) => { return GenIcon(signalTowerLine)(props); }; /** * The react component for the `signal-wifi-1-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 1 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-1-fill.svg) */ export const SignalWifi1FillIcon: IconType = (props) => { return GenIcon(signalWifi1Fill)(props); }; /** * The react component for the `signal-wifi-1-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 1 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-1-line.svg) */ export const SignalWifi1LineIcon: IconType = (props) => { return GenIcon(signalWifi1Line)(props); }; /** * The react component for the `signal-wifi-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-2-fill.svg) */ export const SignalWifi2FillIcon: IconType = (props) => { return GenIcon(signalWifi2Fill)(props); }; /** * The react component for the `signal-wifi-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-2-line.svg) */ export const SignalWifi2LineIcon: IconType = (props) => { return GenIcon(signalWifi2Line)(props); }; /** * The react component for the `signal-wifi-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-3-fill.svg) */ export const SignalWifi3FillIcon: IconType = (props) => { return GenIcon(signalWifi3Fill)(props); }; /** * The react component for the `signal-wifi-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-3-line.svg) */ export const SignalWifi3LineIcon: IconType = (props) => { return GenIcon(signalWifi3Line)(props); }; /** * The react component for the `signal-wifi-error-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Error Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-error-fill.svg) */ export const SignalWifiErrorFillIcon: IconType = (props) => { return GenIcon(signalWifiErrorFill)(props); }; /** * The react component for the `signal-wifi-error-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Error Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-error-line.svg) */ export const SignalWifiErrorLineIcon: IconType = (props) => { return GenIcon(signalWifiErrorLine)(props); }; /** * The react component for the `signal-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-fill.svg) */ export const SignalWifiFillIcon: IconType = (props) => { return GenIcon(signalWifiFill)(props); }; /** * The react component for the `signal-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-line.svg) */ export const SignalWifiLineIcon: IconType = (props) => { return GenIcon(signalWifiLine)(props); }; /** * The react component for the `signal-wifi-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-off-fill.svg) */ export const SignalWifiOffFillIcon: IconType = (props) => { return GenIcon(signalWifiOffFill)(props); }; /** * The react component for the `signal-wifi-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Signal Wifi Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/signal-wifi-off-line.svg) */ export const SignalWifiOffLineIcon: IconType = (props) => { return GenIcon(signalWifiOffLine)(props); }; /** * The react component for the `sim-card-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sim Card 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sim-card-2-fill.svg) */ export const SimCard2FillIcon: IconType = (props) => { return GenIcon(simCard2Fill)(props); }; /** * The react component for the `sim-card-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sim Card 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sim-card-2-line.svg) */ export const SimCard2LineIcon: IconType = (props) => { return GenIcon(simCard2Line)(props); }; /** * The react component for the `sim-card-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sim Card Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sim-card-fill.svg) */ export const SimCardFillIcon: IconType = (props) => { return GenIcon(simCardFill)(props); }; /** * The react component for the `sim-card-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sim Card Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/sim-card-line.svg) */ export const SimCardLineIcon: IconType = (props) => { return GenIcon(simCardLine)(props); }; /** * The react component for the `sip-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sip Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/sip-fill.svg) */ export const SipFillIcon: IconType = (props) => { return GenIcon(sipFill)(props); }; /** * The react component for the `sip-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sip Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/sip-line.svg) */ export const SipLineIcon: IconType = (props) => { return GenIcon(sipLine)(props); }; /** * The react component for the `skip-back-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Back Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-back-fill.svg) */ export const SkipBackFillIcon: IconType = (props) => { return GenIcon(skipBackFill)(props); }; /** * The react component for the `skip-back-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Back Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-back-line.svg) */ export const SkipBackLineIcon: IconType = (props) => { return GenIcon(skipBackLine)(props); }; /** * The react component for the `skip-back-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Back Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-back-mini-fill.svg) */ export const SkipBackMiniFillIcon: IconType = (props) => { return GenIcon(skipBackMiniFill)(props); }; /** * The react component for the `skip-back-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Back Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-back-mini-line.svg) */ export const SkipBackMiniLineIcon: IconType = (props) => { return GenIcon(skipBackMiniLine)(props); }; /** * The react component for the `skip-forward-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Forward Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-forward-fill.svg) */ export const SkipForwardFillIcon: IconType = (props) => { return GenIcon(skipForwardFill)(props); }; /** * The react component for the `skip-forward-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Forward Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-forward-line.svg) */ export const SkipForwardLineIcon: IconType = (props) => { return GenIcon(skipForwardLine)(props); }; /** * The react component for the `skip-forward-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Forward Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-forward-mini-fill.svg) */ export const SkipForwardMiniFillIcon: IconType = (props) => { return GenIcon(skipForwardMiniFill)(props); }; /** * The react component for the `skip-forward-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skip Forward Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/skip-forward-mini-line.svg) */ export const SkipForwardMiniLineIcon: IconType = (props) => { return GenIcon(skipForwardMiniLine)(props); }; /** * The react component for the `skull-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skull 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/skull-2-fill.svg) */ export const Skull2FillIcon: IconType = (props) => { return GenIcon(skull2Fill)(props); }; /** * The react component for the `skull-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skull 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/skull-2-line.svg) */ export const Skull2LineIcon: IconType = (props) => { return GenIcon(skull2Line)(props); }; /** * The react component for the `skull-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skull Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/skull-fill.svg) */ export const SkullFillIcon: IconType = (props) => { return GenIcon(skullFill)(props); }; /** * The react component for the `skull-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skull Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/skull-line.svg) */ export const SkullLineIcon: IconType = (props) => { return GenIcon(skullLine)(props); }; /** * The react component for the `skype-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skype Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/skype-fill.svg) */ export const SkypeFillIcon: IconType = (props) => { return GenIcon(skypeFill)(props); }; /** * The react component for the `skype-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Skype Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/skype-line.svg) */ export const SkypeLineIcon: IconType = (props) => { return GenIcon(skypeLine)(props); }; /** * The react component for the `slack-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slack Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/slack-fill.svg) */ export const SlackFillIcon: IconType = (props) => { return GenIcon(slackFill)(props); }; /** * The react component for the `slack-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slack Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/slack-line.svg) */ export const SlackLineIcon: IconType = (props) => { return GenIcon(slackLine)(props); }; /** * The react component for the `slice-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slice Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/slice-fill.svg) */ export const SliceFillIcon: IconType = (props) => { return GenIcon(sliceFill)(props); }; /** * The react component for the `slice-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slice Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/slice-line.svg) */ export const SliceLineIcon: IconType = (props) => { return GenIcon(sliceLine)(props); }; /** * The react component for the `slideshow-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-2-fill.svg) */ export const Slideshow2FillIcon: IconType = (props) => { return GenIcon(slideshow2Fill)(props); }; /** * The react component for the `slideshow-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-2-line.svg) */ export const Slideshow2LineIcon: IconType = (props) => { return GenIcon(slideshow2Line)(props); }; /** * The react component for the `slideshow-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-3-fill.svg) */ export const Slideshow3FillIcon: IconType = (props) => { return GenIcon(slideshow3Fill)(props); }; /** * The react component for the `slideshow-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-3-line.svg) */ export const Slideshow3LineIcon: IconType = (props) => { return GenIcon(slideshow3Line)(props); }; /** * The react component for the `slideshow-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-4-fill.svg) */ export const Slideshow4FillIcon: IconType = (props) => { return GenIcon(slideshow4Fill)(props); }; /** * The react component for the `slideshow-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-4-line.svg) */ export const Slideshow4LineIcon: IconType = (props) => { return GenIcon(slideshow4Line)(props); }; /** * The react component for the `slideshow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-fill.svg) */ export const SlideshowFillIcon: IconType = (props) => { return GenIcon(slideshowFill)(props); }; /** * The react component for the `slideshow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Slideshow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/slideshow-line.svg) */ export const SlideshowLineIcon: IconType = (props) => { return GenIcon(slideshowLine)(props); }; /** * The react component for the `smartphone-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Smartphone Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/smartphone-fill.svg) */ export const SmartphoneFillIcon: IconType = (props) => { return GenIcon(smartphoneFill)(props); }; /** * The react component for the `smartphone-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Smartphone Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/smartphone-line.svg) */ export const SmartphoneLineIcon: IconType = (props) => { return GenIcon(smartphoneLine)(props); }; /** * The react component for the `snapchat-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Snapchat Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/snapchat-fill.svg) */ export const SnapchatFillIcon: IconType = (props) => { return GenIcon(snapchatFill)(props); }; /** * The react component for the `snapchat-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Snapchat Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/snapchat-line.svg) */ export const SnapchatLineIcon: IconType = (props) => { return GenIcon(snapchatLine)(props); }; /** * The react component for the `snowy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Snowy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/snowy-fill.svg) */ export const SnowyFillIcon: IconType = (props) => { return GenIcon(snowyFill)(props); }; /** * The react component for the `snowy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Snowy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/snowy-line.svg) */ export const SnowyLineIcon: IconType = (props) => { return GenIcon(snowyLine)(props); }; /** * The react component for the `sound-module-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sound Module Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/sound-module-fill.svg) */ export const SoundModuleFillIcon: IconType = (props) => { return GenIcon(soundModuleFill)(props); }; /** * The react component for the `sound-module-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sound Module Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/sound-module-line.svg) */ export const SoundModuleLineIcon: IconType = (props) => { return GenIcon(soundModuleLine)(props); }; /** * The react component for the `soundcloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Soundcloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/soundcloud-fill.svg) */ export const SoundcloudFillIcon: IconType = (props) => { return GenIcon(soundcloudFill)(props); }; /** * The react component for the `soundcloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Soundcloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/soundcloud-line.svg) */ export const SoundcloudLineIcon: IconType = (props) => { return GenIcon(soundcloudLine)(props); }; /** * The react component for the `space-ship-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Space Ship Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/space-ship-fill.svg) */ export const SpaceShipFillIcon: IconType = (props) => { return GenIcon(spaceShipFill)(props); }; /** * The react component for the `space-ship-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Space Ship Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/space-ship-line.svg) */ export const SpaceShipLineIcon: IconType = (props) => { return GenIcon(spaceShipLine)(props); }; /** * The react component for the `spam-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spam 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/spam-2-fill.svg) */ export const Spam2FillIcon: IconType = (props) => { return GenIcon(spam2Fill)(props); }; /** * The react component for the `spam-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spam 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/spam-2-line.svg) */ export const Spam2LineIcon: IconType = (props) => { return GenIcon(spam2Line)(props); }; /** * The react component for the `spam-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spam 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/spam-3-fill.svg) */ export const Spam3FillIcon: IconType = (props) => { return GenIcon(spam3Fill)(props); }; /** * The react component for the `spam-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spam 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/spam-3-line.svg) */ export const Spam3LineIcon: IconType = (props) => { return GenIcon(spam3Line)(props); }; /** * The react component for the `spam-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spam Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/spam-fill.svg) */ export const SpamFillIcon: IconType = (props) => { return GenIcon(spamFill)(props); }; /** * The react component for the `speaker-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-2-fill.svg) */ export const Speaker2FillIcon: IconType = (props) => { return GenIcon(speaker2Fill)(props); }; /** * The react component for the `speaker-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-2-line.svg) */ export const Speaker2LineIcon: IconType = (props) => { return GenIcon(speaker2Line)(props); }; /** * The react component for the `speaker-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-3-fill.svg) */ export const Speaker3FillIcon: IconType = (props) => { return GenIcon(speaker3Fill)(props); }; /** * The react component for the `speaker-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-3-line.svg) */ export const Speaker3LineIcon: IconType = (props) => { return GenIcon(speaker3Line)(props); }; /** * The react component for the `speaker-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-fill.svg) */ export const SpeakerFillIcon: IconType = (props) => { return GenIcon(speakerFill)(props); }; /** * The react component for the `speaker-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speaker Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speaker-line.svg) */ export const SpeakerLineIcon: IconType = (props) => { return GenIcon(speakerLine)(props); }; /** * The react component for the `spectrum-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spectrum Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/spectrum-fill.svg) */ export const SpectrumFillIcon: IconType = (props) => { return GenIcon(spectrumFill)(props); }; /** * The react component for the `spectrum-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spectrum Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/spectrum-line.svg) */ export const SpectrumLineIcon: IconType = (props) => { return GenIcon(spectrumLine)(props); }; /** * The react component for the `speed-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speed Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speed-fill.svg) */ export const SpeedFillIcon: IconType = (props) => { return GenIcon(speedFill)(props); }; /** * The react component for the `speed-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speed Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speed-line.svg) */ export const SpeedLineIcon: IconType = (props) => { return GenIcon(speedLine)(props); }; /** * The react component for the `speed-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speed Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speed-mini-fill.svg) */ export const SpeedMiniFillIcon: IconType = (props) => { return GenIcon(speedMiniFill)(props); }; /** * The react component for the `speed-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Speed Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/speed-mini-line.svg) */ export const SpeedMiniLineIcon: IconType = (props) => { return GenIcon(speedMiniLine)(props); }; /** * The react component for the `spotify-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spotify Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/spotify-fill.svg) */ export const SpotifyFillIcon: IconType = (props) => { return GenIcon(spotifyFill)(props); }; /** * The react component for the `spotify-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spotify Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/spotify-line.svg) */ export const SpotifyLineIcon: IconType = (props) => { return GenIcon(spotifyLine)(props); }; /** * The react component for the `spy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/spy-fill.svg) */ export const SpyFillIcon: IconType = (props) => { return GenIcon(spyFill)(props); }; /** * The react component for the `spy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Spy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/spy-line.svg) */ export const SpyLineIcon: IconType = (props) => { return GenIcon(spyLine)(props); }; /** * The react component for the `stack-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stack Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/stack-fill.svg) */ export const StackFillIcon: IconType = (props) => { return GenIcon(stackFill)(props); }; /** * The react component for the `stack-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stack Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/stack-line.svg) */ export const StackLineIcon: IconType = (props) => { return GenIcon(stackLine)(props); }; /** * The react component for the `stack-overflow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stack Overflow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/stack-overflow-fill.svg) */ export const StackOverflowFillIcon: IconType = (props) => { return GenIcon(stackOverflowFill)(props); }; /** * The react component for the `stack-overflow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stack Overflow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/stack-overflow-line.svg) */ export const StackOverflowLineIcon: IconType = (props) => { return GenIcon(stackOverflowLine)(props); }; /** * The react component for the `stackshare-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stackshare Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/stackshare-fill.svg) */ export const StackshareFillIcon: IconType = (props) => { return GenIcon(stackshareFill)(props); }; /** * The react component for the `stackshare-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stackshare Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/stackshare-line.svg) */ export const StackshareLineIcon: IconType = (props) => { return GenIcon(stackshareLine)(props); }; /** * The react component for the `star-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-fill.svg) */ export const StarFillIcon: IconType = (props) => { return GenIcon(starFill)(props); }; /** * The react component for the `star-half-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Half Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-half-fill.svg) */ export const StarHalfFillIcon: IconType = (props) => { return GenIcon(starHalfFill)(props); }; /** * The react component for the `star-half-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Half Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-half-line.svg) */ export const StarHalfLineIcon: IconType = (props) => { return GenIcon(starHalfLine)(props); }; /** * The react component for the `star-half-s-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Half S Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-half-s-fill.svg) */ export const StarHalfSFillIcon: IconType = (props) => { return GenIcon(starHalfSFill)(props); }; /** * The react component for the `star-half-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Half S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-half-s-line.svg) */ export const StarHalfSLineIcon: IconType = (props) => { return GenIcon(starHalfSLine)(props); }; /** * The react component for the `star-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-line.svg) */ export const StarLineIcon: IconType = (props) => { return GenIcon(starLine)(props); }; /** * The react component for the `star-s-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star S Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-s-fill.svg) */ export const StarSFillIcon: IconType = (props) => { return GenIcon(starSFill)(props); }; /** * The react component for the `star-s-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star S Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/star-s-line.svg) */ export const StarSLineIcon: IconType = (props) => { return GenIcon(starSLine)(props); }; /** * The react component for the `star-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/star-smile-fill.svg) */ export const StarSmileFillIcon: IconType = (props) => { return GenIcon(starSmileFill)(props); }; /** * The react component for the `star-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Star Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/star-smile-line.svg) */ export const StarSmileLineIcon: IconType = (props) => { return GenIcon(starSmileLine)(props); }; /** * The react component for the `steam-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steam Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/steam-fill.svg) */ export const SteamFillIcon: IconType = (props) => { return GenIcon(steamFill)(props); }; /** * The react component for the `steam-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steam Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/steam-line.svg) */ export const SteamLineIcon: IconType = (props) => { return GenIcon(steamLine)(props); }; /** * The react component for the `steering-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steering 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/steering-2-fill.svg) */ export const Steering2FillIcon: IconType = (props) => { return GenIcon(steering2Fill)(props); }; /** * The react component for the `steering-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steering 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/steering-2-line.svg) */ export const Steering2LineIcon: IconType = (props) => { return GenIcon(steering2Line)(props); }; /** * The react component for the `steering-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steering Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/steering-fill.svg) */ export const SteeringFillIcon: IconType = (props) => { return GenIcon(steeringFill)(props); }; /** * The react component for the `steering-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Steering Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/steering-line.svg) */ export const SteeringLineIcon: IconType = (props) => { return GenIcon(steeringLine)(props); }; /** * The react component for the `stethoscope-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stethoscope Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/stethoscope-fill.svg) */ export const StethoscopeFillIcon: IconType = (props) => { return GenIcon(stethoscopeFill)(props); }; /** * The react component for the `stethoscope-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stethoscope Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/stethoscope-line.svg) */ export const StethoscopeLineIcon: IconType = (props) => { return GenIcon(stethoscopeLine)(props); }; /** * The react component for the `sticky-note-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sticky Note 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/sticky-note-2-fill.svg) */ export const StickyNote2FillIcon: IconType = (props) => { return GenIcon(stickyNote2Fill)(props); }; /** * The react component for the `sticky-note-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sticky Note 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/sticky-note-2-line.svg) */ export const StickyNote2LineIcon: IconType = (props) => { return GenIcon(stickyNote2Line)(props); }; /** * The react component for the `sticky-note-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sticky Note Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/sticky-note-fill.svg) */ export const StickyNoteFillIcon: IconType = (props) => { return GenIcon(stickyNoteFill)(props); }; /** * The react component for the `sticky-note-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sticky Note Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/sticky-note-line.svg) */ export const StickyNoteLineIcon: IconType = (props) => { return GenIcon(stickyNoteLine)(props); }; /** * The react component for the `stock-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stock Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/stock-fill.svg) */ export const StockFillIcon: IconType = (props) => { return GenIcon(stockFill)(props); }; /** * The react component for the `stock-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stock Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/stock-line.svg) */ export const StockLineIcon: IconType = (props) => { return GenIcon(stockLine)(props); }; /** * The react component for the `stop-circle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Circle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-circle-fill.svg) */ export const StopCircleFillIcon: IconType = (props) => { return GenIcon(stopCircleFill)(props); }; /** * The react component for the `stop-circle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Circle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-circle-line.svg) */ export const StopCircleLineIcon: IconType = (props) => { return GenIcon(stopCircleLine)(props); }; /** * The react component for the `stop-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-fill.svg) */ export const StopFillIcon: IconType = (props) => { return GenIcon(stopFill)(props); }; /** * The react component for the `stop-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-line.svg) */ export const StopLineIcon: IconType = (props) => { return GenIcon(stopLine)(props); }; /** * The react component for the `stop-mini-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Mini Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-mini-fill.svg) */ export const StopMiniFillIcon: IconType = (props) => { return GenIcon(stopMiniFill)(props); }; /** * The react component for the `stop-mini-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Stop Mini Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/stop-mini-line.svg) */ export const StopMiniLineIcon: IconType = (props) => { return GenIcon(stopMiniLine)(props); }; /** * The react component for the `store-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-2-fill.svg) */ export const Store2FillIcon: IconType = (props) => { return GenIcon(store2Fill)(props); }; /** * The react component for the `store-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-2-line.svg) */ export const Store2LineIcon: IconType = (props) => { return GenIcon(store2Line)(props); }; /** * The react component for the `store-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-3-fill.svg) */ export const Store3FillIcon: IconType = (props) => { return GenIcon(store3Fill)(props); }; /** * The react component for the `store-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-3-line.svg) */ export const Store3LineIcon: IconType = (props) => { return GenIcon(store3Line)(props); }; /** * The react component for the `store-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-fill.svg) */ export const StoreFillIcon: IconType = (props) => { return GenIcon(storeFill)(props); }; /** * The react component for the `store-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Store Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Buildings/store-line.svg) */ export const StoreLineIcon: IconType = (props) => { return GenIcon(storeLine)(props); }; /** * The react component for the `subtract-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Subtract Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/subtract-fill.svg) */ export const SubtractFillIcon: IconType = (props) => { return GenIcon(subtractFill)(props); }; /** * The react component for the `subway-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Subway Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/subway-fill.svg) */ export const SubwayFillIcon: IconType = (props) => { return GenIcon(subwayFill)(props); }; /** * The react component for the `subway-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Subway Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/subway-line.svg) */ export const SubwayLineIcon: IconType = (props) => { return GenIcon(subwayLine)(props); }; /** * The react component for the `subway-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Subway Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/subway-wifi-fill.svg) */ export const SubwayWifiFillIcon: IconType = (props) => { return GenIcon(subwayWifiFill)(props); }; /** * The react component for the `subway-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Subway Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/subway-wifi-line.svg) */ export const SubwayWifiLineIcon: IconType = (props) => { return GenIcon(subwayWifiLine)(props); }; /** * The react component for the `suitcase-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-2-fill.svg) */ export const Suitcase2FillIcon: IconType = (props) => { return GenIcon(suitcase2Fill)(props); }; /** * The react component for the `suitcase-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-2-line.svg) */ export const Suitcase2LineIcon: IconType = (props) => { return GenIcon(suitcase2Line)(props); }; /** * The react component for the `suitcase-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-3-fill.svg) */ export const Suitcase3FillIcon: IconType = (props) => { return GenIcon(suitcase3Fill)(props); }; /** * The react component for the `suitcase-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-3-line.svg) */ export const Suitcase3LineIcon: IconType = (props) => { return GenIcon(suitcase3Line)(props); }; /** * The react component for the `suitcase-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-fill.svg) */ export const SuitcaseFillIcon: IconType = (props) => { return GenIcon(suitcaseFill)(props); }; /** * The react component for the `suitcase-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Suitcase Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/suitcase-line.svg) */ export const SuitcaseLineIcon: IconType = (props) => { return GenIcon(suitcaseLine)(props); }; /** * The react component for the `sun-cloudy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Cloudy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-cloudy-fill.svg) */ export const SunCloudyFillIcon: IconType = (props) => { return GenIcon(sunCloudyFill)(props); }; /** * The react component for the `sun-cloudy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Cloudy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-cloudy-line.svg) */ export const SunCloudyLineIcon: IconType = (props) => { return GenIcon(sunCloudyLine)(props); }; /** * The react component for the `sun-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-fill.svg) */ export const SunFillIcon: IconType = (props) => { return GenIcon(sunFill)(props); }; /** * The react component for the `sun-foggy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Foggy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-foggy-fill.svg) */ export const SunFoggyFillIcon: IconType = (props) => { return GenIcon(sunFoggyFill)(props); }; /** * The react component for the `sun-foggy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Foggy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-foggy-line.svg) */ export const SunFoggyLineIcon: IconType = (props) => { return GenIcon(sunFoggyLine)(props); }; /** * The react component for the `sun-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sun Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/sun-line.svg) */ export const SunLineIcon: IconType = (props) => { return GenIcon(sunLine)(props); }; /** * The react component for the `surgical-mask-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Surgical Mask Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/surgical-mask-fill.svg) */ export const SurgicalMaskFillIcon: IconType = (props) => { return GenIcon(surgicalMaskFill)(props); }; /** * The react component for the `surgical-mask-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Surgical Mask Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/surgical-mask-line.svg) */ export const SurgicalMaskLineIcon: IconType = (props) => { return GenIcon(surgicalMaskLine)(props); }; /** * The react component for the `surround-sound-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Surround Sound Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/surround-sound-fill.svg) */ export const SurroundSoundFillIcon: IconType = (props) => { return GenIcon(surroundSoundFill)(props); }; /** * The react component for the `surround-sound-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Surround Sound Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/surround-sound-line.svg) */ export const SurroundSoundLineIcon: IconType = (props) => { return GenIcon(surroundSoundLine)(props); }; /** * The react component for the `survey-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Survey Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/survey-fill.svg) */ export const SurveyFillIcon: IconType = (props) => { return GenIcon(surveyFill)(props); }; /** * The react component for the `survey-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Survey Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/survey-line.svg) */ export const SurveyLineIcon: IconType = (props) => { return GenIcon(surveyLine)(props); }; /** * The react component for the `swap-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Swap Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/swap-box-fill.svg) */ export const SwapBoxFillIcon: IconType = (props) => { return GenIcon(swapBoxFill)(props); }; /** * The react component for the `swap-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Swap Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/swap-box-line.svg) */ export const SwapBoxLineIcon: IconType = (props) => { return GenIcon(swapBoxLine)(props); }; /** * The react component for the `swap-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Swap Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/swap-fill.svg) */ export const SwapFillIcon: IconType = (props) => { return GenIcon(swapFill)(props); }; /** * The react component for the `swap-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Swap Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/swap-line.svg) */ export const SwapLineIcon: IconType = (props) => { return GenIcon(swapLine)(props); }; /** * The react component for the `switch-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Switch Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/switch-fill.svg) */ export const SwitchFillIcon: IconType = (props) => { return GenIcon(switchFill)(props); }; /** * The react component for the `switch-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Switch Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/switch-line.svg) */ export const SwitchLineIcon: IconType = (props) => { return GenIcon(switchLine)(props); }; /** * The react component for the `sword-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sword Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/sword-fill.svg) */ export const SwordFillIcon: IconType = (props) => { return GenIcon(swordFill)(props); }; /** * The react component for the `sword-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Sword Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/sword-line.svg) */ export const SwordLineIcon: IconType = (props) => { return GenIcon(swordLine)(props); }; /** * The react component for the `syringe-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Syringe Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/syringe-fill.svg) */ export const SyringeFillIcon: IconType = (props) => { return GenIcon(syringeFill)(props); }; /** * The react component for the `syringe-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Syringe Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/syringe-line.svg) */ export const SyringeLineIcon: IconType = (props) => { return GenIcon(syringeLine)(props); }; /** * The react component for the `t-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/t-box-fill.svg) */ export const TBoxFillIcon: IconType = (props) => { return GenIcon(tBoxFill)(props); }; /** * The react component for the `t-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/t-box-line.svg) */ export const TBoxLineIcon: IconType = (props) => { return GenIcon(tBoxLine)(props); }; /** * The react component for the `t-shirt-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-2-fill.svg) */ export const TShirt2FillIcon: IconType = (props) => { return GenIcon(tShirt2Fill)(props); }; /** * The react component for the `t-shirt-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-2-line.svg) */ export const TShirt2LineIcon: IconType = (props) => { return GenIcon(tShirt2Line)(props); }; /** * The react component for the `t-shirt-air-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt Air Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-air-fill.svg) */ export const TShirtAirFillIcon: IconType = (props) => { return GenIcon(tShirtAirFill)(props); }; /** * The react component for the `t-shirt-air-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt Air Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-air-line.svg) */ export const TShirtAirLineIcon: IconType = (props) => { return GenIcon(tShirtAirLine)(props); }; /** * The react component for the `t-shirt-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-fill.svg) */ export const TShirtFillIcon: IconType = (props) => { return GenIcon(tShirtFill)(props); }; /** * The react component for the `t-shirt-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![T Shirt Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/t-shirt-line.svg) */ export const TShirtLineIcon: IconType = (props) => { return GenIcon(tShirtLine)(props); }; /** * The react component for the `table-alt-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Table Alt Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/table-alt-fill.svg) */ export const TableAltFillIcon: IconType = (props) => { return GenIcon(tableAltFill)(props); }; /** * The react component for the `table-alt-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Table Alt Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/table-alt-line.svg) */ export const TableAltLineIcon: IconType = (props) => { return GenIcon(tableAltLine)(props); }; /** * The react component for the `table-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Table Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/table-fill.svg) */ export const TableFillIcon: IconType = (props) => { return GenIcon(tableFill)(props); }; /** * The react component for the `tablet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tablet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tablet-fill.svg) */ export const TabletFillIcon: IconType = (props) => { return GenIcon(tabletFill)(props); }; /** * The react component for the `tablet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tablet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tablet-line.svg) */ export const TabletLineIcon: IconType = (props) => { return GenIcon(tabletLine)(props); }; /** * The react component for the `takeaway-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Takeaway Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/takeaway-fill.svg) */ export const TakeawayFillIcon: IconType = (props) => { return GenIcon(takeawayFill)(props); }; /** * The react component for the `takeaway-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Takeaway Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/takeaway-line.svg) */ export const TakeawayLineIcon: IconType = (props) => { return GenIcon(takeawayLine)(props); }; /** * The react component for the `taobao-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taobao Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/taobao-fill.svg) */ export const TaobaoFillIcon: IconType = (props) => { return GenIcon(taobaoFill)(props); }; /** * The react component for the `taobao-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taobao Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/taobao-line.svg) */ export const TaobaoLineIcon: IconType = (props) => { return GenIcon(taobaoLine)(props); }; /** * The react component for the `tape-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tape Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/tape-fill.svg) */ export const TapeFillIcon: IconType = (props) => { return GenIcon(tapeFill)(props); }; /** * The react component for the `tape-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tape Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/tape-line.svg) */ export const TapeLineIcon: IconType = (props) => { return GenIcon(tapeLine)(props); }; /** * The react component for the `task-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Task Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/task-fill.svg) */ export const TaskFillIcon: IconType = (props) => { return GenIcon(taskFill)(props); }; /** * The react component for the `task-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Task Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/task-line.svg) */ export const TaskLineIcon: IconType = (props) => { return GenIcon(taskLine)(props); }; /** * The react component for the `taxi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taxi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/taxi-fill.svg) */ export const TaxiFillIcon: IconType = (props) => { return GenIcon(taxiFill)(props); }; /** * The react component for the `taxi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taxi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/taxi-line.svg) */ export const TaxiLineIcon: IconType = (props) => { return GenIcon(taxiLine)(props); }; /** * The react component for the `taxi-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taxi Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/taxi-wifi-fill.svg) */ export const TaxiWifiFillIcon: IconType = (props) => { return GenIcon(taxiWifiFill)(props); }; /** * The react component for the `taxi-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Taxi Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/taxi-wifi-line.svg) */ export const TaxiWifiLineIcon: IconType = (props) => { return GenIcon(taxiWifiLine)(props); }; /** * The react component for the `team-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Team Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/team-fill.svg) */ export const TeamFillIcon: IconType = (props) => { return GenIcon(teamFill)(props); }; /** * The react component for the `team-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Team Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/team-line.svg) */ export const TeamLineIcon: IconType = (props) => { return GenIcon(teamLine)(props); }; /** * The react component for the `telegram-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Telegram Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/telegram-fill.svg) */ export const TelegramFillIcon: IconType = (props) => { return GenIcon(telegramFill)(props); }; /** * The react component for the `telegram-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Telegram Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/telegram-line.svg) */ export const TelegramLineIcon: IconType = (props) => { return GenIcon(telegramLine)(props); }; /** * The react component for the `temp-cold-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Temp Cold Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/temp-cold-fill.svg) */ export const TempColdFillIcon: IconType = (props) => { return GenIcon(tempColdFill)(props); }; /** * The react component for the `temp-cold-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Temp Cold Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/temp-cold-line.svg) */ export const TempColdLineIcon: IconType = (props) => { return GenIcon(tempColdLine)(props); }; /** * The react component for the `temp-hot-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Temp Hot Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/temp-hot-fill.svg) */ export const TempHotFillIcon: IconType = (props) => { return GenIcon(tempHotFill)(props); }; /** * The react component for the `temp-hot-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Temp Hot Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/temp-hot-line.svg) */ export const TempHotLineIcon: IconType = (props) => { return GenIcon(tempHotLine)(props); }; /** * The react component for the `terminal-box-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Box Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-box-fill.svg) */ export const TerminalBoxFillIcon: IconType = (props) => { return GenIcon(terminalBoxFill)(props); }; /** * The react component for the `terminal-box-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Box Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-box-line.svg) */ export const TerminalBoxLineIcon: IconType = (props) => { return GenIcon(terminalBoxLine)(props); }; /** * The react component for the `terminal-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-fill.svg) */ export const TerminalFillIcon: IconType = (props) => { return GenIcon(terminalFill)(props); }; /** * The react component for the `terminal-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-line.svg) */ export const TerminalLineIcon: IconType = (props) => { return GenIcon(terminalLine)(props); }; /** * The react component for the `terminal-window-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Window Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-window-fill.svg) */ export const TerminalWindowFillIcon: IconType = (props) => { return GenIcon(terminalWindowFill)(props); }; /** * The react component for the `terminal-window-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Terminal Window Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Development/terminal-window-line.svg) */ export const TerminalWindowLineIcon: IconType = (props) => { return GenIcon(terminalWindowLine)(props); }; /** * The react component for the `test-tube-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Test Tube Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/test-tube-fill.svg) */ export const TestTubeFillIcon: IconType = (props) => { return GenIcon(testTubeFill)(props); }; /** * The react component for the `test-tube-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Test Tube Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/test-tube-line.svg) */ export const TestTubeLineIcon: IconType = (props) => { return GenIcon(testTubeLine)(props); }; /** * The react component for the `thermometer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thermometer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/thermometer-fill.svg) */ export const ThermometerFillIcon: IconType = (props) => { return GenIcon(thermometerFill)(props); }; /** * The react component for the `thermometer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thermometer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/thermometer-line.svg) */ export const ThermometerLineIcon: IconType = (props) => { return GenIcon(thermometerLine)(props); }; /** * The react component for the `thumb-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thumb Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/thumb-down-fill.svg) */ export const ThumbDownFillIcon: IconType = (props) => { return GenIcon(thumbDownFill)(props); }; /** * The react component for the `thumb-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thumb Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/thumb-down-line.svg) */ export const ThumbDownLineIcon: IconType = (props) => { return GenIcon(thumbDownLine)(props); }; /** * The react component for the `thumb-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thumb Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/thumb-up-fill.svg) */ export const ThumbUpFillIcon: IconType = (props) => { return GenIcon(thumbUpFill)(props); }; /** * The react component for the `thumb-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thumb Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/thumb-up-line.svg) */ export const ThumbUpLineIcon: IconType = (props) => { return GenIcon(thumbUpLine)(props); }; /** * The react component for the `thunderstorms-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thunderstorms Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/thunderstorms-fill.svg) */ export const ThunderstormsFillIcon: IconType = (props) => { return GenIcon(thunderstormsFill)(props); }; /** * The react component for the `thunderstorms-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Thunderstorms Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/thunderstorms-line.svg) */ export const ThunderstormsLineIcon: IconType = (props) => { return GenIcon(thunderstormsLine)(props); }; /** * The react component for the `ticket-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ticket 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/ticket-2-fill.svg) */ export const Ticket2FillIcon: IconType = (props) => { return GenIcon(ticket2Fill)(props); }; /** * The react component for the `ticket-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ticket 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/ticket-2-line.svg) */ export const Ticket2LineIcon: IconType = (props) => { return GenIcon(ticket2Line)(props); }; /** * The react component for the `ticket-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ticket Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/ticket-fill.svg) */ export const TicketFillIcon: IconType = (props) => { return GenIcon(ticketFill)(props); }; /** * The react component for the `ticket-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ticket Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/ticket-line.svg) */ export const TicketLineIcon: IconType = (props) => { return GenIcon(ticketLine)(props); }; /** * The react component for the `time-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Time Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/time-fill.svg) */ export const TimeFillIcon: IconType = (props) => { return GenIcon(timeFill)(props); }; /** * The react component for the `time-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Time Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/time-line.svg) */ export const TimeLineIcon: IconType = (props) => { return GenIcon(timeLine)(props); }; /** * The react component for the `timer-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-2-fill.svg) */ export const Timer2FillIcon: IconType = (props) => { return GenIcon(timer2Fill)(props); }; /** * The react component for the `timer-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-2-line.svg) */ export const Timer2LineIcon: IconType = (props) => { return GenIcon(timer2Line)(props); }; /** * The react component for the `timer-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-fill.svg) */ export const TimerFillIcon: IconType = (props) => { return GenIcon(timerFill)(props); }; /** * The react component for the `timer-flash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer Flash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-flash-fill.svg) */ export const TimerFlashFillIcon: IconType = (props) => { return GenIcon(timerFlashFill)(props); }; /** * The react component for the `timer-flash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer Flash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-flash-line.svg) */ export const TimerFlashLineIcon: IconType = (props) => { return GenIcon(timerFlashLine)(props); }; /** * The react component for the `timer-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Timer Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/timer-line.svg) */ export const TimerLineIcon: IconType = (props) => { return GenIcon(timerLine)(props); }; /** * The react component for the `todo-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Todo Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/todo-fill.svg) */ export const TodoFillIcon: IconType = (props) => { return GenIcon(todoFill)(props); }; /** * The react component for the `todo-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Todo Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Document/todo-line.svg) */ export const TodoLineIcon: IconType = (props) => { return GenIcon(todoLine)(props); }; /** * The react component for the `toggle-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Toggle Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/toggle-fill.svg) */ export const ToggleFillIcon: IconType = (props) => { return GenIcon(toggleFill)(props); }; /** * The react component for the `toggle-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Toggle Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/toggle-line.svg) */ export const ToggleLineIcon: IconType = (props) => { return GenIcon(toggleLine)(props); }; /** * The react component for the `tools-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tools Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/tools-fill.svg) */ export const ToolsFillIcon: IconType = (props) => { return GenIcon(toolsFill)(props); }; /** * The react component for the `tools-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tools Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Design/tools-line.svg) */ export const ToolsLineIcon: IconType = (props) => { return GenIcon(toolsLine)(props); }; /** * The react component for the `tornado-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tornado Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/tornado-fill.svg) */ export const TornadoFillIcon: IconType = (props) => { return GenIcon(tornadoFill)(props); }; /** * The react component for the `tornado-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tornado Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/tornado-line.svg) */ export const TornadoLineIcon: IconType = (props) => { return GenIcon(tornadoLine)(props); }; /** * The react component for the `trademark-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trademark Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/trademark-fill.svg) */ export const TrademarkFillIcon: IconType = (props) => { return GenIcon(trademarkFill)(props); }; /** * The react component for the `trademark-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trademark Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/trademark-line.svg) */ export const TrademarkLineIcon: IconType = (props) => { return GenIcon(trademarkLine)(props); }; /** * The react component for the `traffic-light-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Traffic Light Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/traffic-light-fill.svg) */ export const TrafficLightFillIcon: IconType = (props) => { return GenIcon(trafficLightFill)(props); }; /** * The react component for the `traffic-light-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Traffic Light Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/traffic-light-line.svg) */ export const TrafficLightLineIcon: IconType = (props) => { return GenIcon(trafficLightLine)(props); }; /** * The react component for the `train-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Train Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/train-fill.svg) */ export const TrainFillIcon: IconType = (props) => { return GenIcon(trainFill)(props); }; /** * The react component for the `train-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Train Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/train-line.svg) */ export const TrainLineIcon: IconType = (props) => { return GenIcon(trainLine)(props); }; /** * The react component for the `train-wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Train Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/train-wifi-fill.svg) */ export const TrainWifiFillIcon: IconType = (props) => { return GenIcon(trainWifiFill)(props); }; /** * The react component for the `train-wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Train Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/train-wifi-line.svg) */ export const TrainWifiLineIcon: IconType = (props) => { return GenIcon(trainWifiLine)(props); }; /** * The react component for the `travesti-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Travesti Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/travesti-fill.svg) */ export const TravestiFillIcon: IconType = (props) => { return GenIcon(travestiFill)(props); }; /** * The react component for the `travesti-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Travesti Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/travesti-line.svg) */ export const TravestiLineIcon: IconType = (props) => { return GenIcon(travestiLine)(props); }; /** * The react component for the `treasure-map-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Treasure Map Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/treasure-map-fill.svg) */ export const TreasureMapFillIcon: IconType = (props) => { return GenIcon(treasureMapFill)(props); }; /** * The react component for the `treasure-map-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Treasure Map Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/treasure-map-line.svg) */ export const TreasureMapLineIcon: IconType = (props) => { return GenIcon(treasureMapLine)(props); }; /** * The react component for the `trello-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trello Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/trello-fill.svg) */ export const TrelloFillIcon: IconType = (props) => { return GenIcon(trelloFill)(props); }; /** * The react component for the `trello-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trello Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/trello-line.svg) */ export const TrelloLineIcon: IconType = (props) => { return GenIcon(trelloLine)(props); }; /** * The react component for the `trophy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trophy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/trophy-fill.svg) */ export const TrophyFillIcon: IconType = (props) => { return GenIcon(trophyFill)(props); }; /** * The react component for the `trophy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Trophy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/trophy-line.svg) */ export const TrophyLineIcon: IconType = (props) => { return GenIcon(trophyLine)(props); }; /** * The react component for the `truck-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Truck Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/truck-fill.svg) */ export const TruckFillIcon: IconType = (props) => { return GenIcon(truckFill)(props); }; /** * The react component for the `truck-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Truck Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/truck-line.svg) */ export const TruckLineIcon: IconType = (props) => { return GenIcon(truckLine)(props); }; /** * The react component for the `tumblr-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tumblr Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/tumblr-fill.svg) */ export const TumblrFillIcon: IconType = (props) => { return GenIcon(tumblrFill)(props); }; /** * The react component for the `tumblr-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tumblr Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/tumblr-line.svg) */ export const TumblrLineIcon: IconType = (props) => { return GenIcon(tumblrLine)(props); }; /** * The react component for the `tv-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tv 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tv-2-fill.svg) */ export const Tv2FillIcon: IconType = (props) => { return GenIcon(tv2Fill)(props); }; /** * The react component for the `tv-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tv 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tv-2-line.svg) */ export const Tv2LineIcon: IconType = (props) => { return GenIcon(tv2Line)(props); }; /** * The react component for the `tv-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tv Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tv-fill.svg) */ export const TvFillIcon: IconType = (props) => { return GenIcon(tvFill)(props); }; /** * The react component for the `tv-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Tv Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/tv-line.svg) */ export const TvLineIcon: IconType = (props) => { return GenIcon(tvLine)(props); }; /** * The react component for the `twitch-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twitch Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/twitch-fill.svg) */ export const TwitchFillIcon: IconType = (props) => { return GenIcon(twitchFill)(props); }; /** * The react component for the `twitch-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twitch Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/twitch-line.svg) */ export const TwitchLineIcon: IconType = (props) => { return GenIcon(twitchLine)(props); }; /** * The react component for the `twitter-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twitter Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/twitter-fill.svg) */ export const TwitterFillIcon: IconType = (props) => { return GenIcon(twitterFill)(props); }; /** * The react component for the `twitter-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Twitter Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/twitter-line.svg) */ export const TwitterLineIcon: IconType = (props) => { return GenIcon(twitterLine)(props); }; /** * The react component for the `typhoon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Typhoon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/typhoon-fill.svg) */ export const TyphoonFillIcon: IconType = (props) => { return GenIcon(typhoonFill)(props); }; /** * The react component for the `typhoon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Typhoon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/typhoon-line.svg) */ export const TyphoonLineIcon: IconType = (props) => { return GenIcon(typhoonLine)(props); }; /** * The react component for the `u-disk-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![U Disk Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/u-disk-fill.svg) */ export const UDiskFillIcon: IconType = (props) => { return GenIcon(uDiskFill)(props); }; /** * The react component for the `u-disk-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![U Disk Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/u-disk-line.svg) */ export const UDiskLineIcon: IconType = (props) => { return GenIcon(uDiskLine)(props); }; /** * The react component for the `ubuntu-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ubuntu Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/ubuntu-fill.svg) */ export const UbuntuFillIcon: IconType = (props) => { return GenIcon(ubuntuFill)(props); }; /** * The react component for the `ubuntu-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Ubuntu Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/ubuntu-line.svg) */ export const UbuntuLineIcon: IconType = (props) => { return GenIcon(ubuntuLine)(props); }; /** * The react component for the `umbrella-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Umbrella Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/umbrella-fill.svg) */ export const UmbrellaFillIcon: IconType = (props) => { return GenIcon(umbrellaFill)(props); }; /** * The react component for the `umbrella-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Umbrella Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/umbrella-line.svg) */ export const UmbrellaLineIcon: IconType = (props) => { return GenIcon(umbrellaLine)(props); }; /** * The react component for the `uninstall-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Uninstall Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/uninstall-fill.svg) */ export const UninstallFillIcon: IconType = (props) => { return GenIcon(uninstallFill)(props); }; /** * The react component for the `uninstall-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Uninstall Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/uninstall-line.svg) */ export const UninstallLineIcon: IconType = (props) => { return GenIcon(uninstallLine)(props); }; /** * The react component for the `unsplash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Unsplash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/unsplash-fill.svg) */ export const UnsplashFillIcon: IconType = (props) => { return GenIcon(unsplashFill)(props); }; /** * The react component for the `unsplash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Unsplash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/unsplash-line.svg) */ export const UnsplashLineIcon: IconType = (props) => { return GenIcon(unsplashLine)(props); }; /** * The react component for the `upload-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-2-line.svg) */ export const Upload2LineIcon: IconType = (props) => { return GenIcon(upload2Line)(props); }; /** * The react component for the `upload-cloud-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Cloud 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-cloud-2-fill.svg) */ export const UploadCloud2FillIcon: IconType = (props) => { return GenIcon(uploadCloud2Fill)(props); }; /** * The react component for the `upload-cloud-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Cloud 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-cloud-2-line.svg) */ export const UploadCloud2LineIcon: IconType = (props) => { return GenIcon(uploadCloud2Line)(props); }; /** * The react component for the `upload-cloud-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Cloud Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-cloud-fill.svg) */ export const UploadCloudFillIcon: IconType = (props) => { return GenIcon(uploadCloudFill)(props); }; /** * The react component for the `upload-cloud-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Cloud Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-cloud-line.svg) */ export const UploadCloudLineIcon: IconType = (props) => { return GenIcon(uploadCloudLine)(props); }; /** * The react component for the `upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-fill.svg) */ export const UploadFillIcon: IconType = (props) => { return GenIcon(uploadFill)(props); }; /** * The react component for the `upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/upload-line.svg) */ export const UploadLineIcon: IconType = (props) => { return GenIcon(uploadLine)(props); }; /** * The react component for the `usb-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Usb Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/usb-fill.svg) */ export const UsbFillIcon: IconType = (props) => { return GenIcon(usbFill)(props); }; /** * The react component for the `usb-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Usb Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/usb-line.svg) */ export const UsbLineIcon: IconType = (props) => { return GenIcon(usbLine)(props); }; /** * The react component for the `user-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-2-fill.svg) */ export const User2FillIcon: IconType = (props) => { return GenIcon(user2Fill)(props); }; /** * The react component for the `user-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-2-line.svg) */ export const User2LineIcon: IconType = (props) => { return GenIcon(user2Line)(props); }; /** * The react component for the `user-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-3-fill.svg) */ export const User3FillIcon: IconType = (props) => { return GenIcon(user3Fill)(props); }; /** * The react component for the `user-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-3-line.svg) */ export const User3LineIcon: IconType = (props) => { return GenIcon(user3Line)(props); }; /** * The react component for the `user-4-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 4 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-4-fill.svg) */ export const User4FillIcon: IconType = (props) => { return GenIcon(user4Fill)(props); }; /** * The react component for the `user-4-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 4 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-4-line.svg) */ export const User4LineIcon: IconType = (props) => { return GenIcon(user4Line)(props); }; /** * The react component for the `user-5-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 5 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-5-fill.svg) */ export const User5FillIcon: IconType = (props) => { return GenIcon(user5Fill)(props); }; /** * The react component for the `user-5-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 5 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-5-line.svg) */ export const User5LineIcon: IconType = (props) => { return GenIcon(user5Line)(props); }; /** * The react component for the `user-6-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 6 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-6-fill.svg) */ export const User6FillIcon: IconType = (props) => { return GenIcon(user6Fill)(props); }; /** * The react component for the `user-6-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User 6 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-6-line.svg) */ export const User6LineIcon: IconType = (props) => { return GenIcon(user6Line)(props); }; /** * The react component for the `user-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-add-fill.svg) */ export const UserAddFillIcon: IconType = (props) => { return GenIcon(userAddFill)(props); }; /** * The react component for the `user-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-add-line.svg) */ export const UserAddLineIcon: IconType = (props) => { return GenIcon(userAddLine)(props); }; /** * The react component for the `user-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-fill.svg) */ export const UserFillIcon: IconType = (props) => { return GenIcon(userFill)(props); }; /** * The react component for the `user-follow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Follow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-follow-fill.svg) */ export const UserFollowFillIcon: IconType = (props) => { return GenIcon(userFollowFill)(props); }; /** * The react component for the `user-follow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Follow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-follow-line.svg) */ export const UserFollowLineIcon: IconType = (props) => { return GenIcon(userFollowLine)(props); }; /** * The react component for the `user-heart-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Heart Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-heart-fill.svg) */ export const UserHeartFillIcon: IconType = (props) => { return GenIcon(userHeartFill)(props); }; /** * The react component for the `user-heart-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Heart Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-heart-line.svg) */ export const UserHeartLineIcon: IconType = (props) => { return GenIcon(userHeartLine)(props); }; /** * The react component for the `user-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-line.svg) */ export const UserLineIcon: IconType = (props) => { return GenIcon(userLine)(props); }; /** * The react component for the `user-location-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Location Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-location-fill.svg) */ export const UserLocationFillIcon: IconType = (props) => { return GenIcon(userLocationFill)(props); }; /** * The react component for the `user-location-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Location Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-location-line.svg) */ export const UserLocationLineIcon: IconType = (props) => { return GenIcon(userLocationLine)(props); }; /** * The react component for the `user-received-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Received 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-received-2-fill.svg) */ export const UserReceived2FillIcon: IconType = (props) => { return GenIcon(userReceived2Fill)(props); }; /** * The react component for the `user-received-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Received 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-received-2-line.svg) */ export const UserReceived2LineIcon: IconType = (props) => { return GenIcon(userReceived2Line)(props); }; /** * The react component for the `user-received-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Received Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-received-fill.svg) */ export const UserReceivedFillIcon: IconType = (props) => { return GenIcon(userReceivedFill)(props); }; /** * The react component for the `user-received-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Received Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-received-line.svg) */ export const UserReceivedLineIcon: IconType = (props) => { return GenIcon(userReceivedLine)(props); }; /** * The react component for the `user-search-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Search Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-search-fill.svg) */ export const UserSearchFillIcon: IconType = (props) => { return GenIcon(userSearchFill)(props); }; /** * The react component for the `user-search-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Search Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-search-line.svg) */ export const UserSearchLineIcon: IconType = (props) => { return GenIcon(userSearchLine)(props); }; /** * The react component for the `user-settings-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Settings Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-settings-fill.svg) */ export const UserSettingsFillIcon: IconType = (props) => { return GenIcon(userSettingsFill)(props); }; /** * The react component for the `user-settings-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Settings Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-settings-line.svg) */ export const UserSettingsLineIcon: IconType = (props) => { return GenIcon(userSettingsLine)(props); }; /** * The react component for the `user-shared-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Shared 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-shared-2-fill.svg) */ export const UserShared2FillIcon: IconType = (props) => { return GenIcon(userShared2Fill)(props); }; /** * The react component for the `user-shared-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Shared 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-shared-2-line.svg) */ export const UserShared2LineIcon: IconType = (props) => { return GenIcon(userShared2Line)(props); }; /** * The react component for the `user-shared-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Shared Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-shared-fill.svg) */ export const UserSharedFillIcon: IconType = (props) => { return GenIcon(userSharedFill)(props); }; /** * The react component for the `user-shared-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Shared Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-shared-line.svg) */ export const UserSharedLineIcon: IconType = (props) => { return GenIcon(userSharedLine)(props); }; /** * The react component for the `user-smile-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Smile Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-smile-fill.svg) */ export const UserSmileFillIcon: IconType = (props) => { return GenIcon(userSmileFill)(props); }; /** * The react component for the `user-smile-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Smile Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-smile-line.svg) */ export const UserSmileLineIcon: IconType = (props) => { return GenIcon(userSmileLine)(props); }; /** * The react component for the `user-star-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Star Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-star-fill.svg) */ export const UserStarFillIcon: IconType = (props) => { return GenIcon(userStarFill)(props); }; /** * The react component for the `user-star-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Star Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-star-line.svg) */ export const UserStarLineIcon: IconType = (props) => { return GenIcon(userStarLine)(props); }; /** * The react component for the `user-unfollow-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Unfollow Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-unfollow-fill.svg) */ export const UserUnfollowFillIcon: IconType = (props) => { return GenIcon(userUnfollowFill)(props); }; /** * The react component for the `user-unfollow-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Unfollow Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-unfollow-line.svg) */ export const UserUnfollowLineIcon: IconType = (props) => { return GenIcon(userUnfollowLine)(props); }; /** * The react component for the `user-voice-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Voice Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-voice-fill.svg) */ export const UserVoiceFillIcon: IconType = (props) => { return GenIcon(userVoiceFill)(props); }; /** * The react component for the `user-voice-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![User Voice Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/user-voice-line.svg) */ export const UserVoiceLineIcon: IconType = (props) => { return GenIcon(userVoiceLine)(props); }; /** * The react component for the `video-add-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Add Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-add-fill.svg) */ export const VideoAddFillIcon: IconType = (props) => { return GenIcon(videoAddFill)(props); }; /** * The react component for the `video-add-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Add Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-add-line.svg) */ export const VideoAddLineIcon: IconType = (props) => { return GenIcon(videoAddLine)(props); }; /** * The react component for the `video-chat-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Chat Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/video-chat-fill.svg) */ export const VideoChatFillIcon: IconType = (props) => { return GenIcon(videoChatFill)(props); }; /** * The react component for the `video-chat-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Chat Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Communication/video-chat-line.svg) */ export const VideoChatLineIcon: IconType = (props) => { return GenIcon(videoChatLine)(props); }; /** * The react component for the `video-download-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Download Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-download-fill.svg) */ export const VideoDownloadFillIcon: IconType = (props) => { return GenIcon(videoDownloadFill)(props); }; /** * The react component for the `video-download-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Download Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-download-line.svg) */ export const VideoDownloadLineIcon: IconType = (props) => { return GenIcon(videoDownloadLine)(props); }; /** * The react component for the `video-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-fill.svg) */ export const VideoFillIcon: IconType = (props) => { return GenIcon(videoFill)(props); }; /** * The react component for the `video-upload-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Upload Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-upload-fill.svg) */ export const VideoUploadFillIcon: IconType = (props) => { return GenIcon(videoUploadFill)(props); }; /** * The react component for the `video-upload-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Video Upload Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/video-upload-line.svg) */ export const VideoUploadLineIcon: IconType = (props) => { return GenIcon(videoUploadLine)(props); }; /** * The react component for the `vidicon-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vidicon 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/vidicon-2-fill.svg) */ export const Vidicon2FillIcon: IconType = (props) => { return GenIcon(vidicon2Fill)(props); }; /** * The react component for the `vidicon-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vidicon 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/vidicon-2-line.svg) */ export const Vidicon2LineIcon: IconType = (props) => { return GenIcon(vidicon2Line)(props); }; /** * The react component for the `vidicon-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vidicon Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/vidicon-fill.svg) */ export const VidiconFillIcon: IconType = (props) => { return GenIcon(vidiconFill)(props); }; /** * The react component for the `vidicon-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vidicon Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/vidicon-line.svg) */ export const VidiconLineIcon: IconType = (props) => { return GenIcon(vidiconLine)(props); }; /** * The react component for the `vimeo-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vimeo Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/vimeo-fill.svg) */ export const VimeoFillIcon: IconType = (props) => { return GenIcon(vimeoFill)(props); }; /** * The react component for the `vimeo-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vimeo Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/vimeo-line.svg) */ export const VimeoLineIcon: IconType = (props) => { return GenIcon(vimeoLine)(props); }; /** * The react component for the `vip-crown-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Crown 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-crown-2-fill.svg) */ export const VipCrown2FillIcon: IconType = (props) => { return GenIcon(vipCrown2Fill)(props); }; /** * The react component for the `vip-crown-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Crown 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-crown-2-line.svg) */ export const VipCrown2LineIcon: IconType = (props) => { return GenIcon(vipCrown2Line)(props); }; /** * The react component for the `vip-crown-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Crown Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-crown-fill.svg) */ export const VipCrownFillIcon: IconType = (props) => { return GenIcon(vipCrownFill)(props); }; /** * The react component for the `vip-crown-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Crown Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-crown-line.svg) */ export const VipCrownLineIcon: IconType = (props) => { return GenIcon(vipCrownLine)(props); }; /** * The react component for the `vip-diamond-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Diamond Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-diamond-fill.svg) */ export const VipDiamondFillIcon: IconType = (props) => { return GenIcon(vipDiamondFill)(props); }; /** * The react component for the `vip-diamond-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Diamond Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-diamond-line.svg) */ export const VipDiamondLineIcon: IconType = (props) => { return GenIcon(vipDiamondLine)(props); }; /** * The react component for the `vip-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-fill.svg) */ export const VipFillIcon: IconType = (props) => { return GenIcon(vipFill)(props); }; /** * The react component for the `vip-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vip Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/vip-line.svg) */ export const VipLineIcon: IconType = (props) => { return GenIcon(vipLine)(props); }; /** * The react component for the `virus-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Virus Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/virus-fill.svg) */ export const VirusFillIcon: IconType = (props) => { return GenIcon(virusFill)(props); }; /** * The react component for the `virus-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Virus Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/virus-line.svg) */ export const VirusLineIcon: IconType = (props) => { return GenIcon(virusLine)(props); }; /** * The react component for the `visa-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Visa Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/visa-fill.svg) */ export const VisaFillIcon: IconType = (props) => { return GenIcon(visaFill)(props); }; /** * The react component for the `visa-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Visa Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/visa-line.svg) */ export const VisaLineIcon: IconType = (props) => { return GenIcon(visaLine)(props); }; /** * The react component for the `voice-recognition-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Voice Recognition Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/voice-recognition-fill.svg) */ export const VoiceRecognitionFillIcon: IconType = (props) => { return GenIcon(voiceRecognitionFill)(props); }; /** * The react component for the `voice-recognition-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Voice Recognition Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/voice-recognition-line.svg) */ export const VoiceRecognitionLineIcon: IconType = (props) => { return GenIcon(voiceRecognitionLine)(props); }; /** * The react component for the `voiceprint-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Voiceprint Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/voiceprint-fill.svg) */ export const VoiceprintFillIcon: IconType = (props) => { return GenIcon(voiceprintFill)(props); }; /** * The react component for the `voiceprint-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Voiceprint Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/voiceprint-line.svg) */ export const VoiceprintLineIcon: IconType = (props) => { return GenIcon(voiceprintLine)(props); }; /** * The react component for the `volume-down-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Down Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-down-fill.svg) */ export const VolumeDownFillIcon: IconType = (props) => { return GenIcon(volumeDownFill)(props); }; /** * The react component for the `volume-down-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Down Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-down-line.svg) */ export const VolumeDownLineIcon: IconType = (props) => { return GenIcon(volumeDownLine)(props); }; /** * The react component for the `volume-mute-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Mute Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-mute-fill.svg) */ export const VolumeMuteFillIcon: IconType = (props) => { return GenIcon(volumeMuteFill)(props); }; /** * The react component for the `volume-mute-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Mute Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-mute-line.svg) */ export const VolumeMuteLineIcon: IconType = (props) => { return GenIcon(volumeMuteLine)(props); }; /** * The react component for the `volume-off-vibrate-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Off Vibrate Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-off-vibrate-fill.svg) */ export const VolumeOffVibrateFillIcon: IconType = (props) => { return GenIcon(volumeOffVibrateFill)(props); }; /** * The react component for the `volume-off-vibrate-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Off Vibrate Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-off-vibrate-line.svg) */ export const VolumeOffVibrateLineIcon: IconType = (props) => { return GenIcon(volumeOffVibrateLine)(props); }; /** * The react component for the `volume-up-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Up Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-up-fill.svg) */ export const VolumeUpFillIcon: IconType = (props) => { return GenIcon(volumeUpFill)(props); }; /** * The react component for the `volume-up-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Up Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-up-line.svg) */ export const VolumeUpLineIcon: IconType = (props) => { return GenIcon(volumeUpLine)(props); }; /** * The react component for the `volume-vibrate-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Vibrate Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-vibrate-fill.svg) */ export const VolumeVibrateFillIcon: IconType = (props) => { return GenIcon(volumeVibrateFill)(props); }; /** * The react component for the `volume-vibrate-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Volume Vibrate Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/volume-vibrate-line.svg) */ export const VolumeVibrateLineIcon: IconType = (props) => { return GenIcon(volumeVibrateLine)(props); }; /** * The react component for the `vuejs-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vuejs Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/vuejs-fill.svg) */ export const VuejsFillIcon: IconType = (props) => { return GenIcon(vuejsFill)(props); }; /** * The react component for the `vuejs-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Vuejs Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/vuejs-line.svg) */ export const VuejsLineIcon: IconType = (props) => { return GenIcon(vuejsLine)(props); }; /** * The react component for the `walk-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Walk Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/walk-fill.svg) */ export const WalkFillIcon: IconType = (props) => { return GenIcon(walkFill)(props); }; /** * The react component for the `walk-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Walk Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Map/walk-line.svg) */ export const WalkLineIcon: IconType = (props) => { return GenIcon(walkLine)(props); }; /** * The react component for the `wallet-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-2-fill.svg) */ export const Wallet2FillIcon: IconType = (props) => { return GenIcon(wallet2Fill)(props); }; /** * The react component for the `wallet-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-2-line.svg) */ export const Wallet2LineIcon: IconType = (props) => { return GenIcon(wallet2Line)(props); }; /** * The react component for the `wallet-3-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet 3 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-3-fill.svg) */ export const Wallet3FillIcon: IconType = (props) => { return GenIcon(wallet3Fill)(props); }; /** * The react component for the `wallet-3-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet 3 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-3-line.svg) */ export const Wallet3LineIcon: IconType = (props) => { return GenIcon(wallet3Line)(props); }; /** * The react component for the `wallet-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-fill.svg) */ export const WalletFillIcon: IconType = (props) => { return GenIcon(walletFill)(props); }; /** * The react component for the `wallet-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wallet Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/wallet-line.svg) */ export const WalletLineIcon: IconType = (props) => { return GenIcon(walletLine)(props); }; /** * The react component for the `water-flash-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Water Flash Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/water-flash-fill.svg) */ export const WaterFlashFillIcon: IconType = (props) => { return GenIcon(waterFlashFill)(props); }; /** * The react component for the `water-flash-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Water Flash Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Finance/water-flash-line.svg) */ export const WaterFlashLineIcon: IconType = (props) => { return GenIcon(waterFlashLine)(props); }; /** * The react component for the `webcam-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Webcam Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/webcam-fill.svg) */ export const WebcamFillIcon: IconType = (props) => { return GenIcon(webcamFill)(props); }; /** * The react component for the `webcam-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Webcam Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Media/webcam-line.svg) */ export const WebcamLineIcon: IconType = (props) => { return GenIcon(webcamLine)(props); }; /** * The react component for the `wechat-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-2-fill.svg) */ export const Wechat2FillIcon: IconType = (props) => { return GenIcon(wechat2Fill)(props); }; /** * The react component for the `wechat-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-2-line.svg) */ export const Wechat2LineIcon: IconType = (props) => { return GenIcon(wechat2Line)(props); }; /** * The react component for the `wechat-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-fill.svg) */ export const WechatFillIcon: IconType = (props) => { return GenIcon(wechatFill)(props); }; /** * The react component for the `wechat-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-line.svg) */ export const WechatLineIcon: IconType = (props) => { return GenIcon(wechatLine)(props); }; /** * The react component for the `wechat-pay-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat Pay Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-pay-fill.svg) */ export const WechatPayFillIcon: IconType = (props) => { return GenIcon(wechatPayFill)(props); }; /** * The react component for the `wechat-pay-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wechat Pay Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/wechat-pay-line.svg) */ export const WechatPayLineIcon: IconType = (props) => { return GenIcon(wechatPayLine)(props); }; /** * The react component for the `weibo-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Weibo Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/weibo-fill.svg) */ export const WeiboFillIcon: IconType = (props) => { return GenIcon(weiboFill)(props); }; /** * The react component for the `weibo-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Weibo Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/weibo-line.svg) */ export const WeiboLineIcon: IconType = (props) => { return GenIcon(weiboLine)(props); }; /** * The react component for the `whatsapp-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Whatsapp Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/whatsapp-fill.svg) */ export const WhatsappFillIcon: IconType = (props) => { return GenIcon(whatsappFill)(props); }; /** * The react component for the `whatsapp-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Whatsapp Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/whatsapp-line.svg) */ export const WhatsappLineIcon: IconType = (props) => { return GenIcon(whatsappLine)(props); }; /** * The react component for the `wheelchair-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wheelchair Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/wheelchair-fill.svg) */ export const WheelchairFillIcon: IconType = (props) => { return GenIcon(wheelchairFill)(props); }; /** * The react component for the `wheelchair-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wheelchair Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Others/wheelchair-line.svg) */ export const WheelchairLineIcon: IconType = (props) => { return GenIcon(wheelchairLine)(props); }; /** * The react component for the `wifi-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wifi Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wifi-fill.svg) */ export const WifiFillIcon: IconType = (props) => { return GenIcon(wifiFill)(props); }; /** * The react component for the `wifi-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wifi Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wifi-line.svg) */ export const WifiLineIcon: IconType = (props) => { return GenIcon(wifiLine)(props); }; /** * The react component for the `wifi-off-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wifi Off Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wifi-off-fill.svg) */ export const WifiOffFillIcon: IconType = (props) => { return GenIcon(wifiOffFill)(props); }; /** * The react component for the `wifi-off-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wifi Off Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wifi-off-line.svg) */ export const WifiOffLineIcon: IconType = (props) => { return GenIcon(wifiOffLine)(props); }; /** * The react component for the `window-2-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Window 2 Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/window-2-fill.svg) */ export const Window2FillIcon: IconType = (props) => { return GenIcon(window2Fill)(props); }; /** * The react component for the `window-2-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Window 2 Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/window-2-line.svg) */ export const Window2LineIcon: IconType = (props) => { return GenIcon(window2Line)(props); }; /** * The react component for the `window-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Window Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/window-fill.svg) */ export const WindowFillIcon: IconType = (props) => { return GenIcon(windowFill)(props); }; /** * The react component for the `window-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Window Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Business/window-line.svg) */ export const WindowLineIcon: IconType = (props) => { return GenIcon(windowLine)(props); }; /** * The react component for the `windows-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Windows Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/windows-fill.svg) */ export const WindowsFillIcon: IconType = (props) => { return GenIcon(windowsFill)(props); }; /** * The react component for the `windows-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Windows Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/windows-line.svg) */ export const WindowsLineIcon: IconType = (props) => { return GenIcon(windowsLine)(props); }; /** * The react component for the `windy-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Windy Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/windy-fill.svg) */ export const WindyFillIcon: IconType = (props) => { return GenIcon(windyFill)(props); }; /** * The react component for the `windy-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Windy Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Weather/windy-line.svg) */ export const WindyLineIcon: IconType = (props) => { return GenIcon(windyLine)(props); }; /** * The react component for the `wireless-charging-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wireless Charging Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wireless-charging-fill.svg) */ export const WirelessChargingFillIcon: IconType = (props) => { return GenIcon(wirelessChargingFill)(props); }; /** * The react component for the `wireless-charging-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Wireless Charging Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Device/wireless-charging-line.svg) */ export const WirelessChargingLineIcon: IconType = (props) => { return GenIcon(wirelessChargingLine)(props); }; /** * The react component for the `women-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Women Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/women-fill.svg) */ export const WomenFillIcon: IconType = (props) => { return GenIcon(womenFill)(props); }; /** * The react component for the `women-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Women Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/User/women-line.svg) */ export const WomenLineIcon: IconType = (props) => { return GenIcon(womenLine)(props); }; /** * The react component for the `xbox-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Xbox Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/xbox-fill.svg) */ export const XboxFillIcon: IconType = (props) => { return GenIcon(xboxFill)(props); }; /** * The react component for the `xbox-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Xbox Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/xbox-line.svg) */ export const XboxLineIcon: IconType = (props) => { return GenIcon(xboxLine)(props); }; /** * The react component for the `xing-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Xing Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/xing-fill.svg) */ export const XingFillIcon: IconType = (props) => { return GenIcon(xingFill)(props); }; /** * The react component for the `xing-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Xing Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/xing-line.svg) */ export const XingLineIcon: IconType = (props) => { return GenIcon(xingLine)(props); }; /** * The react component for the `youtube-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Youtube Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/youtube-fill.svg) */ export const YoutubeFillIcon: IconType = (props) => { return GenIcon(youtubeFill)(props); }; /** * The react component for the `youtube-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Youtube Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/youtube-line.svg) */ export const YoutubeLineIcon: IconType = (props) => { return GenIcon(youtubeLine)(props); }; /** * The react component for the `zcool-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zcool Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/zcool-fill.svg) */ export const ZcoolFillIcon: IconType = (props) => { return GenIcon(zcoolFill)(props); }; /** * The react component for the `zcool-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zcool Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/zcool-line.svg) */ export const ZcoolLineIcon: IconType = (props) => { return GenIcon(zcoolLine)(props); }; /** * The react component for the `zhihu-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zhihu Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/zhihu-fill.svg) */ export const ZhihuFillIcon: IconType = (props) => { return GenIcon(zhihuFill)(props); }; /** * The react component for the `zhihu-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zhihu Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Logos/zhihu-line.svg) */ export const ZhihuLineIcon: IconType = (props) => { return GenIcon(zhihuLine)(props); }; /** * The react component for the `zoom-in-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zoom In Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/zoom-in-fill.svg) */ export const ZoomInFillIcon: IconType = (props) => { return GenIcon(zoomInFill)(props); }; /** * The react component for the `zoom-in-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zoom In Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/zoom-in-line.svg) */ export const ZoomInLineIcon: IconType = (props) => { return GenIcon(zoomInLine)(props); }; /** * The react component for the `zoom-out-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zoom Out Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/zoom-out-fill.svg) */ export const ZoomOutFillIcon: IconType = (props) => { return GenIcon(zoomOutFill)(props); }; /** * The react component for the `zoom-out-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zoom Out Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/System/zoom-out-line.svg) */ export const ZoomOutLineIcon: IconType = (props) => { return GenIcon(zoomOutLine)(props); }; /** * The react component for the `zzz-fill.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zzz Fill Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/zzz-fill.svg) */ export const ZzzFillIcon: IconType = (props) => { return GenIcon(zzzFill)(props); }; /** * The react component for the `zzz-line.svg` icon created by [RemixIcons](https://remixicons.com). * ![Zzz Line Icon](https://cdn.jsdelivr.net/npm/remixicon@2.5.0/icons/Health/zzz-line.svg) */ export const ZzzLineIcon: IconType = (props) => { return GenIcon(zzzLine)(props); }; export * from './core';
the_stack
import { MLASTElement, MLASTHTMLAttr, MLASTPreprocessorSpecificAttr } from '@markuplint/ml-ast'; import { nodeListToDebugMaps } from '@markuplint/parser-utils'; import { parse } from './'; describe('parser', () => { it('empty code', () => { const doc = parse(''); expect(doc.nodeList).toStrictEqual([]); expect(doc.nodeList.length).toBe(0); }); it('text only', () => { const doc = parse('| text'); expect(doc.nodeList[0].nodeName).toBe('#text'); expect(doc.nodeList[0].raw).toBe('text'); expect(doc.nodeList.length).toBe(1); }); it('element', () => { const doc = parse('div'); expect(doc.nodeList[0].nodeName).toBe('div'); expect(doc.nodeList[0].raw).toBe('div'); expect(doc.nodeList.length).toBe(1); }); it('with attribute', () => { const doc = parse('div(data-attr="value")'); expect(doc.nodeList[0].nodeName).toBe('div'); expect(doc.nodeList[0].raw).toBe('div(data-attr="value")'); expect(doc.nodeList.length).toBe(1); expect((doc.nodeList[0] as MLASTElement).attributes.length).toBe(1); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTHTMLAttr).name.raw).toBe('data-attr'); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTHTMLAttr).value.raw).toBe('value'); }); it('with dynamic attribute', () => { const doc = parse( 'div(data-attr= variable + variable2 data-attr2 = variable3 + variable4 data-attr3 data-attr4 = `${variable5}`)', ); expect(doc.nodeList[0].nodeName).toBe('div'); expect(doc.nodeList[0].raw).toBe( 'div(data-attr= variable + variable2 data-attr2 = variable3 + variable4 data-attr3 data-attr4 = `${variable5}`)', ); expect(doc.nodeList.length).toBe(1); expect((doc.nodeList[0] as MLASTElement).attributes.length).toBe(4); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTHTMLAttr).name.raw).toBe('data-attr'); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTHTMLAttr).value.raw).toBe( 'variable + variable2', ); expect(((doc.nodeList[0] as MLASTElement).attributes[1] as MLASTHTMLAttr).name.raw).toBe('data-attr2'); expect(((doc.nodeList[0] as MLASTElement).attributes[1] as MLASTHTMLAttr).value.raw).toBe( 'variable3 + variable4', ); expect(((doc.nodeList[0] as MLASTElement).attributes[2] as MLASTHTMLAttr).name.raw).toBe('data-attr3'); expect(((doc.nodeList[0] as MLASTElement).attributes[2] as MLASTHTMLAttr).value.raw).toBe(''); expect(((doc.nodeList[0] as MLASTElement).attributes[3] as MLASTHTMLAttr).name.raw).toBe('data-attr4'); expect(((doc.nodeList[0] as MLASTElement).attributes[3] as MLASTHTMLAttr).value.raw).toBe('${variable5}'); }); it('ID and Classes', () => { const doc = parse('div#the-id.the-class.the-class2'); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTPreprocessorSpecificAttr).potentialName).toBe( 'id', ); expect(((doc.nodeList[0] as MLASTElement).attributes[0] as MLASTPreprocessorSpecificAttr).potentialValue).toBe( 'the-id', ); expect(((doc.nodeList[0] as MLASTElement).attributes[1] as MLASTPreprocessorSpecificAttr).potentialName).toBe( 'class', ); expect(((doc.nodeList[0] as MLASTElement).attributes[1] as MLASTPreprocessorSpecificAttr).potentialValue).toBe( 'the-class', ); expect(((doc.nodeList[0] as MLASTElement).attributes[2] as MLASTPreprocessorSpecificAttr).potentialName).toBe( 'class', ); expect(((doc.nodeList[0] as MLASTElement).attributes[2] as MLASTPreprocessorSpecificAttr).potentialValue).toBe( 'the-class2', ); }); it('HTML in Pug', () => { const doc = parse( `div <span data-hoge hoge>Text</span> <span data-hoge2 hoge2>Text2</span>`, ); // console.log(doc.nodeList); // const map = nodeListToDebugMaps(doc.nodeList); // console.log(map); expect((doc.nodeList[0] as MLASTElement).nodeName).toBe('div'); expect((doc.nodeList[1] as MLASTElement).nodeName).toBe('span'); expect(((doc.nodeList[1] as MLASTElement).attributes[0] as MLASTHTMLAttr).name.raw).toBe('data-hoge'); expect(((doc.nodeList[1] as MLASTElement).attributes[1] as MLASTHTMLAttr).name.raw).toBe('hoge'); expect(((doc.nodeList[0] as MLASTElement).childNodes![0] as MLASTElement).nodeName).toBe('span'); }); it('standard code', () => { const doc = parse(`doctype html html head meta(charset='UTF-8') meta(name="viewport" content='width=device-width, initial-scale=1.0') meta(http-equiv='X-UA-Compatible' content='ie=edge') title Document body script. const i = 0; // html-comment div | text&amp;div table tr th header td cell table tbody tr th header td cell img(src=path/to) `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList[doc.nodeList.length - 1]); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:13](0,12)#doctype: doctype␣html', '[2:1]>[2:5](13,17)html: html', '[3:2]>[3:6](19,23)head: head', "[4:3]>[4:24](26,47)meta: meta(charset='UTF-8')", '[5:3]>[5:72](50,119)meta: meta(name="viewport"␣content=\'width=device-width,␣initial-scale=1.0\')', "[6:3]>[6:55](122,174)meta: meta(http-equiv='X-UA-Compatible'␣content='ie=edge')", '[7:3]>[7:8](177,182)title: title', '[7:9]>[8:2](183,193)#text: Document⏎→', '[8:2]>[8:6](193,197)body: body', '[9:3]>[9:9](200,206)script: script', '[10:4]>[10:16](211,223)#text: const␣i␣=␣0;', '[11:3]>[11:18](226,241)#comment: //␣html-comment', '[12:3]>[12:6](244,247)div: div', '[13:6]>[14:3](253,268)#text: text&amp;div⏎→→', '[14:3]>[14:8](268,273)table: table', '[15:4]>[15:6](277,279)tr: tr', '[16:4]>[16:6](283,285)th: th', '[16:7]>[16:13](286,292)#text: header', '[17:4]>[17:6](296,298)td: td', '[17:7]>[18:3](299,306)#text: cell⏎→→', '[18:3]>[18:8](306,311)table: table', '[19:4]>[19:9](315,320)tbody: tbody', '[20:4]>[20:6](324,326)tr: tr', '[21:5]>[21:7](331,333)th: th', '[21:8]>[21:14](334,340)#text: header', '[22:5]>[22:7](345,347)td: td', '[22:8]>[23:3](348,355)#text: cell⏎→→', '[23:3]>[23:19](355,371)img: img(src=path/to)', ]); }); it('minimum code', () => { const doc = parse(`html head title Title body h1 Title `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:5](0,4)html: html', '[2:2]>[2:6](6,10)head: head', '[3:3]>[3:8](13,18)title: title', '[3:9]>[4:2](19,26)#text: Title⏎→', '[4:2]>[4:6](26,30)body: body', '[5:3]>[5:5](33,35)h1: h1', '[5:6]>[6:1](36,42)#text: Title⏎', ]); }); it('deep structure code', () => { const doc = parse(`div(data-depth=0) div(data-depth=1) div(data-depth=2) div(data-depth=3) div(data-depth=4) div(data-depth=5) div(data-depth=6) div(data-depth=7) div(data-depth=8) div(data-depth=9) div(data-depth=10) div(data-depth=11) div(data-depth=12) div(data-depth=13) div(data-depth=14) div(data-depth=15) div(data-depth=16) div(data-depth=17) div(data-depth=18) div(data-depth=19) `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:18](0,17)div: div(data-depth=0)', '[2:3]>[2:20](20,37)div: div(data-depth=1)', '[3:4]>[3:21](41,58)div: div(data-depth=2)', '[4:5]>[4:22](63,80)div: div(data-depth=3)', '[5:6]>[5:23](86,103)div: div(data-depth=4)', '[6:7]>[6:24](110,127)div: div(data-depth=5)', '[7:8]>[7:25](135,152)div: div(data-depth=6)', '[8:9]>[8:26](161,178)div: div(data-depth=7)', '[9:10]>[9:27](188,205)div: div(data-depth=8)', '[10:11]>[10:28](216,233)div: div(data-depth=9)', '[11:12]>[11:30](245,263)div: div(data-depth=10)', '[12:13]>[12:31](276,294)div: div(data-depth=11)', '[13:14]>[13:32](308,326)div: div(data-depth=12)', '[14:15]>[14:33](341,359)div: div(data-depth=13)', '[15:16]>[15:34](375,393)div: div(data-depth=14)', '[16:17]>[16:35](410,428)div: div(data-depth=15)', '[17:18]>[17:36](446,464)div: div(data-depth=16)', '[18:19]>[18:37](483,501)div: div(data-depth=17)', '[19:20]>[19:38](521,539)div: div(data-depth=18)', '[20:21]>[20:39](560,578)div: div(data-depth=19)', ]); }); it('code in code', () => { const doc = parse(`ul each i in obj li= i `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:3](0,2)ul: ul', '[2:2]>[2:15](4,17)Each: each␣i␣in␣obj', '[3:3]>[3:5](20,22)li: li', '[3:5]>[3:8](22,25)Code: =␣i', ]); }); it('code in code', () => { const doc = parse(`if bool | 1 else if bool2 | 2 else | 3 `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:8](0,7)Conditional: if␣bool', '[2:4]>[3:1](11,13)#text: 1⏎', '[3:1]>[3:14](13,26)Conditional: else␣if␣bool2', '[4:4]>[5:1](30,32)#text: 2⏎', '[5:1]>[5:5](32,36)Conditional: else', '[6:4]>[7:1](40,42)#text: 3⏎', ]); }); it('HTML in Pug', () => { const doc = parse( `section div <span> <img src="path/to"> </span> `, ); // console.log(doc.nodeList); const map = nodeListToDebugMaps(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:8](0,7)section: section', '[2:2]>[2:5](9,12)div: div', '[3:3]>[3:9](15,21)span: <span>', '[3:9]>[4:4](21,25)#text: ⏎→→→', '[4:4]>[4:25](25,44)img: <img␣src="path/to">', '[4:23]>[5:3](44,47)#text: ⏎→→', '[5:3]>[5:10](47,54)span: </span>', '[5:10]>[6:4](54,58)#text: ⏎→→→', ]); }); it('tag interpolation (Issue #58)', () => { const doc = parse(`p | lorem #[span ipsum]`); const map = nodeListToDebugMaps(doc.nodeList); // console.log(map); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:2](0,1)p: p', '[2:4]>[2:10](5,11)#text: lorem␣', '[2:12]>[2:16](13,17)span: span', '[2:17]>[2:22](18,23)#text: ipsum', ]); }); it('block-in-tag div', () => { const doc = parse(`div. <span>text</span>`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:4](0,3)div: div', '[2:2]>[2:8](6,12)span: <span>', '[2:8]>[2:12](12,16)#text: text', '[2:12]>[2:19](16,23)span: </span>', ]); }); it('block-in-tag div 2', () => { const doc = parse(`.root. <div> text </div>`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:6](0,5)div: .root', '[1:7]>[2:2](6,8)#text: ⏎→', '[2:2]>[2:13](8,13)div: <div>', '[2:7]>[4:2](13,22)#text: ⏎→→text⏎→', '[4:2]>[4:8](22,28)div: </div>', ]); }); it('block-in-tag div 3', () => { const doc = parse(`.root. <div> <img /> </div>`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:6](0,5)div: .root', '[1:7]>[2:2](6,8)#text: ⏎→', '[2:2]>[2:13](8,13)div: <div>', '[2:7]>[3:3](13,16)#text: ⏎→→', '[3:3]>[3:16](16,23)img: <img␣/>', '[3:10]>[4:2](23,25)#text: ⏎→', '[4:2]>[4:8](25,31)div: </div>', ]); }); it('block-in-tag script', () => { const doc = parse(`script. const $span = '<span>text</span>';`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:7](0,6)script: script', "[2:2]>[2:36](9,43)#text: const␣$span␣=␣'<span>text</span>';", ]); }); it('block-in-tag script2', () => { const doc = parse(`div. <script> var a = "<aaaa>"; </script>`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:4](0,3)div: div', '[2:2]>[2:10](6,14)script: <script>', '[2:10]>[2:29](14,33)#text: ␣var␣a␣=␣"<aaaa>";␣', '[2:29]>[2:38](33,42)script: </script>', ]); const code = (doc.nodeList[1] as MLASTElement).childNodes![0]; expect(code.raw).toBe(' var a = "<aaaa>"; '); expect(code.parentNode!.nodeName).toBe('script'); }); it('block-in-tag attr', () => { const doc = parse(`div. <input invalid-attr/> <input invalid-attr/>`); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[1:1]>[1:4](0,3)div: div', '[1:5]>[2:2](4,6)#text: ⏎→', '[2:2]>[2:27](6,27)input: <input␣invalid-attr/>', '[2:23]>[3:2](27,29)#text: ⏎→', '[3:2]>[3:27](29,50)input: <input␣invalid-attr/>', ]); const input1 = doc.nodeList[2] as MLASTElement; const input2 = doc.nodeList[4] as MLASTElement; expect(input1.startOffset).toBe(6); expect(input1.startLine).toBe(2); expect(input1.startCol).toBe(2); expect(input1.attributes[0].startLine).toBe(2); expect(input1.attributes[0].startCol).toBe(8); expect(input2.startOffset).toBe(29); expect(input2.startLine).toBe(3); expect(input2.startCol).toBe(2); expect(input2.attributes[0].startLine).toBe(3); expect(input2.attributes[0].startCol).toBe(8); }); it('block-in-tag attr2', () => { const doc = parse( '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndiv.\n\t<input invalid-attr/>\n\t<input invalid-attr invalid-attr2/>', ); const map = nodeListToDebugMaps(doc.nodeList); expect(doc.parseError).toBeUndefined(); expect(map).toStrictEqual([ '[21:1]>[21:4](20,23)div: div', '[21:5]>[22:2](24,26)#text: ⏎→', '[22:2]>[22:27](26,47)input: <input␣invalid-attr/>', '[22:23]>[23:2](47,49)#text: ⏎→', '[23:2]>[23:41](49,84)input: <input␣invalid-attr␣invalid-attr2/>', ]); const input1 = doc.nodeList[2] as MLASTElement; const input2 = doc.nodeList[4] as MLASTElement; const attr1 = input1.attributes[0] as MLASTHTMLAttr; const attr2 = input2.attributes[0] as MLASTHTMLAttr; const attr3 = input2.attributes[1] as MLASTHTMLAttr; expect(attr1.startLine).toBe(22); expect(attr1.startCol).toBe(8); expect(attr1.name.startLine).toBe(22); expect(attr1.name.startCol).toBe(9); expect(attr2.startLine).toBe(23); expect(attr2.startCol).toBe(8); expect(attr2.name.startLine).toBe(23); expect(attr2.name.startCol).toBe(9); expect(attr3.startLine).toBe(23); expect(attr3.startCol).toBe(21); expect(attr3.name.startLine).toBe(23); expect(attr3.name.startCol).toBe(22); }); // TODO: If there is an HTML tag in siblings // it.only('html', () => { // const doc = parse('div\n<input invalid-attr/>\n<input invalid-attr/>'); // const map = nodeListToDebugMaps(doc.nodeList); // expect(doc.parseError).toBeUndefined(); // expect(map).toStrictEqual(['[1:1]>[1:4](0,3)div: div', '[2:1]>[2:22](4,25)input: <input␣invalid-attr/>']); // const input1 = doc.nodeList[1] as MLASTElement; // const input2 = doc.nodeList[2] as MLASTElement; // const attr1 = input1.attributes[0] as MLASTHTMLAttr; // const attr2 = input2.attributes[0] as MLASTHTMLAttr; // expect(attr1.startLine).toBe(2); // expect(attr1.startCol).toBe(8); // expect(attr1.name.startLine).toBe(2); // expect(attr1.name.startCol).toBe(9); // expect(attr2.startLine).toBe(3); // expect(attr2.startCol).toBe(8); // expect(attr2.name.startLine).toBe(3); // expect(attr2.name.startCol).toBe(9); // }); it('attribute', () => { const doc = parse('div(data-hoge="content")'); const attr = (doc.nodeList[0] as MLASTElement).attributes[0]; if (attr.type !== 'html-attr') { return; } expect(attr.raw).toEqual('data-hoge="content"'); expect(attr.name.raw).toEqual('data-hoge'); expect(attr.equal.raw).toEqual('='); expect(attr.startQuote.raw).toEqual('"'); expect(attr.value.raw).toEqual('content'); expect(attr.endQuote.raw).toEqual('"'); }); it('attribute 2', () => { const doc = parse("div(data-hoge='content')"); const attr = (doc.nodeList[0] as MLASTElement).attributes[0]; if (attr.type !== 'html-attr') { return; } expect(attr.raw).toEqual("data-hoge='content'"); expect(attr.name.raw).toEqual('data-hoge'); expect(attr.equal.raw).toEqual('='); expect(attr.startQuote.raw).toEqual("'"); expect(attr.value.raw).toEqual('content'); expect(attr.endQuote.raw).toEqual("'"); }); it('attribute 3', () => { const doc = parse(`div. <span data-attr="value">`); // console.log(doc.nodeList); const attr = (doc.nodeList[1] as MLASTElement).attributes[0]; if (attr.type !== 'html-attr') { return; } expect(attr.raw).toEqual(' data-attr="value"'); expect(attr.startCol).toEqual(7); expect(attr.name.raw).toEqual('data-attr'); expect(attr.name.startCol).toEqual(8); expect(attr.equal.raw).toEqual('='); expect(attr.equal.startCol).toEqual(17); expect(attr.startQuote.raw).toEqual('"'); expect(attr.startQuote.startCol).toEqual(18); expect(attr.value.raw).toEqual('value'); expect(attr.value.startCol).toEqual(19); expect(attr.endQuote.raw).toEqual('"'); expect(attr.endQuote.startCol).toEqual(24); }); it('add space to below', () => { const doc = parse(` \n \n \nhtml head title Title body h1 Title `); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:4](0,3)#text: ␣␣␣', '[4:1]>[4:5](20,24)html: html', '[5:2]>[5:6](26,30)head: head', '[6:3]>[6:8](33,38)title: title', '[6:9]>[7:2](39,46)#text: Title⏎→', '[7:2]>[7:6](46,50)body: body', '[8:3]>[8:5](53,55)h1: h1', '[8:6]>[9:1](56,62)#text: Title⏎', ]); }); it('with frontmatter', () => { const doc = parse( `--- prop: value --- html head title Title body h1 Title `, 0, 0, 0, true, ); const map = nodeListToDebugMaps(doc.nodeList); // console.log(doc.nodeList); // console.log(map); expect(map).toStrictEqual([ '[1:1]>[1:4](0,3)#text: ␣␣␣', '[4:1]>[4:5](20,24)html: html', '[5:2]>[5:6](26,30)head: head', '[6:3]>[6:8](33,38)title: title', '[6:9]>[7:2](39,46)#text: Title⏎→', '[7:2]>[7:6](46,50)body: body', '[8:3]>[8:5](53,55)h1: h1', '[8:6]>[9:1](56,62)#text: Title⏎', ]); }); });
the_stack
import { Syntax, id, nullLoc } from './javascript'; import { FreeVar, Vars } from './logic'; import { MessageException } from './message'; import { getOptions } from './options'; import { SMTOutput } from './smt'; import { SExpr, matchSExpr, parseSExpr } from './util'; import { stringifyExpression } from './codegen'; export namespace JSVal { export interface Num { type: 'num'; v: number; } export interface Bool { type: 'bool'; v: boolean; } export interface Str { type: 'str'; v: string; } export interface Null { type: 'null'; } export interface Undefined { type: 'undefined'; } export interface Fun { type: 'fun'; body: Syntax.FunctionExpression; } export interface Obj { type: 'obj'; v: { [key: string]: JSVal }; } export interface ObjCls { type: 'obj-cls'; cls: string; args: Array<Value>; } export interface Arr { type: 'arr'; elems: Array<Value>; } export type Value = Num | Bool | Str | Null | Undefined | Fun | Obj | ObjCls | Arr; } export type JSVal = JSVal.Value; interface LazyObjCls { type: 'obj-cls'; cls: string; args: Array<LazyValue>; } interface ArrRef { type: 'arr-ref'; name: string; } interface ObjRef { type: 'obj-ref'; name: string; } interface FunRef { type: 'fun-ref'; name: string; } interface Loc { type: 'loc'; name: string; } type LazyValue = JSVal.Num | JSVal.Bool | JSVal.Str | JSVal.Null | JSVal.Undefined | JSVal.Obj | LazyObjCls | ArrRef | ObjRef | FunRef; type ArrLengths = (arr: ArrRef) => number; type ArrElems = (arr: ArrRef, idx: number) => LazyValue; type ObjProperties = (obj: ObjRef) => string; type ObjFields = (obj: ObjRef, prop: string) => LazyValue; type HeapMapping = (loc: Loc) => LazyValue; interface LazyFun { type: 'fun'; body: Array<{ cond: Array<JSVal>, ret: LazyValue }>; } export function plainToJSVal (val: any): JSVal { if (typeof val === 'number') { return { type: 'num', v: val }; } else if (typeof val === 'boolean') { return { type: 'bool', v: val }; } else if (typeof val === 'string') { return { type: 'str', v: val }; } else if (val === null) { return { type: 'null' }; } else if (val === undefined) { return { type: 'undefined' }; } else if (val instanceof Array) { return { type: 'arr', elems: val.map(plainToJSVal) }; } else if ('_cls_' in val && '_args_' in val) { return { type: 'obj-cls', cls: val._cls_, args: val._args_.map(plainToJSVal) }; } else if (typeof val === 'object') { const obj: { [key: string]: JSVal } = {}; Object.keys(val).forEach(key => obj[key] = plainToJSVal(val[key])); return { type: 'obj', v: obj }; } else { throw new Error('unsupported '); } } export function valueToJavaScript (val: JSVal): Syntax.Expression { switch (val.type) { case 'num': case 'bool': case 'str': return { type: 'Literal', value: val.v, loc: nullLoc() }; case 'null': return { type: 'Literal', value: null, loc: nullLoc() }; case 'undefined': return { type: 'Literal', value: undefined, loc: nullLoc() }; case 'fun': return val.body; case 'obj': return { type: 'ObjectExpression', properties: Object.keys(val.v).map(key => ({ key, value: valueToJavaScript(val.v[key]) })), loc: nullLoc() }; case 'obj-cls': return { type: 'NewExpression', callee: id(val.cls), args: val.args.map(arg => valueToJavaScript(arg)), loc: nullLoc() }; case 'arr': return { type: 'ArrayExpression', elements: val.elems.map(arg => valueToJavaScript(arg)), loc: nullLoc() }; } } export function valueToPlain (val: JSVal): any { switch (val.type) { case 'num': case 'bool': case 'str': return val.v; case 'null': return null; case 'undefined': return undefined; case 'fun': /* tslint:disable:no-eval */ return eval(`(() => ${stringifyExpression(val.body)})()`); case 'obj': const obj: { [key: string]: any } = {}; Object.keys(val.v).forEach(key => obj[key] = valueToPlain(val.v[key])); return obj; case 'obj-cls': // FIXME: use class instance return `new ${val.cls}(${val.args.map(arg => valueToPlain(arg)).join(', ')})`; case 'arr': return val.elems.map(elem => valueToPlain(elem)); } } export function valueToString (val: JSVal): string { switch (val.type) { case 'num': case 'bool': case 'str': return String(val.v); case 'null': return 'null'; case 'undefined': return 'undefined'; case 'fun': const str = stringifyExpression(val.body); return str.substr(1, str.length - 2); // remove outer parens case 'obj': const formatKey = (s: string) => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s) ? s : '"' + s + '"'; return `{ ${Object.keys(val.v).map(key => `${formatKey(key)}:${valueToString(val.v[key])}`).join(', ')} }`; case 'obj-cls': return `new ${val.cls}(${val.args.map(arg => valueToString(arg)).join(', ')})`; case 'arr': return `[${val.elems.map(elem => valueToString(elem)).join(', ')}]`; } } export class Model { private arrLengths: ArrLengths | null = null; private arrElems: ArrElems | null = null; private objProperties: ObjProperties | null = null; private objPropertyMappings: { [varname: string]: Set<string> } = {}; private objFields: ObjFields | null = null; private heapMappings: { [varname: string]: HeapMapping } = {}; private vars: { [varname: string]: LazyValue } = {}; private locs: { [varname: string]: Loc } = {}; private heaps: Array<string> = []; private funs: { [funcref: string]: Array<LazyFun> } = {}; private funDefaults: Array<LazyValue> = []; constructor (smt: SMTOutput) { // assumes smt starts with "sat", so remove "sat" const smt2 = smt.slice(3, smt.length); if (smt2.trim().startsWith('(error')) this.modelError(smt2.trim()); let data: SExpr; try { data = parseSExpr(smt2.trim()); } catch (e) { throw this.modelError(e.message); } if (typeof data === 'string') throw this.modelError(data); if (data.length < 2) throw this.modelError(smt); if (data[0] !== 'model') throw this.modelError(smt); data.slice(1).forEach(s => this.parseDefinition(s)); } public valueOf (name: FreeVar): JSVal { if (typeof name === 'string') { const val = this.vars[name]; if (!val) return { type: 'undefined' }; return this.hydrate(val); } else { const loc = this.locs[name.name]; if (!loc) throw this.modelError(`no such loc ${name.name}`); const heap = this.heapMappings[this.heaps[name.heap]]; if (!heap) throw this.modelError(`no such heap ${name.heap}`); return this.hydrate(heap(loc)); } } public variables (): Vars { return new Set([...Object.keys(this.vars), ...Object.keys(this.locs)]); } public mutableVariables (): Vars { return new Set([...Object.keys(this.locs)]); } private parseDefinition (data: SExpr) { if (typeof data === 'string' || data.length < 1) { throw this.modelError('expected define-fun'); } const m = matchSExpr(data, ['define-fun', { name: 'name' }, { group: 'args' }, { expr: 'return' }, { expr: 'body' }]); if (m === null) return; // skip everything except for define-fun const name: string = m.name as string; if (name.startsWith('v_')) { this.vars[name.substr(2)] = this.parseLazyValue(m.body); } else if (name.startsWith('l_')) { const locVal = m.body; if (typeof locVal !== 'string') throw this.modelError('expected loc'); this.locs[name.substr(2)] = { type: 'loc', name: locVal }; } else if (name.startsWith('h_')) { this.heaps[parseInt(name.substr(2), 10)] = this.parseHeap(m.body); } else if (name === 'arrlength') { this.arrLengths = this.parseArrayLengths(m.body); } else if (name === 'arrelems') { this.arrElems = this.parseArrayElems(m.body); } else if (name === 'objproperties') { this.objProperties = this.parseObjectProperties(m.body); } else if (name === 'objfield') { this.objFields = this.parseObjectFields(m.body); } else if (name.startsWith('c_')) { return; // skip class names } else if (name.startsWith('app')) { this.parseFunctions(m.body, parseInt(name.substr(3), 10)); } else if (name.startsWith('pre') || name.startsWith('post') || name.startsWith('eff') || name.startsWith('call')) { return; // skip functions } else { const heapMatch = matchSExpr(data, ['define-fun', { name: 'name' }, [['x!0', 'Loc']], 'JSVal', { expr: 'body' }]); if (heapMatch !== null) { this.heapMappings[heapMatch.name as string] = this.parseHeapMapping(heapMatch.body); } else { const propertiesMatch = matchSExpr(data, ['define-fun', { name: 'name' }, [['x!0', 'String']], 'Bool', { expr: 'body' }]); if (propertiesMatch !== null) { const mapping = this.parsePropertyMapping(propertiesMatch.body); this.objPropertyMappings[propertiesMatch.name as string] = mapping === null ? new Set() : mapping; } else { throw this.modelError(`unexpected key: ${name}`); } } } } private modelError (smt: SMTOutput): MessageException { return new MessageException({ status: 'error', type: 'unrecognized-model', loc: { file: getOptions().filename, start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }, description: `cannot parse smt ${smt}` }); } private parseNum (v: SExpr): JSVal.Num { if (typeof v === 'string') { return { type: 'num', v: parseFloat(v) }; } const matchNeg = matchSExpr(v, ['-', { expr: 'num' }]); if (matchNeg !== null) { const num = this.parseNum(matchNeg.num); return { type: 'num', v: - num.v }; } const matchDiv = matchSExpr(v, ['/', { expr: 'n' }, { expr: 'd' }]); if (matchDiv !== null) { const n = this.parseNum(matchDiv.n); const d = this.parseNum(matchDiv.d); return { type: 'num', v: n.v / d.v }; } throw this.modelError(`cannot parse number ${v}`); } private tryParseSimpleValue (s: SExpr): JSVal | null { if (typeof s === 'string') { if (s === 'jsundefined') { return { type: 'undefined' }; } else if (s === 'jsnull') { return { type: 'null' }; } else { return null; } } else { if (s.length < 1) return null; const tag = s[0]; if (typeof tag !== 'string') return null; if (tag === 'jsbool') { if (s.length !== 2) return null; const v = s[1]; if (typeof v !== 'string') return null; return { type: 'bool', v: v === 'true' }; } else if (tag === 'jsint' || tag === 'jsreal') { if (s.length !== 2) return null; return this.parseNum(s[1]); } else if (tag === 'jsstr') { if (s.length !== 2) return null; const v = s[1]; if (typeof v !== 'string') return null; return { type: 'str', v: v.substr(1, v.length - 2) }; } else { return null; } } } private parseLazyValue (s: SExpr): LazyValue { if (typeof s === 'string') { if (s === 'jsundefined') { return { type: 'undefined' }; } else if (s === 'jsnull') { return { type: 'null' }; } else if (s.startsWith('jsobj_')) { return { type: 'obj-cls', cls: s.substr(6), args: [] }; } else if (s.startsWith('Arr!')) { return { type: 'arr-ref', name: s }; } else { throw this.modelError(s); } } else { if (s.length < 1) throw this.modelError(s.toString()); const tag = s[0]; if (typeof tag !== 'string') throw this.modelError(tag.toString()); if (tag === 'jsbool') { if (s.length !== 2) throw this.modelError(s.toString()); const v = s[1]; if (typeof v !== 'string') throw this.modelError(s.toString()); return { type: 'bool', v: v === 'true' }; } else if (tag === 'jsint' || tag === 'jsreal') { if (s.length !== 2) throw this.modelError(s.toString()); return this.parseNum(s[1]); } else if (tag === 'jsstr') { if (s.length !== 2) throw this.modelError(s.toString()); const v = s[1]; if (typeof v !== 'string') throw this.modelError(s.toString()); const vchars = v.substr(1, v.length - 2); // replace "\x00" with "\0", etc. const vreplaced = vchars.replace(/\\x(\d\d)/g, (m, c) => String.fromCharCode(parseInt(c, 16))); return { type: 'str', v: vreplaced }; } else if (tag === 'jsfun') { if (s.length !== 2) throw this.modelError(s.toString()); const v = s[1]; if (typeof v !== 'string') throw this.modelError(s.toString()); return { type: 'fun-ref', name: v }; } else if (tag === 'jsobj') { if (s.length !== 2) throw this.modelError(s.toString()); const v = s[1]; if (typeof v !== 'string') throw this.modelError(s.toString()); return { type: 'obj-ref', name: v }; } else if (tag === 'jsobj_Array') { if (s.length !== 2) throw this.modelError(s.toString()); const v = s[1]; if (typeof v !== 'string') throw this.modelError(s.toString()); return { type: 'arr-ref', name: v }; } else if (tag.startsWith('jsobj_')) { return { type: 'obj-cls', cls: tag.substr(6), args: s.slice(1).map(a => this.parseLazyValue(a)) }; } else { throw this.modelError(tag); } } } private parseHeap (smt: SExpr): string { const m = matchSExpr(smt, ['_', 'as-array', { name: 'name' }]); if (!m) throw this.modelError('expected (_ as-array $name)'); return m.name as string; } private parseHeapMapping (smt: SExpr): HeapMapping { const iteMatch = matchSExpr(smt, ['ite', ['=', 'x!0', { name: 'loc' }], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parseHeapMapping(iteMatch.then); const els = this.parseHeapMapping(iteMatch.els); return (loc: Loc) => loc.name === iteMatch.loc ? then(loc) : els(loc); } else { const val: LazyValue = this.parseLazyValue(smt); return (loc: Loc) => val; } } private parseArrayLengths (smt: SExpr): ArrLengths { const iteMatch = matchSExpr(smt, ['ite', ['=', 'x!0', { name: 'arr' }], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parseArrayLengths(iteMatch.then); const els = this.parseArrayLengths(iteMatch.els); return (arrRef: ArrRef) => arrRef.name === iteMatch.arr ? then(arrRef) : els(arrRef); } else { if (typeof smt !== 'string') throw this.modelError('expected num'); return (arrRef: ArrRef) => parseInt(smt, 10); } } private parseArrayElems (smt: SExpr): ArrElems { const iteMatch = matchSExpr(smt, ['ite', ['and', ['=', 'x!0', { name: 'arr' }], ['=', 'x!1', { name: 'i' }]], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parseArrayElems(iteMatch.then); const els = this.parseArrayElems(iteMatch.els); const arr = iteMatch.arr as string; const i = parseInt(iteMatch.i as string, 10); return (arrRef: ArrRef, idx: number) => arrRef.name === arr && idx === i ? then(arrRef, idx) : els(arrRef, idx); } else { const val: LazyValue = this.parseLazyValue(smt); return (arrRef: ArrRef, idx: number) => val; } } private parseFunctions (smt: SExpr, numArgs: number): void { // only find direct matches and treat final value explicitly const iteMatch = matchSExpr(smt, ['ite', { group: 'cond' }, { expr: 'then' }, { expr: 'els' }]); if (!iteMatch) { this.funDefaults[numArgs] = this.parseLazyValue(smt); return; } this.parseFunctions(iteMatch.els, numArgs); // process remaining functions first const condList = iteMatch.cond as Array<string>; if (condList.length < 3 || condList[0] !== 'and') throw this.modelError('expected (and ...)'); const funcMatch = matchSExpr(condList[1], ['=', 'x!0', ['jsfun', { name: 'func' }]]); if (!funcMatch) return; // skip non-function value mappings const funcName = funcMatch.func as string; const funcBlocks: Array<LazyFun> = funcName in this.funs ? this.funs[funcName] : (this.funs[funcName] = []); const fun: LazyFun = numArgs in funcBlocks ? funcBlocks[numArgs] : (funcBlocks[numArgs] = { type: 'fun', body: [] }); const fullCond: Array<JSVal> = []; // ignore 'and', func match, this arg and heap cond -> remaining part of cond are arguments for (let idx = 4; idx < condList.length; idx++) { const condMatch = matchSExpr(condList[idx], ['=', `x!${idx - 1}`, { expr: 'val' }]); if (!condMatch) throw this.modelError('expected (= x!idx $val)'); const matchVal: JSVal | null = this.tryParseSimpleValue(condMatch.val); if (!matchVal) return; fullCond.push(matchVal); } const then = this.parseLazyValue(iteMatch.then); fun.body.unshift({ cond: fullCond, ret: then }); } private parseObjectProperties (smt: SExpr): ObjProperties { const iteMatch = matchSExpr(smt, ['ite', ['=', 'x!0', { name: 'obj' }], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parseObjectProperties(iteMatch.then); const els = this.parseObjectProperties(iteMatch.els); return (objRef: ObjRef) => objRef.name === iteMatch.obj ? then(objRef) : els(objRef); } const asArrayMatch = matchSExpr(smt, ['_', 'as-array', { name: 'name' }]); if (!asArrayMatch) throw this.modelError('expected (_ as-array $name)'); return (objRef: ObjRef) => asArrayMatch.name as string; } private parsePropertyMapping (smt: SExpr): Set<string> | null { const iteMatch = matchSExpr(smt, ['ite', ['=', 'x!0', { name: 'prop' }], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parsePropertyMapping(iteMatch.then); const els = this.parsePropertyMapping(iteMatch.els); const prop = iteMatch.prop as string; if (prop.length < 2 || prop[0] !== '"' || prop[prop.length - 1] !== '"') { throw this.modelError('expected string'); } if (then === null) { // if (p = "prop") then false else $x -> $x return els; } else if (els === null) { // if (p = "prop") then $x else false -> ["prop", $x] return new Set([prop.substr(1, prop.length - 2), ...then]); } else { // if (p = "prop") then $x else $y -> ["prop", $x, $y] return new Set([prop.substr(1, prop.length - 2), ...then, ...els]); } } else if (smt === 'true') { // include properties on path return new Set(); } else if (smt === 'false') { // do not include properties on path return null; } else { throw this.modelError('expected (true)') ; } } private parseObjectFields (smt: SExpr): ObjFields { const iteMatch = matchSExpr(smt, ['ite', ['and', ['=', 'x!0', { name: 'obj' }], ['=', 'x!1', { name: 's' }]], { expr: 'then' }, { expr: 'els' }]); if (iteMatch) { const then = this.parseObjectFields(iteMatch.then); const els = this.parseObjectFields(iteMatch.els); const arr = iteMatch.obj as string; const str = iteMatch.s as string; if (str.length < 2 || str[0] !== '"' || str[str.length - 1] !== '"') { throw this.modelError('expected string'); } return (objRef: ObjRef, prop: string) => objRef.name === arr && prop === str.substr(1, str.length - 2) ? then(objRef, prop) : els(objRef, prop); } else { const val: LazyValue = this.parseLazyValue(smt); return (objRef: ObjRef, prop: string) => val; } } private hydrate (val: LazyValue): JSVal { switch (val.type) { case 'obj-cls': return { type: 'obj-cls', cls: val.cls, args: val.args.map(a => this.hydrate(a)) }; case 'fun-ref': const body: Array<Syntax.Statement> = []; let numArgs = 0; if (this.funs && val.name in this.funs) { const funcBlocks: Array<LazyFun> = this.funs[val.name]; if (Object.keys(funcBlocks).length !== 1) { throw this.modelError('no support for variable argument functions'); } numArgs = parseInt(Object.keys(funcBlocks)[0], 10); const fun = funcBlocks[numArgs]; let defaultVal = this.funDefaults[numArgs]; fun.body.forEach(({ cond, ret }) => { if (cond.length === 0) { defaultVal = ret; } else { body.push({ type: 'IfStatement', test: cond .map((condExpr, argIdx): Syntax.Expression => ({ type: 'BinaryExpression', operator: '===', left: id(`x_${argIdx}`), right: valueToJavaScript(condExpr), loc: nullLoc() })) .reduceRight((prev, curr) => ({ type: 'LogicalExpression', operator: '&&', left: curr, right: prev, loc: nullLoc() })), consequent: { type: 'BlockStatement', body: [{ type: 'ReturnStatement', argument: valueToJavaScript(this.hydrate(ret)), loc: nullLoc() }], loc: nullLoc() }, alternate: { type: 'BlockStatement', body: [], loc: nullLoc() }, loc: nullLoc() }); } }); body.push({ type: 'ReturnStatement', argument: valueToJavaScript(this.hydrate(defaultVal)), loc: nullLoc() }); } return { type: 'fun', body: { type: 'FunctionExpression', id: null, params: [...Array(numArgs)].map((_, idx) => id(`x_${idx}`)), requires: [], ensures: [], body: { type: 'BlockStatement', body, loc: nullLoc() }, freeVars: [], loc: nullLoc() } }; case 'arr-ref': if (this.arrLengths === null) throw this.modelError('no arrlength'); return { type: 'arr', elems: [...Array(this.arrLengths(val))].map((_, i) => { if (this.arrElems === null) throw this.modelError('no arrelems'); return this.hydrate(this.arrElems(val, i)); }) }; case 'obj-ref': if (this.objProperties === null) throw this.modelError('no objproperties'); if (this.objFields === null) throw this.modelError('no objfields'); const obj: { [key: string]: JSVal } = {}; const objAlias: string = this.objProperties(val); if (!(objAlias in this.objPropertyMappings)) throw this.modelError(`no mapping for ${this.objProperties(val)}`); for (const key of this.objPropertyMappings[objAlias]) { obj[key] = this.hydrate(this.objFields(val, key)); } return { type: 'obj', v: obj }; default: return val; } } }
the_stack